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.

279016 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC || JUCE_IOS
  76. #if defined (DEBUG) || defined (_DEBUG) || ! (defined (NDEBUG) || defined (_NDEBUG))
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #if ! (defined (DEBUG) || defined (_DEBUG) || defined (NDEBUG) || defined (_NDEBUG))
  80. #warning "Neither NDEBUG or DEBUG has been defined - you should set one of these to make it clear whether this is a release build,"
  81. #endif
  82. #ifdef __LITTLE_ENDIAN__
  83. #define JUCE_LITTLE_ENDIAN 1
  84. #else
  85. #define JUCE_BIG_ENDIAN 1
  86. #endif
  87. #endif
  88. #if JUCE_MAC
  89. #if defined (__ppc__) || defined (__ppc64__)
  90. #define JUCE_PPC 1
  91. #else
  92. #define JUCE_INTEL 1
  93. #endif
  94. #ifdef __LP64__
  95. #define JUCE_64BIT 1
  96. #else
  97. #define JUCE_32BIT 1
  98. #endif
  99. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  100. #error "Building for OSX 10.3 is no longer supported!"
  101. #endif
  102. #ifndef MAC_OS_X_VERSION_10_5
  103. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  104. #endif
  105. #endif
  106. #if JUCE_LINUX
  107. #ifdef _DEBUG
  108. #define JUCE_DEBUG 1
  109. #endif
  110. // Allow override for big-endian Linux platforms
  111. #ifndef JUCE_BIG_ENDIAN
  112. #define JUCE_LITTLE_ENDIAN 1
  113. #endif
  114. #if defined (__LP64__) || defined (_LP64)
  115. #define JUCE_64BIT 1
  116. #else
  117. #define JUCE_32BIT 1
  118. #endif
  119. #define JUCE_INTEL 1
  120. #endif
  121. // Compiler type macros.
  122. #ifdef __GNUC__
  123. #define JUCE_GCC 1
  124. #elif defined (_MSC_VER)
  125. #define JUCE_MSVC 1
  126. #if _MSC_VER < 1500
  127. #define JUCE_VC8_OR_EARLIER 1
  128. #if _MSC_VER < 1400
  129. #define JUCE_VC7_OR_EARLIER 1
  130. #if _MSC_VER < 1300
  131. #define JUCE_VC6 1
  132. #endif
  133. #endif
  134. #endif
  135. #if ! JUCE_VC7_OR_EARLIER
  136. #define JUCE_USE_INTRINSICS 1
  137. #endif
  138. #else
  139. #error unknown compiler
  140. #endif
  141. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  142. /*** End of inlined file: juce_TargetPlatform.h ***/
  143. // FORCE_AMALGAMATOR_INCLUDE
  144. /*** Start of inlined file: juce_Config.h ***/
  145. #ifndef __JUCE_CONFIG_JUCEHEADER__
  146. #define __JUCE_CONFIG_JUCEHEADER__
  147. /*
  148. This file contains macros that enable/disable various JUCE features.
  149. */
  150. /** The name of the namespace that all Juce classes and functions will be
  151. put inside. If this is not defined, no namespace will be used.
  152. */
  153. #ifndef JUCE_NAMESPACE
  154. #define JUCE_NAMESPACE juce
  155. #endif
  156. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  157. project settings, but if you define this value, you can override this to force
  158. it to be true or false.
  159. */
  160. #ifndef JUCE_FORCE_DEBUG
  161. //#define JUCE_FORCE_DEBUG 0
  162. #endif
  163. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  164. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  165. Enabling it will also leave this turned on in release builds. When it's disabled,
  166. however, the jassert and jassertfalse macros will not be compiled in a
  167. release build.
  168. @see jassert, jassertfalse, Logger
  169. */
  170. #ifndef JUCE_LOG_ASSERTIONS
  171. #define JUCE_LOG_ASSERTIONS 0
  172. #endif
  173. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  174. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  175. on your Windows build machine.
  176. See the comments in the ASIOAudioIODevice class's header file for more
  177. info about this.
  178. */
  179. #ifndef JUCE_ASIO
  180. #define JUCE_ASIO 0
  181. #endif
  182. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  183. */
  184. #ifndef JUCE_WASAPI
  185. #define JUCE_WASAPI 0
  186. #endif
  187. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  188. */
  189. #ifndef JUCE_DIRECTSOUND
  190. #define JUCE_DIRECTSOUND 1
  191. #endif
  192. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  193. #ifndef JUCE_ALSA
  194. #define JUCE_ALSA 1
  195. #endif
  196. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  197. #ifndef JUCE_JACK
  198. #define JUCE_JACK 0
  199. #endif
  200. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  201. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  202. installed, and its header files will need to be on your include path.
  203. */
  204. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  205. #define JUCE_QUICKTIME 0
  206. #endif
  207. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  208. #undef JUCE_QUICKTIME
  209. #endif
  210. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  211. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  212. */
  213. #ifndef JUCE_OPENGL
  214. #define JUCE_OPENGL 1
  215. #endif
  216. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  217. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  218. */
  219. #ifndef JUCE_DIRECT2D
  220. #define JUCE_DIRECT2D 0
  221. #endif
  222. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  223. If your app doesn't need to read FLAC files, you might want to disable this to
  224. reduce the size of your codebase and build time.
  225. */
  226. #ifndef JUCE_USE_FLAC
  227. #define JUCE_USE_FLAC 1
  228. #endif
  229. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  230. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  231. reduce the size of your codebase and build time.
  232. */
  233. #ifndef JUCE_USE_OGGVORBIS
  234. #define JUCE_USE_OGGVORBIS 1
  235. #endif
  236. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  237. Unless you're using CD-burning, you should probably turn this flag off to
  238. reduce code size.
  239. */
  240. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  241. #define JUCE_USE_CDBURNER 1
  242. #endif
  243. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  244. Unless you're using CD-reading, you should probably turn this flag off to
  245. reduce code size.
  246. */
  247. #ifndef JUCE_USE_CDREADER
  248. #define JUCE_USE_CDREADER 1
  249. #endif
  250. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  251. */
  252. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  253. #define JUCE_USE_CAMERA 0
  254. #endif
  255. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  256. gets repainted will flash in a random colour, so that you can check exactly how much and how
  257. often your components are being drawn.
  258. */
  259. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  260. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  261. #endif
  262. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  263. Unless you specifically want to disable this, it's best to leave this option turned on.
  264. */
  265. #ifndef JUCE_USE_XINERAMA
  266. #define JUCE_USE_XINERAMA 1
  267. #endif
  268. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  269. turned on unless you have a good reason to disable it.
  270. */
  271. #ifndef JUCE_USE_XSHM
  272. #define JUCE_USE_XSHM 1
  273. #endif
  274. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  275. */
  276. #ifndef JUCE_USE_XRENDER
  277. #define JUCE_USE_XRENDER 0
  278. #endif
  279. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  280. unless you have a good reason to disable it.
  281. */
  282. #ifndef JUCE_USE_XCURSOR
  283. #define JUCE_USE_XCURSOR 1
  284. #endif
  285. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  286. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  287. you're building a plugin hosting app.
  288. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  289. */
  290. #ifndef JUCE_PLUGINHOST_VST
  291. #define JUCE_PLUGINHOST_VST 0
  292. #endif
  293. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  294. of course, and should only be enabled if you're building a plugin hosting app.
  295. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  296. */
  297. #ifndef JUCE_PLUGINHOST_AU
  298. #define JUCE_PLUGINHOST_AU 0
  299. #endif
  300. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  301. This should be enabled if you're writing a console application.
  302. */
  303. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  304. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  305. #endif
  306. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  307. If you're not using any embedded web-pages, turning this off may reduce your code size.
  308. */
  309. #ifndef JUCE_WEB_BROWSER
  310. #define JUCE_WEB_BROWSER 1
  311. #endif
  312. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  313. Carbon isn't required for a normal app, but may be needed by specialised classes like
  314. plugin-hosts, which support older APIs.
  315. */
  316. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  317. #define JUCE_SUPPORT_CARBON 1
  318. #endif
  319. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  320. You might need to tweak this if you're linking to an external zlib library in your app,
  321. but for normal apps, this option should be left alone.
  322. */
  323. #ifndef JUCE_INCLUDE_ZLIB_CODE
  324. #define JUCE_INCLUDE_ZLIB_CODE 1
  325. #endif
  326. #ifndef JUCE_INCLUDE_FLAC_CODE
  327. #define JUCE_INCLUDE_FLAC_CODE 1
  328. #endif
  329. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  330. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  331. #endif
  332. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  333. #define JUCE_INCLUDE_PNGLIB_CODE 1
  334. #endif
  335. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  336. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  337. #endif
  338. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check for certain objects when
  339. the app terminates. See the LeakedObjectDetector class and the JUCE_LEAK_DETECTOR
  340. macro for more details about enabling leak checking for specific classes.
  341. */
  342. #if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
  343. #define JUCE_CHECK_MEMORY_LEAKS 1
  344. #endif
  345. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  346. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  347. are passed to the JUCEApplication::unhandledException() callback for logging.
  348. */
  349. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  350. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  351. #endif
  352. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  353. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  354. #undef JUCE_QUICKTIME
  355. #define JUCE_QUICKTIME 0
  356. #undef JUCE_OPENGL
  357. #define JUCE_OPENGL 0
  358. #undef JUCE_USE_CDBURNER
  359. #define JUCE_USE_CDBURNER 0
  360. #undef JUCE_USE_CDREADER
  361. #define JUCE_USE_CDREADER 0
  362. #undef JUCE_WEB_BROWSER
  363. #define JUCE_WEB_BROWSER 0
  364. #undef JUCE_PLUGINHOST_AU
  365. #define JUCE_PLUGINHOST_AU 0
  366. #undef JUCE_PLUGINHOST_VST
  367. #define JUCE_PLUGINHOST_VST 0
  368. #endif
  369. #endif
  370. /*** End of inlined file: juce_Config.h ***/
  371. // FORCE_AMALGAMATOR_INCLUDE
  372. #ifndef JUCE_BUILD_CORE
  373. #define JUCE_BUILD_CORE 1
  374. #endif
  375. #ifndef JUCE_BUILD_MISC
  376. #define JUCE_BUILD_MISC 1
  377. #endif
  378. #ifndef JUCE_BUILD_GUI
  379. #define JUCE_BUILD_GUI 1
  380. #endif
  381. #ifndef JUCE_BUILD_NATIVE
  382. #define JUCE_BUILD_NATIVE 1
  383. #endif
  384. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  385. #undef JUCE_BUILD_MISC
  386. #undef JUCE_BUILD_GUI
  387. #endif
  388. //==============================================================================
  389. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  390. #if JUCE_WINDOWS
  391. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  392. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  393. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  394. #ifndef STRICT
  395. #define STRICT 1
  396. #endif
  397. #undef WIN32_LEAN_AND_MEAN
  398. #define WIN32_LEAN_AND_MEAN 1
  399. #if JUCE_MSVC
  400. #pragma warning (push)
  401. #pragma warning (disable : 4100 4201 4514 4312 4995)
  402. #endif
  403. #define _WIN32_WINNT 0x0500
  404. #define _UNICODE 1
  405. #define UNICODE 1
  406. #ifndef _WIN32_IE
  407. #define _WIN32_IE 0x0400
  408. #endif
  409. #include <windows.h>
  410. #include <windowsx.h>
  411. #include <commdlg.h>
  412. #include <shellapi.h>
  413. #include <mmsystem.h>
  414. #include <vfw.h>
  415. #include <tchar.h>
  416. #include <stddef.h>
  417. #include <ctime>
  418. #include <wininet.h>
  419. #include <nb30.h>
  420. #include <iphlpapi.h>
  421. #include <mapi.h>
  422. #include <float.h>
  423. #include <process.h>
  424. #include <Exdisp.h>
  425. #include <exdispid.h>
  426. #include <shlobj.h>
  427. #if ! JUCE_MINGW
  428. #include <crtdbg.h>
  429. #include <comutil.h>
  430. #endif
  431. #if JUCE_OPENGL
  432. #include <gl/gl.h>
  433. #endif
  434. #undef PACKED
  435. #if JUCE_ASIO && JUCE_BUILD_NATIVE
  436. /*
  437. This is very frustrating - we only need to use a handful of definitions from
  438. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  439. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  440. implementation...
  441. ..unfortunately that would break Steinberg's license agreement for use of
  442. their SDK, so I'm not allowed to do this.
  443. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  444. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  445. (see www.steinberg.net/Steinberg/Developers.asp).
  446. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  447. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  448. if you prefer). Make sure that your header search path will find the
  449. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  450. files are actually needed - so to simplify things, you could just copy
  451. these into your JUCE directory).
  452. If you're compiling and you get an error here because you don't have the
  453. ASIO SDK installed, you can disable ASIO support by commenting-out the
  454. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  455. */
  456. #include <iasiodrv.h>
  457. #endif
  458. #if JUCE_USE_CDBURNER && JUCE_BUILD_NATIVE
  459. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  460. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  461. flag in juce_Config.h to avoid these includes.
  462. */
  463. #include <imapi.h>
  464. #include <imapierror.h>
  465. #endif
  466. #if JUCE_USE_CAMERA && JUCE_BUILD_NATIVE
  467. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  468. These files are provided in the normal Windows SDK, but some Microsoft plonker
  469. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  470. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  471. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  472. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  473. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  474. The dummy file just needs to contain the following content:
  475. #define __IDxtCompositor_INTERFACE_DEFINED__
  476. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  477. #define __IDxtJpeg_INTERFACE_DEFINED__
  478. #define __IDxtKey_INTERFACE_DEFINED__
  479. ..and that should be enough to convince qedit.h that you have the SDK!
  480. */
  481. #include <dshow.h>
  482. #include <qedit.h>
  483. #include <dshowasf.h>
  484. #endif
  485. #if JUCE_WASAPI && JUCE_BUILD_NATIVE
  486. #include <MMReg.h>
  487. #include <mmdeviceapi.h>
  488. #include <Audioclient.h>
  489. #include <Avrt.h>
  490. #include <functiondiscoverykeys.h>
  491. #endif
  492. #if JUCE_QUICKTIME
  493. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  494. add its header directory to your include path.
  495. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  496. flag in juce_Config.h
  497. */
  498. #include <Movies.h>
  499. #include <QTML.h>
  500. #include <QuickTimeComponents.h>
  501. #include <MediaHandlers.h>
  502. #include <ImageCodec.h>
  503. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  504. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  505. your include search path to make these import statements work.
  506. */
  507. #import <QTOLibrary.dll>
  508. #import <QTOControl.dll>
  509. #endif
  510. #if JUCE_MSVC
  511. #pragma warning (pop)
  512. #endif
  513. #if JUCE_DIRECT2D && JUCE_BUILD_NATIVE
  514. #include <d2d1.h>
  515. #include <dwrite.h>
  516. #endif
  517. /** A simple COM smart pointer.
  518. Avoids having to include ATL just to get one of these.
  519. */
  520. template <class ComClass>
  521. class ComSmartPtr
  522. {
  523. public:
  524. ComSmartPtr() throw() : p (0) {}
  525. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  526. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  527. ~ComSmartPtr() { release(); }
  528. operator ComClass*() const throw() { return p; }
  529. ComClass& operator*() const throw() { return *p; }
  530. ComClass* operator->() const throw() { return p; }
  531. ComSmartPtr& operator= (ComClass* const newP)
  532. {
  533. if (newP != 0) newP->AddRef();
  534. release();
  535. p = newP;
  536. return *this;
  537. }
  538. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  539. // Releases and nullifies this pointer and returns its address
  540. ComClass** resetAndGetPointerAddress()
  541. {
  542. release();
  543. p = 0;
  544. return &p;
  545. }
  546. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  547. {
  548. #ifndef __MINGW32__
  549. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  550. #else
  551. return E_NOTIMPL;
  552. #endif
  553. }
  554. template <class OtherComClass>
  555. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  556. {
  557. if (p == 0)
  558. return E_POINTER;
  559. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  560. }
  561. private:
  562. ComClass* p;
  563. void release() { if (p != 0) p->Release(); }
  564. ComClass** operator&() throw(); // private to avoid it being used accidentally
  565. };
  566. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  567. */
  568. template <class ComClass>
  569. class ComBaseClassHelper : public ComClass
  570. {
  571. public:
  572. ComBaseClassHelper() : refCount (1) {}
  573. virtual ~ComBaseClassHelper() {}
  574. HRESULT __stdcall QueryInterface (REFIID refId, void** result)
  575. {
  576. #ifndef __MINGW32__
  577. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  578. #endif
  579. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  580. *result = 0;
  581. return E_NOINTERFACE;
  582. }
  583. ULONG __stdcall AddRef() { return ++refCount; }
  584. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  585. protected:
  586. int refCount;
  587. };
  588. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  589. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  590. #elif JUCE_LINUX
  591. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  592. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  593. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  594. /*
  595. This file wraps together all the linux-specific headers, so
  596. that we can include them all just once, and compile all our
  597. platform-specific stuff in one big lump, keeping it out of the
  598. way of the rest of the codebase.
  599. */
  600. #include <sched.h>
  601. #include <pthread.h>
  602. #include <sys/time.h>
  603. #include <errno.h>
  604. #include <sys/stat.h>
  605. #include <sys/dir.h>
  606. #include <sys/ptrace.h>
  607. #include <sys/vfs.h>
  608. #include <sys/wait.h>
  609. #include <fnmatch.h>
  610. #include <utime.h>
  611. #include <pwd.h>
  612. #include <fcntl.h>
  613. #include <dlfcn.h>
  614. #include <netdb.h>
  615. #include <arpa/inet.h>
  616. #include <netinet/in.h>
  617. #include <sys/types.h>
  618. #include <sys/ioctl.h>
  619. #include <sys/socket.h>
  620. #include <net/if.h>
  621. #include <sys/sysinfo.h>
  622. #include <sys/file.h>
  623. #include <signal.h>
  624. /* Got a build error here? You'll need to install the freetype library...
  625. The name of the package to install is "libfreetype6-dev".
  626. */
  627. #include <ft2build.h>
  628. #include FT_FREETYPE_H
  629. #include <X11/Xlib.h>
  630. #include <X11/Xatom.h>
  631. #include <X11/Xresource.h>
  632. #include <X11/Xutil.h>
  633. #include <X11/Xmd.h>
  634. #include <X11/keysym.h>
  635. #include <X11/cursorfont.h>
  636. #if JUCE_USE_XINERAMA
  637. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  638. #include <X11/extensions/Xinerama.h>
  639. #endif
  640. #if JUCE_USE_XSHM
  641. #include <X11/extensions/XShm.h>
  642. #include <sys/shm.h>
  643. #include <sys/ipc.h>
  644. #endif
  645. #if JUCE_USE_XRENDER
  646. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  647. #include <X11/extensions/Xrender.h>
  648. #include <X11/extensions/Xcomposite.h>
  649. #endif
  650. #if JUCE_USE_XCURSOR
  651. // If you're missing this header, try installing the libxcursor-dev package
  652. #include <X11/Xcursor/Xcursor.h>
  653. #endif
  654. #if JUCE_OPENGL
  655. /* Got an include error here?
  656. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  657. and "freeglut3-dev".
  658. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  659. want to disable it.
  660. */
  661. #include <GL/glx.h>
  662. #endif
  663. #undef KeyPress
  664. #if JUCE_ALSA
  665. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  666. not got your paths set up correctly to find its header files.
  667. The package you need to install to get ASLA support is "libasound2-dev".
  668. If you don't have the ALSA library and don't want to build Juce with audio support,
  669. just disable the JUCE_ALSA flag in juce_Config.h
  670. */
  671. #include <alsa/asoundlib.h>
  672. #endif
  673. #if JUCE_JACK
  674. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  675. installed, or you've not got your paths set up correctly to find its header files.
  676. The package you need to install to get JACK support is "libjack-dev".
  677. If you don't have the jack-audio-connection-kit library and don't want to build
  678. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  679. */
  680. #include <jack/jack.h>
  681. //#include <jack/transport.h>
  682. #endif
  683. #undef SIZEOF
  684. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  685. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  686. #elif JUCE_MAC || JUCE_IPHONE
  687. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  688. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  689. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  690. /*
  691. This file wraps together all the mac-specific code, so that
  692. we can include all the native headers just once, and compile all our
  693. platform-specific stuff in one big lump, keeping it out of the way of
  694. the rest of the codebase.
  695. */
  696. #define USE_COREGRAPHICS_RENDERING 1
  697. #if JUCE_IOS
  698. #import <Foundation/Foundation.h>
  699. #import <UIKit/UIKit.h>
  700. #import <AudioToolbox/AudioToolbox.h>
  701. #import <AVFoundation/AVFoundation.h>
  702. #import <CoreData/CoreData.h>
  703. #import <MobileCoreServices/MobileCoreServices.h>
  704. #import <QuartzCore/QuartzCore.h>
  705. #include <sys/fcntl.h>
  706. #if JUCE_OPENGL
  707. #include <OpenGLES/ES1/gl.h>
  708. #include <OpenGLES/ES1/glext.h>
  709. #endif
  710. #else
  711. #import <Cocoa/Cocoa.h>
  712. #import <CoreAudio/HostTime.h>
  713. #if JUCE_BUILD_NATIVE
  714. #import <CoreAudio/AudioHardware.h>
  715. #import <CoreMIDI/MIDIServices.h>
  716. #import <QTKit/QTKit.h>
  717. #import <WebKit/WebKit.h>
  718. #import <DiscRecording/DiscRecording.h>
  719. #import <IOKit/IOKitLib.h>
  720. #import <IOKit/IOCFPlugIn.h>
  721. #import <IOKit/hid/IOHIDLib.h>
  722. #import <IOKit/hid/IOHIDKeys.h>
  723. #import <IOKit/pwr_mgt/IOPMLib.h>
  724. #endif
  725. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  726. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  727. #include <Carbon/Carbon.h>
  728. #endif
  729. #include <sys/dir.h>
  730. #endif
  731. #include <sys/socket.h>
  732. #include <sys/sysctl.h>
  733. #include <sys/stat.h>
  734. #include <sys/param.h>
  735. #include <sys/mount.h>
  736. #include <fnmatch.h>
  737. #include <utime.h>
  738. #include <dlfcn.h>
  739. #include <ifaddrs.h>
  740. #include <net/if_dl.h>
  741. #include <mach/mach_time.h>
  742. #include <mach-o/dyld.h>
  743. #if MACOS_10_4_OR_EARLIER
  744. #include <GLUT/glut.h>
  745. #endif
  746. #if ! CGFLOAT_DEFINED
  747. #define CGFloat float
  748. #endif
  749. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  750. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  751. #else
  752. #error "Unknown platform!"
  753. #endif
  754. #endif
  755. //==============================================================================
  756. #define DONT_SET_USING_JUCE_NAMESPACE 1
  757. #undef max
  758. #undef min
  759. #define NO_DUMMY_DECL
  760. #define JUCE_AMALGAMATED_TEMPLATE 1
  761. #if JUCE_BUILD_NATIVE
  762. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  763. #endif
  764. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  765. #pragma warning (disable: 4309 4305)
  766. #endif
  767. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  768. BEGIN_JUCE_NAMESPACE
  769. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  770. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  771. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  772. /**
  773. Creates a floating carbon window that can be used to hold a carbon UI.
  774. This is a handy class that's designed to be inlined where needed, e.g.
  775. in the audio plugin hosting code.
  776. */
  777. class CarbonViewWrapperComponent : public Component,
  778. public ComponentMovementWatcher,
  779. public Timer
  780. {
  781. public:
  782. CarbonViewWrapperComponent()
  783. : ComponentMovementWatcher (this),
  784. wrapperWindow (0),
  785. carbonWindow (0),
  786. embeddedView (0),
  787. recursiveResize (false)
  788. {
  789. }
  790. virtual ~CarbonViewWrapperComponent()
  791. {
  792. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  793. }
  794. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  795. virtual void removeView (HIViewRef embeddedView) = 0;
  796. virtual void mouseDown (int, int) {}
  797. virtual void paint() {}
  798. virtual bool getEmbeddedViewSize (int& w, int& h)
  799. {
  800. if (embeddedView == 0)
  801. return false;
  802. HIRect bounds;
  803. HIViewGetBounds (embeddedView, &bounds);
  804. w = jmax (1, roundToInt (bounds.size.width));
  805. h = jmax (1, roundToInt (bounds.size.height));
  806. return true;
  807. }
  808. void createWindow()
  809. {
  810. if (wrapperWindow == 0)
  811. {
  812. Rect r;
  813. r.left = getScreenX();
  814. r.top = getScreenY();
  815. r.right = r.left + getWidth();
  816. r.bottom = r.top + getHeight();
  817. CreateNewWindow (kDocumentWindowClass,
  818. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  819. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  820. &r, &wrapperWindow);
  821. jassert (wrapperWindow != 0);
  822. if (wrapperWindow == 0)
  823. return;
  824. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  825. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  826. [ownerWindow addChildWindow: carbonWindow
  827. ordered: NSWindowAbove];
  828. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  829. EventTypeSpec windowEventTypes[] =
  830. {
  831. { kEventClassWindow, kEventWindowGetClickActivation },
  832. { kEventClassWindow, kEventWindowHandleDeactivate },
  833. { kEventClassWindow, kEventWindowBoundsChanging },
  834. { kEventClassMouse, kEventMouseDown },
  835. { kEventClassMouse, kEventMouseMoved },
  836. { kEventClassMouse, kEventMouseDragged },
  837. { kEventClassMouse, kEventMouseUp},
  838. { kEventClassWindow, kEventWindowDrawContent },
  839. { kEventClassWindow, kEventWindowShown },
  840. { kEventClassWindow, kEventWindowHidden }
  841. };
  842. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  843. InstallWindowEventHandler (wrapperWindow, upp,
  844. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  845. windowEventTypes, this, &eventHandlerRef);
  846. setOurSizeToEmbeddedViewSize();
  847. setEmbeddedWindowToOurSize();
  848. creationTime = Time::getCurrentTime();
  849. }
  850. }
  851. void deleteWindow()
  852. {
  853. removeView (embeddedView);
  854. embeddedView = 0;
  855. if (wrapperWindow != 0)
  856. {
  857. RemoveEventHandler (eventHandlerRef);
  858. DisposeWindow (wrapperWindow);
  859. wrapperWindow = 0;
  860. }
  861. }
  862. void setOurSizeToEmbeddedViewSize()
  863. {
  864. int w, h;
  865. if (getEmbeddedViewSize (w, h))
  866. {
  867. if (w != getWidth() || h != getHeight())
  868. {
  869. startTimer (50);
  870. setSize (w, h);
  871. if (getParentComponent() != 0)
  872. getParentComponent()->setSize (w, h);
  873. }
  874. else
  875. {
  876. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  877. }
  878. }
  879. else
  880. {
  881. stopTimer();
  882. }
  883. }
  884. void setEmbeddedWindowToOurSize()
  885. {
  886. if (! recursiveResize)
  887. {
  888. recursiveResize = true;
  889. if (embeddedView != 0)
  890. {
  891. HIRect r;
  892. r.origin.x = 0;
  893. r.origin.y = 0;
  894. r.size.width = (float) getWidth();
  895. r.size.height = (float) getHeight();
  896. HIViewSetFrame (embeddedView, &r);
  897. }
  898. if (wrapperWindow != 0)
  899. {
  900. Rect wr;
  901. wr.left = getScreenX();
  902. wr.top = getScreenY();
  903. wr.right = wr.left + getWidth();
  904. wr.bottom = wr.top + getHeight();
  905. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  906. ShowWindow (wrapperWindow);
  907. }
  908. recursiveResize = false;
  909. }
  910. }
  911. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  912. {
  913. setEmbeddedWindowToOurSize();
  914. }
  915. void componentPeerChanged()
  916. {
  917. deleteWindow();
  918. createWindow();
  919. }
  920. void componentVisibilityChanged (Component&)
  921. {
  922. if (isShowing())
  923. createWindow();
  924. else
  925. deleteWindow();
  926. setEmbeddedWindowToOurSize();
  927. }
  928. static void recursiveHIViewRepaint (HIViewRef view)
  929. {
  930. HIViewSetNeedsDisplay (view, true);
  931. HIViewRef child = HIViewGetFirstSubview (view);
  932. while (child != 0)
  933. {
  934. recursiveHIViewRepaint (child);
  935. child = HIViewGetNextView (child);
  936. }
  937. }
  938. void timerCallback()
  939. {
  940. setOurSizeToEmbeddedViewSize();
  941. // To avoid strange overpainting problems when the UI is first opened, we'll
  942. // repaint it a few times during the first second that it's on-screen..
  943. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  944. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  945. }
  946. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  947. {
  948. switch (GetEventKind (event))
  949. {
  950. case kEventWindowHandleDeactivate:
  951. ActivateWindow (wrapperWindow, TRUE);
  952. return noErr;
  953. case kEventWindowGetClickActivation:
  954. {
  955. getTopLevelComponent()->toFront (false);
  956. [carbonWindow makeKeyAndOrderFront: nil];
  957. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  958. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  959. sizeof (ClickActivationResult), &howToHandleClick);
  960. HIViewSetNeedsDisplay (embeddedView, true);
  961. return noErr;
  962. }
  963. }
  964. return eventNotHandledErr;
  965. }
  966. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  967. {
  968. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  969. }
  970. protected:
  971. WindowRef wrapperWindow;
  972. NSWindow* carbonWindow;
  973. HIViewRef embeddedView;
  974. bool recursiveResize;
  975. Time creationTime;
  976. EventHandlerRef eventHandlerRef;
  977. };
  978. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  979. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  980. END_JUCE_NAMESPACE
  981. #endif
  982. //==============================================================================
  983. #if JUCE_BUILD_CORE
  984. /*** Start of inlined file: juce_FileLogger.cpp ***/
  985. BEGIN_JUCE_NAMESPACE
  986. FileLogger::FileLogger (const File& logFile_,
  987. const String& welcomeMessage,
  988. const int maxInitialFileSizeBytes)
  989. : logFile (logFile_)
  990. {
  991. if (maxInitialFileSizeBytes >= 0)
  992. trimFileSize (maxInitialFileSizeBytes);
  993. if (! logFile_.exists())
  994. {
  995. // do this so that the parent directories get created..
  996. logFile_.create();
  997. }
  998. String welcome;
  999. welcome << newLine
  1000. << "**********************************************************" << newLine
  1001. << welcomeMessage << newLine
  1002. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1003. logMessage (welcome);
  1004. }
  1005. FileLogger::~FileLogger()
  1006. {
  1007. }
  1008. void FileLogger::logMessage (const String& message)
  1009. {
  1010. DBG (message);
  1011. const ScopedLock sl (logLock);
  1012. FileOutputStream out (logFile, 256);
  1013. out << message << newLine;
  1014. }
  1015. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1016. {
  1017. if (maxFileSizeBytes <= 0)
  1018. {
  1019. logFile.deleteFile();
  1020. }
  1021. else
  1022. {
  1023. const int64 fileSize = logFile.getSize();
  1024. if (fileSize > maxFileSizeBytes)
  1025. {
  1026. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1027. jassert (in != 0);
  1028. if (in != 0)
  1029. {
  1030. in->setPosition (fileSize - maxFileSizeBytes);
  1031. String content;
  1032. {
  1033. MemoryBlock contentToSave;
  1034. contentToSave.setSize (maxFileSizeBytes + 4);
  1035. contentToSave.fillWith (0);
  1036. in->read (contentToSave.getData(), maxFileSizeBytes);
  1037. in = 0;
  1038. content = contentToSave.toString();
  1039. }
  1040. int newStart = 0;
  1041. while (newStart < fileSize
  1042. && content[newStart] != '\n'
  1043. && content[newStart] != '\r')
  1044. ++newStart;
  1045. logFile.deleteFile();
  1046. logFile.appendText (content.substring (newStart), false, false);
  1047. }
  1048. }
  1049. }
  1050. }
  1051. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1052. const String& logFileName,
  1053. const String& welcomeMessage,
  1054. const int maxInitialFileSizeBytes)
  1055. {
  1056. #if JUCE_MAC
  1057. File logFile ("~/Library/Logs");
  1058. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1059. .getChildFile (logFileName);
  1060. #else
  1061. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1062. if (logFile.isDirectory())
  1063. {
  1064. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1065. .getChildFile (logFileName);
  1066. }
  1067. #endif
  1068. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1069. }
  1070. END_JUCE_NAMESPACE
  1071. /*** End of inlined file: juce_FileLogger.cpp ***/
  1072. /*** Start of inlined file: juce_Logger.cpp ***/
  1073. BEGIN_JUCE_NAMESPACE
  1074. Logger::Logger()
  1075. {
  1076. }
  1077. Logger::~Logger()
  1078. {
  1079. }
  1080. Logger* Logger::currentLogger = 0;
  1081. void Logger::setCurrentLogger (Logger* const newLogger,
  1082. const bool deleteOldLogger)
  1083. {
  1084. Logger* const oldLogger = currentLogger;
  1085. currentLogger = newLogger;
  1086. if (deleteOldLogger)
  1087. delete oldLogger;
  1088. }
  1089. void Logger::writeToLog (const String& message)
  1090. {
  1091. if (currentLogger != 0)
  1092. currentLogger->logMessage (message);
  1093. else
  1094. outputDebugString (message);
  1095. }
  1096. #if JUCE_LOG_ASSERTIONS
  1097. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1098. {
  1099. String m ("JUCE Assertion failure in ");
  1100. m << filename << ", line " << lineNum;
  1101. Logger::writeToLog (m);
  1102. }
  1103. #endif
  1104. END_JUCE_NAMESPACE
  1105. /*** End of inlined file: juce_Logger.cpp ***/
  1106. /*** Start of inlined file: juce_Random.cpp ***/
  1107. BEGIN_JUCE_NAMESPACE
  1108. Random::Random (const int64 seedValue) throw()
  1109. : seed (seedValue)
  1110. {
  1111. }
  1112. Random::~Random() throw()
  1113. {
  1114. }
  1115. void Random::setSeed (const int64 newSeed) throw()
  1116. {
  1117. seed = newSeed;
  1118. }
  1119. void Random::combineSeed (const int64 seedValue) throw()
  1120. {
  1121. seed ^= nextInt64() ^ seedValue;
  1122. }
  1123. void Random::setSeedRandomly()
  1124. {
  1125. combineSeed ((int64) (pointer_sized_int) this);
  1126. combineSeed (Time::getMillisecondCounter());
  1127. combineSeed (Time::getHighResolutionTicks());
  1128. combineSeed (Time::getHighResolutionTicksPerSecond());
  1129. combineSeed (Time::currentTimeMillis());
  1130. }
  1131. int Random::nextInt() throw()
  1132. {
  1133. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1134. return (int) (seed >> 16);
  1135. }
  1136. int Random::nextInt (const int maxValue) throw()
  1137. {
  1138. jassert (maxValue > 0);
  1139. return (nextInt() & 0x7fffffff) % maxValue;
  1140. }
  1141. int64 Random::nextInt64() throw()
  1142. {
  1143. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1144. }
  1145. bool Random::nextBool() throw()
  1146. {
  1147. return (nextInt() & 0x80000000) != 0;
  1148. }
  1149. float Random::nextFloat() throw()
  1150. {
  1151. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1152. }
  1153. double Random::nextDouble() throw()
  1154. {
  1155. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1156. }
  1157. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1158. {
  1159. BigInteger n;
  1160. do
  1161. {
  1162. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1163. }
  1164. while (n >= maximumValue);
  1165. return n;
  1166. }
  1167. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1168. {
  1169. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1170. while ((startBit & 31) != 0 && numBits > 0)
  1171. {
  1172. arrayToChange.setBit (startBit++, nextBool());
  1173. --numBits;
  1174. }
  1175. while (numBits >= 32)
  1176. {
  1177. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1178. startBit += 32;
  1179. numBits -= 32;
  1180. }
  1181. while (--numBits >= 0)
  1182. arrayToChange.setBit (startBit + numBits, nextBool());
  1183. }
  1184. Random& Random::getSystemRandom() throw()
  1185. {
  1186. static Random sysRand (1);
  1187. return sysRand;
  1188. }
  1189. END_JUCE_NAMESPACE
  1190. /*** End of inlined file: juce_Random.cpp ***/
  1191. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1192. BEGIN_JUCE_NAMESPACE
  1193. RelativeTime::RelativeTime (const double seconds_) throw()
  1194. : seconds (seconds_)
  1195. {
  1196. }
  1197. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1198. : seconds (other.seconds)
  1199. {
  1200. }
  1201. RelativeTime::~RelativeTime() throw()
  1202. {
  1203. }
  1204. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1205. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1206. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1207. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1208. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1209. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1210. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1211. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1212. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1213. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1214. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1215. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1216. {
  1217. if (seconds < 0.001 && seconds > -0.001)
  1218. return returnValueForZeroTime;
  1219. String result;
  1220. result.preallocateStorage (16);
  1221. if (seconds < 0)
  1222. result << '-';
  1223. int fieldsShown = 0;
  1224. int n = std::abs ((int) inWeeks());
  1225. if (n > 0)
  1226. {
  1227. result << n << (n == 1 ? TRANS(" week ")
  1228. : TRANS(" weeks "));
  1229. ++fieldsShown;
  1230. }
  1231. n = std::abs ((int) inDays()) % 7;
  1232. if (n > 0)
  1233. {
  1234. result << n << (n == 1 ? TRANS(" day ")
  1235. : TRANS(" days "));
  1236. ++fieldsShown;
  1237. }
  1238. if (fieldsShown < 2)
  1239. {
  1240. n = std::abs ((int) inHours()) % 24;
  1241. if (n > 0)
  1242. {
  1243. result << n << (n == 1 ? TRANS(" hr ")
  1244. : TRANS(" hrs "));
  1245. ++fieldsShown;
  1246. }
  1247. if (fieldsShown < 2)
  1248. {
  1249. n = std::abs ((int) inMinutes()) % 60;
  1250. if (n > 0)
  1251. {
  1252. result << n << (n == 1 ? TRANS(" min ")
  1253. : TRANS(" mins "));
  1254. ++fieldsShown;
  1255. }
  1256. if (fieldsShown < 2)
  1257. {
  1258. n = std::abs ((int) inSeconds()) % 60;
  1259. if (n > 0)
  1260. {
  1261. result << n << (n == 1 ? TRANS(" sec ")
  1262. : TRANS(" secs "));
  1263. ++fieldsShown;
  1264. }
  1265. if (fieldsShown == 0)
  1266. {
  1267. n = std::abs ((int) inMilliseconds()) % 1000;
  1268. if (n > 0)
  1269. result << n << TRANS(" ms");
  1270. }
  1271. }
  1272. }
  1273. }
  1274. return result.trimEnd();
  1275. }
  1276. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1277. {
  1278. seconds = other.seconds;
  1279. return *this;
  1280. }
  1281. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1282. {
  1283. seconds += timeToAdd.seconds;
  1284. return *this;
  1285. }
  1286. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1287. {
  1288. seconds -= timeToSubtract.seconds;
  1289. return *this;
  1290. }
  1291. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1292. {
  1293. seconds += secondsToAdd;
  1294. return *this;
  1295. }
  1296. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1297. {
  1298. seconds -= secondsToSubtract;
  1299. return *this;
  1300. }
  1301. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1302. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  1303. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() > t2.inSeconds(); }
  1304. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() < t2.inSeconds(); }
  1305. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() >= t2.inSeconds(); }
  1306. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1307. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1308. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1309. END_JUCE_NAMESPACE
  1310. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1311. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1312. BEGIN_JUCE_NAMESPACE
  1313. SystemStats::CPUFlags SystemStats::cpuFlags;
  1314. const String SystemStats::getJUCEVersion()
  1315. {
  1316. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1317. + "." + String (JUCE_MINOR_VERSION)
  1318. + "." + String (JUCE_BUILDNUMBER);
  1319. }
  1320. #ifdef JUCE_DLL
  1321. void* juce_Malloc (int size) { return malloc (size); }
  1322. void* juce_Calloc (int size) { return calloc (1, size); }
  1323. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1324. void juce_Free (void* block) { free (block); }
  1325. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1326. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1327. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1328. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1329. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1330. #endif
  1331. #endif
  1332. END_JUCE_NAMESPACE
  1333. /*** End of inlined file: juce_SystemStats.cpp ***/
  1334. /*** Start of inlined file: juce_Time.cpp ***/
  1335. #if JUCE_MSVC
  1336. #pragma warning (push)
  1337. #pragma warning (disable: 4514)
  1338. #endif
  1339. #ifndef JUCE_WINDOWS
  1340. #include <sys/time.h>
  1341. #else
  1342. #include <ctime>
  1343. #endif
  1344. #include <sys/timeb.h>
  1345. #if JUCE_MSVC
  1346. #pragma warning (pop)
  1347. #ifdef _INC_TIME_INL
  1348. #define USE_NEW_SECURE_TIME_FNS
  1349. #endif
  1350. #endif
  1351. BEGIN_JUCE_NAMESPACE
  1352. namespace TimeHelpers
  1353. {
  1354. static struct tm millisToLocal (const int64 millis) throw()
  1355. {
  1356. struct tm result;
  1357. const int64 seconds = millis / 1000;
  1358. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1359. {
  1360. // use extended maths for dates beyond 1970 to 2037..
  1361. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1362. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1363. const int days = (int) (jdm / literal64bit (86400));
  1364. const int a = 32044 + days;
  1365. const int b = (4 * a + 3) / 146097;
  1366. const int c = a - (b * 146097) / 4;
  1367. const int d = (4 * c + 3) / 1461;
  1368. const int e = c - (d * 1461) / 4;
  1369. const int m = (5 * e + 2) / 153;
  1370. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1371. result.tm_mon = m + 2 - 12 * (m / 10);
  1372. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1373. result.tm_wday = (days + 1) % 7;
  1374. result.tm_yday = -1;
  1375. int t = (int) (jdm % literal64bit (86400));
  1376. result.tm_hour = t / 3600;
  1377. t %= 3600;
  1378. result.tm_min = t / 60;
  1379. result.tm_sec = t % 60;
  1380. result.tm_isdst = -1;
  1381. }
  1382. else
  1383. {
  1384. time_t now = static_cast <time_t> (seconds);
  1385. #if JUCE_WINDOWS
  1386. #ifdef USE_NEW_SECURE_TIME_FNS
  1387. if (now >= 0 && now <= 0x793406fff)
  1388. localtime_s (&result, &now);
  1389. else
  1390. zeromem (&result, sizeof (result));
  1391. #else
  1392. result = *localtime (&now);
  1393. #endif
  1394. #else
  1395. // more thread-safe
  1396. localtime_r (&now, &result);
  1397. #endif
  1398. }
  1399. return result;
  1400. }
  1401. static int extendedModulo (const int64 value, const int modulo) throw()
  1402. {
  1403. return (int) (value >= 0 ? (value % modulo)
  1404. : (value - ((value / modulo) + 1) * modulo));
  1405. }
  1406. static uint32 lastMSCounterValue = 0;
  1407. }
  1408. Time::Time() throw()
  1409. : millisSinceEpoch (0)
  1410. {
  1411. }
  1412. Time::Time (const Time& other) throw()
  1413. : millisSinceEpoch (other.millisSinceEpoch)
  1414. {
  1415. }
  1416. Time::Time (const int64 ms) throw()
  1417. : millisSinceEpoch (ms)
  1418. {
  1419. }
  1420. Time::Time (const int year,
  1421. const int month,
  1422. const int day,
  1423. const int hours,
  1424. const int minutes,
  1425. const int seconds,
  1426. const int milliseconds,
  1427. const bool useLocalTime) throw()
  1428. {
  1429. jassert (year > 100); // year must be a 4-digit version
  1430. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1431. {
  1432. // use extended maths for dates beyond 1970 to 2037..
  1433. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1434. : 0;
  1435. const int a = (13 - month) / 12;
  1436. const int y = year + 4800 - a;
  1437. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1438. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1439. - 32045;
  1440. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1441. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1442. + milliseconds;
  1443. }
  1444. else
  1445. {
  1446. struct tm t;
  1447. t.tm_year = year - 1900;
  1448. t.tm_mon = month;
  1449. t.tm_mday = day;
  1450. t.tm_hour = hours;
  1451. t.tm_min = minutes;
  1452. t.tm_sec = seconds;
  1453. t.tm_isdst = -1;
  1454. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1455. if (millisSinceEpoch < 0)
  1456. millisSinceEpoch = 0;
  1457. else
  1458. millisSinceEpoch += milliseconds;
  1459. }
  1460. }
  1461. Time::~Time() throw()
  1462. {
  1463. }
  1464. Time& Time::operator= (const Time& other) throw()
  1465. {
  1466. millisSinceEpoch = other.millisSinceEpoch;
  1467. return *this;
  1468. }
  1469. int64 Time::currentTimeMillis() throw()
  1470. {
  1471. static uint32 lastCounterResult = 0xffffffff;
  1472. static int64 correction = 0;
  1473. const uint32 now = getMillisecondCounter();
  1474. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1475. if (now < lastCounterResult)
  1476. {
  1477. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1478. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1479. {
  1480. // get the time once using normal library calls, and store the difference needed to
  1481. // turn the millisecond counter into a real time.
  1482. #if JUCE_WINDOWS
  1483. struct _timeb t;
  1484. #ifdef USE_NEW_SECURE_TIME_FNS
  1485. _ftime_s (&t);
  1486. #else
  1487. _ftime (&t);
  1488. #endif
  1489. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1490. #else
  1491. struct timeval tv;
  1492. struct timezone tz;
  1493. gettimeofday (&tv, &tz);
  1494. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1495. #endif
  1496. }
  1497. }
  1498. lastCounterResult = now;
  1499. return correction + now;
  1500. }
  1501. uint32 juce_millisecondsSinceStartup() throw();
  1502. uint32 Time::getMillisecondCounter() throw()
  1503. {
  1504. const uint32 now = juce_millisecondsSinceStartup();
  1505. if (now < TimeHelpers::lastMSCounterValue)
  1506. {
  1507. // in multi-threaded apps this might be called concurrently, so
  1508. // make sure that our last counter value only increases and doesn't
  1509. // go backwards..
  1510. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1511. TimeHelpers::lastMSCounterValue = now;
  1512. }
  1513. else
  1514. {
  1515. TimeHelpers::lastMSCounterValue = now;
  1516. }
  1517. return now;
  1518. }
  1519. uint32 Time::getApproximateMillisecondCounter() throw()
  1520. {
  1521. jassert (TimeHelpers::lastMSCounterValue != 0);
  1522. return TimeHelpers::lastMSCounterValue;
  1523. }
  1524. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1525. {
  1526. for (;;)
  1527. {
  1528. const uint32 now = getMillisecondCounter();
  1529. if (now >= targetTime)
  1530. break;
  1531. const int toWait = targetTime - now;
  1532. if (toWait > 2)
  1533. {
  1534. Thread::sleep (jmin (20, toWait >> 1));
  1535. }
  1536. else
  1537. {
  1538. // xxx should consider using mutex_pause on the mac as it apparently
  1539. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1540. for (int i = 10; --i >= 0;)
  1541. Thread::yield();
  1542. }
  1543. }
  1544. }
  1545. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1546. {
  1547. return ticks / (double) getHighResolutionTicksPerSecond();
  1548. }
  1549. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1550. {
  1551. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1552. }
  1553. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1554. {
  1555. return Time (currentTimeMillis());
  1556. }
  1557. const String Time::toString (const bool includeDate,
  1558. const bool includeTime,
  1559. const bool includeSeconds,
  1560. const bool use24HourClock) const throw()
  1561. {
  1562. String result;
  1563. if (includeDate)
  1564. {
  1565. result << getDayOfMonth() << ' '
  1566. << getMonthName (true) << ' '
  1567. << getYear();
  1568. if (includeTime)
  1569. result << ' ';
  1570. }
  1571. if (includeTime)
  1572. {
  1573. const int mins = getMinutes();
  1574. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1575. << (mins < 10 ? ":0" : ":") << mins;
  1576. if (includeSeconds)
  1577. {
  1578. const int secs = getSeconds();
  1579. result << (secs < 10 ? ":0" : ":") << secs;
  1580. }
  1581. if (! use24HourClock)
  1582. result << (isAfternoon() ? "pm" : "am");
  1583. }
  1584. return result.trimEnd();
  1585. }
  1586. const String Time::formatted (const String& format) const
  1587. {
  1588. String buffer;
  1589. int bufferSize = 128;
  1590. buffer.preallocateStorage (bufferSize);
  1591. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1592. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1593. {
  1594. bufferSize += 128;
  1595. buffer.preallocateStorage (bufferSize);
  1596. }
  1597. return buffer;
  1598. }
  1599. int Time::getYear() const throw()
  1600. {
  1601. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1602. }
  1603. int Time::getMonth() const throw()
  1604. {
  1605. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1606. }
  1607. int Time::getDayOfMonth() const throw()
  1608. {
  1609. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1610. }
  1611. int Time::getDayOfWeek() const throw()
  1612. {
  1613. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1614. }
  1615. int Time::getHours() const throw()
  1616. {
  1617. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1618. }
  1619. int Time::getHoursInAmPmFormat() const throw()
  1620. {
  1621. const int hours = getHours();
  1622. if (hours == 0)
  1623. return 12;
  1624. else if (hours <= 12)
  1625. return hours;
  1626. else
  1627. return hours - 12;
  1628. }
  1629. bool Time::isAfternoon() const throw()
  1630. {
  1631. return getHours() >= 12;
  1632. }
  1633. int Time::getMinutes() const throw()
  1634. {
  1635. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1636. }
  1637. int Time::getSeconds() const throw()
  1638. {
  1639. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1640. }
  1641. int Time::getMilliseconds() const throw()
  1642. {
  1643. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1644. }
  1645. bool Time::isDaylightSavingTime() const throw()
  1646. {
  1647. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1648. }
  1649. const String Time::getTimeZone() const throw()
  1650. {
  1651. String zone[2];
  1652. #if JUCE_WINDOWS
  1653. _tzset();
  1654. #ifdef USE_NEW_SECURE_TIME_FNS
  1655. {
  1656. char name [128];
  1657. size_t length;
  1658. for (int i = 0; i < 2; ++i)
  1659. {
  1660. zeromem (name, sizeof (name));
  1661. _get_tzname (&length, name, 127, i);
  1662. zone[i] = name;
  1663. }
  1664. }
  1665. #else
  1666. const char** const zonePtr = (const char**) _tzname;
  1667. zone[0] = zonePtr[0];
  1668. zone[1] = zonePtr[1];
  1669. #endif
  1670. #else
  1671. tzset();
  1672. const char** const zonePtr = (const char**) tzname;
  1673. zone[0] = zonePtr[0];
  1674. zone[1] = zonePtr[1];
  1675. #endif
  1676. if (isDaylightSavingTime())
  1677. {
  1678. zone[0] = zone[1];
  1679. if (zone[0].length() > 3
  1680. && zone[0].containsIgnoreCase ("daylight")
  1681. && zone[0].contains ("GMT"))
  1682. zone[0] = "BST";
  1683. }
  1684. return zone[0].substring (0, 3);
  1685. }
  1686. const String Time::getMonthName (const bool threeLetterVersion) const
  1687. {
  1688. return getMonthName (getMonth(), threeLetterVersion);
  1689. }
  1690. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1691. {
  1692. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1693. }
  1694. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1695. {
  1696. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1697. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1698. monthNumber %= 12;
  1699. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1700. : longMonthNames [monthNumber]);
  1701. }
  1702. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1703. {
  1704. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1705. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1706. day %= 7;
  1707. return TRANS (threeLetterVersion ? shortDayNames [day]
  1708. : longDayNames [day]);
  1709. }
  1710. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1711. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1712. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1713. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1714. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1715. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1716. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1717. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  1718. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  1719. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  1720. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  1721. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1722. END_JUCE_NAMESPACE
  1723. /*** End of inlined file: juce_Time.cpp ***/
  1724. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1725. BEGIN_JUCE_NAMESPACE
  1726. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1727. #endif
  1728. #if JUCE_WINDOWS
  1729. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1730. #endif
  1731. #if JUCE_DEBUG
  1732. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1733. #endif
  1734. static bool juceInitialisedNonGUI = false;
  1735. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1736. {
  1737. if (! juceInitialisedNonGUI)
  1738. {
  1739. juceInitialisedNonGUI = true;
  1740. JUCE_AUTORELEASEPOOL
  1741. DBG (SystemStats::getJUCEVersion());
  1742. SystemStats::initialiseStats();
  1743. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1744. }
  1745. // Some basic tests, to keep an eye on things and make sure these types work ok
  1746. // on all platforms. Let me know if any of these assertions fail on your system!
  1747. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1748. static_jassert (sizeof (int8) == 1);
  1749. static_jassert (sizeof (uint8) == 1);
  1750. static_jassert (sizeof (int16) == 2);
  1751. static_jassert (sizeof (uint16) == 2);
  1752. static_jassert (sizeof (int32) == 4);
  1753. static_jassert (sizeof (uint32) == 4);
  1754. static_jassert (sizeof (int64) == 8);
  1755. static_jassert (sizeof (uint64) == 8);
  1756. }
  1757. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1758. {
  1759. if (juceInitialisedNonGUI)
  1760. {
  1761. juceInitialisedNonGUI = false;
  1762. JUCE_AUTORELEASEPOOL
  1763. LocalisedStrings::setCurrentMappings (0);
  1764. Thread::stopAllThreads (3000);
  1765. #if JUCE_WINDOWS
  1766. juce_shutdownWin32Sockets();
  1767. #endif
  1768. #if JUCE_DEBUG
  1769. juce_CheckForDanglingStreams();
  1770. #endif
  1771. }
  1772. }
  1773. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1774. static bool juceInitialisedGUI = false;
  1775. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1776. {
  1777. if (! juceInitialisedGUI)
  1778. {
  1779. juceInitialisedGUI = true;
  1780. JUCE_AUTORELEASEPOOL
  1781. initialiseJuce_NonGUI();
  1782. MessageManager::getInstance();
  1783. LookAndFeel::setDefaultLookAndFeel (0);
  1784. #if JUCE_DEBUG
  1785. try // This section is just a safety-net for catching builds without RTTI enabled..
  1786. {
  1787. MemoryOutputStream mo;
  1788. OutputStream* o = &mo;
  1789. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1790. o = dynamic_cast <MemoryOutputStream*> (o);
  1791. jassert (o != 0);
  1792. }
  1793. catch (...)
  1794. {
  1795. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1796. jassertfalse;
  1797. }
  1798. #endif
  1799. }
  1800. }
  1801. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1802. {
  1803. if (juceInitialisedGUI)
  1804. {
  1805. juceInitialisedGUI = false;
  1806. JUCE_AUTORELEASEPOOL
  1807. DeletedAtShutdown::deleteAll();
  1808. LookAndFeel::clearDefaultLookAndFeel();
  1809. delete MessageManager::getInstance();
  1810. shutdownJuce_NonGUI();
  1811. }
  1812. }
  1813. #endif
  1814. #if JUCE_UNIT_TESTS
  1815. class AtomicTests : public UnitTest
  1816. {
  1817. public:
  1818. AtomicTests() : UnitTest ("Atomics") {}
  1819. void runTest()
  1820. {
  1821. beginTest ("Misc");
  1822. char a1[7];
  1823. expect (numElementsInArray(a1) == 7);
  1824. int a2[3];
  1825. expect (numElementsInArray(a2) == 3);
  1826. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1827. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1828. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1829. beginTest ("Atomic types");
  1830. AtomicTester <int>::testInteger (*this);
  1831. AtomicTester <unsigned int>::testInteger (*this);
  1832. AtomicTester <int32>::testInteger (*this);
  1833. AtomicTester <uint32>::testInteger (*this);
  1834. AtomicTester <long>::testInteger (*this);
  1835. AtomicTester <void*>::testInteger (*this);
  1836. AtomicTester <int*>::testInteger (*this);
  1837. AtomicTester <float>::testFloat (*this);
  1838. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1839. AtomicTester <int64>::testInteger (*this);
  1840. AtomicTester <uint64>::testInteger (*this);
  1841. AtomicTester <double>::testFloat (*this);
  1842. #endif
  1843. }
  1844. template <typename Type>
  1845. class AtomicTester
  1846. {
  1847. public:
  1848. AtomicTester() {}
  1849. static void testInteger (UnitTest& test)
  1850. {
  1851. Atomic<Type> a, b;
  1852. a.set ((Type) 10);
  1853. a += (Type) 15;
  1854. a.memoryBarrier();
  1855. a -= (Type) 5;
  1856. ++a; ++a; --a;
  1857. a.memoryBarrier();
  1858. testFloat (test);
  1859. }
  1860. static void testFloat (UnitTest& test)
  1861. {
  1862. Atomic<Type> a, b;
  1863. a = (Type) 21;
  1864. a.memoryBarrier();
  1865. /* These are some simple test cases to check the atomics - let me know
  1866. if any of these assertions fail on your system!
  1867. */
  1868. test.expect (a.get() == (Type) 21);
  1869. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1870. test.expect (a.get() == (Type) 21);
  1871. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1872. test.expect (a.get() == (Type) 101);
  1873. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1874. test.expect (a.get() == (Type) 101);
  1875. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1876. test.expect (a.get() == (Type) 200);
  1877. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1878. test.expect (a.get() == (Type) 300);
  1879. b = a;
  1880. test.expect (b.get() == a.get());
  1881. }
  1882. };
  1883. };
  1884. static AtomicTests atomicUnitTests;
  1885. #endif
  1886. END_JUCE_NAMESPACE
  1887. /*** End of inlined file: juce_Initialisation.cpp ***/
  1888. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1889. BEGIN_JUCE_NAMESPACE
  1890. AbstractFifo::AbstractFifo (const int capacity) throw()
  1891. : bufferSize (capacity)
  1892. {
  1893. jassert (bufferSize > 0);
  1894. }
  1895. AbstractFifo::~AbstractFifo() {}
  1896. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1897. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1898. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1899. void AbstractFifo::reset() throw()
  1900. {
  1901. validEnd = 0;
  1902. validStart = 0;
  1903. }
  1904. void AbstractFifo::setTotalSize (int newSize) throw()
  1905. {
  1906. jassert (newSize > 0);
  1907. reset();
  1908. bufferSize = newSize;
  1909. }
  1910. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1911. {
  1912. const int vs = validStart.get();
  1913. const int ve = validEnd.get();
  1914. const int freeSpace = bufferSize - (ve - vs);
  1915. numToWrite = jmin (numToWrite, freeSpace);
  1916. if (numToWrite <= 0)
  1917. {
  1918. startIndex1 = 0;
  1919. startIndex2 = 0;
  1920. blockSize1 = 0;
  1921. blockSize2 = 0;
  1922. }
  1923. else
  1924. {
  1925. startIndex1 = (int) (ve % bufferSize);
  1926. startIndex2 = 0;
  1927. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1928. numToWrite -= blockSize1;
  1929. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  1930. }
  1931. }
  1932. void AbstractFifo::finishedWrite (int numWritten) throw()
  1933. {
  1934. jassert (numWritten >= 0 && numWritten < bufferSize);
  1935. validEnd += numWritten;
  1936. }
  1937. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1938. {
  1939. const int vs = validStart.get();
  1940. const int ve = validEnd.get();
  1941. const int numReady = ve - vs;
  1942. numWanted = jmin (numWanted, numReady);
  1943. if (numWanted <= 0)
  1944. {
  1945. startIndex1 = 0;
  1946. startIndex2 = 0;
  1947. blockSize1 = 0;
  1948. blockSize2 = 0;
  1949. }
  1950. else
  1951. {
  1952. startIndex1 = (int) (vs % bufferSize);
  1953. startIndex2 = 0;
  1954. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  1955. numWanted -= blockSize1;
  1956. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  1957. }
  1958. }
  1959. void AbstractFifo::finishedRead (int numRead) throw()
  1960. {
  1961. jassert (numRead >= 0 && numRead < bufferSize);
  1962. validStart += numRead;
  1963. }
  1964. END_JUCE_NAMESPACE
  1965. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  1966. /*** Start of inlined file: juce_BigInteger.cpp ***/
  1967. BEGIN_JUCE_NAMESPACE
  1968. BigInteger::BigInteger()
  1969. : numValues (4),
  1970. highestBit (-1),
  1971. negative (false)
  1972. {
  1973. values.calloc (numValues + 1);
  1974. }
  1975. BigInteger::BigInteger (const int32 value)
  1976. : numValues (4),
  1977. highestBit (31),
  1978. negative (value < 0)
  1979. {
  1980. values.calloc (numValues + 1);
  1981. values[0] = abs (value);
  1982. highestBit = getHighestBit();
  1983. }
  1984. BigInteger::BigInteger (const uint32 value)
  1985. : numValues (4),
  1986. highestBit (31),
  1987. negative (false)
  1988. {
  1989. values.calloc (numValues + 1);
  1990. values[0] = value;
  1991. highestBit = getHighestBit();
  1992. }
  1993. BigInteger::BigInteger (int64 value)
  1994. : numValues (4),
  1995. highestBit (63),
  1996. negative (value < 0)
  1997. {
  1998. values.calloc (numValues + 1);
  1999. if (value < 0)
  2000. value = -value;
  2001. values[0] = (uint32) value;
  2002. values[1] = (uint32) (value >> 32);
  2003. highestBit = getHighestBit();
  2004. }
  2005. BigInteger::BigInteger (const BigInteger& other)
  2006. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2007. highestBit (other.getHighestBit()),
  2008. negative (other.negative)
  2009. {
  2010. values.malloc (numValues + 1);
  2011. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2012. }
  2013. BigInteger::~BigInteger()
  2014. {
  2015. }
  2016. void BigInteger::swapWith (BigInteger& other) throw()
  2017. {
  2018. values.swapWith (other.values);
  2019. swapVariables (numValues, other.numValues);
  2020. swapVariables (highestBit, other.highestBit);
  2021. swapVariables (negative, other.negative);
  2022. }
  2023. BigInteger& BigInteger::operator= (const BigInteger& other)
  2024. {
  2025. if (this != &other)
  2026. {
  2027. highestBit = other.getHighestBit();
  2028. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2029. negative = other.negative;
  2030. values.malloc (numValues + 1);
  2031. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2032. }
  2033. return *this;
  2034. }
  2035. void BigInteger::ensureSize (const int numVals)
  2036. {
  2037. if (numVals + 2 >= numValues)
  2038. {
  2039. int oldSize = numValues;
  2040. numValues = ((numVals + 2) * 3) / 2;
  2041. values.realloc (numValues + 1);
  2042. while (oldSize < numValues)
  2043. values [oldSize++] = 0;
  2044. }
  2045. }
  2046. bool BigInteger::operator[] (const int bit) const throw()
  2047. {
  2048. return bit <= highestBit && bit >= 0
  2049. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2050. }
  2051. int BigInteger::toInteger() const throw()
  2052. {
  2053. const int n = (int) (values[0] & 0x7fffffff);
  2054. return negative ? -n : n;
  2055. }
  2056. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2057. {
  2058. BigInteger r;
  2059. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2060. r.ensureSize (bitToIndex (numBits));
  2061. r.highestBit = numBits;
  2062. int i = 0;
  2063. while (numBits > 0)
  2064. {
  2065. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2066. numBits -= 32;
  2067. startBit += 32;
  2068. }
  2069. r.highestBit = r.getHighestBit();
  2070. return r;
  2071. }
  2072. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2073. {
  2074. if (numBits > 32)
  2075. {
  2076. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2077. numBits = 32;
  2078. }
  2079. numBits = jmin (numBits, highestBit + 1 - startBit);
  2080. if (numBits <= 0)
  2081. return 0;
  2082. const int pos = bitToIndex (startBit);
  2083. const int offset = startBit & 31;
  2084. const int endSpace = 32 - numBits;
  2085. uint32 n = ((uint32) values [pos]) >> offset;
  2086. if (offset > endSpace)
  2087. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2088. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2089. }
  2090. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2091. {
  2092. if (numBits > 32)
  2093. {
  2094. jassertfalse;
  2095. numBits = 32;
  2096. }
  2097. for (int i = 0; i < numBits; ++i)
  2098. {
  2099. setBit (startBit + i, (valueToSet & 1) != 0);
  2100. valueToSet >>= 1;
  2101. }
  2102. }
  2103. void BigInteger::clear()
  2104. {
  2105. if (numValues > 16)
  2106. {
  2107. numValues = 4;
  2108. values.calloc (numValues + 1);
  2109. }
  2110. else
  2111. {
  2112. zeromem (values, sizeof (uint32) * (numValues + 1));
  2113. }
  2114. highestBit = -1;
  2115. negative = false;
  2116. }
  2117. void BigInteger::setBit (const int bit)
  2118. {
  2119. if (bit >= 0)
  2120. {
  2121. if (bit > highestBit)
  2122. {
  2123. ensureSize (bitToIndex (bit));
  2124. highestBit = bit;
  2125. }
  2126. values [bitToIndex (bit)] |= bitToMask (bit);
  2127. }
  2128. }
  2129. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2130. {
  2131. if (shouldBeSet)
  2132. setBit (bit);
  2133. else
  2134. clearBit (bit);
  2135. }
  2136. void BigInteger::clearBit (const int bit) throw()
  2137. {
  2138. if (bit >= 0 && bit <= highestBit)
  2139. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2140. }
  2141. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2142. {
  2143. while (--numBits >= 0)
  2144. setBit (startBit++, shouldBeSet);
  2145. }
  2146. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2147. {
  2148. if (bit >= 0)
  2149. shiftBits (1, bit);
  2150. setBit (bit, shouldBeSet);
  2151. }
  2152. bool BigInteger::isZero() const throw()
  2153. {
  2154. return getHighestBit() < 0;
  2155. }
  2156. bool BigInteger::isOne() const throw()
  2157. {
  2158. return getHighestBit() == 0 && ! negative;
  2159. }
  2160. bool BigInteger::isNegative() const throw()
  2161. {
  2162. return negative && ! isZero();
  2163. }
  2164. void BigInteger::setNegative (const bool neg) throw()
  2165. {
  2166. negative = neg;
  2167. }
  2168. void BigInteger::negate() throw()
  2169. {
  2170. negative = (! negative) && ! isZero();
  2171. }
  2172. #if JUCE_USE_INTRINSICS
  2173. #pragma intrinsic (_BitScanReverse)
  2174. #endif
  2175. namespace BitFunctions
  2176. {
  2177. inline int countBitsInInt32 (uint32 n) throw()
  2178. {
  2179. n -= ((n >> 1) & 0x55555555);
  2180. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2181. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2182. n += (n >> 8);
  2183. n += (n >> 16);
  2184. return n & 0x3f;
  2185. }
  2186. inline int highestBitInInt (uint32 n) throw()
  2187. {
  2188. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2189. #if JUCE_GCC
  2190. return 31 - __builtin_clz (n);
  2191. #elif JUCE_USE_INTRINSICS
  2192. unsigned long highest;
  2193. _BitScanReverse (&highest, n);
  2194. return (int) highest;
  2195. #else
  2196. n |= (n >> 1);
  2197. n |= (n >> 2);
  2198. n |= (n >> 4);
  2199. n |= (n >> 8);
  2200. n |= (n >> 16);
  2201. return countBitsInInt32 (n >> 1);
  2202. #endif
  2203. }
  2204. }
  2205. int BigInteger::countNumberOfSetBits() const throw()
  2206. {
  2207. int total = 0;
  2208. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2209. total += BitFunctions::countBitsInInt32 (values[i]);
  2210. return total;
  2211. }
  2212. int BigInteger::getHighestBit() const throw()
  2213. {
  2214. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2215. {
  2216. const uint32 n = values[i];
  2217. if (n != 0)
  2218. return BitFunctions::highestBitInInt (n) + (i << 5);
  2219. }
  2220. return -1;
  2221. }
  2222. int BigInteger::findNextSetBit (int i) const throw()
  2223. {
  2224. for (; i <= highestBit; ++i)
  2225. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2226. return i;
  2227. return -1;
  2228. }
  2229. int BigInteger::findNextClearBit (int i) const throw()
  2230. {
  2231. for (; i <= highestBit; ++i)
  2232. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2233. break;
  2234. return i;
  2235. }
  2236. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2237. {
  2238. if (other.isNegative())
  2239. return operator-= (-other);
  2240. if (isNegative())
  2241. {
  2242. if (compareAbsolute (other) < 0)
  2243. {
  2244. BigInteger temp (*this);
  2245. temp.negate();
  2246. *this = other;
  2247. operator-= (temp);
  2248. }
  2249. else
  2250. {
  2251. negate();
  2252. operator-= (other);
  2253. negate();
  2254. }
  2255. }
  2256. else
  2257. {
  2258. if (other.highestBit > highestBit)
  2259. highestBit = other.highestBit;
  2260. ++highestBit;
  2261. const int numInts = bitToIndex (highestBit) + 1;
  2262. ensureSize (numInts);
  2263. int64 remainder = 0;
  2264. for (int i = 0; i <= numInts; ++i)
  2265. {
  2266. if (i < numValues)
  2267. remainder += values[i];
  2268. if (i < other.numValues)
  2269. remainder += other.values[i];
  2270. values[i] = (uint32) remainder;
  2271. remainder >>= 32;
  2272. }
  2273. jassert (remainder == 0);
  2274. highestBit = getHighestBit();
  2275. }
  2276. return *this;
  2277. }
  2278. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2279. {
  2280. if (other.isNegative())
  2281. return operator+= (-other);
  2282. if (! isNegative())
  2283. {
  2284. if (compareAbsolute (other) < 0)
  2285. {
  2286. BigInteger temp (other);
  2287. swapWith (temp);
  2288. operator-= (temp);
  2289. negate();
  2290. return *this;
  2291. }
  2292. }
  2293. else
  2294. {
  2295. negate();
  2296. operator+= (other);
  2297. negate();
  2298. return *this;
  2299. }
  2300. const int numInts = bitToIndex (highestBit) + 1;
  2301. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2302. int64 amountToSubtract = 0;
  2303. for (int i = 0; i <= numInts; ++i)
  2304. {
  2305. if (i <= maxOtherInts)
  2306. amountToSubtract += (int64) other.values[i];
  2307. if (values[i] >= amountToSubtract)
  2308. {
  2309. values[i] = (uint32) (values[i] - amountToSubtract);
  2310. amountToSubtract = 0;
  2311. }
  2312. else
  2313. {
  2314. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2315. values[i] = (uint32) n;
  2316. amountToSubtract = 1;
  2317. }
  2318. }
  2319. return *this;
  2320. }
  2321. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2322. {
  2323. BigInteger total;
  2324. highestBit = getHighestBit();
  2325. const bool wasNegative = isNegative();
  2326. setNegative (false);
  2327. for (int i = 0; i <= highestBit; ++i)
  2328. {
  2329. if (operator[](i))
  2330. {
  2331. BigInteger n (other);
  2332. n.setNegative (false);
  2333. n <<= i;
  2334. total += n;
  2335. }
  2336. }
  2337. total.setNegative (wasNegative ^ other.isNegative());
  2338. swapWith (total);
  2339. return *this;
  2340. }
  2341. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2342. {
  2343. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2344. const int divHB = divisor.getHighestBit();
  2345. const int ourHB = getHighestBit();
  2346. if (divHB < 0 || ourHB < 0)
  2347. {
  2348. // division by zero
  2349. remainder.clear();
  2350. clear();
  2351. }
  2352. else
  2353. {
  2354. const bool wasNegative = isNegative();
  2355. swapWith (remainder);
  2356. remainder.setNegative (false);
  2357. clear();
  2358. BigInteger temp (divisor);
  2359. temp.setNegative (false);
  2360. int leftShift = ourHB - divHB;
  2361. temp <<= leftShift;
  2362. while (leftShift >= 0)
  2363. {
  2364. if (remainder.compareAbsolute (temp) >= 0)
  2365. {
  2366. remainder -= temp;
  2367. setBit (leftShift);
  2368. }
  2369. if (--leftShift >= 0)
  2370. temp >>= 1;
  2371. }
  2372. negative = wasNegative ^ divisor.isNegative();
  2373. remainder.setNegative (wasNegative);
  2374. }
  2375. }
  2376. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2377. {
  2378. BigInteger remainder;
  2379. divideBy (other, remainder);
  2380. return *this;
  2381. }
  2382. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2383. {
  2384. // this operation doesn't take into account negative values..
  2385. jassert (isNegative() == other.isNegative());
  2386. if (other.highestBit >= 0)
  2387. {
  2388. ensureSize (bitToIndex (other.highestBit));
  2389. int n = bitToIndex (other.highestBit) + 1;
  2390. while (--n >= 0)
  2391. values[n] |= other.values[n];
  2392. if (other.highestBit > highestBit)
  2393. highestBit = other.highestBit;
  2394. highestBit = getHighestBit();
  2395. }
  2396. return *this;
  2397. }
  2398. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2399. {
  2400. // this operation doesn't take into account negative values..
  2401. jassert (isNegative() == other.isNegative());
  2402. int n = numValues;
  2403. while (n > other.numValues)
  2404. values[--n] = 0;
  2405. while (--n >= 0)
  2406. values[n] &= other.values[n];
  2407. if (other.highestBit < highestBit)
  2408. highestBit = other.highestBit;
  2409. highestBit = getHighestBit();
  2410. return *this;
  2411. }
  2412. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2413. {
  2414. // this operation will only work with the absolute values
  2415. jassert (isNegative() == other.isNegative());
  2416. if (other.highestBit >= 0)
  2417. {
  2418. ensureSize (bitToIndex (other.highestBit));
  2419. int n = bitToIndex (other.highestBit) + 1;
  2420. while (--n >= 0)
  2421. values[n] ^= other.values[n];
  2422. if (other.highestBit > highestBit)
  2423. highestBit = other.highestBit;
  2424. highestBit = getHighestBit();
  2425. }
  2426. return *this;
  2427. }
  2428. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2429. {
  2430. BigInteger remainder;
  2431. divideBy (divisor, remainder);
  2432. swapWith (remainder);
  2433. return *this;
  2434. }
  2435. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2436. {
  2437. shiftBits (numBitsToShift, 0);
  2438. return *this;
  2439. }
  2440. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2441. {
  2442. return operator<<= (-numBitsToShift);
  2443. }
  2444. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2445. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2446. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2447. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2448. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2449. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2450. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2451. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2452. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2453. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2454. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2455. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2456. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2457. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2458. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2459. int BigInteger::compare (const BigInteger& other) const throw()
  2460. {
  2461. if (isNegative() == other.isNegative())
  2462. {
  2463. const int absComp = compareAbsolute (other);
  2464. return isNegative() ? -absComp : absComp;
  2465. }
  2466. else
  2467. {
  2468. return isNegative() ? -1 : 1;
  2469. }
  2470. }
  2471. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2472. {
  2473. const int h1 = getHighestBit();
  2474. const int h2 = other.getHighestBit();
  2475. if (h1 > h2)
  2476. return 1;
  2477. else if (h1 < h2)
  2478. return -1;
  2479. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2480. if (values[i] != other.values[i])
  2481. return (values[i] > other.values[i]) ? 1 : -1;
  2482. return 0;
  2483. }
  2484. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2485. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2486. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2487. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2488. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2489. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2490. void BigInteger::shiftBits (int bits, const int startBit)
  2491. {
  2492. if (highestBit < 0)
  2493. return;
  2494. if (startBit > 0)
  2495. {
  2496. if (bits < 0)
  2497. {
  2498. // right shift
  2499. for (int i = startBit; i <= highestBit; ++i)
  2500. setBit (i, operator[] (i - bits));
  2501. highestBit = getHighestBit();
  2502. }
  2503. else if (bits > 0)
  2504. {
  2505. // left shift
  2506. for (int i = highestBit + 1; --i >= startBit;)
  2507. setBit (i + bits, operator[] (i));
  2508. while (--bits >= 0)
  2509. clearBit (bits + startBit);
  2510. }
  2511. }
  2512. else
  2513. {
  2514. if (bits < 0)
  2515. {
  2516. // right shift
  2517. bits = -bits;
  2518. if (bits > highestBit)
  2519. {
  2520. clear();
  2521. }
  2522. else
  2523. {
  2524. const int wordsToMove = bitToIndex (bits);
  2525. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2526. highestBit -= bits;
  2527. if (wordsToMove > 0)
  2528. {
  2529. int i;
  2530. for (i = 0; i < top; ++i)
  2531. values [i] = values [i + wordsToMove];
  2532. for (i = 0; i < wordsToMove; ++i)
  2533. values [top + i] = 0;
  2534. bits &= 31;
  2535. }
  2536. if (bits != 0)
  2537. {
  2538. const int invBits = 32 - bits;
  2539. --top;
  2540. for (int i = 0; i < top; ++i)
  2541. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2542. values[top] = (values[top] >> bits);
  2543. }
  2544. highestBit = getHighestBit();
  2545. }
  2546. }
  2547. else if (bits > 0)
  2548. {
  2549. // left shift
  2550. ensureSize (bitToIndex (highestBit + bits) + 1);
  2551. const int wordsToMove = bitToIndex (bits);
  2552. int top = 1 + bitToIndex (highestBit);
  2553. highestBit += bits;
  2554. if (wordsToMove > 0)
  2555. {
  2556. int i;
  2557. for (i = top; --i >= 0;)
  2558. values [i + wordsToMove] = values [i];
  2559. for (i = 0; i < wordsToMove; ++i)
  2560. values [i] = 0;
  2561. bits &= 31;
  2562. }
  2563. if (bits != 0)
  2564. {
  2565. const int invBits = 32 - bits;
  2566. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2567. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2568. values [wordsToMove] = values [wordsToMove] << bits;
  2569. }
  2570. highestBit = getHighestBit();
  2571. }
  2572. }
  2573. }
  2574. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2575. {
  2576. while (! m->isZero())
  2577. {
  2578. if (n->compareAbsolute (*m) > 0)
  2579. swapVariables (m, n);
  2580. *m -= *n;
  2581. }
  2582. return *n;
  2583. }
  2584. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2585. {
  2586. BigInteger m (*this);
  2587. while (! n.isZero())
  2588. {
  2589. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2590. return simpleGCD (&m, &n);
  2591. BigInteger temp1 (m), temp2;
  2592. temp1.divideBy (n, temp2);
  2593. m = n;
  2594. n = temp2;
  2595. }
  2596. return m;
  2597. }
  2598. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2599. {
  2600. BigInteger exp (exponent);
  2601. exp %= modulus;
  2602. BigInteger value (1);
  2603. swapWith (value);
  2604. value %= modulus;
  2605. while (! exp.isZero())
  2606. {
  2607. if (exp [0])
  2608. {
  2609. operator*= (value);
  2610. operator%= (modulus);
  2611. }
  2612. value *= value;
  2613. value %= modulus;
  2614. exp >>= 1;
  2615. }
  2616. }
  2617. void BigInteger::inverseModulo (const BigInteger& modulus)
  2618. {
  2619. if (modulus.isOne() || modulus.isNegative())
  2620. {
  2621. clear();
  2622. return;
  2623. }
  2624. if (isNegative() || compareAbsolute (modulus) >= 0)
  2625. operator%= (modulus);
  2626. if (isOne())
  2627. return;
  2628. if (! (*this)[0])
  2629. {
  2630. // not invertible
  2631. clear();
  2632. return;
  2633. }
  2634. BigInteger a1 (modulus);
  2635. BigInteger a2 (*this);
  2636. BigInteger b1 (modulus);
  2637. BigInteger b2 (1);
  2638. while (! a2.isOne())
  2639. {
  2640. BigInteger temp1, temp2, multiplier (a1);
  2641. multiplier.divideBy (a2, temp1);
  2642. temp1 = a2;
  2643. temp1 *= multiplier;
  2644. temp2 = a1;
  2645. temp2 -= temp1;
  2646. a1 = a2;
  2647. a2 = temp2;
  2648. temp1 = b2;
  2649. temp1 *= multiplier;
  2650. temp2 = b1;
  2651. temp2 -= temp1;
  2652. b1 = b2;
  2653. b2 = temp2;
  2654. }
  2655. while (b2.isNegative())
  2656. b2 += modulus;
  2657. b2 %= modulus;
  2658. swapWith (b2);
  2659. }
  2660. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2661. {
  2662. return stream << value.toString (10);
  2663. }
  2664. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2665. {
  2666. String s;
  2667. BigInteger v (*this);
  2668. if (base == 2 || base == 8 || base == 16)
  2669. {
  2670. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2671. static const char* const hexDigits = "0123456789abcdef";
  2672. for (;;)
  2673. {
  2674. const int remainder = v.getBitRangeAsInt (0, bits);
  2675. v >>= bits;
  2676. if (remainder == 0 && v.isZero())
  2677. break;
  2678. s = String::charToString (hexDigits [remainder]) + s;
  2679. }
  2680. }
  2681. else if (base == 10)
  2682. {
  2683. const BigInteger ten (10);
  2684. BigInteger remainder;
  2685. for (;;)
  2686. {
  2687. v.divideBy (ten, remainder);
  2688. if (remainder.isZero() && v.isZero())
  2689. break;
  2690. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2691. }
  2692. }
  2693. else
  2694. {
  2695. jassertfalse; // can't do the specified base!
  2696. return String::empty;
  2697. }
  2698. s = s.paddedLeft ('0', minimumNumCharacters);
  2699. return isNegative() ? "-" + s : s;
  2700. }
  2701. void BigInteger::parseString (const String& text, const int base)
  2702. {
  2703. clear();
  2704. const juce_wchar* t = text;
  2705. if (base == 2 || base == 8 || base == 16)
  2706. {
  2707. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2708. for (;;)
  2709. {
  2710. const juce_wchar c = *t++;
  2711. const int digit = CharacterFunctions::getHexDigitValue (c);
  2712. if (((uint32) digit) < (uint32) base)
  2713. {
  2714. operator<<= (bits);
  2715. operator+= (digit);
  2716. }
  2717. else if (c == 0)
  2718. {
  2719. break;
  2720. }
  2721. }
  2722. }
  2723. else if (base == 10)
  2724. {
  2725. const BigInteger ten ((uint32) 10);
  2726. for (;;)
  2727. {
  2728. const juce_wchar c = *t++;
  2729. if (c >= '0' && c <= '9')
  2730. {
  2731. operator*= (ten);
  2732. operator+= ((int) (c - '0'));
  2733. }
  2734. else if (c == 0)
  2735. {
  2736. break;
  2737. }
  2738. }
  2739. }
  2740. setNegative (text.trimStart().startsWithChar ('-'));
  2741. }
  2742. const MemoryBlock BigInteger::toMemoryBlock() const
  2743. {
  2744. const int numBytes = (getHighestBit() + 8) >> 3;
  2745. MemoryBlock mb ((size_t) numBytes);
  2746. for (int i = 0; i < numBytes; ++i)
  2747. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2748. return mb;
  2749. }
  2750. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2751. {
  2752. clear();
  2753. for (int i = (int) data.getSize(); --i >= 0;)
  2754. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2755. }
  2756. END_JUCE_NAMESPACE
  2757. /*** End of inlined file: juce_BigInteger.cpp ***/
  2758. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2759. BEGIN_JUCE_NAMESPACE
  2760. MemoryBlock::MemoryBlock() throw()
  2761. : size (0)
  2762. {
  2763. }
  2764. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2765. {
  2766. if (initialSize > 0)
  2767. {
  2768. size = initialSize;
  2769. data.allocate (initialSize, initialiseToZero);
  2770. }
  2771. else
  2772. {
  2773. size = 0;
  2774. }
  2775. }
  2776. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2777. : size (other.size)
  2778. {
  2779. if (size > 0)
  2780. {
  2781. jassert (other.data != 0);
  2782. data.malloc (size);
  2783. memcpy (data, other.data, size);
  2784. }
  2785. }
  2786. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2787. : size (jmax ((size_t) 0, sizeInBytes))
  2788. {
  2789. jassert (sizeInBytes >= 0);
  2790. if (size > 0)
  2791. {
  2792. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2793. data.malloc (size);
  2794. if (dataToInitialiseFrom != 0)
  2795. memcpy (data, dataToInitialiseFrom, size);
  2796. }
  2797. }
  2798. MemoryBlock::~MemoryBlock() throw()
  2799. {
  2800. jassert (size >= 0); // should never happen
  2801. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2802. }
  2803. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2804. {
  2805. if (this != &other)
  2806. {
  2807. setSize (other.size, false);
  2808. memcpy (data, other.data, size);
  2809. }
  2810. return *this;
  2811. }
  2812. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2813. {
  2814. return matches (other.data, other.size);
  2815. }
  2816. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2817. {
  2818. return ! operator== (other);
  2819. }
  2820. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2821. {
  2822. return size == dataSize
  2823. && memcmp (data, dataToCompare, size) == 0;
  2824. }
  2825. // this will resize the block to this size
  2826. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2827. {
  2828. if (size != newSize)
  2829. {
  2830. if (newSize <= 0)
  2831. {
  2832. data.free();
  2833. size = 0;
  2834. }
  2835. else
  2836. {
  2837. if (data != 0)
  2838. {
  2839. data.realloc (newSize);
  2840. if (initialiseToZero && (newSize > size))
  2841. zeromem (data + size, newSize - size);
  2842. }
  2843. else
  2844. {
  2845. data.allocate (newSize, initialiseToZero);
  2846. }
  2847. size = newSize;
  2848. }
  2849. }
  2850. }
  2851. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2852. {
  2853. if (size < minimumSize)
  2854. setSize (minimumSize, initialiseToZero);
  2855. }
  2856. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2857. {
  2858. swapVariables (size, other.size);
  2859. data.swapWith (other.data);
  2860. }
  2861. void MemoryBlock::fillWith (const uint8 value) throw()
  2862. {
  2863. memset (data, (int) value, size);
  2864. }
  2865. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2866. {
  2867. if (numBytes > 0)
  2868. {
  2869. const size_t oldSize = size;
  2870. setSize (size + numBytes);
  2871. memcpy (data + oldSize, srcData, numBytes);
  2872. }
  2873. }
  2874. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2875. {
  2876. const char* d = static_cast<const char*> (src);
  2877. if (offset < 0)
  2878. {
  2879. d -= offset;
  2880. num -= offset;
  2881. offset = 0;
  2882. }
  2883. if (offset + num > size)
  2884. num = size - offset;
  2885. if (num > 0)
  2886. memcpy (data + offset, d, num);
  2887. }
  2888. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2889. {
  2890. char* d = static_cast<char*> (dst);
  2891. if (offset < 0)
  2892. {
  2893. zeromem (d, -offset);
  2894. d -= offset;
  2895. num += offset;
  2896. offset = 0;
  2897. }
  2898. if (offset + num > size)
  2899. {
  2900. const size_t newNum = size - offset;
  2901. zeromem (d + newNum, num - newNum);
  2902. num = newNum;
  2903. }
  2904. if (num > 0)
  2905. memcpy (d, data + offset, num);
  2906. }
  2907. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2908. {
  2909. if (startByte < 0)
  2910. {
  2911. numBytesToRemove += startByte;
  2912. startByte = 0;
  2913. }
  2914. if (startByte + numBytesToRemove >= size)
  2915. {
  2916. setSize (startByte);
  2917. }
  2918. else if (numBytesToRemove > 0)
  2919. {
  2920. memmove (data + startByte,
  2921. data + startByte + numBytesToRemove,
  2922. size - (startByte + numBytesToRemove));
  2923. setSize (size - numBytesToRemove);
  2924. }
  2925. }
  2926. const String MemoryBlock::toString() const
  2927. {
  2928. return String (static_cast <const char*> (getData()), size);
  2929. }
  2930. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2931. {
  2932. int res = 0;
  2933. size_t byte = bitRangeStart >> 3;
  2934. int offsetInByte = (int) bitRangeStart & 7;
  2935. size_t bitsSoFar = 0;
  2936. while (numBits > 0 && (size_t) byte < size)
  2937. {
  2938. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2939. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2940. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2941. bitsSoFar += bitsThisTime;
  2942. numBits -= bitsThisTime;
  2943. ++byte;
  2944. offsetInByte = 0;
  2945. }
  2946. return res;
  2947. }
  2948. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2949. {
  2950. size_t byte = bitRangeStart >> 3;
  2951. int offsetInByte = (int) bitRangeStart & 7;
  2952. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2953. while (numBits > 0 && (size_t) byte < size)
  2954. {
  2955. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2956. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  2957. const unsigned int tempBits = bitsToSet << offsetInByte;
  2958. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  2959. ++byte;
  2960. numBits -= bitsThisTime;
  2961. bitsToSet >>= bitsThisTime;
  2962. mask >>= bitsThisTime;
  2963. offsetInByte = 0;
  2964. }
  2965. }
  2966. void MemoryBlock::loadFromHexString (const String& hex)
  2967. {
  2968. ensureSize (hex.length() >> 1);
  2969. char* dest = data;
  2970. int i = 0;
  2971. for (;;)
  2972. {
  2973. int byte = 0;
  2974. for (int loop = 2; --loop >= 0;)
  2975. {
  2976. byte <<= 4;
  2977. for (;;)
  2978. {
  2979. const juce_wchar c = hex [i++];
  2980. if (c >= '0' && c <= '9')
  2981. {
  2982. byte |= c - '0';
  2983. break;
  2984. }
  2985. else if (c >= 'a' && c <= 'z')
  2986. {
  2987. byte |= c - ('a' - 10);
  2988. break;
  2989. }
  2990. else if (c >= 'A' && c <= 'Z')
  2991. {
  2992. byte |= c - ('A' - 10);
  2993. break;
  2994. }
  2995. else if (c == 0)
  2996. {
  2997. setSize (static_cast <size_t> (dest - data));
  2998. return;
  2999. }
  3000. }
  3001. }
  3002. *dest++ = (char) byte;
  3003. }
  3004. }
  3005. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3006. const String MemoryBlock::toBase64Encoding() const
  3007. {
  3008. const size_t numChars = ((size << 3) + 5) / 6;
  3009. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3010. const int initialLen = destString.length();
  3011. destString.preallocateStorage (initialLen + 2 + numChars);
  3012. juce_wchar* d = destString;
  3013. d += initialLen;
  3014. *d++ = '.';
  3015. for (size_t i = 0; i < numChars; ++i)
  3016. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3017. *d++ = 0;
  3018. return destString;
  3019. }
  3020. bool MemoryBlock::fromBase64Encoding (const String& s)
  3021. {
  3022. const int startPos = s.indexOfChar ('.') + 1;
  3023. if (startPos <= 0)
  3024. return false;
  3025. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3026. setSize (numBytesNeeded, true);
  3027. const int numChars = s.length() - startPos;
  3028. const juce_wchar* srcChars = s;
  3029. srcChars += startPos;
  3030. int pos = 0;
  3031. for (int i = 0; i < numChars; ++i)
  3032. {
  3033. const char c = (char) srcChars[i];
  3034. for (int j = 0; j < 64; ++j)
  3035. {
  3036. if (encodingTable[j] == c)
  3037. {
  3038. setBitRange (pos, 6, j);
  3039. pos += 6;
  3040. break;
  3041. }
  3042. }
  3043. }
  3044. return true;
  3045. }
  3046. END_JUCE_NAMESPACE
  3047. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3048. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3049. BEGIN_JUCE_NAMESPACE
  3050. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3051. : properties (ignoreCaseOfKeyNames),
  3052. fallbackProperties (0),
  3053. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3054. {
  3055. }
  3056. PropertySet::PropertySet (const PropertySet& other)
  3057. : properties (other.properties),
  3058. fallbackProperties (other.fallbackProperties),
  3059. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3060. {
  3061. }
  3062. PropertySet& PropertySet::operator= (const PropertySet& other)
  3063. {
  3064. properties = other.properties;
  3065. fallbackProperties = other.fallbackProperties;
  3066. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3067. propertyChanged();
  3068. return *this;
  3069. }
  3070. PropertySet::~PropertySet()
  3071. {
  3072. }
  3073. void PropertySet::clear()
  3074. {
  3075. const ScopedLock sl (lock);
  3076. if (properties.size() > 0)
  3077. {
  3078. properties.clear();
  3079. propertyChanged();
  3080. }
  3081. }
  3082. const String PropertySet::getValue (const String& keyName,
  3083. const String& defaultValue) const throw()
  3084. {
  3085. const ScopedLock sl (lock);
  3086. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3087. if (index >= 0)
  3088. return properties.getAllValues() [index];
  3089. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3090. : defaultValue;
  3091. }
  3092. int PropertySet::getIntValue (const String& keyName,
  3093. const int defaultValue) const throw()
  3094. {
  3095. const ScopedLock sl (lock);
  3096. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3097. if (index >= 0)
  3098. return properties.getAllValues() [index].getIntValue();
  3099. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3100. : defaultValue;
  3101. }
  3102. double PropertySet::getDoubleValue (const String& keyName,
  3103. const double defaultValue) const throw()
  3104. {
  3105. const ScopedLock sl (lock);
  3106. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3107. if (index >= 0)
  3108. return properties.getAllValues()[index].getDoubleValue();
  3109. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3110. : defaultValue;
  3111. }
  3112. bool PropertySet::getBoolValue (const String& keyName,
  3113. const bool defaultValue) const throw()
  3114. {
  3115. const ScopedLock sl (lock);
  3116. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3117. if (index >= 0)
  3118. return properties.getAllValues() [index].getIntValue() != 0;
  3119. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3120. : defaultValue;
  3121. }
  3122. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3123. {
  3124. return XmlDocument::parse (getValue (keyName));
  3125. }
  3126. void PropertySet::setValue (const String& keyName, const var& v)
  3127. {
  3128. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3129. if (keyName.isNotEmpty())
  3130. {
  3131. const String value (v.toString());
  3132. const ScopedLock sl (lock);
  3133. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3134. if (index < 0 || properties.getAllValues() [index] != value)
  3135. {
  3136. properties.set (keyName, value);
  3137. propertyChanged();
  3138. }
  3139. }
  3140. }
  3141. void PropertySet::removeValue (const String& keyName)
  3142. {
  3143. if (keyName.isNotEmpty())
  3144. {
  3145. const ScopedLock sl (lock);
  3146. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3147. if (index >= 0)
  3148. {
  3149. properties.remove (keyName);
  3150. propertyChanged();
  3151. }
  3152. }
  3153. }
  3154. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3155. {
  3156. setValue (keyName, xml == 0 ? var::null
  3157. : var (xml->createDocument (String::empty, true)));
  3158. }
  3159. bool PropertySet::containsKey (const String& keyName) const throw()
  3160. {
  3161. const ScopedLock sl (lock);
  3162. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3163. }
  3164. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3165. {
  3166. const ScopedLock sl (lock);
  3167. fallbackProperties = fallbackProperties_;
  3168. }
  3169. XmlElement* PropertySet::createXml (const String& nodeName) const
  3170. {
  3171. const ScopedLock sl (lock);
  3172. XmlElement* const xml = new XmlElement (nodeName);
  3173. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3174. {
  3175. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3176. e->setAttribute ("name", properties.getAllKeys()[i]);
  3177. e->setAttribute ("val", properties.getAllValues()[i]);
  3178. }
  3179. return xml;
  3180. }
  3181. void PropertySet::restoreFromXml (const XmlElement& xml)
  3182. {
  3183. const ScopedLock sl (lock);
  3184. clear();
  3185. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3186. {
  3187. if (e->hasAttribute ("name")
  3188. && e->hasAttribute ("val"))
  3189. {
  3190. properties.set (e->getStringAttribute ("name"),
  3191. e->getStringAttribute ("val"));
  3192. }
  3193. }
  3194. if (properties.size() > 0)
  3195. propertyChanged();
  3196. }
  3197. void PropertySet::propertyChanged()
  3198. {
  3199. }
  3200. END_JUCE_NAMESPACE
  3201. /*** End of inlined file: juce_PropertySet.cpp ***/
  3202. /*** Start of inlined file: juce_Identifier.cpp ***/
  3203. BEGIN_JUCE_NAMESPACE
  3204. StringPool& Identifier::getPool()
  3205. {
  3206. static StringPool pool;
  3207. return pool;
  3208. }
  3209. Identifier::Identifier() throw()
  3210. : name (0)
  3211. {
  3212. }
  3213. Identifier::Identifier (const Identifier& other) throw()
  3214. : name (other.name)
  3215. {
  3216. }
  3217. Identifier& Identifier::operator= (const Identifier& other) throw()
  3218. {
  3219. name = other.name;
  3220. return *this;
  3221. }
  3222. Identifier::Identifier (const String& name_)
  3223. : name (Identifier::getPool().getPooledString (name_))
  3224. {
  3225. /* An Identifier string must be suitable for use as a script variable or XML
  3226. attribute, so it can only contain this limited set of characters.. */
  3227. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3228. }
  3229. Identifier::Identifier (const char* const name_)
  3230. : name (Identifier::getPool().getPooledString (name_))
  3231. {
  3232. /* An Identifier string must be suitable for use as a script variable or XML
  3233. attribute, so it can only contain this limited set of characters.. */
  3234. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3235. }
  3236. Identifier::~Identifier()
  3237. {
  3238. }
  3239. END_JUCE_NAMESPACE
  3240. /*** End of inlined file: juce_Identifier.cpp ***/
  3241. /*** Start of inlined file: juce_Variant.cpp ***/
  3242. BEGIN_JUCE_NAMESPACE
  3243. class var::VariantType
  3244. {
  3245. public:
  3246. VariantType() {}
  3247. virtual ~VariantType() {}
  3248. virtual int toInt (const ValueUnion&) const { return 0; }
  3249. virtual double toDouble (const ValueUnion&) const { return 0; }
  3250. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3251. virtual bool toBool (const ValueUnion&) const { return false; }
  3252. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3253. virtual bool isVoid() const throw() { return false; }
  3254. virtual bool isInt() const throw() { return false; }
  3255. virtual bool isBool() const throw() { return false; }
  3256. virtual bool isDouble() const throw() { return false; }
  3257. virtual bool isString() const throw() { return false; }
  3258. virtual bool isObject() const throw() { return false; }
  3259. virtual bool isMethod() const throw() { return false; }
  3260. virtual void cleanUp (ValueUnion&) const throw() {}
  3261. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3262. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3263. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3264. };
  3265. class var::VariantType_Void : public var::VariantType
  3266. {
  3267. public:
  3268. VariantType_Void() {}
  3269. static const VariantType_Void instance;
  3270. bool isVoid() const throw() { return true; }
  3271. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3272. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3273. };
  3274. class var::VariantType_Int : public var::VariantType
  3275. {
  3276. public:
  3277. VariantType_Int() {}
  3278. static const VariantType_Int instance;
  3279. int toInt (const ValueUnion& data) const { return data.intValue; };
  3280. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3281. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3282. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3283. bool isInt() const throw() { return true; }
  3284. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3285. {
  3286. return otherType.toInt (otherData) == data.intValue;
  3287. }
  3288. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3289. {
  3290. output.writeCompressedInt (5);
  3291. output.writeByte (1);
  3292. output.writeInt (data.intValue);
  3293. }
  3294. };
  3295. class var::VariantType_Double : public var::VariantType
  3296. {
  3297. public:
  3298. VariantType_Double() {}
  3299. static const VariantType_Double instance;
  3300. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3301. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3302. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3303. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3304. bool isDouble() const throw() { return true; }
  3305. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3306. {
  3307. return otherType.toDouble (otherData) == data.doubleValue;
  3308. }
  3309. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3310. {
  3311. output.writeCompressedInt (9);
  3312. output.writeByte (4);
  3313. output.writeDouble (data.doubleValue);
  3314. }
  3315. };
  3316. class var::VariantType_Bool : public var::VariantType
  3317. {
  3318. public:
  3319. VariantType_Bool() {}
  3320. static const VariantType_Bool instance;
  3321. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3322. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3323. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3324. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3325. bool isBool() const throw() { return true; }
  3326. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3327. {
  3328. return otherType.toBool (otherData) == data.boolValue;
  3329. }
  3330. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3331. {
  3332. output.writeCompressedInt (1);
  3333. output.writeByte (data.boolValue ? 2 : 3);
  3334. }
  3335. };
  3336. class var::VariantType_String : public var::VariantType
  3337. {
  3338. public:
  3339. VariantType_String() {}
  3340. static const VariantType_String instance;
  3341. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3342. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3343. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3344. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3345. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3346. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3347. || data.stringValue->trim().equalsIgnoreCase ("true")
  3348. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3349. bool isString() const throw() { return true; }
  3350. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3351. {
  3352. return otherType.toString (otherData) == *data.stringValue;
  3353. }
  3354. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3355. {
  3356. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3357. output.writeCompressedInt (len + 1);
  3358. output.writeByte (5);
  3359. HeapBlock<char> temp (len);
  3360. data.stringValue->copyToUTF8 (temp, len);
  3361. output.write (temp, len);
  3362. }
  3363. };
  3364. class var::VariantType_Object : public var::VariantType
  3365. {
  3366. public:
  3367. VariantType_Object() {}
  3368. static const VariantType_Object instance;
  3369. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3370. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3371. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3372. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3373. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3374. bool isObject() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toObject (otherData) == data.objectValue;
  3378. }
  3379. void writeToStream (const ValueUnion&, OutputStream& output) const
  3380. {
  3381. jassertfalse; // Can't write an object to a stream!
  3382. output.writeCompressedInt (0);
  3383. }
  3384. };
  3385. class var::VariantType_Method : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_Method() {}
  3389. static const VariantType_Method instance;
  3390. const String toString (const ValueUnion&) const { return "Method"; }
  3391. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3392. bool isMethod() const throw() { return true; }
  3393. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3394. {
  3395. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3396. }
  3397. void writeToStream (const ValueUnion&, OutputStream& output) const
  3398. {
  3399. jassertfalse; // Can't write a method to a stream!
  3400. output.writeCompressedInt (0);
  3401. }
  3402. };
  3403. const var::VariantType_Void var::VariantType_Void::instance;
  3404. const var::VariantType_Int var::VariantType_Int::instance;
  3405. const var::VariantType_Bool var::VariantType_Bool::instance;
  3406. const var::VariantType_Double var::VariantType_Double::instance;
  3407. const var::VariantType_String var::VariantType_String::instance;
  3408. const var::VariantType_Object var::VariantType_Object::instance;
  3409. const var::VariantType_Method var::VariantType_Method::instance;
  3410. var::var() throw() : type (&VariantType_Void::instance)
  3411. {
  3412. }
  3413. var::~var() throw()
  3414. {
  3415. type->cleanUp (value);
  3416. }
  3417. const var var::null;
  3418. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3419. {
  3420. type->createCopy (value, valueToCopy.value);
  3421. }
  3422. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3423. {
  3424. value.intValue = value_;
  3425. }
  3426. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3427. {
  3428. value.boolValue = value_;
  3429. }
  3430. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3431. {
  3432. value.doubleValue = value_;
  3433. }
  3434. var::var (const String& value_) : type (&VariantType_String::instance)
  3435. {
  3436. value.stringValue = new String (value_);
  3437. }
  3438. var::var (const char* const value_) : type (&VariantType_String::instance)
  3439. {
  3440. value.stringValue = new String (value_);
  3441. }
  3442. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3443. {
  3444. value.stringValue = new String (value_);
  3445. }
  3446. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3447. {
  3448. value.objectValue = object;
  3449. if (object != 0)
  3450. object->incReferenceCount();
  3451. }
  3452. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3453. {
  3454. value.methodValue = method_;
  3455. }
  3456. bool var::isVoid() const throw() { return type->isVoid(); }
  3457. bool var::isInt() const throw() { return type->isInt(); }
  3458. bool var::isBool() const throw() { return type->isBool(); }
  3459. bool var::isDouble() const throw() { return type->isDouble(); }
  3460. bool var::isString() const throw() { return type->isString(); }
  3461. bool var::isObject() const throw() { return type->isObject(); }
  3462. bool var::isMethod() const throw() { return type->isMethod(); }
  3463. var::operator int() const { return type->toInt (value); }
  3464. var::operator bool() const { return type->toBool (value); }
  3465. var::operator float() const { return (float) type->toDouble (value); }
  3466. var::operator double() const { return type->toDouble (value); }
  3467. const String var::toString() const { return type->toString (value); }
  3468. var::operator const String() const { return type->toString (value); }
  3469. DynamicObject* var::getObject() const { return type->toObject (value); }
  3470. void var::swapWith (var& other) throw()
  3471. {
  3472. swapVariables (type, other.type);
  3473. swapVariables (value, other.value);
  3474. }
  3475. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3476. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3477. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3478. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3479. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3480. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3481. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3482. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3483. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3484. bool var::equals (const var& other) const throw()
  3485. {
  3486. return type->equals (value, other.value, *other.type);
  3487. }
  3488. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3489. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3490. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3491. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3492. void var::writeToStream (OutputStream& output) const
  3493. {
  3494. type->writeToStream (value, output);
  3495. }
  3496. const var var::readFromStream (InputStream& input)
  3497. {
  3498. const int numBytes = input.readCompressedInt();
  3499. if (numBytes > 0)
  3500. {
  3501. switch (input.readByte())
  3502. {
  3503. case 1: return var (input.readInt());
  3504. case 2: return var (true);
  3505. case 3: return var (false);
  3506. case 4: return var (input.readDouble());
  3507. case 5:
  3508. {
  3509. MemoryOutputStream mo;
  3510. mo.writeFromInputStream (input, numBytes - 1);
  3511. return var (mo.toUTF8());
  3512. }
  3513. default: input.skipNextBytes (numBytes - 1); break;
  3514. }
  3515. }
  3516. return var::null;
  3517. }
  3518. const var var::operator[] (const Identifier& propertyName) const
  3519. {
  3520. DynamicObject* const o = getObject();
  3521. return o != 0 ? o->getProperty (propertyName) : var::null;
  3522. }
  3523. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3524. {
  3525. DynamicObject* const o = getObject();
  3526. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3527. }
  3528. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3529. {
  3530. if (isMethod())
  3531. {
  3532. DynamicObject* const target = targetObject.getObject();
  3533. if (target != 0)
  3534. return (target->*(value.methodValue)) (arguments, numArguments);
  3535. }
  3536. return var::null;
  3537. }
  3538. const var var::call (const Identifier& method) const
  3539. {
  3540. return invoke (method, 0, 0);
  3541. }
  3542. const var var::call (const Identifier& method, const var& arg1) const
  3543. {
  3544. return invoke (method, &arg1, 1);
  3545. }
  3546. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3547. {
  3548. var args[] = { arg1, arg2 };
  3549. return invoke (method, args, 2);
  3550. }
  3551. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3552. {
  3553. var args[] = { arg1, arg2, arg3 };
  3554. return invoke (method, args, 3);
  3555. }
  3556. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3557. {
  3558. var args[] = { arg1, arg2, arg3, arg4 };
  3559. return invoke (method, args, 4);
  3560. }
  3561. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3562. {
  3563. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3564. return invoke (method, args, 5);
  3565. }
  3566. END_JUCE_NAMESPACE
  3567. /*** End of inlined file: juce_Variant.cpp ***/
  3568. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3569. BEGIN_JUCE_NAMESPACE
  3570. NamedValueSet::NamedValue::NamedValue() throw()
  3571. {
  3572. }
  3573. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3574. : name (name_), value (value_)
  3575. {
  3576. }
  3577. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3578. {
  3579. return name == other.name && value == other.value;
  3580. }
  3581. NamedValueSet::NamedValueSet() throw()
  3582. {
  3583. }
  3584. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3585. {
  3586. values.addCopyOfList (other.values);
  3587. }
  3588. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3589. {
  3590. clear();
  3591. values.addCopyOfList (other.values);
  3592. return *this;
  3593. }
  3594. NamedValueSet::~NamedValueSet()
  3595. {
  3596. clear();
  3597. }
  3598. void NamedValueSet::clear()
  3599. {
  3600. values.deleteAll();
  3601. }
  3602. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3603. {
  3604. const NamedValue* i1 = values;
  3605. const NamedValue* i2 = other.values;
  3606. while (i1 != 0 && i2 != 0)
  3607. {
  3608. if (! (*i1 == *i2))
  3609. return false;
  3610. i1 = i1->nextListItem;
  3611. i2 = i2->nextListItem;
  3612. }
  3613. return true;
  3614. }
  3615. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3616. {
  3617. return ! operator== (other);
  3618. }
  3619. int NamedValueSet::size() const throw()
  3620. {
  3621. return values.size();
  3622. }
  3623. const var& NamedValueSet::operator[] (const Identifier& name) const
  3624. {
  3625. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3626. if (i->name == name)
  3627. return i->value;
  3628. return var::null;
  3629. }
  3630. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3631. {
  3632. const var* v = getVarPointer (name);
  3633. return v != 0 ? *v : defaultReturnValue;
  3634. }
  3635. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3636. {
  3637. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3638. if (i->name == name)
  3639. return &(i->value);
  3640. return 0;
  3641. }
  3642. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3643. {
  3644. LinkedListPointer<NamedValue>* i = &values;
  3645. while (i->get() != 0)
  3646. {
  3647. NamedValue* const v = i->get();
  3648. if (v->name == name)
  3649. {
  3650. if (v->value == newValue)
  3651. return false;
  3652. v->value = newValue;
  3653. return true;
  3654. }
  3655. i = &(v->nextListItem);
  3656. }
  3657. i->insertNext (new NamedValue (name, newValue));
  3658. return true;
  3659. }
  3660. bool NamedValueSet::contains (const Identifier& name) const
  3661. {
  3662. return getVarPointer (name) != 0;
  3663. }
  3664. bool NamedValueSet::remove (const Identifier& name)
  3665. {
  3666. LinkedListPointer<NamedValue>* i = &values;
  3667. for (;;)
  3668. {
  3669. NamedValue* const v = i->get();
  3670. if (v == 0)
  3671. break;
  3672. if (v->name == name)
  3673. {
  3674. delete i->removeNext();
  3675. return true;
  3676. }
  3677. i = &(v->nextListItem);
  3678. }
  3679. return false;
  3680. }
  3681. const Identifier NamedValueSet::getName (const int index) const
  3682. {
  3683. const NamedValue* const v = values[index];
  3684. jassert (v != 0);
  3685. return v->name;
  3686. }
  3687. const var NamedValueSet::getValueAt (const int index) const
  3688. {
  3689. const NamedValue* const v = values[index];
  3690. jassert (v != 0);
  3691. return v->value;
  3692. }
  3693. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3694. {
  3695. clear();
  3696. LinkedListPointer<NamedValue>::Appender appender (values);
  3697. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3698. for (int i = 0; i < numAtts; ++i)
  3699. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3700. }
  3701. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3702. {
  3703. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3704. {
  3705. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3706. xml.setAttribute (i->name.toString(),
  3707. i->value.toString());
  3708. }
  3709. }
  3710. END_JUCE_NAMESPACE
  3711. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3712. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3713. BEGIN_JUCE_NAMESPACE
  3714. DynamicObject::DynamicObject()
  3715. {
  3716. }
  3717. DynamicObject::~DynamicObject()
  3718. {
  3719. }
  3720. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3721. {
  3722. var* const v = properties.getVarPointer (propertyName);
  3723. return v != 0 && ! v->isMethod();
  3724. }
  3725. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3726. {
  3727. return properties [propertyName];
  3728. }
  3729. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3730. {
  3731. properties.set (propertyName, newValue);
  3732. }
  3733. void DynamicObject::removeProperty (const Identifier& propertyName)
  3734. {
  3735. properties.remove (propertyName);
  3736. }
  3737. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3738. {
  3739. return getProperty (methodName).isMethod();
  3740. }
  3741. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3742. const var* parameters,
  3743. int numParameters)
  3744. {
  3745. return properties [methodName].invoke (var (this), parameters, numParameters);
  3746. }
  3747. void DynamicObject::setMethod (const Identifier& name,
  3748. var::MethodFunction methodFunction)
  3749. {
  3750. properties.set (name, var (methodFunction));
  3751. }
  3752. void DynamicObject::clear()
  3753. {
  3754. properties.clear();
  3755. }
  3756. END_JUCE_NAMESPACE
  3757. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3758. /*** Start of inlined file: juce_Expression.cpp ***/
  3759. BEGIN_JUCE_NAMESPACE
  3760. class Expression::Helpers
  3761. {
  3762. public:
  3763. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3764. // This helper function is needed to work around VC6 scoping bugs
  3765. static const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3766. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3767. class Constant : public Term
  3768. {
  3769. public:
  3770. Constant (const double value_, bool isResolutionTarget_)
  3771. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3772. Type getType() const throw() { return constantType; }
  3773. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3774. double evaluate (const EvaluationContext&, int) const { return value; }
  3775. int getNumInputs() const { return 0; }
  3776. Term* getInput (int) const { return 0; }
  3777. const TermPtr negated()
  3778. {
  3779. return new Constant (-value, isResolutionTarget);
  3780. }
  3781. const String toString() const
  3782. {
  3783. if (isResolutionTarget)
  3784. return "@" + String (value);
  3785. return String (value);
  3786. }
  3787. double value;
  3788. bool isResolutionTarget;
  3789. };
  3790. class Symbol : public Term
  3791. {
  3792. public:
  3793. explicit Symbol (const String& symbol_)
  3794. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3795. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3796. {}
  3797. Symbol (const String& symbol_, const String& member_)
  3798. : mainSymbol (symbol_),
  3799. member (member_)
  3800. {}
  3801. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3802. {
  3803. if (++recursionDepth > 256)
  3804. throw EvaluationError ("Recursive symbol references");
  3805. try
  3806. {
  3807. return getTermFor (c.getSymbolValue (mainSymbol, member))->evaluate (c, recursionDepth);
  3808. }
  3809. catch (...)
  3810. {}
  3811. return 0;
  3812. }
  3813. Type getType() const throw() { return symbolType; }
  3814. Term* clone() const { return new Symbol (mainSymbol, member); }
  3815. int getNumInputs() const { return 0; }
  3816. Term* getInput (int) const { return 0; }
  3817. const String toString() const { return joinParts (mainSymbol, member); }
  3818. void getSymbolParts (String& objectName, String& memberName) const { objectName = mainSymbol; memberName = member; }
  3819. static const String joinParts (const String& mainSymbol, const String& member)
  3820. {
  3821. return member.isEmpty() ? mainSymbol
  3822. : mainSymbol + "." + member;
  3823. }
  3824. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3825. {
  3826. if (s == mainSymbol)
  3827. return true;
  3828. if (++recursionDepth > 256)
  3829. throw EvaluationError ("Recursive symbol references");
  3830. try
  3831. {
  3832. return c != 0 && getTermFor (c->getSymbolValue (mainSymbol, member))->referencesSymbol (s, c, recursionDepth);
  3833. }
  3834. catch (EvaluationError&)
  3835. {
  3836. return false;
  3837. }
  3838. }
  3839. String mainSymbol, member;
  3840. };
  3841. class Function : public Term
  3842. {
  3843. public:
  3844. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3845. : functionName (functionName_), parameters (parameters_)
  3846. {}
  3847. Term* clone() const { return new Function (functionName, parameters); }
  3848. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3849. {
  3850. HeapBlock <double> params (parameters.size());
  3851. for (int i = 0; i < parameters.size(); ++i)
  3852. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3853. return c.evaluateFunction (functionName, params, parameters.size());
  3854. }
  3855. Type getType() const throw() { return functionType; }
  3856. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3857. int getNumInputs() const { return parameters.size(); }
  3858. Term* getInput (int i) const { return parameters [i]; }
  3859. const String getFunctionName() const { return functionName; }
  3860. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3861. {
  3862. for (int i = 0; i < parameters.size(); ++i)
  3863. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3864. return true;
  3865. return false;
  3866. }
  3867. const String toString() const
  3868. {
  3869. if (parameters.size() == 0)
  3870. return functionName + "()";
  3871. String s (functionName + " (");
  3872. for (int i = 0; i < parameters.size(); ++i)
  3873. {
  3874. s << parameters.getUnchecked(i)->toString();
  3875. if (i < parameters.size() - 1)
  3876. s << ", ";
  3877. }
  3878. s << ')';
  3879. return s;
  3880. }
  3881. const String functionName;
  3882. ReferenceCountedArray<Term> parameters;
  3883. };
  3884. class Negate : public Term
  3885. {
  3886. public:
  3887. explicit Negate (const TermPtr& input_) : input (input_)
  3888. {
  3889. jassert (input_ != 0);
  3890. }
  3891. Type getType() const throw() { return operatorType; }
  3892. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3893. int getNumInputs() const { return 1; }
  3894. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3895. Term* clone() const { return new Negate (input->clone()); }
  3896. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3897. const String getFunctionName() const { return "-"; }
  3898. const TermPtr negated()
  3899. {
  3900. return input;
  3901. }
  3902. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3903. {
  3904. (void) input_;
  3905. jassert (input_ == input);
  3906. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3907. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3908. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3909. }
  3910. const String toString() const
  3911. {
  3912. if (input->getOperatorPrecedence() > 0)
  3913. return "-(" + input->toString() + ")";
  3914. else
  3915. return "-" + input->toString();
  3916. }
  3917. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3918. {
  3919. return input->referencesSymbol (s, c, recursionDepth);
  3920. }
  3921. private:
  3922. const TermPtr input;
  3923. };
  3924. class BinaryTerm : public Term
  3925. {
  3926. public:
  3927. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3928. {
  3929. jassert (left_ != 0 && right_ != 0);
  3930. }
  3931. int getInputIndexFor (const Term* possibleInput) const
  3932. {
  3933. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3934. }
  3935. Type getType() const throw() { return operatorType; }
  3936. int getNumInputs() const { return 2; }
  3937. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3938. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3939. {
  3940. return left->referencesSymbol (s, c, recursionDepth)
  3941. || right->referencesSymbol (s, c, recursionDepth);
  3942. }
  3943. const String toString() const
  3944. {
  3945. String s;
  3946. const int ourPrecendence = getOperatorPrecedence();
  3947. if (left->getOperatorPrecedence() > ourPrecendence)
  3948. s << '(' << left->toString() << ')';
  3949. else
  3950. s = left->toString();
  3951. s << ' ' << getFunctionName() << ' ';
  3952. if (right->getOperatorPrecedence() >= ourPrecendence)
  3953. s << '(' << right->toString() << ')';
  3954. else
  3955. s << right->toString();
  3956. return s;
  3957. }
  3958. protected:
  3959. const TermPtr left, right;
  3960. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3961. {
  3962. jassert (input == left || input == right);
  3963. if (input != left && input != right)
  3964. return 0;
  3965. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3966. if (dest == 0)
  3967. return new Constant (overallTarget, false);
  3968. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3969. }
  3970. };
  3971. class Add : public BinaryTerm
  3972. {
  3973. public:
  3974. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3975. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3976. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3977. int getOperatorPrecedence() const { return 2; }
  3978. const String getFunctionName() const { return "+"; }
  3979. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3980. {
  3981. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3982. if (newDest == 0)
  3983. return 0;
  3984. return new Subtract (newDest, (input == left ? right : left)->clone());
  3985. }
  3986. private:
  3987. JUCE_DECLARE_NON_COPYABLE (Add);
  3988. };
  3989. class Subtract : public BinaryTerm
  3990. {
  3991. public:
  3992. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3993. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  3994. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  3995. int getOperatorPrecedence() const { return 2; }
  3996. const String getFunctionName() const { return "-"; }
  3997. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3998. {
  3999. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4000. if (newDest == 0)
  4001. return 0;
  4002. if (input == left)
  4003. return new Add (newDest, right->clone());
  4004. else
  4005. return new Subtract (left->clone(), newDest);
  4006. }
  4007. private:
  4008. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4009. };
  4010. class Multiply : public BinaryTerm
  4011. {
  4012. public:
  4013. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4014. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4015. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4016. const String getFunctionName() const { return "*"; }
  4017. int getOperatorPrecedence() const { return 1; }
  4018. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4019. {
  4020. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4021. if (newDest == 0)
  4022. return 0;
  4023. return new Divide (newDest, (input == left ? right : left)->clone());
  4024. }
  4025. private:
  4026. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4027. };
  4028. class Divide : public BinaryTerm
  4029. {
  4030. public:
  4031. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4032. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4033. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4034. const String getFunctionName() const { return "/"; }
  4035. int getOperatorPrecedence() const { return 1; }
  4036. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4037. {
  4038. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4039. if (newDest == 0)
  4040. return 0;
  4041. if (input == left)
  4042. return new Multiply (newDest, right->clone());
  4043. else
  4044. return new Divide (left->clone(), newDest);
  4045. }
  4046. private:
  4047. JUCE_DECLARE_NON_COPYABLE (Divide);
  4048. };
  4049. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4050. {
  4051. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4052. if (inputIndex >= 0)
  4053. return topLevel;
  4054. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4055. {
  4056. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4057. if (t != 0)
  4058. return t;
  4059. }
  4060. return 0;
  4061. }
  4062. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4063. {
  4064. {
  4065. Constant* const c = dynamic_cast<Constant*> (term);
  4066. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4067. return c;
  4068. }
  4069. if (dynamic_cast<Function*> (term) != 0)
  4070. return 0;
  4071. int i;
  4072. const int numIns = term->getNumInputs();
  4073. for (i = 0; i < numIns; ++i)
  4074. {
  4075. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4076. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4077. return c;
  4078. }
  4079. for (i = 0; i < numIns; ++i)
  4080. {
  4081. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4082. if (c != 0)
  4083. return c;
  4084. }
  4085. return 0;
  4086. }
  4087. static bool containsAnySymbols (const Term* const t)
  4088. {
  4089. if (t->getType() == Expression::symbolType)
  4090. return true;
  4091. for (int i = t->getNumInputs(); --i >= 0;)
  4092. if (containsAnySymbols (t->getInput (i)))
  4093. return true;
  4094. return false;
  4095. }
  4096. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4097. {
  4098. Symbol* const sym = dynamic_cast<Symbol*> (t);
  4099. if (sym != 0 && sym->mainSymbol == oldName)
  4100. {
  4101. sym->mainSymbol = newName;
  4102. return true;
  4103. }
  4104. bool anyChanged = false;
  4105. for (int i = t->getNumInputs(); --i >= 0;)
  4106. if (renameSymbol (t->getInput (i), oldName, newName))
  4107. anyChanged = true;
  4108. return anyChanged;
  4109. }
  4110. class Parser
  4111. {
  4112. public:
  4113. Parser (const String& stringToParse, int& textIndex_)
  4114. : textString (stringToParse), textIndex (textIndex_)
  4115. {
  4116. text = textString;
  4117. }
  4118. const TermPtr readExpression()
  4119. {
  4120. TermPtr lhs (readMultiplyOrDivideExpression());
  4121. char opType;
  4122. while (lhs != 0 && readOperator ("+-", &opType))
  4123. {
  4124. TermPtr rhs (readMultiplyOrDivideExpression());
  4125. if (rhs == 0)
  4126. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4127. if (opType == '+')
  4128. lhs = new Add (lhs, rhs);
  4129. else
  4130. lhs = new Subtract (lhs, rhs);
  4131. }
  4132. return lhs;
  4133. }
  4134. private:
  4135. const String textString;
  4136. const juce_wchar* text;
  4137. int& textIndex;
  4138. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4139. {
  4140. return c >= '0' && c <= '9';
  4141. }
  4142. void skipWhitespace (int& i) throw()
  4143. {
  4144. while (CharacterFunctions::isWhitespace (text [i]))
  4145. ++i;
  4146. }
  4147. bool readChar (const juce_wchar required) throw()
  4148. {
  4149. if (text[textIndex] == required)
  4150. {
  4151. ++textIndex;
  4152. return true;
  4153. }
  4154. return false;
  4155. }
  4156. bool readOperator (const char* ops, char* const opType = 0) throw()
  4157. {
  4158. skipWhitespace (textIndex);
  4159. while (*ops != 0)
  4160. {
  4161. if (readChar (*ops))
  4162. {
  4163. if (opType != 0)
  4164. *opType = *ops;
  4165. return true;
  4166. }
  4167. ++ops;
  4168. }
  4169. return false;
  4170. }
  4171. bool readIdentifier (String& identifier) throw()
  4172. {
  4173. skipWhitespace (textIndex);
  4174. int i = textIndex;
  4175. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4176. {
  4177. ++i;
  4178. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4179. ++i;
  4180. }
  4181. if (i > textIndex)
  4182. {
  4183. identifier = String (text + textIndex, i - textIndex);
  4184. textIndex = i;
  4185. return true;
  4186. }
  4187. return false;
  4188. }
  4189. Term* readNumber() throw()
  4190. {
  4191. skipWhitespace (textIndex);
  4192. int i = textIndex;
  4193. const bool isResolutionTarget = (text[i] == '@');
  4194. if (isResolutionTarget)
  4195. {
  4196. ++i;
  4197. skipWhitespace (i);
  4198. textIndex = i;
  4199. }
  4200. if (text[i] == '-')
  4201. {
  4202. ++i;
  4203. skipWhitespace (i);
  4204. }
  4205. int numDigits = 0;
  4206. while (isDecimalDigit (text[i]))
  4207. {
  4208. ++i;
  4209. ++numDigits;
  4210. }
  4211. const bool hasPoint = (text[i] == '.');
  4212. if (hasPoint)
  4213. {
  4214. ++i;
  4215. while (isDecimalDigit (text[i]))
  4216. {
  4217. ++i;
  4218. ++numDigits;
  4219. }
  4220. }
  4221. if (numDigits == 0)
  4222. return 0;
  4223. juce_wchar c = text[i];
  4224. const bool hasExponent = (c == 'e' || c == 'E');
  4225. if (hasExponent)
  4226. {
  4227. ++i;
  4228. c = text[i];
  4229. if (c == '+' || c == '-')
  4230. ++i;
  4231. int numExpDigits = 0;
  4232. while (isDecimalDigit (text[i]))
  4233. {
  4234. ++i;
  4235. ++numExpDigits;
  4236. }
  4237. if (numExpDigits == 0)
  4238. return 0;
  4239. }
  4240. const int start = textIndex;
  4241. textIndex = i;
  4242. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4243. }
  4244. const TermPtr readMultiplyOrDivideExpression()
  4245. {
  4246. TermPtr lhs (readUnaryExpression());
  4247. char opType;
  4248. while (lhs != 0 && readOperator ("*/", &opType))
  4249. {
  4250. TermPtr rhs (readUnaryExpression());
  4251. if (rhs == 0)
  4252. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4253. if (opType == '*')
  4254. lhs = new Multiply (lhs, rhs);
  4255. else
  4256. lhs = new Divide (lhs, rhs);
  4257. }
  4258. return lhs;
  4259. }
  4260. const TermPtr readUnaryExpression()
  4261. {
  4262. char opType;
  4263. if (readOperator ("+-", &opType))
  4264. {
  4265. TermPtr term (readUnaryExpression());
  4266. if (term == 0)
  4267. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4268. if (opType == '-')
  4269. term = term->negated();
  4270. return term;
  4271. }
  4272. return readPrimaryExpression();
  4273. }
  4274. const TermPtr readPrimaryExpression()
  4275. {
  4276. TermPtr e (readParenthesisedExpression());
  4277. if (e != 0)
  4278. return e;
  4279. e = readNumber();
  4280. if (e != 0)
  4281. return e;
  4282. String identifier;
  4283. if (readIdentifier (identifier))
  4284. {
  4285. if (readOperator ("(")) // method call...
  4286. {
  4287. Function* const f = new Function (identifier, ReferenceCountedArray<Term>());
  4288. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4289. TermPtr param (readExpression());
  4290. if (param == 0)
  4291. {
  4292. if (readOperator (")"))
  4293. return func.release();
  4294. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4295. }
  4296. f->parameters.add (param);
  4297. while (readOperator (","))
  4298. {
  4299. param = readExpression();
  4300. if (param == 0)
  4301. throw ParseError ("Expected expression after \",\"");
  4302. f->parameters.add (param);
  4303. }
  4304. if (readOperator (")"))
  4305. return func.release();
  4306. throw ParseError ("Expected \")\"");
  4307. }
  4308. else // just a symbol..
  4309. {
  4310. return new Symbol (identifier);
  4311. }
  4312. }
  4313. return 0;
  4314. }
  4315. const TermPtr readParenthesisedExpression()
  4316. {
  4317. if (! readOperator ("("))
  4318. return 0;
  4319. const TermPtr e (readExpression());
  4320. if (e == 0 || ! readOperator (")"))
  4321. return 0;
  4322. return e;
  4323. }
  4324. JUCE_DECLARE_NON_COPYABLE (Parser);
  4325. };
  4326. };
  4327. Expression::Expression()
  4328. : term (new Expression::Helpers::Constant (0, false))
  4329. {
  4330. }
  4331. Expression::~Expression()
  4332. {
  4333. }
  4334. Expression::Expression (Term* const term_)
  4335. : term (term_)
  4336. {
  4337. jassert (term != 0);
  4338. }
  4339. Expression::Expression (const double constant)
  4340. : term (new Expression::Helpers::Constant (constant, false))
  4341. {
  4342. }
  4343. Expression::Expression (const Expression& other)
  4344. : term (other.term)
  4345. {
  4346. }
  4347. Expression& Expression::operator= (const Expression& other)
  4348. {
  4349. term = other.term;
  4350. return *this;
  4351. }
  4352. Expression::Expression (const String& stringToParse)
  4353. {
  4354. int i = 0;
  4355. Helpers::Parser parser (stringToParse, i);
  4356. term = parser.readExpression();
  4357. if (term == 0)
  4358. term = new Helpers::Constant (0, false);
  4359. }
  4360. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4361. {
  4362. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4363. const Helpers::TermPtr term (parser.readExpression());
  4364. if (term != 0)
  4365. return Expression (term);
  4366. return Expression();
  4367. }
  4368. double Expression::evaluate() const
  4369. {
  4370. return evaluate (Expression::EvaluationContext());
  4371. }
  4372. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4373. {
  4374. return term->evaluate (context, 0);
  4375. }
  4376. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4377. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4378. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4379. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4380. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4381. const String Expression::toString() const
  4382. {
  4383. return term->toString();
  4384. }
  4385. const Expression Expression::symbol (const String& symbol)
  4386. {
  4387. return Expression (new Helpers::Symbol (symbol));
  4388. }
  4389. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4390. {
  4391. ReferenceCountedArray<Term> params;
  4392. for (int i = 0; i < parameters.size(); ++i)
  4393. params.add (parameters.getReference(i).term);
  4394. return Expression (new Helpers::Function (functionName, params));
  4395. }
  4396. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4397. const Expression::EvaluationContext& context) const
  4398. {
  4399. ScopedPointer<Term> newTerm (term->clone());
  4400. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4401. if (termToAdjust == 0)
  4402. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4403. if (termToAdjust == 0)
  4404. {
  4405. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4406. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4407. }
  4408. jassert (termToAdjust != 0);
  4409. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4410. if (parent == 0)
  4411. {
  4412. termToAdjust->value = targetValue;
  4413. }
  4414. else
  4415. {
  4416. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4417. if (reverseTerm == 0)
  4418. return Expression (targetValue);
  4419. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4420. }
  4421. return Expression (newTerm.release());
  4422. }
  4423. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4424. {
  4425. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4426. if (oldSymbol == newSymbol)
  4427. return *this;
  4428. Expression newExpression (term->clone());
  4429. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4430. return newExpression;
  4431. }
  4432. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4433. {
  4434. return term->referencesSymbol (symbol, context, 0);
  4435. }
  4436. bool Expression::usesAnySymbols() const
  4437. {
  4438. return Helpers::containsAnySymbols (term);
  4439. }
  4440. Expression::Type Expression::getType() const throw()
  4441. {
  4442. return term->getType();
  4443. }
  4444. const String Expression::getSymbol() const
  4445. {
  4446. String objectName, memberName;
  4447. term->getSymbolParts (objectName, memberName);
  4448. return Expression::Helpers::Symbol::joinParts (objectName, memberName);
  4449. }
  4450. void Expression::getSymbolParts (String& objectName, String& memberName) const
  4451. {
  4452. term->getSymbolParts (objectName, memberName);
  4453. }
  4454. const String Expression::getFunction() const
  4455. {
  4456. return term->getFunctionName();
  4457. }
  4458. const String Expression::getOperator() const
  4459. {
  4460. return term->getFunctionName();
  4461. }
  4462. int Expression::getNumInputs() const
  4463. {
  4464. return term->getNumInputs();
  4465. }
  4466. const Expression Expression::getInput (int index) const
  4467. {
  4468. return Expression (term->getInput (index));
  4469. }
  4470. int Expression::Term::getOperatorPrecedence() const
  4471. {
  4472. return 0;
  4473. }
  4474. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4475. {
  4476. return false;
  4477. }
  4478. int Expression::Term::getInputIndexFor (const Term*) const
  4479. {
  4480. return -1;
  4481. }
  4482. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4483. {
  4484. jassertfalse;
  4485. return 0;
  4486. }
  4487. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4488. {
  4489. return new Helpers::Negate (this);
  4490. }
  4491. void Expression::Term::getSymbolParts (String&, String&) const
  4492. {
  4493. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4494. }
  4495. const String Expression::Term::getFunctionName() const
  4496. {
  4497. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4498. return String::empty;
  4499. }
  4500. Expression::ParseError::ParseError (const String& message)
  4501. : description (message)
  4502. {
  4503. DBG ("Expression::ParseError: " + message);
  4504. }
  4505. Expression::EvaluationError::EvaluationError (const String& message)
  4506. : description (message)
  4507. {
  4508. DBG ("Expression::EvaluationError: " + description);
  4509. }
  4510. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4511. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4512. {
  4513. DBG ("Expression::EvaluationError: " + description);
  4514. }
  4515. Expression::EvaluationContext::EvaluationContext() {}
  4516. Expression::EvaluationContext::~EvaluationContext() {}
  4517. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4518. {
  4519. throw EvaluationError (symbol, member);
  4520. }
  4521. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4522. {
  4523. if (numParams > 0)
  4524. {
  4525. if (functionName == "min")
  4526. {
  4527. double v = parameters[0];
  4528. for (int i = 1; i < numParams; ++i)
  4529. v = jmin (v, parameters[i]);
  4530. return v;
  4531. }
  4532. else if (functionName == "max")
  4533. {
  4534. double v = parameters[0];
  4535. for (int i = 1; i < numParams; ++i)
  4536. v = jmax (v, parameters[i]);
  4537. return v;
  4538. }
  4539. else if (numParams == 1)
  4540. {
  4541. if (functionName == "sin") return sin (parameters[0]);
  4542. else if (functionName == "cos") return cos (parameters[0]);
  4543. else if (functionName == "tan") return tan (parameters[0]);
  4544. else if (functionName == "abs") return std::abs (parameters[0]);
  4545. }
  4546. }
  4547. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4548. }
  4549. END_JUCE_NAMESPACE
  4550. /*** End of inlined file: juce_Expression.cpp ***/
  4551. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4552. BEGIN_JUCE_NAMESPACE
  4553. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4554. {
  4555. jassert (keyData != 0);
  4556. jassert (keyBytes > 0);
  4557. static const uint32 initialPValues [18] =
  4558. {
  4559. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4560. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4561. 0x9216d5d9, 0x8979fb1b
  4562. };
  4563. static const uint32 initialSValues [4 * 256] =
  4564. {
  4565. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4566. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4567. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4568. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4569. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4570. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4571. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4572. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4573. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4574. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4575. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4576. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4577. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4578. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4579. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4580. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4581. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4582. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4583. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4584. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4585. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4586. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4587. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4588. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4589. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4590. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4591. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4592. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4593. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4594. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4595. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4596. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4597. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4598. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4599. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4600. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4601. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4602. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4603. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4604. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4605. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4606. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4607. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4608. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4609. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4610. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4611. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4612. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4613. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4614. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4615. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4616. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4617. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4618. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4619. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4620. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4621. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4622. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4623. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4624. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4625. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4626. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4627. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4628. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4629. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4630. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4631. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4632. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4633. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4634. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4635. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4636. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4637. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4638. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4639. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4640. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4641. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4642. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4643. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4644. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4645. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4646. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4647. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4648. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4649. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4650. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4651. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4652. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4653. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4654. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4655. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4656. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4657. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4658. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4659. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4660. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4661. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4662. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4663. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4664. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4665. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4666. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4667. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4668. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4669. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4670. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4671. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4672. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4673. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4674. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4675. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4676. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4677. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4678. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4679. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4680. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4681. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4682. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4683. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4684. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4685. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4686. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4687. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4688. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4689. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4690. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4691. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4692. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4693. };
  4694. memcpy (p, initialPValues, sizeof (p));
  4695. int i, j = 0;
  4696. for (i = 4; --i >= 0;)
  4697. {
  4698. s[i].malloc (256);
  4699. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4700. }
  4701. for (i = 0; i < 18; ++i)
  4702. {
  4703. uint32 d = 0;
  4704. for (int k = 0; k < 4; ++k)
  4705. {
  4706. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4707. if (++j >= keyBytes)
  4708. j = 0;
  4709. }
  4710. p[i] = initialPValues[i] ^ d;
  4711. }
  4712. uint32 l = 0, r = 0;
  4713. for (i = 0; i < 18; i += 2)
  4714. {
  4715. encrypt (l, r);
  4716. p[i] = l;
  4717. p[i + 1] = r;
  4718. }
  4719. for (i = 0; i < 4; ++i)
  4720. {
  4721. for (j = 0; j < 256; j += 2)
  4722. {
  4723. encrypt (l, r);
  4724. s[i][j] = l;
  4725. s[i][j + 1] = r;
  4726. }
  4727. }
  4728. }
  4729. BlowFish::BlowFish (const BlowFish& other)
  4730. {
  4731. for (int i = 4; --i >= 0;)
  4732. s[i].malloc (256);
  4733. operator= (other);
  4734. }
  4735. BlowFish& BlowFish::operator= (const BlowFish& other)
  4736. {
  4737. memcpy (p, other.p, sizeof (p));
  4738. for (int i = 4; --i >= 0;)
  4739. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4740. return *this;
  4741. }
  4742. BlowFish::~BlowFish()
  4743. {
  4744. }
  4745. uint32 BlowFish::F (const uint32 x) const throw()
  4746. {
  4747. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4748. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4749. }
  4750. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4751. {
  4752. uint32 l = data1;
  4753. uint32 r = data2;
  4754. for (int i = 0; i < 16; ++i)
  4755. {
  4756. l ^= p[i];
  4757. r ^= F(l);
  4758. swapVariables (l, r);
  4759. }
  4760. data1 = r ^ p[17];
  4761. data2 = l ^ p[16];
  4762. }
  4763. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4764. {
  4765. uint32 l = data1;
  4766. uint32 r = data2;
  4767. for (int i = 17; i > 1; --i)
  4768. {
  4769. l ^= p[i];
  4770. r ^= F(l);
  4771. swapVariables (l, r);
  4772. }
  4773. data1 = r ^ p[0];
  4774. data2 = l ^ p[1];
  4775. }
  4776. END_JUCE_NAMESPACE
  4777. /*** End of inlined file: juce_BlowFish.cpp ***/
  4778. /*** Start of inlined file: juce_MD5.cpp ***/
  4779. BEGIN_JUCE_NAMESPACE
  4780. MD5::MD5()
  4781. {
  4782. zerostruct (result);
  4783. }
  4784. MD5::MD5 (const MD5& other)
  4785. {
  4786. memcpy (result, other.result, sizeof (result));
  4787. }
  4788. MD5& MD5::operator= (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. return *this;
  4792. }
  4793. MD5::MD5 (const MemoryBlock& data)
  4794. {
  4795. ProcessContext context;
  4796. context.processBlock (data.getData(), data.getSize());
  4797. context.finish (result);
  4798. }
  4799. MD5::MD5 (const void* data, const size_t numBytes)
  4800. {
  4801. ProcessContext context;
  4802. context.processBlock (data, numBytes);
  4803. context.finish (result);
  4804. }
  4805. MD5::MD5 (const String& text)
  4806. {
  4807. ProcessContext context;
  4808. const int len = text.length();
  4809. const juce_wchar* const t = text;
  4810. for (int i = 0; i < len; ++i)
  4811. {
  4812. // force the string into integer-sized unicode characters, to try to make it
  4813. // get the same results on all platforms + compilers.
  4814. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4815. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4816. }
  4817. context.finish (result);
  4818. }
  4819. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4820. {
  4821. ProcessContext context;
  4822. if (numBytesToRead < 0)
  4823. numBytesToRead = std::numeric_limits<int64>::max();
  4824. while (numBytesToRead > 0)
  4825. {
  4826. uint8 tempBuffer [512];
  4827. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4828. if (bytesRead <= 0)
  4829. break;
  4830. numBytesToRead -= bytesRead;
  4831. context.processBlock (tempBuffer, bytesRead);
  4832. }
  4833. context.finish (result);
  4834. }
  4835. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4836. {
  4837. processStream (input, numBytesToRead);
  4838. }
  4839. MD5::MD5 (const File& file)
  4840. {
  4841. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4842. if (fin != 0)
  4843. processStream (*fin, -1);
  4844. else
  4845. zerostruct (result);
  4846. }
  4847. MD5::~MD5()
  4848. {
  4849. }
  4850. namespace MD5Functions
  4851. {
  4852. void encode (void* const output, const void* const input, const int numBytes) throw()
  4853. {
  4854. for (int i = 0; i < (numBytes >> 2); ++i)
  4855. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4856. }
  4857. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4858. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4859. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4860. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4861. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4862. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4863. {
  4864. a += F (b, c, d) + x + ac;
  4865. a = rotateLeft (a, s) + b;
  4866. }
  4867. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4868. {
  4869. a += G (b, c, d) + x + ac;
  4870. a = rotateLeft (a, s) + b;
  4871. }
  4872. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4873. {
  4874. a += H (b, c, d) + x + ac;
  4875. a = rotateLeft (a, s) + b;
  4876. }
  4877. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4878. {
  4879. a += I (b, c, d) + x + ac;
  4880. a = rotateLeft (a, s) + b;
  4881. }
  4882. }
  4883. MD5::ProcessContext::ProcessContext()
  4884. {
  4885. state[0] = 0x67452301;
  4886. state[1] = 0xefcdab89;
  4887. state[2] = 0x98badcfe;
  4888. state[3] = 0x10325476;
  4889. count[0] = 0;
  4890. count[1] = 0;
  4891. }
  4892. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4893. {
  4894. int bufferPos = ((count[0] >> 3) & 0x3F);
  4895. count[0] += (uint32) (dataSize << 3);
  4896. if (count[0] < ((uint32) dataSize << 3))
  4897. count[1]++;
  4898. count[1] += (uint32) (dataSize >> 29);
  4899. const size_t spaceLeft = 64 - bufferPos;
  4900. size_t i = 0;
  4901. if (dataSize >= spaceLeft)
  4902. {
  4903. memcpy (buffer + bufferPos, data, spaceLeft);
  4904. transform (buffer);
  4905. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4906. transform (static_cast <const char*> (data) + i);
  4907. bufferPos = 0;
  4908. }
  4909. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4910. }
  4911. void MD5::ProcessContext::finish (void* const result)
  4912. {
  4913. unsigned char encodedLength[8];
  4914. MD5Functions::encode (encodedLength, count, 8);
  4915. // Pad out to 56 mod 64.
  4916. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4917. const int paddingLength = (index < 56) ? (56 - index)
  4918. : (120 - index);
  4919. uint8 paddingBuffer [64];
  4920. zeromem (paddingBuffer, paddingLength);
  4921. paddingBuffer [0] = 0x80;
  4922. processBlock (paddingBuffer, paddingLength);
  4923. processBlock (encodedLength, 8);
  4924. MD5Functions::encode (result, state, 16);
  4925. zerostruct (buffer);
  4926. }
  4927. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4928. {
  4929. using namespace MD5Functions;
  4930. uint32 a = state[0];
  4931. uint32 b = state[1];
  4932. uint32 c = state[2];
  4933. uint32 d = state[3];
  4934. uint32 x[16];
  4935. encode (x, bufferToTransform, 64);
  4936. enum Constants
  4937. {
  4938. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4939. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4940. };
  4941. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4942. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4943. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4944. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4945. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4946. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4947. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4948. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4949. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4950. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4951. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4952. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4953. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4954. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4955. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4956. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4957. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4958. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4959. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4960. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4961. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4962. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4963. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4964. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4965. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4966. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4967. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4968. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4969. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4970. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4971. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4972. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4973. state[0] += a;
  4974. state[1] += b;
  4975. state[2] += c;
  4976. state[3] += d;
  4977. zerostruct (x);
  4978. }
  4979. const MemoryBlock MD5::getRawChecksumData() const
  4980. {
  4981. return MemoryBlock (result, sizeof (result));
  4982. }
  4983. const String MD5::toHexString() const
  4984. {
  4985. return String::toHexString (result, sizeof (result), 0);
  4986. }
  4987. bool MD5::operator== (const MD5& other) const
  4988. {
  4989. return memcmp (result, other.result, sizeof (result)) == 0;
  4990. }
  4991. bool MD5::operator!= (const MD5& other) const
  4992. {
  4993. return ! operator== (other);
  4994. }
  4995. END_JUCE_NAMESPACE
  4996. /*** End of inlined file: juce_MD5.cpp ***/
  4997. /*** Start of inlined file: juce_Primes.cpp ***/
  4998. BEGIN_JUCE_NAMESPACE
  4999. namespace PrimesHelpers
  5000. {
  5001. void createSmallSieve (const int numBits, BigInteger& result)
  5002. {
  5003. result.setBit (numBits);
  5004. result.clearBit (numBits); // to enlarge the array
  5005. result.setBit (0);
  5006. int n = 2;
  5007. do
  5008. {
  5009. for (int i = n + n; i < numBits; i += n)
  5010. result.setBit (i);
  5011. n = result.findNextClearBit (n + 1);
  5012. }
  5013. while (n <= (numBits >> 1));
  5014. }
  5015. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5016. const BigInteger& smallSieve, const int smallSieveSize)
  5017. {
  5018. jassert (! base[0]); // must be even!
  5019. result.setBit (numBits);
  5020. result.clearBit (numBits); // to enlarge the array
  5021. int index = smallSieve.findNextClearBit (0);
  5022. do
  5023. {
  5024. const int prime = (index << 1) + 1;
  5025. BigInteger r (base), remainder;
  5026. r.divideBy (prime, remainder);
  5027. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5028. if (r.isZero())
  5029. i += prime;
  5030. if ((i & 1) == 0)
  5031. i += prime;
  5032. i = (i - 1) >> 1;
  5033. while (i < numBits)
  5034. {
  5035. result.setBit (i);
  5036. i += prime;
  5037. }
  5038. index = smallSieve.findNextClearBit (index + 1);
  5039. }
  5040. while (index < smallSieveSize);
  5041. }
  5042. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5043. const int numBits, BigInteger& result, const int certainty)
  5044. {
  5045. for (int i = 0; i < numBits; ++i)
  5046. {
  5047. if (! sieve[i])
  5048. {
  5049. result = base + (unsigned int) ((i << 1) + 1);
  5050. if (Primes::isProbablyPrime (result, certainty))
  5051. return true;
  5052. }
  5053. }
  5054. return false;
  5055. }
  5056. bool passesMillerRabin (const BigInteger& n, int iterations)
  5057. {
  5058. const BigInteger one (1), two (2);
  5059. const BigInteger nMinusOne (n - one);
  5060. BigInteger d (nMinusOne);
  5061. const int s = d.findNextSetBit (0);
  5062. d >>= s;
  5063. BigInteger smallPrimes;
  5064. int numBitsInSmallPrimes = 0;
  5065. for (;;)
  5066. {
  5067. numBitsInSmallPrimes += 256;
  5068. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5069. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5070. if (numPrimesFound > iterations + 1)
  5071. break;
  5072. }
  5073. int smallPrime = 2;
  5074. while (--iterations >= 0)
  5075. {
  5076. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5077. BigInteger r (smallPrime);
  5078. r.exponentModulo (d, n);
  5079. if (r != one && r != nMinusOne)
  5080. {
  5081. for (int j = 0; j < s; ++j)
  5082. {
  5083. r.exponentModulo (two, n);
  5084. if (r == nMinusOne)
  5085. break;
  5086. }
  5087. if (r != nMinusOne)
  5088. return false;
  5089. }
  5090. }
  5091. return true;
  5092. }
  5093. }
  5094. const BigInteger Primes::createProbablePrime (const int bitLength,
  5095. const int certainty,
  5096. const int* randomSeeds,
  5097. int numRandomSeeds)
  5098. {
  5099. using namespace PrimesHelpers;
  5100. int defaultSeeds [16];
  5101. if (numRandomSeeds <= 0)
  5102. {
  5103. randomSeeds = defaultSeeds;
  5104. numRandomSeeds = numElementsInArray (defaultSeeds);
  5105. Random r (0);
  5106. for (int j = 10; --j >= 0;)
  5107. {
  5108. r.setSeedRandomly();
  5109. for (int i = numRandomSeeds; --i >= 0;)
  5110. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5111. }
  5112. }
  5113. BigInteger smallSieve;
  5114. const int smallSieveSize = 15000;
  5115. createSmallSieve (smallSieveSize, smallSieve);
  5116. BigInteger p;
  5117. for (int i = numRandomSeeds; --i >= 0;)
  5118. {
  5119. BigInteger p2;
  5120. Random r (randomSeeds[i]);
  5121. r.fillBitsRandomly (p2, 0, bitLength);
  5122. p ^= p2;
  5123. }
  5124. p.setBit (bitLength - 1);
  5125. p.clearBit (0);
  5126. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5127. while (p.getHighestBit() < bitLength)
  5128. {
  5129. p += 2 * searchLen;
  5130. BigInteger sieve;
  5131. bigSieve (p, searchLen, sieve,
  5132. smallSieve, smallSieveSize);
  5133. BigInteger candidate;
  5134. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5135. return candidate;
  5136. }
  5137. jassertfalse;
  5138. return BigInteger();
  5139. }
  5140. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5141. {
  5142. using namespace PrimesHelpers;
  5143. if (! number[0])
  5144. return false;
  5145. if (number.getHighestBit() <= 10)
  5146. {
  5147. const int num = number.getBitRangeAsInt (0, 10);
  5148. for (int i = num / 2; --i > 1;)
  5149. if (num % i == 0)
  5150. return false;
  5151. return true;
  5152. }
  5153. else
  5154. {
  5155. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5156. return false;
  5157. return passesMillerRabin (number, certainty);
  5158. }
  5159. }
  5160. END_JUCE_NAMESPACE
  5161. /*** End of inlined file: juce_Primes.cpp ***/
  5162. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5163. BEGIN_JUCE_NAMESPACE
  5164. RSAKey::RSAKey()
  5165. {
  5166. }
  5167. RSAKey::RSAKey (const String& s)
  5168. {
  5169. if (s.containsChar (','))
  5170. {
  5171. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5172. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5173. }
  5174. else
  5175. {
  5176. // the string needs to be two hex numbers, comma-separated..
  5177. jassertfalse;
  5178. }
  5179. }
  5180. RSAKey::~RSAKey()
  5181. {
  5182. }
  5183. bool RSAKey::operator== (const RSAKey& other) const throw()
  5184. {
  5185. return part1 == other.part1 && part2 == other.part2;
  5186. }
  5187. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5188. {
  5189. return ! operator== (other);
  5190. }
  5191. const String RSAKey::toString() const
  5192. {
  5193. return part1.toString (16) + "," + part2.toString (16);
  5194. }
  5195. bool RSAKey::applyToValue (BigInteger& value) const
  5196. {
  5197. if (part1.isZero() || part2.isZero() || value <= 0)
  5198. {
  5199. jassertfalse; // using an uninitialised key
  5200. value.clear();
  5201. return false;
  5202. }
  5203. BigInteger result;
  5204. while (! value.isZero())
  5205. {
  5206. result *= part2;
  5207. BigInteger remainder;
  5208. value.divideBy (part2, remainder);
  5209. remainder.exponentModulo (part1, part2);
  5210. result += remainder;
  5211. }
  5212. value.swapWith (result);
  5213. return true;
  5214. }
  5215. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5216. {
  5217. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5218. // are fast to divide + multiply
  5219. for (int i = 2; i <= 65536; i *= 2)
  5220. {
  5221. const BigInteger e (1 + i);
  5222. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5223. return e;
  5224. }
  5225. BigInteger e (4);
  5226. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5227. ++e;
  5228. return e;
  5229. }
  5230. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5231. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5232. {
  5233. jassert (numBits > 16); // not much point using less than this..
  5234. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5235. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5236. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5237. const BigInteger n (p * q);
  5238. const BigInteger m (--p * --q);
  5239. const BigInteger e (findBestCommonDivisor (p, q));
  5240. BigInteger d (e);
  5241. d.inverseModulo (m);
  5242. publicKey.part1 = e;
  5243. publicKey.part2 = n;
  5244. privateKey.part1 = d;
  5245. privateKey.part2 = n;
  5246. }
  5247. END_JUCE_NAMESPACE
  5248. /*** End of inlined file: juce_RSAKey.cpp ***/
  5249. /*** Start of inlined file: juce_InputStream.cpp ***/
  5250. BEGIN_JUCE_NAMESPACE
  5251. char InputStream::readByte()
  5252. {
  5253. char temp = 0;
  5254. read (&temp, 1);
  5255. return temp;
  5256. }
  5257. bool InputStream::readBool()
  5258. {
  5259. return readByte() != 0;
  5260. }
  5261. short InputStream::readShort()
  5262. {
  5263. char temp[2];
  5264. if (read (temp, 2) == 2)
  5265. return (short) ByteOrder::littleEndianShort (temp);
  5266. return 0;
  5267. }
  5268. short InputStream::readShortBigEndian()
  5269. {
  5270. char temp[2];
  5271. if (read (temp, 2) == 2)
  5272. return (short) ByteOrder::bigEndianShort (temp);
  5273. return 0;
  5274. }
  5275. int InputStream::readInt()
  5276. {
  5277. char temp[4];
  5278. if (read (temp, 4) == 4)
  5279. return (int) ByteOrder::littleEndianInt (temp);
  5280. return 0;
  5281. }
  5282. int InputStream::readIntBigEndian()
  5283. {
  5284. char temp[4];
  5285. if (read (temp, 4) == 4)
  5286. return (int) ByteOrder::bigEndianInt (temp);
  5287. return 0;
  5288. }
  5289. int InputStream::readCompressedInt()
  5290. {
  5291. const unsigned char sizeByte = readByte();
  5292. if (sizeByte == 0)
  5293. return 0;
  5294. const int numBytes = (sizeByte & 0x7f);
  5295. if (numBytes > 4)
  5296. {
  5297. jassertfalse; // trying to read corrupt data - this method must only be used
  5298. // to read data that was written by OutputStream::writeCompressedInt()
  5299. return 0;
  5300. }
  5301. char bytes[4] = { 0, 0, 0, 0 };
  5302. if (read (bytes, numBytes) != numBytes)
  5303. return 0;
  5304. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5305. return (sizeByte >> 7) ? -num : num;
  5306. }
  5307. int64 InputStream::readInt64()
  5308. {
  5309. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5310. if (read (n.asBytes, 8) == 8)
  5311. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5312. return 0;
  5313. }
  5314. int64 InputStream::readInt64BigEndian()
  5315. {
  5316. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5317. if (read (n.asBytes, 8) == 8)
  5318. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5319. return 0;
  5320. }
  5321. float InputStream::readFloat()
  5322. {
  5323. // the union below relies on these types being the same size...
  5324. static_jassert (sizeof (int32) == sizeof (float));
  5325. union { int32 asInt; float asFloat; } n;
  5326. n.asInt = (int32) readInt();
  5327. return n.asFloat;
  5328. }
  5329. float InputStream::readFloatBigEndian()
  5330. {
  5331. union { int32 asInt; float asFloat; } n;
  5332. n.asInt = (int32) readIntBigEndian();
  5333. return n.asFloat;
  5334. }
  5335. double InputStream::readDouble()
  5336. {
  5337. union { int64 asInt; double asDouble; } n;
  5338. n.asInt = readInt64();
  5339. return n.asDouble;
  5340. }
  5341. double InputStream::readDoubleBigEndian()
  5342. {
  5343. union { int64 asInt; double asDouble; } n;
  5344. n.asInt = readInt64BigEndian();
  5345. return n.asDouble;
  5346. }
  5347. const String InputStream::readString()
  5348. {
  5349. MemoryBlock buffer (256);
  5350. char* data = static_cast<char*> (buffer.getData());
  5351. size_t i = 0;
  5352. while ((data[i] = readByte()) != 0)
  5353. {
  5354. if (++i >= buffer.getSize())
  5355. {
  5356. buffer.setSize (buffer.getSize() + 512);
  5357. data = static_cast<char*> (buffer.getData());
  5358. }
  5359. }
  5360. return String::fromUTF8 (data, (int) i);
  5361. }
  5362. const String InputStream::readNextLine()
  5363. {
  5364. MemoryBlock buffer (256);
  5365. char* data = static_cast<char*> (buffer.getData());
  5366. size_t i = 0;
  5367. while ((data[i] = readByte()) != 0)
  5368. {
  5369. if (data[i] == '\n')
  5370. break;
  5371. if (data[i] == '\r')
  5372. {
  5373. const int64 lastPos = getPosition();
  5374. if (readByte() != '\n')
  5375. setPosition (lastPos);
  5376. break;
  5377. }
  5378. if (++i >= buffer.getSize())
  5379. {
  5380. buffer.setSize (buffer.getSize() + 512);
  5381. data = static_cast<char*> (buffer.getData());
  5382. }
  5383. }
  5384. return String::fromUTF8 (data, (int) i);
  5385. }
  5386. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5387. {
  5388. MemoryOutputStream mo (block, true);
  5389. return mo.writeFromInputStream (*this, numBytes);
  5390. }
  5391. const String InputStream::readEntireStreamAsString()
  5392. {
  5393. MemoryOutputStream mo;
  5394. mo.writeFromInputStream (*this, -1);
  5395. return mo.toString();
  5396. }
  5397. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5398. {
  5399. if (numBytesToSkip > 0)
  5400. {
  5401. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5402. HeapBlock<char> temp (skipBufferSize);
  5403. while (numBytesToSkip > 0 && ! isExhausted())
  5404. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5405. }
  5406. }
  5407. END_JUCE_NAMESPACE
  5408. /*** End of inlined file: juce_InputStream.cpp ***/
  5409. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5410. BEGIN_JUCE_NAMESPACE
  5411. #if JUCE_DEBUG
  5412. static Array<void*, CriticalSection> activeStreams;
  5413. void juce_CheckForDanglingStreams()
  5414. {
  5415. /*
  5416. It's always a bad idea to leak any object, but if you're leaking output
  5417. streams, then there's a good chance that you're failing to flush a file
  5418. to disk properly, which could result in corrupted data and other similar
  5419. nastiness..
  5420. */
  5421. jassert (activeStreams.size() == 0);
  5422. };
  5423. #endif
  5424. OutputStream::OutputStream()
  5425. : newLineString (NewLine::getDefault())
  5426. {
  5427. #if JUCE_DEBUG
  5428. activeStreams.add (this);
  5429. #endif
  5430. }
  5431. OutputStream::~OutputStream()
  5432. {
  5433. #if JUCE_DEBUG
  5434. activeStreams.removeValue (this);
  5435. #endif
  5436. }
  5437. void OutputStream::writeBool (const bool b)
  5438. {
  5439. writeByte (b ? (char) 1
  5440. : (char) 0);
  5441. }
  5442. void OutputStream::writeByte (char byte)
  5443. {
  5444. write (&byte, 1);
  5445. }
  5446. void OutputStream::writeShort (short value)
  5447. {
  5448. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5449. write (&v, 2);
  5450. }
  5451. void OutputStream::writeShortBigEndian (short value)
  5452. {
  5453. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5454. write (&v, 2);
  5455. }
  5456. void OutputStream::writeInt (int value)
  5457. {
  5458. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5459. write (&v, 4);
  5460. }
  5461. void OutputStream::writeIntBigEndian (int value)
  5462. {
  5463. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5464. write (&v, 4);
  5465. }
  5466. void OutputStream::writeCompressedInt (int value)
  5467. {
  5468. unsigned int un = (value < 0) ? (unsigned int) -value
  5469. : (unsigned int) value;
  5470. uint8 data[5];
  5471. int num = 0;
  5472. while (un > 0)
  5473. {
  5474. data[++num] = (uint8) un;
  5475. un >>= 8;
  5476. }
  5477. data[0] = (uint8) num;
  5478. if (value < 0)
  5479. data[0] |= 0x80;
  5480. write (data, num + 1);
  5481. }
  5482. void OutputStream::writeInt64 (int64 value)
  5483. {
  5484. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5485. write (&v, 8);
  5486. }
  5487. void OutputStream::writeInt64BigEndian (int64 value)
  5488. {
  5489. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5490. write (&v, 8);
  5491. }
  5492. void OutputStream::writeFloat (float value)
  5493. {
  5494. union { int asInt; float asFloat; } n;
  5495. n.asFloat = value;
  5496. writeInt (n.asInt);
  5497. }
  5498. void OutputStream::writeFloatBigEndian (float value)
  5499. {
  5500. union { int asInt; float asFloat; } n;
  5501. n.asFloat = value;
  5502. writeIntBigEndian (n.asInt);
  5503. }
  5504. void OutputStream::writeDouble (double value)
  5505. {
  5506. union { int64 asInt; double asDouble; } n;
  5507. n.asDouble = value;
  5508. writeInt64 (n.asInt);
  5509. }
  5510. void OutputStream::writeDoubleBigEndian (double value)
  5511. {
  5512. union { int64 asInt; double asDouble; } n;
  5513. n.asDouble = value;
  5514. writeInt64BigEndian (n.asInt);
  5515. }
  5516. void OutputStream::writeString (const String& text)
  5517. {
  5518. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5519. // if lots of large, persistent strings were to be written to streams).
  5520. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5521. HeapBlock<char> temp (numBytes);
  5522. text.copyToUTF8 (temp, numBytes);
  5523. write (temp, numBytes);
  5524. }
  5525. void OutputStream::writeText (const String& text, const bool asUnicode,
  5526. const bool writeUnicodeHeaderBytes)
  5527. {
  5528. if (asUnicode)
  5529. {
  5530. if (writeUnicodeHeaderBytes)
  5531. write ("\x0ff\x0fe", 2);
  5532. const juce_wchar* src = text;
  5533. bool lastCharWasReturn = false;
  5534. while (*src != 0)
  5535. {
  5536. if (*src == L'\n' && ! lastCharWasReturn)
  5537. writeShort ((short) L'\r');
  5538. lastCharWasReturn = (*src == L'\r');
  5539. writeShort ((short) *src++);
  5540. }
  5541. }
  5542. else
  5543. {
  5544. const char* src = text.toUTF8();
  5545. const char* t = src;
  5546. for (;;)
  5547. {
  5548. if (*t == '\n')
  5549. {
  5550. if (t > src)
  5551. write (src, (int) (t - src));
  5552. write ("\r\n", 2);
  5553. src = t + 1;
  5554. }
  5555. else if (*t == '\r')
  5556. {
  5557. if (t[1] == '\n')
  5558. ++t;
  5559. }
  5560. else if (*t == 0)
  5561. {
  5562. if (t > src)
  5563. write (src, (int) (t - src));
  5564. break;
  5565. }
  5566. ++t;
  5567. }
  5568. }
  5569. }
  5570. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5571. {
  5572. if (numBytesToWrite < 0)
  5573. numBytesToWrite = std::numeric_limits<int64>::max();
  5574. int numWritten = 0;
  5575. while (numBytesToWrite > 0 && ! source.isExhausted())
  5576. {
  5577. char buffer [8192];
  5578. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5579. if (num <= 0)
  5580. break;
  5581. write (buffer, num);
  5582. numBytesToWrite -= num;
  5583. numWritten += num;
  5584. }
  5585. return numWritten;
  5586. }
  5587. void OutputStream::setNewLineString (const String& newLineString_)
  5588. {
  5589. newLineString = newLineString_;
  5590. }
  5591. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5592. {
  5593. return stream << String (number);
  5594. }
  5595. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5596. {
  5597. return stream << String (number);
  5598. }
  5599. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5600. {
  5601. stream.writeByte (character);
  5602. return stream;
  5603. }
  5604. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5605. {
  5606. stream.write (text, (int) strlen (text));
  5607. return stream;
  5608. }
  5609. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5610. {
  5611. stream.write (data.getData(), (int) data.getSize());
  5612. return stream;
  5613. }
  5614. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5615. {
  5616. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5617. if (in != 0)
  5618. stream.writeFromInputStream (*in, -1);
  5619. return stream;
  5620. }
  5621. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5622. {
  5623. return stream << stream.getNewLineString();
  5624. }
  5625. END_JUCE_NAMESPACE
  5626. /*** End of inlined file: juce_OutputStream.cpp ***/
  5627. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5628. BEGIN_JUCE_NAMESPACE
  5629. DirectoryIterator::DirectoryIterator (const File& directory,
  5630. bool isRecursive_,
  5631. const String& wildCard_,
  5632. const int whatToLookFor_)
  5633. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5634. wildCard (wildCard_),
  5635. path (File::addTrailingSeparator (directory.getFullPathName())),
  5636. index (-1),
  5637. totalNumFiles (-1),
  5638. whatToLookFor (whatToLookFor_),
  5639. isRecursive (isRecursive_),
  5640. hasBeenAdvanced (false)
  5641. {
  5642. // you have to specify the type of files you're looking for!
  5643. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5644. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5645. }
  5646. DirectoryIterator::~DirectoryIterator()
  5647. {
  5648. }
  5649. bool DirectoryIterator::next()
  5650. {
  5651. return next (0, 0, 0, 0, 0, 0);
  5652. }
  5653. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5654. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5655. {
  5656. hasBeenAdvanced = true;
  5657. if (subIterator != 0)
  5658. {
  5659. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5660. return true;
  5661. subIterator = 0;
  5662. }
  5663. String filename;
  5664. bool isDirectory, isHidden;
  5665. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5666. {
  5667. ++index;
  5668. if (! filename.containsOnly ("."))
  5669. {
  5670. const File fileFound (path + filename, 0);
  5671. bool matches = false;
  5672. if (isDirectory)
  5673. {
  5674. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5675. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5676. matches = (whatToLookFor & File::findDirectories) != 0;
  5677. }
  5678. else
  5679. {
  5680. matches = (whatToLookFor & File::findFiles) != 0;
  5681. }
  5682. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5683. if (matches && isRecursive)
  5684. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5685. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5686. matches = ! isHidden;
  5687. if (matches)
  5688. {
  5689. currentFile = fileFound;
  5690. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5691. if (isDirResult != 0) *isDirResult = isDirectory;
  5692. return true;
  5693. }
  5694. else if (subIterator != 0)
  5695. {
  5696. return next();
  5697. }
  5698. }
  5699. }
  5700. return false;
  5701. }
  5702. const File DirectoryIterator::getFile() const
  5703. {
  5704. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5705. return subIterator->getFile();
  5706. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5707. jassert (hasBeenAdvanced);
  5708. return currentFile;
  5709. }
  5710. float DirectoryIterator::getEstimatedProgress() const
  5711. {
  5712. if (totalNumFiles < 0)
  5713. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5714. if (totalNumFiles <= 0)
  5715. return 0.0f;
  5716. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5717. : (float) index;
  5718. return detailedIndex / totalNumFiles;
  5719. }
  5720. END_JUCE_NAMESPACE
  5721. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5722. /*** Start of inlined file: juce_File.cpp ***/
  5723. #if ! JUCE_WINDOWS
  5724. #include <pwd.h>
  5725. #endif
  5726. BEGIN_JUCE_NAMESPACE
  5727. File::File (const String& fullPathName)
  5728. : fullPath (parseAbsolutePath (fullPathName))
  5729. {
  5730. }
  5731. File::File (const String& path, int)
  5732. : fullPath (path)
  5733. {
  5734. }
  5735. const File File::createFileWithoutCheckingPath (const String& path)
  5736. {
  5737. return File (path, 0);
  5738. }
  5739. File::File (const File& other)
  5740. : fullPath (other.fullPath)
  5741. {
  5742. }
  5743. File& File::operator= (const String& newPath)
  5744. {
  5745. fullPath = parseAbsolutePath (newPath);
  5746. return *this;
  5747. }
  5748. File& File::operator= (const File& other)
  5749. {
  5750. fullPath = other.fullPath;
  5751. return *this;
  5752. }
  5753. const File File::nonexistent;
  5754. const String File::parseAbsolutePath (const String& p)
  5755. {
  5756. if (p.isEmpty())
  5757. return String::empty;
  5758. #if JUCE_WINDOWS
  5759. // Windows..
  5760. String path (p.replaceCharacter ('/', '\\'));
  5761. if (path.startsWithChar (File::separator))
  5762. {
  5763. if (path[1] != File::separator)
  5764. {
  5765. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5766. If you're trying to parse a string that may be either a relative path or an absolute path,
  5767. you MUST provide a context against which the partial path can be evaluated - you can do
  5768. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5769. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5770. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5771. */
  5772. jassertfalse;
  5773. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5774. }
  5775. }
  5776. else if (! path.containsChar (':'))
  5777. {
  5778. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5779. If you're trying to parse a string that may be either a relative path or an absolute path,
  5780. you MUST provide a context against which the partial path can be evaluated - you can do
  5781. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5782. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5783. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5784. */
  5785. jassertfalse;
  5786. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5787. }
  5788. #else
  5789. // Mac or Linux..
  5790. String path (p.replaceCharacter ('\\', '/'));
  5791. if (path.startsWithChar ('~'))
  5792. {
  5793. if (path[1] == File::separator || path[1] == 0)
  5794. {
  5795. // expand a name of the form "~/abc"
  5796. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5797. + path.substring (1);
  5798. }
  5799. else
  5800. {
  5801. // expand a name of type "~dave/abc"
  5802. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5803. struct passwd* const pw = getpwnam (userName.toUTF8());
  5804. if (pw != 0)
  5805. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5806. }
  5807. }
  5808. else if (! path.startsWithChar (File::separator))
  5809. {
  5810. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5811. If you're trying to parse a string that may be either a relative path or an absolute path,
  5812. you MUST provide a context against which the partial path can be evaluated - you can do
  5813. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5814. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5815. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5816. */
  5817. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5818. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5819. }
  5820. #endif
  5821. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5822. path = path.dropLastCharacters (1);
  5823. return path;
  5824. }
  5825. const String File::addTrailingSeparator (const String& path)
  5826. {
  5827. return path.endsWithChar (File::separator) ? path
  5828. : path + File::separator;
  5829. }
  5830. #if JUCE_LINUX
  5831. #define NAMES_ARE_CASE_SENSITIVE 1
  5832. #endif
  5833. bool File::areFileNamesCaseSensitive()
  5834. {
  5835. #if NAMES_ARE_CASE_SENSITIVE
  5836. return true;
  5837. #else
  5838. return false;
  5839. #endif
  5840. }
  5841. bool File::operator== (const File& other) const
  5842. {
  5843. #if NAMES_ARE_CASE_SENSITIVE
  5844. return fullPath == other.fullPath;
  5845. #else
  5846. return fullPath.equalsIgnoreCase (other.fullPath);
  5847. #endif
  5848. }
  5849. bool File::operator!= (const File& other) const
  5850. {
  5851. return ! operator== (other);
  5852. }
  5853. bool File::operator< (const File& other) const
  5854. {
  5855. #if NAMES_ARE_CASE_SENSITIVE
  5856. return fullPath < other.fullPath;
  5857. #else
  5858. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5859. #endif
  5860. }
  5861. bool File::operator> (const File& other) const
  5862. {
  5863. #if NAMES_ARE_CASE_SENSITIVE
  5864. return fullPath > other.fullPath;
  5865. #else
  5866. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5867. #endif
  5868. }
  5869. bool File::setReadOnly (const bool shouldBeReadOnly,
  5870. const bool applyRecursively) const
  5871. {
  5872. bool worked = true;
  5873. if (applyRecursively && isDirectory())
  5874. {
  5875. Array <File> subFiles;
  5876. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5877. for (int i = subFiles.size(); --i >= 0;)
  5878. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5879. }
  5880. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5881. }
  5882. bool File::deleteRecursively() const
  5883. {
  5884. bool worked = true;
  5885. if (isDirectory())
  5886. {
  5887. Array<File> subFiles;
  5888. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5889. for (int i = subFiles.size(); --i >= 0;)
  5890. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5891. }
  5892. return deleteFile() && worked;
  5893. }
  5894. bool File::moveFileTo (const File& newFile) const
  5895. {
  5896. if (newFile.fullPath == fullPath)
  5897. return true;
  5898. #if ! NAMES_ARE_CASE_SENSITIVE
  5899. if (*this != newFile)
  5900. #endif
  5901. if (! newFile.deleteFile())
  5902. return false;
  5903. return moveInternal (newFile);
  5904. }
  5905. bool File::copyFileTo (const File& newFile) const
  5906. {
  5907. return (*this == newFile)
  5908. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5909. }
  5910. bool File::copyDirectoryTo (const File& newDirectory) const
  5911. {
  5912. if (isDirectory() && newDirectory.createDirectory())
  5913. {
  5914. Array<File> subFiles;
  5915. findChildFiles (subFiles, File::findFiles, false);
  5916. int i;
  5917. for (i = 0; i < subFiles.size(); ++i)
  5918. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5919. return false;
  5920. subFiles.clear();
  5921. findChildFiles (subFiles, File::findDirectories, false);
  5922. for (i = 0; i < subFiles.size(); ++i)
  5923. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5924. return false;
  5925. return true;
  5926. }
  5927. return false;
  5928. }
  5929. const String File::getPathUpToLastSlash() const
  5930. {
  5931. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5932. if (lastSlash > 0)
  5933. return fullPath.substring (0, lastSlash);
  5934. else if (lastSlash == 0)
  5935. return separatorString;
  5936. else
  5937. return fullPath;
  5938. }
  5939. const File File::getParentDirectory() const
  5940. {
  5941. return File (getPathUpToLastSlash(), (int) 0);
  5942. }
  5943. const String File::getFileName() const
  5944. {
  5945. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5946. }
  5947. int File::hashCode() const
  5948. {
  5949. return fullPath.hashCode();
  5950. }
  5951. int64 File::hashCode64() const
  5952. {
  5953. return fullPath.hashCode64();
  5954. }
  5955. const String File::getFileNameWithoutExtension() const
  5956. {
  5957. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5958. const int lastDot = fullPath.lastIndexOfChar ('.');
  5959. if (lastDot > lastSlash)
  5960. return fullPath.substring (lastSlash, lastDot);
  5961. else
  5962. return fullPath.substring (lastSlash);
  5963. }
  5964. bool File::isAChildOf (const File& potentialParent) const
  5965. {
  5966. if (potentialParent == File::nonexistent)
  5967. return false;
  5968. const String ourPath (getPathUpToLastSlash());
  5969. #if NAMES_ARE_CASE_SENSITIVE
  5970. if (potentialParent.fullPath == ourPath)
  5971. #else
  5972. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5973. #endif
  5974. {
  5975. return true;
  5976. }
  5977. else if (potentialParent.fullPath.length() >= ourPath.length())
  5978. {
  5979. return false;
  5980. }
  5981. else
  5982. {
  5983. return getParentDirectory().isAChildOf (potentialParent);
  5984. }
  5985. }
  5986. bool File::isAbsolutePath (const String& path)
  5987. {
  5988. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5989. #if JUCE_WINDOWS
  5990. || (path.isNotEmpty() && path[1] == ':');
  5991. #else
  5992. || path.startsWithChar ('~');
  5993. #endif
  5994. }
  5995. const File File::getChildFile (String relativePath) const
  5996. {
  5997. if (isAbsolutePath (relativePath))
  5998. {
  5999. // the path is really absolute..
  6000. return File (relativePath);
  6001. }
  6002. else
  6003. {
  6004. // it's relative, so remove any ../ or ./ bits at the start.
  6005. String path (fullPath);
  6006. if (relativePath[0] == '.')
  6007. {
  6008. #if JUCE_WINDOWS
  6009. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6010. #else
  6011. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6012. #endif
  6013. while (relativePath[0] == '.')
  6014. {
  6015. if (relativePath[1] == '.')
  6016. {
  6017. if (relativePath [2] == 0 || relativePath[2] == separator)
  6018. {
  6019. const int lastSlash = path.lastIndexOfChar (separator);
  6020. if (lastSlash >= 0)
  6021. path = path.substring (0, lastSlash);
  6022. relativePath = relativePath.substring (3);
  6023. }
  6024. else
  6025. {
  6026. break;
  6027. }
  6028. }
  6029. else if (relativePath[1] == separator)
  6030. {
  6031. relativePath = relativePath.substring (2);
  6032. }
  6033. else
  6034. {
  6035. break;
  6036. }
  6037. }
  6038. }
  6039. return File (addTrailingSeparator (path) + relativePath);
  6040. }
  6041. }
  6042. const File File::getSiblingFile (const String& fileName) const
  6043. {
  6044. return getParentDirectory().getChildFile (fileName);
  6045. }
  6046. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6047. {
  6048. if (bytes == 1)
  6049. {
  6050. return "1 byte";
  6051. }
  6052. else if (bytes < 1024)
  6053. {
  6054. return String ((int) bytes) + " bytes";
  6055. }
  6056. else if (bytes < 1024 * 1024)
  6057. {
  6058. return String (bytes / 1024.0, 1) + " KB";
  6059. }
  6060. else if (bytes < 1024 * 1024 * 1024)
  6061. {
  6062. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6063. }
  6064. else
  6065. {
  6066. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6067. }
  6068. }
  6069. bool File::create() const
  6070. {
  6071. if (exists())
  6072. return true;
  6073. {
  6074. const File parentDir (getParentDirectory());
  6075. if (parentDir == *this || ! parentDir.createDirectory())
  6076. return false;
  6077. FileOutputStream fo (*this, 8);
  6078. }
  6079. return exists();
  6080. }
  6081. bool File::createDirectory() const
  6082. {
  6083. if (! isDirectory())
  6084. {
  6085. const File parentDir (getParentDirectory());
  6086. if (parentDir == *this || ! parentDir.createDirectory())
  6087. return false;
  6088. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6089. return isDirectory();
  6090. }
  6091. return true;
  6092. }
  6093. const Time File::getCreationTime() const
  6094. {
  6095. int64 m, a, c;
  6096. getFileTimesInternal (m, a, c);
  6097. return Time (c);
  6098. }
  6099. const Time File::getLastModificationTime() const
  6100. {
  6101. int64 m, a, c;
  6102. getFileTimesInternal (m, a, c);
  6103. return Time (m);
  6104. }
  6105. const Time File::getLastAccessTime() const
  6106. {
  6107. int64 m, a, c;
  6108. getFileTimesInternal (m, a, c);
  6109. return Time (a);
  6110. }
  6111. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6112. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6113. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6114. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6115. {
  6116. if (! existsAsFile())
  6117. return false;
  6118. FileInputStream in (*this);
  6119. return getSize() == in.readIntoMemoryBlock (destBlock);
  6120. }
  6121. const String File::loadFileAsString() const
  6122. {
  6123. if (! existsAsFile())
  6124. return String::empty;
  6125. FileInputStream in (*this);
  6126. return in.readEntireStreamAsString();
  6127. }
  6128. int File::findChildFiles (Array<File>& results,
  6129. const int whatToLookFor,
  6130. const bool searchRecursively,
  6131. const String& wildCardPattern) const
  6132. {
  6133. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6134. int total = 0;
  6135. while (di.next())
  6136. {
  6137. results.add (di.getFile());
  6138. ++total;
  6139. }
  6140. return total;
  6141. }
  6142. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6143. {
  6144. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6145. int total = 0;
  6146. while (di.next())
  6147. ++total;
  6148. return total;
  6149. }
  6150. bool File::containsSubDirectories() const
  6151. {
  6152. if (isDirectory())
  6153. {
  6154. DirectoryIterator di (*this, false, "*", findDirectories);
  6155. return di.next();
  6156. }
  6157. return false;
  6158. }
  6159. const File File::getNonexistentChildFile (const String& prefix_,
  6160. const String& suffix,
  6161. bool putNumbersInBrackets) const
  6162. {
  6163. File f (getChildFile (prefix_ + suffix));
  6164. if (f.exists())
  6165. {
  6166. int num = 2;
  6167. String prefix (prefix_);
  6168. // remove any bracketed numbers that may already be on the end..
  6169. if (prefix.trim().endsWithChar (')'))
  6170. {
  6171. putNumbersInBrackets = true;
  6172. const int openBracks = prefix.lastIndexOfChar ('(');
  6173. const int closeBracks = prefix.lastIndexOfChar (')');
  6174. if (openBracks > 0
  6175. && closeBracks > openBracks
  6176. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6177. {
  6178. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6179. prefix = prefix.substring (0, openBracks);
  6180. }
  6181. }
  6182. // also use brackets if it ends in a digit.
  6183. putNumbersInBrackets = putNumbersInBrackets
  6184. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6185. do
  6186. {
  6187. if (putNumbersInBrackets)
  6188. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6189. else
  6190. f = getChildFile (prefix + String (num++) + suffix);
  6191. } while (f.exists());
  6192. }
  6193. return f;
  6194. }
  6195. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6196. {
  6197. if (exists())
  6198. {
  6199. return getParentDirectory()
  6200. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6201. getFileExtension(),
  6202. putNumbersInBrackets);
  6203. }
  6204. else
  6205. {
  6206. return *this;
  6207. }
  6208. }
  6209. const String File::getFileExtension() const
  6210. {
  6211. String ext;
  6212. if (! isDirectory())
  6213. {
  6214. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6215. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6216. ext = fullPath.substring (indexOfDot);
  6217. }
  6218. return ext;
  6219. }
  6220. bool File::hasFileExtension (const String& possibleSuffix) const
  6221. {
  6222. if (possibleSuffix.isEmpty())
  6223. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6224. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6225. if (semicolon >= 0)
  6226. {
  6227. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6228. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6229. }
  6230. else
  6231. {
  6232. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6233. {
  6234. if (possibleSuffix.startsWithChar ('.'))
  6235. return true;
  6236. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6237. if (dotPos >= 0)
  6238. return fullPath [dotPos] == '.';
  6239. }
  6240. }
  6241. return false;
  6242. }
  6243. const File File::withFileExtension (const String& newExtension) const
  6244. {
  6245. if (fullPath.isEmpty())
  6246. return File::nonexistent;
  6247. String filePart (getFileName());
  6248. int i = filePart.lastIndexOfChar ('.');
  6249. if (i >= 0)
  6250. filePart = filePart.substring (0, i);
  6251. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6252. filePart << '.';
  6253. return getSiblingFile (filePart + newExtension);
  6254. }
  6255. bool File::startAsProcess (const String& parameters) const
  6256. {
  6257. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6258. }
  6259. FileInputStream* File::createInputStream() const
  6260. {
  6261. if (existsAsFile())
  6262. return new FileInputStream (*this);
  6263. return 0;
  6264. }
  6265. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6266. {
  6267. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6268. if (out->failedToOpen())
  6269. return 0;
  6270. return out.release();
  6271. }
  6272. bool File::appendData (const void* const dataToAppend,
  6273. const int numberOfBytes) const
  6274. {
  6275. if (numberOfBytes > 0)
  6276. {
  6277. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6278. if (out == 0)
  6279. return false;
  6280. out->write (dataToAppend, numberOfBytes);
  6281. }
  6282. return true;
  6283. }
  6284. bool File::replaceWithData (const void* const dataToWrite,
  6285. const int numberOfBytes) const
  6286. {
  6287. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6288. if (numberOfBytes <= 0)
  6289. return deleteFile();
  6290. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6291. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6292. return tempFile.overwriteTargetFileWithTemporary();
  6293. }
  6294. bool File::appendText (const String& text,
  6295. const bool asUnicode,
  6296. const bool writeUnicodeHeaderBytes) const
  6297. {
  6298. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6299. if (out != 0)
  6300. {
  6301. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6302. return true;
  6303. }
  6304. return false;
  6305. }
  6306. bool File::replaceWithText (const String& textToWrite,
  6307. const bool asUnicode,
  6308. const bool writeUnicodeHeaderBytes) const
  6309. {
  6310. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6311. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6312. return tempFile.overwriteTargetFileWithTemporary();
  6313. }
  6314. bool File::hasIdenticalContentTo (const File& other) const
  6315. {
  6316. if (other == *this)
  6317. return true;
  6318. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6319. {
  6320. FileInputStream in1 (*this), in2 (other);
  6321. const int bufferSize = 4096;
  6322. HeapBlock <char> buffer1, buffer2;
  6323. buffer1.malloc (bufferSize);
  6324. buffer2.malloc (bufferSize);
  6325. for (;;)
  6326. {
  6327. const int num1 = in1.read (buffer1, bufferSize);
  6328. const int num2 = in2.read (buffer2, bufferSize);
  6329. if (num1 != num2)
  6330. break;
  6331. if (num1 <= 0)
  6332. return true;
  6333. if (memcmp (buffer1, buffer2, num1) != 0)
  6334. break;
  6335. }
  6336. }
  6337. return false;
  6338. }
  6339. const String File::createLegalPathName (const String& original)
  6340. {
  6341. String s (original);
  6342. String start;
  6343. if (s[1] == ':')
  6344. {
  6345. start = s.substring (0, 2);
  6346. s = s.substring (2);
  6347. }
  6348. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6349. .substring (0, 1024);
  6350. }
  6351. const String File::createLegalFileName (const String& original)
  6352. {
  6353. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6354. const int maxLength = 128; // only the length of the filename, not the whole path
  6355. const int len = s.length();
  6356. if (len > maxLength)
  6357. {
  6358. const int lastDot = s.lastIndexOfChar ('.');
  6359. if (lastDot > jmax (0, len - 12))
  6360. {
  6361. s = s.substring (0, maxLength - (len - lastDot))
  6362. + s.substring (lastDot);
  6363. }
  6364. else
  6365. {
  6366. s = s.substring (0, maxLength);
  6367. }
  6368. }
  6369. return s;
  6370. }
  6371. const String File::getRelativePathFrom (const File& dir) const
  6372. {
  6373. String thisPath (fullPath);
  6374. {
  6375. int len = thisPath.length();
  6376. while (--len >= 0 && thisPath [len] == File::separator)
  6377. thisPath [len] = 0;
  6378. }
  6379. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6380. : dir.fullPath));
  6381. const int len = jmin (thisPath.length(), dirPath.length());
  6382. int commonBitLength = 0;
  6383. for (int i = 0; i < len; ++i)
  6384. {
  6385. #if NAMES_ARE_CASE_SENSITIVE
  6386. if (thisPath[i] != dirPath[i])
  6387. #else
  6388. if (CharacterFunctions::toLowerCase (thisPath[i])
  6389. != CharacterFunctions::toLowerCase (dirPath[i]))
  6390. #endif
  6391. {
  6392. break;
  6393. }
  6394. ++commonBitLength;
  6395. }
  6396. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6397. --commonBitLength;
  6398. // if the only common bit is the root, then just return the full path..
  6399. if (commonBitLength <= 0
  6400. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6401. return fullPath;
  6402. thisPath = thisPath.substring (commonBitLength);
  6403. dirPath = dirPath.substring (commonBitLength);
  6404. while (dirPath.isNotEmpty())
  6405. {
  6406. #if JUCE_WINDOWS
  6407. thisPath = "..\\" + thisPath;
  6408. #else
  6409. thisPath = "../" + thisPath;
  6410. #endif
  6411. const int sep = dirPath.indexOfChar (separator);
  6412. if (sep >= 0)
  6413. dirPath = dirPath.substring (sep + 1);
  6414. else
  6415. dirPath = String::empty;
  6416. }
  6417. return thisPath;
  6418. }
  6419. const File File::createTempFile (const String& fileNameEnding)
  6420. {
  6421. const File tempFile (getSpecialLocation (tempDirectory)
  6422. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6423. .withFileExtension (fileNameEnding));
  6424. if (tempFile.exists())
  6425. return createTempFile (fileNameEnding);
  6426. else
  6427. return tempFile;
  6428. }
  6429. #if JUCE_UNIT_TESTS
  6430. class FileTests : public UnitTest
  6431. {
  6432. public:
  6433. FileTests() : UnitTest ("Files") {}
  6434. void runTest()
  6435. {
  6436. beginTest ("Reading");
  6437. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6438. const File temp (File::getSpecialLocation (File::tempDirectory));
  6439. expect (! File::nonexistent.exists());
  6440. expect (home.isDirectory());
  6441. expect (home.exists());
  6442. expect (! home.existsAsFile());
  6443. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6444. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6445. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6446. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6447. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6448. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6449. expect (home.getBytesFreeOnVolume() > 0);
  6450. expect (! home.isHidden());
  6451. expect (home.isOnHardDisk());
  6452. expect (! home.isOnCDRomDrive());
  6453. expect (File::getCurrentWorkingDirectory().exists());
  6454. expect (home.setAsCurrentWorkingDirectory());
  6455. expect (File::getCurrentWorkingDirectory() == home);
  6456. {
  6457. Array<File> roots;
  6458. File::findFileSystemRoots (roots);
  6459. expect (roots.size() > 0);
  6460. int numRootsExisting = 0;
  6461. for (int i = 0; i < roots.size(); ++i)
  6462. if (roots[i].exists())
  6463. ++numRootsExisting;
  6464. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6465. expect (numRootsExisting > 0);
  6466. }
  6467. beginTest ("Writing");
  6468. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6469. expect (demoFolder.deleteRecursively());
  6470. expect (demoFolder.createDirectory());
  6471. expect (demoFolder.isDirectory());
  6472. expect (demoFolder.getParentDirectory() == temp);
  6473. expect (temp.isDirectory());
  6474. {
  6475. Array<File> files;
  6476. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6477. expect (files.contains (demoFolder));
  6478. }
  6479. {
  6480. Array<File> files;
  6481. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6482. expect (files.contains (demoFolder));
  6483. }
  6484. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6485. expect (tempFile.getFileExtension() == ".txt");
  6486. expect (tempFile.hasFileExtension (".txt"));
  6487. expect (tempFile.hasFileExtension ("txt"));
  6488. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6489. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6490. expect (tempFile.hasWriteAccess());
  6491. {
  6492. FileOutputStream fo (tempFile);
  6493. fo.write ("0123456789", 10);
  6494. }
  6495. expect (tempFile.exists());
  6496. expect (tempFile.getSize() == 10);
  6497. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6498. expect (tempFile.loadFileAsString() == "0123456789");
  6499. expect (! demoFolder.containsSubDirectories());
  6500. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6501. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6502. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6503. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6504. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6505. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6506. expect (demoFolder.containsSubDirectories());
  6507. expect (tempFile.hasWriteAccess());
  6508. tempFile.setReadOnly (true);
  6509. expect (! tempFile.hasWriteAccess());
  6510. tempFile.setReadOnly (false);
  6511. expect (tempFile.hasWriteAccess());
  6512. Time t (Time::getCurrentTime());
  6513. tempFile.setLastModificationTime (t);
  6514. Time t2 = tempFile.getLastModificationTime();
  6515. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6516. {
  6517. MemoryBlock mb;
  6518. tempFile.loadFileAsData (mb);
  6519. expect (mb.getSize() == 10);
  6520. expect (mb[0] == '0');
  6521. }
  6522. expect (tempFile.appendData ("abcdefghij", 10));
  6523. expect (tempFile.getSize() == 20);
  6524. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6525. expect (tempFile.getSize() == 10);
  6526. File tempFile2 (tempFile.getNonexistentSibling (false));
  6527. expect (tempFile.copyFileTo (tempFile2));
  6528. expect (tempFile2.exists());
  6529. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6530. expect (tempFile.deleteFile());
  6531. expect (! tempFile.exists());
  6532. expect (tempFile2.moveFileTo (tempFile));
  6533. expect (tempFile.exists());
  6534. expect (! tempFile2.exists());
  6535. expect (demoFolder.deleteRecursively());
  6536. expect (! demoFolder.exists());
  6537. }
  6538. };
  6539. static FileTests fileUnitTests;
  6540. #endif
  6541. END_JUCE_NAMESPACE
  6542. /*** End of inlined file: juce_File.cpp ***/
  6543. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6544. BEGIN_JUCE_NAMESPACE
  6545. int64 juce_fileSetPosition (void* handle, int64 pos);
  6546. FileInputStream::FileInputStream (const File& f)
  6547. : file (f),
  6548. fileHandle (0),
  6549. currentPosition (0),
  6550. totalSize (0),
  6551. needToSeek (true)
  6552. {
  6553. openHandle();
  6554. }
  6555. FileInputStream::~FileInputStream()
  6556. {
  6557. closeHandle();
  6558. }
  6559. int64 FileInputStream::getTotalLength()
  6560. {
  6561. return totalSize;
  6562. }
  6563. int FileInputStream::read (void* buffer, int bytesToRead)
  6564. {
  6565. if (needToSeek)
  6566. {
  6567. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6568. return 0;
  6569. needToSeek = false;
  6570. }
  6571. const size_t num = readInternal (buffer, bytesToRead);
  6572. currentPosition += num;
  6573. return (int) num;
  6574. }
  6575. bool FileInputStream::isExhausted()
  6576. {
  6577. return currentPosition >= totalSize;
  6578. }
  6579. int64 FileInputStream::getPosition()
  6580. {
  6581. return currentPosition;
  6582. }
  6583. bool FileInputStream::setPosition (int64 pos)
  6584. {
  6585. pos = jlimit ((int64) 0, totalSize, pos);
  6586. needToSeek |= (currentPosition != pos);
  6587. currentPosition = pos;
  6588. return true;
  6589. }
  6590. END_JUCE_NAMESPACE
  6591. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6592. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6593. BEGIN_JUCE_NAMESPACE
  6594. int64 juce_fileSetPosition (void* handle, int64 pos);
  6595. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6596. : file (f),
  6597. fileHandle (0),
  6598. currentPosition (0),
  6599. bufferSize (bufferSize_),
  6600. bytesInBuffer (0),
  6601. buffer (jmax (bufferSize_, 16))
  6602. {
  6603. openHandle();
  6604. }
  6605. FileOutputStream::~FileOutputStream()
  6606. {
  6607. flush();
  6608. closeHandle();
  6609. }
  6610. int64 FileOutputStream::getPosition()
  6611. {
  6612. return currentPosition;
  6613. }
  6614. bool FileOutputStream::setPosition (int64 newPosition)
  6615. {
  6616. if (newPosition != currentPosition)
  6617. {
  6618. flush();
  6619. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6620. }
  6621. return newPosition == currentPosition;
  6622. }
  6623. void FileOutputStream::flush()
  6624. {
  6625. if (bytesInBuffer > 0)
  6626. {
  6627. writeInternal (buffer, bytesInBuffer);
  6628. bytesInBuffer = 0;
  6629. }
  6630. flushInternal();
  6631. }
  6632. bool FileOutputStream::write (const void* const src, const int numBytes)
  6633. {
  6634. if (bytesInBuffer + numBytes < bufferSize)
  6635. {
  6636. memcpy (buffer + bytesInBuffer, src, numBytes);
  6637. bytesInBuffer += numBytes;
  6638. currentPosition += numBytes;
  6639. }
  6640. else
  6641. {
  6642. if (bytesInBuffer > 0)
  6643. {
  6644. // flush the reservoir
  6645. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6646. bytesInBuffer = 0;
  6647. if (! wroteOk)
  6648. return false;
  6649. }
  6650. if (numBytes < bufferSize)
  6651. {
  6652. memcpy (buffer + bytesInBuffer, src, numBytes);
  6653. bytesInBuffer += numBytes;
  6654. currentPosition += numBytes;
  6655. }
  6656. else
  6657. {
  6658. const int bytesWritten = writeInternal (src, numBytes);
  6659. if (bytesWritten < 0)
  6660. return false;
  6661. currentPosition += bytesWritten;
  6662. return bytesWritten == numBytes;
  6663. }
  6664. }
  6665. return true;
  6666. }
  6667. END_JUCE_NAMESPACE
  6668. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6669. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6670. BEGIN_JUCE_NAMESPACE
  6671. FileSearchPath::FileSearchPath()
  6672. {
  6673. }
  6674. FileSearchPath::FileSearchPath (const String& path)
  6675. {
  6676. init (path);
  6677. }
  6678. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6679. : directories (other.directories)
  6680. {
  6681. }
  6682. FileSearchPath::~FileSearchPath()
  6683. {
  6684. }
  6685. FileSearchPath& FileSearchPath::operator= (const String& path)
  6686. {
  6687. init (path);
  6688. return *this;
  6689. }
  6690. void FileSearchPath::init (const String& path)
  6691. {
  6692. directories.clear();
  6693. directories.addTokens (path, ";", "\"");
  6694. directories.trim();
  6695. directories.removeEmptyStrings();
  6696. for (int i = directories.size(); --i >= 0;)
  6697. directories.set (i, directories[i].unquoted());
  6698. }
  6699. int FileSearchPath::getNumPaths() const
  6700. {
  6701. return directories.size();
  6702. }
  6703. const File FileSearchPath::operator[] (const int index) const
  6704. {
  6705. return File (directories [index]);
  6706. }
  6707. const String FileSearchPath::toString() const
  6708. {
  6709. StringArray directories2 (directories);
  6710. for (int i = directories2.size(); --i >= 0;)
  6711. if (directories2[i].containsChar (';'))
  6712. directories2.set (i, directories2[i].quoted());
  6713. return directories2.joinIntoString (";");
  6714. }
  6715. void FileSearchPath::add (const File& dir, const int insertIndex)
  6716. {
  6717. directories.insert (insertIndex, dir.getFullPathName());
  6718. }
  6719. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6720. {
  6721. for (int i = 0; i < directories.size(); ++i)
  6722. if (File (directories[i]) == dir)
  6723. return;
  6724. add (dir);
  6725. }
  6726. void FileSearchPath::remove (const int index)
  6727. {
  6728. directories.remove (index);
  6729. }
  6730. void FileSearchPath::addPath (const FileSearchPath& other)
  6731. {
  6732. for (int i = 0; i < other.getNumPaths(); ++i)
  6733. addIfNotAlreadyThere (other[i]);
  6734. }
  6735. void FileSearchPath::removeRedundantPaths()
  6736. {
  6737. for (int i = directories.size(); --i >= 0;)
  6738. {
  6739. const File d1 (directories[i]);
  6740. for (int j = directories.size(); --j >= 0;)
  6741. {
  6742. const File d2 (directories[j]);
  6743. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6744. {
  6745. directories.remove (i);
  6746. break;
  6747. }
  6748. }
  6749. }
  6750. }
  6751. void FileSearchPath::removeNonExistentPaths()
  6752. {
  6753. for (int i = directories.size(); --i >= 0;)
  6754. if (! File (directories[i]).isDirectory())
  6755. directories.remove (i);
  6756. }
  6757. int FileSearchPath::findChildFiles (Array<File>& results,
  6758. const int whatToLookFor,
  6759. const bool searchRecursively,
  6760. const String& wildCardPattern) const
  6761. {
  6762. int total = 0;
  6763. for (int i = 0; i < directories.size(); ++i)
  6764. total += operator[] (i).findChildFiles (results,
  6765. whatToLookFor,
  6766. searchRecursively,
  6767. wildCardPattern);
  6768. return total;
  6769. }
  6770. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6771. const bool checkRecursively) const
  6772. {
  6773. for (int i = directories.size(); --i >= 0;)
  6774. {
  6775. const File d (directories[i]);
  6776. if (checkRecursively)
  6777. {
  6778. if (fileToCheck.isAChildOf (d))
  6779. return true;
  6780. }
  6781. else
  6782. {
  6783. if (fileToCheck.getParentDirectory() == d)
  6784. return true;
  6785. }
  6786. }
  6787. return false;
  6788. }
  6789. END_JUCE_NAMESPACE
  6790. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6791. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6792. BEGIN_JUCE_NAMESPACE
  6793. NamedPipe::NamedPipe()
  6794. : internal (0)
  6795. {
  6796. }
  6797. NamedPipe::~NamedPipe()
  6798. {
  6799. close();
  6800. }
  6801. bool NamedPipe::openExisting (const String& pipeName)
  6802. {
  6803. currentPipeName = pipeName;
  6804. return openInternal (pipeName, false);
  6805. }
  6806. bool NamedPipe::createNewPipe (const String& pipeName)
  6807. {
  6808. currentPipeName = pipeName;
  6809. return openInternal (pipeName, true);
  6810. }
  6811. bool NamedPipe::isOpen() const
  6812. {
  6813. return internal != 0;
  6814. }
  6815. const String NamedPipe::getName() const
  6816. {
  6817. return currentPipeName;
  6818. }
  6819. // other methods for this class are implemented in the platform-specific files
  6820. END_JUCE_NAMESPACE
  6821. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6822. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6823. BEGIN_JUCE_NAMESPACE
  6824. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6825. {
  6826. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6827. "temp_" + String (Random::getSystemRandom().nextInt()),
  6828. suffix,
  6829. optionFlags);
  6830. }
  6831. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6832. : targetFile (targetFile_)
  6833. {
  6834. // If you use this constructor, you need to give it a valid target file!
  6835. jassert (targetFile != File::nonexistent);
  6836. createTempFile (targetFile.getParentDirectory(),
  6837. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6838. targetFile.getFileExtension(),
  6839. optionFlags);
  6840. }
  6841. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6842. const String& suffix, const int optionFlags)
  6843. {
  6844. if ((optionFlags & useHiddenFile) != 0)
  6845. name = "." + name;
  6846. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6847. }
  6848. TemporaryFile::~TemporaryFile()
  6849. {
  6850. if (! deleteTemporaryFile())
  6851. {
  6852. /* Failed to delete our temporary file! The most likely reason for this would be
  6853. that you've not closed an output stream that was being used to write to file.
  6854. If you find that something beyond your control is changing permissions on
  6855. your temporary files and preventing them from being deleted, you may want to
  6856. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6857. handle them appropriately.
  6858. */
  6859. jassertfalse;
  6860. }
  6861. }
  6862. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6863. {
  6864. // This method only works if you created this object with the constructor
  6865. // that takes a target file!
  6866. jassert (targetFile != File::nonexistent);
  6867. if (temporaryFile.exists())
  6868. {
  6869. // Have a few attempts at overwriting the file before giving up..
  6870. for (int i = 5; --i >= 0;)
  6871. {
  6872. if (temporaryFile.moveFileTo (targetFile))
  6873. return true;
  6874. Thread::sleep (100);
  6875. }
  6876. }
  6877. else
  6878. {
  6879. // There's no temporary file to use. If your write failed, you should
  6880. // probably check, and not bother calling this method.
  6881. jassertfalse;
  6882. }
  6883. return false;
  6884. }
  6885. bool TemporaryFile::deleteTemporaryFile() const
  6886. {
  6887. // Have a few attempts at deleting the file before giving up..
  6888. for (int i = 5; --i >= 0;)
  6889. {
  6890. if (temporaryFile.deleteFile())
  6891. return true;
  6892. Thread::sleep (50);
  6893. }
  6894. return false;
  6895. }
  6896. END_JUCE_NAMESPACE
  6897. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6898. /*** Start of inlined file: juce_Socket.cpp ***/
  6899. #if JUCE_WINDOWS
  6900. #include <winsock2.h>
  6901. #if JUCE_MSVC
  6902. #pragma warning (push)
  6903. #pragma warning (disable : 4127 4389 4018)
  6904. #endif
  6905. #else
  6906. #if JUCE_LINUX
  6907. #include <sys/types.h>
  6908. #include <sys/socket.h>
  6909. #include <sys/errno.h>
  6910. #include <unistd.h>
  6911. #include <netinet/in.h>
  6912. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6913. #include <CoreServices/CoreServices.h>
  6914. #endif
  6915. #include <fcntl.h>
  6916. #include <netdb.h>
  6917. #include <arpa/inet.h>
  6918. #include <netinet/tcp.h>
  6919. #endif
  6920. BEGIN_JUCE_NAMESPACE
  6921. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6922. typedef socklen_t juce_socklen_t;
  6923. #else
  6924. typedef int juce_socklen_t;
  6925. #endif
  6926. #if JUCE_WINDOWS
  6927. namespace SocketHelpers
  6928. {
  6929. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6930. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6931. void initWin32Sockets()
  6932. {
  6933. static CriticalSection lock;
  6934. const ScopedLock sl (lock);
  6935. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6936. {
  6937. WSADATA wsaData;
  6938. const WORD wVersionRequested = MAKEWORD (1, 1);
  6939. WSAStartup (wVersionRequested, &wsaData);
  6940. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6941. }
  6942. }
  6943. }
  6944. void juce_shutdownWin32Sockets()
  6945. {
  6946. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6947. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6948. }
  6949. #endif
  6950. namespace SocketHelpers
  6951. {
  6952. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6953. {
  6954. const int sndBufSize = 65536;
  6955. const int rcvBufSize = 65536;
  6956. const int one = 1;
  6957. return handle > 0
  6958. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6959. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6960. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6961. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6962. }
  6963. bool bindSocketToPort (const int handle, const int port) throw()
  6964. {
  6965. if (handle <= 0 || port <= 0)
  6966. return false;
  6967. struct sockaddr_in servTmpAddr;
  6968. zerostruct (servTmpAddr);
  6969. servTmpAddr.sin_family = PF_INET;
  6970. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6971. servTmpAddr.sin_port = htons ((uint16) port);
  6972. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6973. }
  6974. int readSocket (const int handle,
  6975. void* const destBuffer, const int maxBytesToRead,
  6976. bool volatile& connected,
  6977. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6978. {
  6979. int bytesRead = 0;
  6980. while (bytesRead < maxBytesToRead)
  6981. {
  6982. int bytesThisTime;
  6983. #if JUCE_WINDOWS
  6984. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6985. #else
  6986. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6987. && errno == EINTR
  6988. && connected)
  6989. {
  6990. }
  6991. #endif
  6992. if (bytesThisTime <= 0 || ! connected)
  6993. {
  6994. if (bytesRead == 0)
  6995. bytesRead = -1;
  6996. break;
  6997. }
  6998. bytesRead += bytesThisTime;
  6999. if (! blockUntilSpecifiedAmountHasArrived)
  7000. break;
  7001. }
  7002. return bytesRead;
  7003. }
  7004. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7005. {
  7006. struct timeval timeout;
  7007. struct timeval* timeoutp;
  7008. if (timeoutMsecs >= 0)
  7009. {
  7010. timeout.tv_sec = timeoutMsecs / 1000;
  7011. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7012. timeoutp = &timeout;
  7013. }
  7014. else
  7015. {
  7016. timeoutp = 0;
  7017. }
  7018. fd_set rset, wset;
  7019. FD_ZERO (&rset);
  7020. FD_SET (handle, &rset);
  7021. FD_ZERO (&wset);
  7022. FD_SET (handle, &wset);
  7023. fd_set* const prset = forReading ? &rset : 0;
  7024. fd_set* const pwset = forReading ? 0 : &wset;
  7025. #if JUCE_WINDOWS
  7026. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7027. return -1;
  7028. #else
  7029. {
  7030. int result;
  7031. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7032. && errno == EINTR)
  7033. {
  7034. }
  7035. if (result < 0)
  7036. return -1;
  7037. }
  7038. #endif
  7039. {
  7040. int opt;
  7041. juce_socklen_t len = sizeof (opt);
  7042. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7043. || opt != 0)
  7044. return -1;
  7045. }
  7046. if ((forReading && FD_ISSET (handle, &rset))
  7047. || ((! forReading) && FD_ISSET (handle, &wset)))
  7048. return 1;
  7049. return 0;
  7050. }
  7051. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7052. {
  7053. #if JUCE_WINDOWS
  7054. u_long nonBlocking = shouldBlock ? 0 : 1;
  7055. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7056. return false;
  7057. #else
  7058. int socketFlags = fcntl (handle, F_GETFL, 0);
  7059. if (socketFlags == -1)
  7060. return false;
  7061. if (shouldBlock)
  7062. socketFlags &= ~O_NONBLOCK;
  7063. else
  7064. socketFlags |= O_NONBLOCK;
  7065. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7066. return false;
  7067. #endif
  7068. return true;
  7069. }
  7070. bool connectSocket (int volatile& handle,
  7071. const bool isDatagram,
  7072. void** serverAddress,
  7073. const String& hostName,
  7074. const int portNumber,
  7075. const int timeOutMillisecs) throw()
  7076. {
  7077. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7078. if (hostEnt == 0)
  7079. return false;
  7080. struct in_addr targetAddress;
  7081. memcpy (&targetAddress.s_addr,
  7082. *(hostEnt->h_addr_list),
  7083. sizeof (targetAddress.s_addr));
  7084. struct sockaddr_in servTmpAddr;
  7085. zerostruct (servTmpAddr);
  7086. servTmpAddr.sin_family = PF_INET;
  7087. servTmpAddr.sin_addr = targetAddress;
  7088. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7089. if (handle < 0)
  7090. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7091. if (handle < 0)
  7092. return false;
  7093. if (isDatagram)
  7094. {
  7095. *serverAddress = new struct sockaddr_in();
  7096. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7097. return true;
  7098. }
  7099. setSocketBlockingState (handle, false);
  7100. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7101. if (result < 0)
  7102. {
  7103. #if JUCE_WINDOWS
  7104. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7105. #else
  7106. if (errno == EINPROGRESS)
  7107. #endif
  7108. {
  7109. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7110. {
  7111. setSocketBlockingState (handle, true);
  7112. return false;
  7113. }
  7114. }
  7115. }
  7116. setSocketBlockingState (handle, true);
  7117. resetSocketOptions (handle, false, false);
  7118. return true;
  7119. }
  7120. }
  7121. StreamingSocket::StreamingSocket()
  7122. : portNumber (0),
  7123. handle (-1),
  7124. connected (false),
  7125. isListener (false)
  7126. {
  7127. #if JUCE_WINDOWS
  7128. SocketHelpers::initWin32Sockets();
  7129. #endif
  7130. }
  7131. StreamingSocket::StreamingSocket (const String& hostName_,
  7132. const int portNumber_,
  7133. const int handle_)
  7134. : hostName (hostName_),
  7135. portNumber (portNumber_),
  7136. handle (handle_),
  7137. connected (true),
  7138. isListener (false)
  7139. {
  7140. #if JUCE_WINDOWS
  7141. SocketHelpers::initWin32Sockets();
  7142. #endif
  7143. SocketHelpers::resetSocketOptions (handle_, false, false);
  7144. }
  7145. StreamingSocket::~StreamingSocket()
  7146. {
  7147. close();
  7148. }
  7149. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7150. {
  7151. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7152. : -1;
  7153. }
  7154. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7155. {
  7156. if (isListener || ! connected)
  7157. return -1;
  7158. #if JUCE_WINDOWS
  7159. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7160. #else
  7161. int result;
  7162. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7163. && errno == EINTR)
  7164. {
  7165. }
  7166. return result;
  7167. #endif
  7168. }
  7169. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7170. const int timeoutMsecs) const
  7171. {
  7172. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7173. : -1;
  7174. }
  7175. bool StreamingSocket::bindToPort (const int port)
  7176. {
  7177. return SocketHelpers::bindSocketToPort (handle, port);
  7178. }
  7179. bool StreamingSocket::connect (const String& remoteHostName,
  7180. const int remotePortNumber,
  7181. const int timeOutMillisecs)
  7182. {
  7183. if (isListener)
  7184. {
  7185. jassertfalse; // a listener socket can't connect to another one!
  7186. return false;
  7187. }
  7188. if (connected)
  7189. close();
  7190. hostName = remoteHostName;
  7191. portNumber = remotePortNumber;
  7192. isListener = false;
  7193. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7194. remotePortNumber, timeOutMillisecs);
  7195. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7196. {
  7197. close();
  7198. return false;
  7199. }
  7200. return true;
  7201. }
  7202. void StreamingSocket::close()
  7203. {
  7204. #if JUCE_WINDOWS
  7205. if (handle != SOCKET_ERROR || connected)
  7206. closesocket (handle);
  7207. connected = false;
  7208. #else
  7209. if (connected)
  7210. {
  7211. connected = false;
  7212. if (isListener)
  7213. {
  7214. // need to do this to interrupt the accept() function..
  7215. StreamingSocket temp;
  7216. temp.connect ("localhost", portNumber, 1000);
  7217. }
  7218. }
  7219. if (handle != -1)
  7220. ::close (handle);
  7221. #endif
  7222. hostName = String::empty;
  7223. portNumber = 0;
  7224. handle = -1;
  7225. isListener = false;
  7226. }
  7227. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7228. {
  7229. if (connected)
  7230. close();
  7231. hostName = "listener";
  7232. portNumber = newPortNumber;
  7233. isListener = true;
  7234. struct sockaddr_in servTmpAddr;
  7235. zerostruct (servTmpAddr);
  7236. servTmpAddr.sin_family = PF_INET;
  7237. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7238. if (localHostName.isNotEmpty())
  7239. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7240. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7241. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7242. if (handle < 0)
  7243. return false;
  7244. const int reuse = 1;
  7245. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7246. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7247. || listen (handle, SOMAXCONN) < 0)
  7248. {
  7249. close();
  7250. return false;
  7251. }
  7252. connected = true;
  7253. return true;
  7254. }
  7255. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7256. {
  7257. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7258. // prepare this socket as a listener.
  7259. if (connected && isListener)
  7260. {
  7261. struct sockaddr address;
  7262. juce_socklen_t len = sizeof (sockaddr);
  7263. const int newSocket = (int) accept (handle, &address, &len);
  7264. if (newSocket >= 0 && connected)
  7265. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7266. portNumber, newSocket);
  7267. }
  7268. return 0;
  7269. }
  7270. bool StreamingSocket::isLocal() const throw()
  7271. {
  7272. return hostName == "127.0.0.1";
  7273. }
  7274. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7275. : portNumber (0),
  7276. handle (-1),
  7277. connected (true),
  7278. allowBroadcast (allowBroadcast_),
  7279. serverAddress (0)
  7280. {
  7281. #if JUCE_WINDOWS
  7282. SocketHelpers::initWin32Sockets();
  7283. #endif
  7284. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7285. bindToPort (localPortNumber);
  7286. }
  7287. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7288. const int handle_, const int localPortNumber)
  7289. : hostName (hostName_),
  7290. portNumber (portNumber_),
  7291. handle (handle_),
  7292. connected (true),
  7293. allowBroadcast (false),
  7294. serverAddress (0)
  7295. {
  7296. #if JUCE_WINDOWS
  7297. SocketHelpers::initWin32Sockets();
  7298. #endif
  7299. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7300. bindToPort (localPortNumber);
  7301. }
  7302. DatagramSocket::~DatagramSocket()
  7303. {
  7304. close();
  7305. delete static_cast <struct sockaddr_in*> (serverAddress);
  7306. serverAddress = 0;
  7307. }
  7308. void DatagramSocket::close()
  7309. {
  7310. #if JUCE_WINDOWS
  7311. closesocket (handle);
  7312. connected = false;
  7313. #else
  7314. connected = false;
  7315. ::close (handle);
  7316. #endif
  7317. hostName = String::empty;
  7318. portNumber = 0;
  7319. handle = -1;
  7320. }
  7321. bool DatagramSocket::bindToPort (const int port)
  7322. {
  7323. return SocketHelpers::bindSocketToPort (handle, port);
  7324. }
  7325. bool DatagramSocket::connect (const String& remoteHostName,
  7326. const int remotePortNumber,
  7327. const int timeOutMillisecs)
  7328. {
  7329. if (connected)
  7330. close();
  7331. hostName = remoteHostName;
  7332. portNumber = remotePortNumber;
  7333. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7334. remoteHostName, remotePortNumber,
  7335. timeOutMillisecs);
  7336. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7337. {
  7338. close();
  7339. return false;
  7340. }
  7341. return true;
  7342. }
  7343. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7344. {
  7345. struct sockaddr address;
  7346. juce_socklen_t len = sizeof (sockaddr);
  7347. while (waitUntilReady (true, -1) == 1)
  7348. {
  7349. char buf[1];
  7350. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7351. {
  7352. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7353. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7354. -1, -1);
  7355. }
  7356. }
  7357. return 0;
  7358. }
  7359. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7360. const int timeoutMsecs) const
  7361. {
  7362. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7363. : -1;
  7364. }
  7365. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7366. {
  7367. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7368. : -1;
  7369. }
  7370. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7371. {
  7372. // You need to call connect() first to set the server address..
  7373. jassert (serverAddress != 0 && connected);
  7374. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7375. numBytesToWrite, 0,
  7376. (const struct sockaddr*) serverAddress,
  7377. sizeof (struct sockaddr_in))
  7378. : -1;
  7379. }
  7380. bool DatagramSocket::isLocal() const throw()
  7381. {
  7382. return hostName == "127.0.0.1";
  7383. }
  7384. #if JUCE_MSVC
  7385. #pragma warning (pop)
  7386. #endif
  7387. END_JUCE_NAMESPACE
  7388. /*** End of inlined file: juce_Socket.cpp ***/
  7389. /*** Start of inlined file: juce_URL.cpp ***/
  7390. BEGIN_JUCE_NAMESPACE
  7391. URL::URL()
  7392. {
  7393. }
  7394. URL::URL (const String& url_)
  7395. : url (url_)
  7396. {
  7397. int i = url.indexOfChar ('?');
  7398. if (i >= 0)
  7399. {
  7400. do
  7401. {
  7402. const int nextAmp = url.indexOfChar (i + 1, '&');
  7403. const int equalsPos = url.indexOfChar (i + 1, '=');
  7404. if (equalsPos > i + 1)
  7405. {
  7406. if (nextAmp < 0)
  7407. {
  7408. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7409. removeEscapeChars (url.substring (equalsPos + 1)));
  7410. }
  7411. else if (nextAmp > 0 && equalsPos < nextAmp)
  7412. {
  7413. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7414. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7415. }
  7416. }
  7417. i = nextAmp;
  7418. }
  7419. while (i >= 0);
  7420. url = url.upToFirstOccurrenceOf ("?", false, false);
  7421. }
  7422. }
  7423. URL::URL (const URL& other)
  7424. : url (other.url),
  7425. postData (other.postData),
  7426. parameters (other.parameters),
  7427. filesToUpload (other.filesToUpload),
  7428. mimeTypes (other.mimeTypes)
  7429. {
  7430. }
  7431. URL& URL::operator= (const URL& other)
  7432. {
  7433. url = other.url;
  7434. postData = other.postData;
  7435. parameters = other.parameters;
  7436. filesToUpload = other.filesToUpload;
  7437. mimeTypes = other.mimeTypes;
  7438. return *this;
  7439. }
  7440. URL::~URL()
  7441. {
  7442. }
  7443. namespace URLHelpers
  7444. {
  7445. const String getMangledParameters (const StringPairArray& parameters)
  7446. {
  7447. String p;
  7448. for (int i = 0; i < parameters.size(); ++i)
  7449. {
  7450. if (i > 0)
  7451. p << '&';
  7452. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7453. << '='
  7454. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7455. }
  7456. return p;
  7457. }
  7458. int findStartOfDomain (const String& url)
  7459. {
  7460. int i = 0;
  7461. while (CharacterFunctions::isLetterOrDigit (url[i])
  7462. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7463. ++i;
  7464. return url[i] == ':' ? i + 1 : 0;
  7465. }
  7466. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7467. {
  7468. MemoryOutputStream data (postData, false);
  7469. if (url.getFilesToUpload().size() > 0)
  7470. {
  7471. // need to upload some files, so do it as multi-part...
  7472. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7473. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7474. data << "--" << boundary;
  7475. int i;
  7476. for (i = 0; i < url.getParameters().size(); ++i)
  7477. {
  7478. data << "\r\nContent-Disposition: form-data; name=\""
  7479. << url.getParameters().getAllKeys() [i]
  7480. << "\"\r\n\r\n"
  7481. << url.getParameters().getAllValues() [i]
  7482. << "\r\n--"
  7483. << boundary;
  7484. }
  7485. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7486. {
  7487. const File file (url.getFilesToUpload().getAllValues() [i]);
  7488. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7489. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7490. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7491. const String mimeType (url.getMimeTypesOfUploadFiles()
  7492. .getValue (paramName, String::empty));
  7493. if (mimeType.isNotEmpty())
  7494. data << "Content-Type: " << mimeType << "\r\n";
  7495. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7496. << file << "\r\n--" << boundary;
  7497. }
  7498. data << "--\r\n";
  7499. data.flush();
  7500. }
  7501. else
  7502. {
  7503. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7504. data.flush();
  7505. // just a short text attachment, so use simple url encoding..
  7506. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7507. << (unsigned int) postData.getSize() << "\r\n";
  7508. }
  7509. }
  7510. }
  7511. const String URL::toString (const bool includeGetParameters) const
  7512. {
  7513. if (includeGetParameters && parameters.size() > 0)
  7514. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7515. else
  7516. return url;
  7517. }
  7518. bool URL::isWellFormed() const
  7519. {
  7520. //xxx TODO
  7521. return url.isNotEmpty();
  7522. }
  7523. const String URL::getDomain() const
  7524. {
  7525. int start = URLHelpers::findStartOfDomain (url);
  7526. while (url[start] == '/')
  7527. ++start;
  7528. const int end1 = url.indexOfChar (start, '/');
  7529. const int end2 = url.indexOfChar (start, ':');
  7530. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7531. : jmin (end1, end2);
  7532. return url.substring (start, end);
  7533. }
  7534. const String URL::getSubPath() const
  7535. {
  7536. int start = URLHelpers::findStartOfDomain (url);
  7537. while (url[start] == '/')
  7538. ++start;
  7539. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7540. return startOfPath <= 0 ? String::empty
  7541. : url.substring (startOfPath);
  7542. }
  7543. const String URL::getScheme() const
  7544. {
  7545. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7546. }
  7547. const URL URL::withNewSubPath (const String& newPath) const
  7548. {
  7549. int start = URLHelpers::findStartOfDomain (url);
  7550. while (url[start] == '/')
  7551. ++start;
  7552. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7553. URL u (*this);
  7554. if (startOfPath > 0)
  7555. u.url = url.substring (0, startOfPath);
  7556. if (! u.url.endsWithChar ('/'))
  7557. u.url << '/';
  7558. if (newPath.startsWithChar ('/'))
  7559. u.url << newPath.substring (1);
  7560. else
  7561. u.url << newPath;
  7562. return u;
  7563. }
  7564. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7565. {
  7566. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7567. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7568. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7569. return true;
  7570. if (possibleURL.containsChar ('@')
  7571. || possibleURL.containsChar (' '))
  7572. return false;
  7573. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7574. .fromLastOccurrenceOf (".", false, false));
  7575. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7576. }
  7577. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7578. {
  7579. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7580. return atSign > 0
  7581. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7582. && (! possibleEmailAddress.endsWithChar ('.'));
  7583. }
  7584. InputStream* URL::createInputStream (const bool usePostCommand,
  7585. OpenStreamProgressCallback* const progressCallback,
  7586. void* const progressCallbackContext,
  7587. const String& extraHeaders,
  7588. const int timeOutMs,
  7589. StringPairArray* const responseHeaders) const
  7590. {
  7591. String headers;
  7592. MemoryBlock headersAndPostData;
  7593. if (usePostCommand)
  7594. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7595. headers += extraHeaders;
  7596. if (! headers.endsWithChar ('\n'))
  7597. headers << "\r\n";
  7598. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7599. progressCallback, progressCallbackContext,
  7600. headers, timeOutMs, responseHeaders);
  7601. }
  7602. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7603. const bool usePostCommand) const
  7604. {
  7605. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7606. if (in != 0)
  7607. {
  7608. in->readIntoMemoryBlock (destData);
  7609. return true;
  7610. }
  7611. return false;
  7612. }
  7613. const String URL::readEntireTextStream (const bool usePostCommand) const
  7614. {
  7615. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7616. if (in != 0)
  7617. return in->readEntireStreamAsString();
  7618. return String::empty;
  7619. }
  7620. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7621. {
  7622. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7623. }
  7624. const URL URL::withParameter (const String& parameterName,
  7625. const String& parameterValue) const
  7626. {
  7627. URL u (*this);
  7628. u.parameters.set (parameterName, parameterValue);
  7629. return u;
  7630. }
  7631. const URL URL::withFileToUpload (const String& parameterName,
  7632. const File& fileToUpload,
  7633. const String& mimeType) const
  7634. {
  7635. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7636. URL u (*this);
  7637. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7638. u.mimeTypes.set (parameterName, mimeType);
  7639. return u;
  7640. }
  7641. const URL URL::withPOSTData (const String& postData_) const
  7642. {
  7643. URL u (*this);
  7644. u.postData = postData_;
  7645. return u;
  7646. }
  7647. const StringPairArray& URL::getParameters() const
  7648. {
  7649. return parameters;
  7650. }
  7651. const StringPairArray& URL::getFilesToUpload() const
  7652. {
  7653. return filesToUpload;
  7654. }
  7655. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7656. {
  7657. return mimeTypes;
  7658. }
  7659. const String URL::removeEscapeChars (const String& s)
  7660. {
  7661. String result (s.replaceCharacter ('+', ' '));
  7662. if (! result.containsChar ('%'))
  7663. return result;
  7664. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7665. // after all the replacements have been made, so that multi-byte chars are handled.
  7666. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7667. for (int i = 0; i < utf8.size(); ++i)
  7668. {
  7669. if (utf8.getUnchecked(i) == '%')
  7670. {
  7671. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7672. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7673. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7674. {
  7675. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7676. utf8.removeRange (i + 1, 2);
  7677. }
  7678. }
  7679. }
  7680. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7681. }
  7682. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7683. {
  7684. const char* const legalChars = isParameter ? "_-.*!'()"
  7685. : ",$_-.*!'()";
  7686. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7687. for (int i = 0; i < utf8.size(); ++i)
  7688. {
  7689. const char c = utf8.getUnchecked(i);
  7690. if (! (CharacterFunctions::isLetterOrDigit (c)
  7691. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7692. {
  7693. if (c == ' ')
  7694. {
  7695. utf8.set (i, '+');
  7696. }
  7697. else
  7698. {
  7699. static const char* const hexDigits = "0123456789abcdef";
  7700. utf8.set (i, '%');
  7701. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7702. utf8.insert (++i, hexDigits [c & 15]);
  7703. }
  7704. }
  7705. }
  7706. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7707. }
  7708. bool URL::launchInDefaultBrowser() const
  7709. {
  7710. String u (toString (true));
  7711. if (u.containsChar ('@') && ! u.containsChar (':'))
  7712. u = "mailto:" + u;
  7713. return PlatformUtilities::openDocument (u, String::empty);
  7714. }
  7715. END_JUCE_NAMESPACE
  7716. /*** End of inlined file: juce_URL.cpp ***/
  7717. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7718. BEGIN_JUCE_NAMESPACE
  7719. MACAddress::MACAddress()
  7720. : asInt64 (0)
  7721. {
  7722. }
  7723. MACAddress::MACAddress (const MACAddress& other)
  7724. : asInt64 (other.asInt64)
  7725. {
  7726. }
  7727. MACAddress& MACAddress::operator= (const MACAddress& other)
  7728. {
  7729. asInt64 = other.asInt64;
  7730. return *this;
  7731. }
  7732. MACAddress::MACAddress (const uint8 bytes[6])
  7733. : asInt64 (0)
  7734. {
  7735. memcpy (asBytes, bytes, sizeof (asBytes));
  7736. }
  7737. const String MACAddress::toString() const
  7738. {
  7739. String s;
  7740. s.preallocateStorage (18);
  7741. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7742. {
  7743. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7744. if (i < numElementsInArray (asBytes) - 1)
  7745. s << '-';
  7746. }
  7747. return s;
  7748. }
  7749. int64 MACAddress::toInt64() const throw()
  7750. {
  7751. int64 n = 0;
  7752. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7753. n = (n << 8) | asBytes[i];
  7754. return n;
  7755. }
  7756. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7757. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7758. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7759. END_JUCE_NAMESPACE
  7760. /*** End of inlined file: juce_MACAddress.cpp ***/
  7761. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7762. BEGIN_JUCE_NAMESPACE
  7763. namespace
  7764. {
  7765. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7766. {
  7767. // You need to supply a real stream when creating a BufferedInputStream
  7768. jassert (source != 0);
  7769. requestedSize = jmax (256, requestedSize);
  7770. const int64 sourceSize = source->getTotalLength();
  7771. if (sourceSize >= 0 && sourceSize < requestedSize)
  7772. requestedSize = jmax (32, (int) sourceSize);
  7773. return requestedSize;
  7774. }
  7775. }
  7776. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7777. const bool deleteSourceWhenDestroyed)
  7778. : source (sourceStream),
  7779. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7780. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7781. position (sourceStream->getPosition()),
  7782. lastReadPos (0),
  7783. bufferStart (position),
  7784. bufferOverlap (128)
  7785. {
  7786. buffer.malloc (bufferSize);
  7787. }
  7788. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7789. : source (&sourceStream),
  7790. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7791. position (sourceStream.getPosition()),
  7792. lastReadPos (0),
  7793. bufferStart (position),
  7794. bufferOverlap (128)
  7795. {
  7796. buffer.malloc (bufferSize);
  7797. }
  7798. BufferedInputStream::~BufferedInputStream()
  7799. {
  7800. }
  7801. int64 BufferedInputStream::getTotalLength()
  7802. {
  7803. return source->getTotalLength();
  7804. }
  7805. int64 BufferedInputStream::getPosition()
  7806. {
  7807. return position;
  7808. }
  7809. bool BufferedInputStream::setPosition (int64 newPosition)
  7810. {
  7811. position = jmax ((int64) 0, newPosition);
  7812. return true;
  7813. }
  7814. bool BufferedInputStream::isExhausted()
  7815. {
  7816. return (position >= lastReadPos)
  7817. && source->isExhausted();
  7818. }
  7819. void BufferedInputStream::ensureBuffered()
  7820. {
  7821. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7822. if (position < bufferStart || position >= bufferEndOverlap)
  7823. {
  7824. int bytesRead;
  7825. if (position < lastReadPos
  7826. && position >= bufferEndOverlap
  7827. && position >= bufferStart)
  7828. {
  7829. const int bytesToKeep = (int) (lastReadPos - position);
  7830. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7831. bufferStart = position;
  7832. bytesRead = source->read (buffer + bytesToKeep,
  7833. bufferSize - bytesToKeep);
  7834. lastReadPos += bytesRead;
  7835. bytesRead += bytesToKeep;
  7836. }
  7837. else
  7838. {
  7839. bufferStart = position;
  7840. source->setPosition (bufferStart);
  7841. bytesRead = source->read (buffer, bufferSize);
  7842. lastReadPos = bufferStart + bytesRead;
  7843. }
  7844. while (bytesRead < bufferSize)
  7845. buffer [bytesRead++] = 0;
  7846. }
  7847. }
  7848. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7849. {
  7850. if (position >= bufferStart
  7851. && position + maxBytesToRead <= lastReadPos)
  7852. {
  7853. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7854. position += maxBytesToRead;
  7855. return maxBytesToRead;
  7856. }
  7857. else
  7858. {
  7859. if (position < bufferStart || position >= lastReadPos)
  7860. ensureBuffered();
  7861. int bytesRead = 0;
  7862. while (maxBytesToRead > 0)
  7863. {
  7864. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7865. if (bytesAvailable > 0)
  7866. {
  7867. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7868. maxBytesToRead -= bytesAvailable;
  7869. bytesRead += bytesAvailable;
  7870. position += bytesAvailable;
  7871. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7872. }
  7873. const int64 oldLastReadPos = lastReadPos;
  7874. ensureBuffered();
  7875. if (oldLastReadPos == lastReadPos)
  7876. break; // if ensureBuffered() failed to read any more data, bail out
  7877. if (isExhausted())
  7878. break;
  7879. }
  7880. return bytesRead;
  7881. }
  7882. }
  7883. const String BufferedInputStream::readString()
  7884. {
  7885. if (position >= bufferStart
  7886. && position < lastReadPos)
  7887. {
  7888. const int maxChars = (int) (lastReadPos - position);
  7889. const char* const src = buffer + (int) (position - bufferStart);
  7890. for (int i = 0; i < maxChars; ++i)
  7891. {
  7892. if (src[i] == 0)
  7893. {
  7894. position += i + 1;
  7895. return String::fromUTF8 (src, i);
  7896. }
  7897. }
  7898. }
  7899. return InputStream::readString();
  7900. }
  7901. END_JUCE_NAMESPACE
  7902. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7903. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7904. BEGIN_JUCE_NAMESPACE
  7905. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  7906. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  7907. {
  7908. }
  7909. FileInputSource::~FileInputSource()
  7910. {
  7911. }
  7912. InputStream* FileInputSource::createInputStream()
  7913. {
  7914. return file.createInputStream();
  7915. }
  7916. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7917. {
  7918. return file.getSiblingFile (relatedItemPath).createInputStream();
  7919. }
  7920. int64 FileInputSource::hashCode() const
  7921. {
  7922. int64 h = file.hashCode();
  7923. if (useFileTimeInHashGeneration)
  7924. h ^= file.getLastModificationTime().toMilliseconds();
  7925. return h;
  7926. }
  7927. END_JUCE_NAMESPACE
  7928. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7929. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7930. BEGIN_JUCE_NAMESPACE
  7931. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7932. const size_t sourceDataSize,
  7933. const bool keepInternalCopy)
  7934. : data (static_cast <const char*> (sourceData)),
  7935. dataSize (sourceDataSize),
  7936. position (0)
  7937. {
  7938. if (keepInternalCopy)
  7939. {
  7940. internalCopy.append (data, sourceDataSize);
  7941. data = static_cast <const char*> (internalCopy.getData());
  7942. }
  7943. }
  7944. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7945. const bool keepInternalCopy)
  7946. : data (static_cast <const char*> (sourceData.getData())),
  7947. dataSize (sourceData.getSize()),
  7948. position (0)
  7949. {
  7950. if (keepInternalCopy)
  7951. {
  7952. internalCopy = sourceData;
  7953. data = static_cast <const char*> (internalCopy.getData());
  7954. }
  7955. }
  7956. MemoryInputStream::~MemoryInputStream()
  7957. {
  7958. }
  7959. int64 MemoryInputStream::getTotalLength()
  7960. {
  7961. return dataSize;
  7962. }
  7963. int MemoryInputStream::read (void* const buffer, const int howMany)
  7964. {
  7965. jassert (howMany >= 0);
  7966. const int num = jmin (howMany, (int) (dataSize - position));
  7967. memcpy (buffer, data + position, num);
  7968. position += num;
  7969. return (int) num;
  7970. }
  7971. bool MemoryInputStream::isExhausted()
  7972. {
  7973. return (position >= dataSize);
  7974. }
  7975. bool MemoryInputStream::setPosition (const int64 pos)
  7976. {
  7977. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  7978. return true;
  7979. }
  7980. int64 MemoryInputStream::getPosition()
  7981. {
  7982. return position;
  7983. }
  7984. #if JUCE_UNIT_TESTS
  7985. class MemoryStreamTests : public UnitTest
  7986. {
  7987. public:
  7988. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  7989. void runTest()
  7990. {
  7991. beginTest ("Basics");
  7992. int randomInt = Random::getSystemRandom().nextInt();
  7993. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  7994. double randomDouble = Random::getSystemRandom().nextDouble();
  7995. String randomString;
  7996. for (int i = 50; --i >= 0;)
  7997. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  7998. MemoryOutputStream mo;
  7999. mo.writeInt (randomInt);
  8000. mo.writeIntBigEndian (randomInt);
  8001. mo.writeCompressedInt (randomInt);
  8002. mo.writeString (randomString);
  8003. mo.writeInt64 (randomInt64);
  8004. mo.writeInt64BigEndian (randomInt64);
  8005. mo.writeDouble (randomDouble);
  8006. mo.writeDoubleBigEndian (randomDouble);
  8007. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8008. expect (mi.readInt() == randomInt);
  8009. expect (mi.readIntBigEndian() == randomInt);
  8010. expect (mi.readCompressedInt() == randomInt);
  8011. expect (mi.readString() == randomString);
  8012. expect (mi.readInt64() == randomInt64);
  8013. expect (mi.readInt64BigEndian() == randomInt64);
  8014. expect (mi.readDouble() == randomDouble);
  8015. expect (mi.readDoubleBigEndian() == randomDouble);
  8016. }
  8017. };
  8018. static MemoryStreamTests memoryInputStreamUnitTests;
  8019. #endif
  8020. END_JUCE_NAMESPACE
  8021. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8022. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8023. BEGIN_JUCE_NAMESPACE
  8024. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8025. : data (internalBlock),
  8026. position (0),
  8027. size (0)
  8028. {
  8029. internalBlock.setSize (initialSize, false);
  8030. }
  8031. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8032. const bool appendToExistingBlockContent)
  8033. : data (memoryBlockToWriteTo),
  8034. position (0),
  8035. size (0)
  8036. {
  8037. if (appendToExistingBlockContent)
  8038. position = size = memoryBlockToWriteTo.getSize();
  8039. }
  8040. MemoryOutputStream::~MemoryOutputStream()
  8041. {
  8042. flush();
  8043. }
  8044. void MemoryOutputStream::flush()
  8045. {
  8046. if (&data != &internalBlock)
  8047. data.setSize (size, false);
  8048. }
  8049. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8050. {
  8051. data.ensureSize (bytesToPreallocate + 1);
  8052. }
  8053. void MemoryOutputStream::reset() throw()
  8054. {
  8055. position = 0;
  8056. size = 0;
  8057. }
  8058. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8059. {
  8060. if (howMany > 0)
  8061. {
  8062. const size_t storageNeeded = position + howMany;
  8063. if (storageNeeded >= data.getSize())
  8064. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8065. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8066. position += howMany;
  8067. size = jmax (size, position);
  8068. }
  8069. return true;
  8070. }
  8071. const void* MemoryOutputStream::getData() const throw()
  8072. {
  8073. void* const d = data.getData();
  8074. if (data.getSize() > size)
  8075. static_cast <char*> (d) [size] = 0;
  8076. return d;
  8077. }
  8078. bool MemoryOutputStream::setPosition (int64 newPosition)
  8079. {
  8080. if (newPosition <= (int64) size)
  8081. {
  8082. // ok to seek backwards
  8083. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8084. return true;
  8085. }
  8086. else
  8087. {
  8088. // trying to make it bigger isn't a good thing to do..
  8089. return false;
  8090. }
  8091. }
  8092. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8093. {
  8094. // before writing from an input, see if we can preallocate to make it more efficient..
  8095. int64 availableData = source.getTotalLength() - source.getPosition();
  8096. if (availableData > 0)
  8097. {
  8098. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8099. availableData = maxNumBytesToWrite;
  8100. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8101. }
  8102. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8103. }
  8104. const String MemoryOutputStream::toUTF8() const
  8105. {
  8106. return String (static_cast <const char*> (getData()), getDataSize());
  8107. }
  8108. const String MemoryOutputStream::toString() const
  8109. {
  8110. return String::createStringFromData (getData(), (int) getDataSize());
  8111. }
  8112. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8113. {
  8114. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8115. return stream;
  8116. }
  8117. END_JUCE_NAMESPACE
  8118. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8119. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8120. BEGIN_JUCE_NAMESPACE
  8121. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8122. const int64 startPositionInSourceStream_,
  8123. const int64 lengthOfSourceStream_,
  8124. const bool deleteSourceWhenDestroyed)
  8125. : source (sourceStream),
  8126. startPositionInSourceStream (startPositionInSourceStream_),
  8127. lengthOfSourceStream (lengthOfSourceStream_)
  8128. {
  8129. if (deleteSourceWhenDestroyed)
  8130. sourceToDelete = source;
  8131. setPosition (0);
  8132. }
  8133. SubregionStream::~SubregionStream()
  8134. {
  8135. }
  8136. int64 SubregionStream::getTotalLength()
  8137. {
  8138. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8139. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8140. : srcLen;
  8141. }
  8142. int64 SubregionStream::getPosition()
  8143. {
  8144. return source->getPosition() - startPositionInSourceStream;
  8145. }
  8146. bool SubregionStream::setPosition (int64 newPosition)
  8147. {
  8148. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8149. }
  8150. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8151. {
  8152. if (lengthOfSourceStream < 0)
  8153. {
  8154. return source->read (destBuffer, maxBytesToRead);
  8155. }
  8156. else
  8157. {
  8158. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8159. if (maxBytesToRead <= 0)
  8160. return 0;
  8161. return source->read (destBuffer, maxBytesToRead);
  8162. }
  8163. }
  8164. bool SubregionStream::isExhausted()
  8165. {
  8166. if (lengthOfSourceStream >= 0)
  8167. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8168. else
  8169. return source->isExhausted();
  8170. }
  8171. END_JUCE_NAMESPACE
  8172. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8173. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8174. BEGIN_JUCE_NAMESPACE
  8175. PerformanceCounter::PerformanceCounter (const String& name_,
  8176. int runsPerPrintout,
  8177. const File& loggingFile)
  8178. : name (name_),
  8179. numRuns (0),
  8180. runsPerPrint (runsPerPrintout),
  8181. totalTime (0),
  8182. outputFile (loggingFile)
  8183. {
  8184. if (outputFile != File::nonexistent)
  8185. {
  8186. String s ("**** Counter for \"");
  8187. s << name_ << "\" started at: "
  8188. << Time::getCurrentTime().toString (true, true)
  8189. << newLine;
  8190. outputFile.appendText (s, false, false);
  8191. }
  8192. }
  8193. PerformanceCounter::~PerformanceCounter()
  8194. {
  8195. printStatistics();
  8196. }
  8197. void PerformanceCounter::start()
  8198. {
  8199. started = Time::getHighResolutionTicks();
  8200. }
  8201. void PerformanceCounter::stop()
  8202. {
  8203. const int64 now = Time::getHighResolutionTicks();
  8204. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8205. if (++numRuns == runsPerPrint)
  8206. printStatistics();
  8207. }
  8208. void PerformanceCounter::printStatistics()
  8209. {
  8210. if (numRuns > 0)
  8211. {
  8212. String s ("Performance count for \"");
  8213. s << name << "\" - average over " << numRuns << " run(s) = ";
  8214. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8215. if (micros > 10000)
  8216. s << (micros/1000) << " millisecs";
  8217. else
  8218. s << micros << " microsecs";
  8219. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8220. Logger::outputDebugString (s);
  8221. s << newLine;
  8222. if (outputFile != File::nonexistent)
  8223. outputFile.appendText (s, false, false);
  8224. numRuns = 0;
  8225. totalTime = 0;
  8226. }
  8227. }
  8228. END_JUCE_NAMESPACE
  8229. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8230. /*** Start of inlined file: juce_Uuid.cpp ***/
  8231. BEGIN_JUCE_NAMESPACE
  8232. Uuid::Uuid()
  8233. {
  8234. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8235. // to make it very very unlikely that two UUIDs will ever be the same..
  8236. static int64 macAddresses[2];
  8237. static bool hasCheckedMacAddresses = false;
  8238. if (! hasCheckedMacAddresses)
  8239. {
  8240. hasCheckedMacAddresses = true;
  8241. Array<MACAddress> result;
  8242. MACAddress::findAllAddresses (result);
  8243. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8244. macAddresses[i] = result[i].toInt64();
  8245. }
  8246. value.asInt64[0] = macAddresses[0];
  8247. value.asInt64[1] = macAddresses[1];
  8248. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8249. // whose seed will carry over between calls to this method.
  8250. Random r (macAddresses[0] ^ macAddresses[1]
  8251. ^ Random::getSystemRandom().nextInt64());
  8252. for (int i = 4; --i >= 0;)
  8253. {
  8254. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8255. value.asInt[i] ^= r.nextInt();
  8256. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8257. }
  8258. }
  8259. Uuid::~Uuid() throw()
  8260. {
  8261. }
  8262. Uuid::Uuid (const Uuid& other)
  8263. : value (other.value)
  8264. {
  8265. }
  8266. Uuid& Uuid::operator= (const Uuid& other)
  8267. {
  8268. value = other.value;
  8269. return *this;
  8270. }
  8271. bool Uuid::operator== (const Uuid& other) const
  8272. {
  8273. return value.asInt64[0] == other.value.asInt64[0]
  8274. && value.asInt64[1] == other.value.asInt64[1];
  8275. }
  8276. bool Uuid::operator!= (const Uuid& other) const
  8277. {
  8278. return ! operator== (other);
  8279. }
  8280. bool Uuid::isNull() const throw()
  8281. {
  8282. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8283. }
  8284. const String Uuid::toString() const
  8285. {
  8286. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8287. }
  8288. Uuid::Uuid (const String& uuidString)
  8289. {
  8290. operator= (uuidString);
  8291. }
  8292. Uuid& Uuid::operator= (const String& uuidString)
  8293. {
  8294. MemoryBlock mb;
  8295. mb.loadFromHexString (uuidString);
  8296. mb.ensureSize (sizeof (value.asBytes), true);
  8297. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8298. return *this;
  8299. }
  8300. Uuid::Uuid (const uint8* const rawData)
  8301. {
  8302. operator= (rawData);
  8303. }
  8304. Uuid& Uuid::operator= (const uint8* const rawData)
  8305. {
  8306. if (rawData != 0)
  8307. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8308. else
  8309. zeromem (value.asBytes, sizeof (value.asBytes));
  8310. return *this;
  8311. }
  8312. END_JUCE_NAMESPACE
  8313. /*** End of inlined file: juce_Uuid.cpp ***/
  8314. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8315. BEGIN_JUCE_NAMESPACE
  8316. class ZipFile::ZipEntryInfo
  8317. {
  8318. public:
  8319. ZipFile::ZipEntry entry;
  8320. int streamOffset;
  8321. int compressedSize;
  8322. bool compressed;
  8323. };
  8324. class ZipFile::ZipInputStream : public InputStream
  8325. {
  8326. public:
  8327. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8328. : file (file_),
  8329. zipEntryInfo (zei),
  8330. pos (0),
  8331. headerSize (0),
  8332. inputStream (0)
  8333. {
  8334. inputStream = file_.inputStream;
  8335. if (file_.inputSource != 0)
  8336. {
  8337. inputStream = streamToDelete = file.inputSource->createInputStream();
  8338. }
  8339. else
  8340. {
  8341. #if JUCE_DEBUG
  8342. file_.numOpenStreams++;
  8343. #endif
  8344. }
  8345. char buffer [30];
  8346. if (inputStream != 0
  8347. && inputStream->setPosition (zei.streamOffset)
  8348. && inputStream->read (buffer, 30) == 30
  8349. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8350. {
  8351. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8352. + ByteOrder::littleEndianShort (buffer + 28);
  8353. }
  8354. }
  8355. ~ZipInputStream()
  8356. {
  8357. #if JUCE_DEBUG
  8358. if (inputStream != 0 && inputStream == file.inputStream)
  8359. file.numOpenStreams--;
  8360. #endif
  8361. }
  8362. int64 getTotalLength()
  8363. {
  8364. return zipEntryInfo.compressedSize;
  8365. }
  8366. int read (void* buffer, int howMany)
  8367. {
  8368. if (headerSize <= 0)
  8369. return 0;
  8370. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8371. if (inputStream == 0)
  8372. return 0;
  8373. int num;
  8374. if (inputStream == file.inputStream)
  8375. {
  8376. const ScopedLock sl (file.lock);
  8377. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8378. num = inputStream->read (buffer, howMany);
  8379. }
  8380. else
  8381. {
  8382. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8383. num = inputStream->read (buffer, howMany);
  8384. }
  8385. pos += num;
  8386. return num;
  8387. }
  8388. bool isExhausted()
  8389. {
  8390. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8391. }
  8392. int64 getPosition()
  8393. {
  8394. return pos;
  8395. }
  8396. bool setPosition (int64 newPos)
  8397. {
  8398. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8399. return true;
  8400. }
  8401. private:
  8402. ZipFile& file;
  8403. ZipEntryInfo zipEntryInfo;
  8404. int64 pos;
  8405. int headerSize;
  8406. InputStream* inputStream;
  8407. ScopedPointer<InputStream> streamToDelete;
  8408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8409. };
  8410. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8411. : inputStream (source_)
  8412. #if JUCE_DEBUG
  8413. , numOpenStreams (0)
  8414. #endif
  8415. {
  8416. if (deleteStreamWhenDestroyed)
  8417. streamToDelete = inputStream;
  8418. init();
  8419. }
  8420. ZipFile::ZipFile (const File& file)
  8421. : inputStream (0)
  8422. #if JUCE_DEBUG
  8423. , numOpenStreams (0)
  8424. #endif
  8425. {
  8426. inputSource = new FileInputSource (file);
  8427. init();
  8428. }
  8429. ZipFile::ZipFile (InputSource* const inputSource_)
  8430. : inputStream (0),
  8431. inputSource (inputSource_)
  8432. #if JUCE_DEBUG
  8433. , numOpenStreams (0)
  8434. #endif
  8435. {
  8436. init();
  8437. }
  8438. ZipFile::~ZipFile()
  8439. {
  8440. #if JUCE_DEBUG
  8441. entries.clear();
  8442. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8443. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8444. Streams can't be kept open after the file is deleted because they need to share the input
  8445. stream that the file uses to read itself.
  8446. */
  8447. jassert (numOpenStreams == 0);
  8448. #endif
  8449. }
  8450. int ZipFile::getNumEntries() const throw()
  8451. {
  8452. return entries.size();
  8453. }
  8454. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8455. {
  8456. ZipEntryInfo* const zei = entries [index];
  8457. return zei != 0 ? &(zei->entry) : 0;
  8458. }
  8459. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8460. {
  8461. for (int i = 0; i < entries.size(); ++i)
  8462. if (entries.getUnchecked (i)->entry.filename == fileName)
  8463. return i;
  8464. return -1;
  8465. }
  8466. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8467. {
  8468. return getEntry (getIndexOfFileName (fileName));
  8469. }
  8470. InputStream* ZipFile::createStreamForEntry (const int index)
  8471. {
  8472. ZipEntryInfo* const zei = entries[index];
  8473. InputStream* stream = 0;
  8474. if (zei != 0)
  8475. {
  8476. stream = new ZipInputStream (*this, *zei);
  8477. if (zei->compressed)
  8478. {
  8479. stream = new GZIPDecompressorInputStream (stream, true, true,
  8480. zei->entry.uncompressedSize);
  8481. // (much faster to unzip in big blocks using a buffer..)
  8482. stream = new BufferedInputStream (stream, 32768, true);
  8483. }
  8484. }
  8485. return stream;
  8486. }
  8487. class ZipFile::ZipFilenameComparator
  8488. {
  8489. public:
  8490. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8491. {
  8492. return first->entry.filename.compare (second->entry.filename);
  8493. }
  8494. };
  8495. void ZipFile::sortEntriesByFilename()
  8496. {
  8497. ZipFilenameComparator sorter;
  8498. entries.sort (sorter);
  8499. }
  8500. void ZipFile::init()
  8501. {
  8502. ScopedPointer <InputStream> toDelete;
  8503. InputStream* in = inputStream;
  8504. if (inputSource != 0)
  8505. {
  8506. in = inputSource->createInputStream();
  8507. toDelete = in;
  8508. }
  8509. if (in != 0)
  8510. {
  8511. int numEntries = 0;
  8512. int pos = findEndOfZipEntryTable (*in, numEntries);
  8513. if (pos >= 0 && pos < in->getTotalLength())
  8514. {
  8515. const int size = (int) (in->getTotalLength() - pos);
  8516. in->setPosition (pos);
  8517. MemoryBlock headerData;
  8518. if (in->readIntoMemoryBlock (headerData, size) == size)
  8519. {
  8520. pos = 0;
  8521. for (int i = 0; i < numEntries; ++i)
  8522. {
  8523. if (pos + 46 > size)
  8524. break;
  8525. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8526. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8527. if (pos + 46 + fileNameLen > size)
  8528. break;
  8529. ZipEntryInfo* const zei = new ZipEntryInfo();
  8530. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8531. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8532. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8533. const int year = 1980 + (date >> 9);
  8534. const int month = ((date >> 5) & 15) - 1;
  8535. const int day = date & 31;
  8536. const int hours = time >> 11;
  8537. const int minutes = (time >> 5) & 63;
  8538. const int seconds = (time & 31) << 1;
  8539. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8540. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8541. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8542. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8543. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8544. entries.add (zei);
  8545. pos += 46 + fileNameLen
  8546. + ByteOrder::littleEndianShort (buffer + 30)
  8547. + ByteOrder::littleEndianShort (buffer + 32);
  8548. }
  8549. }
  8550. }
  8551. }
  8552. }
  8553. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8554. {
  8555. BufferedInputStream in (input, 8192);
  8556. in.setPosition (in.getTotalLength());
  8557. int64 pos = in.getPosition();
  8558. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8559. char buffer [32];
  8560. zeromem (buffer, sizeof (buffer));
  8561. while (pos > lowestPos)
  8562. {
  8563. in.setPosition (pos - 22);
  8564. pos = in.getPosition();
  8565. memcpy (buffer + 22, buffer, 4);
  8566. if (in.read (buffer, 22) != 22)
  8567. return 0;
  8568. for (int i = 0; i < 22; ++i)
  8569. {
  8570. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8571. {
  8572. in.setPosition (pos + i);
  8573. in.read (buffer, 22);
  8574. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8575. return ByteOrder::littleEndianInt (buffer + 16);
  8576. }
  8577. }
  8578. }
  8579. return 0;
  8580. }
  8581. bool ZipFile::uncompressTo (const File& targetDirectory,
  8582. const bool shouldOverwriteFiles)
  8583. {
  8584. for (int i = 0; i < entries.size(); ++i)
  8585. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8586. return false;
  8587. return true;
  8588. }
  8589. bool ZipFile::uncompressEntry (const int index,
  8590. const File& targetDirectory,
  8591. bool shouldOverwriteFiles)
  8592. {
  8593. const ZipEntryInfo* zei = entries [index];
  8594. if (zei != 0)
  8595. {
  8596. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8597. if (zei->entry.filename.endsWithChar ('/'))
  8598. {
  8599. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8600. }
  8601. else
  8602. {
  8603. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8604. if (in != 0)
  8605. {
  8606. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8607. return false;
  8608. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8609. {
  8610. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8611. if (out != 0)
  8612. {
  8613. out->writeFromInputStream (*in, -1);
  8614. out = 0;
  8615. targetFile.setCreationTime (zei->entry.fileTime);
  8616. targetFile.setLastModificationTime (zei->entry.fileTime);
  8617. targetFile.setLastAccessTime (zei->entry.fileTime);
  8618. return true;
  8619. }
  8620. }
  8621. }
  8622. }
  8623. }
  8624. return false;
  8625. }
  8626. END_JUCE_NAMESPACE
  8627. /*** End of inlined file: juce_ZipFile.cpp ***/
  8628. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8629. #if JUCE_MSVC
  8630. #pragma warning (push)
  8631. #pragma warning (disable: 4514 4996)
  8632. #endif
  8633. #include <cwctype>
  8634. #include <cctype>
  8635. #include <ctime>
  8636. BEGIN_JUCE_NAMESPACE
  8637. int CharacterFunctions::length (const char* const s) throw()
  8638. {
  8639. return (int) strlen (s);
  8640. }
  8641. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8642. {
  8643. return (int) wcslen (s);
  8644. }
  8645. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8646. {
  8647. strncpy (dest, src, maxChars);
  8648. }
  8649. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8650. {
  8651. wcsncpy (dest, src, maxChars);
  8652. }
  8653. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8654. {
  8655. mbstowcs (dest, src, maxChars);
  8656. }
  8657. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8658. {
  8659. wcstombs (dest, src, maxChars);
  8660. }
  8661. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8662. {
  8663. return (int) wcstombs (0, src, 0);
  8664. }
  8665. void CharacterFunctions::append (char* dest, const char* src) throw()
  8666. {
  8667. strcat (dest, src);
  8668. }
  8669. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8670. {
  8671. wcscat (dest, src);
  8672. }
  8673. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8674. {
  8675. return strcmp (s1, s2);
  8676. }
  8677. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8678. {
  8679. jassert (s1 != 0 && s2 != 0);
  8680. return wcscmp (s1, s2);
  8681. }
  8682. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8683. {
  8684. jassert (s1 != 0 && s2 != 0);
  8685. return strncmp (s1, s2, maxChars);
  8686. }
  8687. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8688. {
  8689. jassert (s1 != 0 && s2 != 0);
  8690. return wcsncmp (s1, s2, maxChars);
  8691. }
  8692. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8693. {
  8694. jassert (s1 != 0 && s2 != 0);
  8695. for (;;)
  8696. {
  8697. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8698. if (diff != 0)
  8699. return diff;
  8700. else if (*s1 == 0)
  8701. break;
  8702. ++s1;
  8703. ++s2;
  8704. }
  8705. return 0;
  8706. }
  8707. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8708. {
  8709. return -compare (s2, s1);
  8710. }
  8711. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8712. {
  8713. jassert (s1 != 0 && s2 != 0);
  8714. #if JUCE_WINDOWS
  8715. return stricmp (s1, s2);
  8716. #else
  8717. return strcasecmp (s1, s2);
  8718. #endif
  8719. }
  8720. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8721. {
  8722. jassert (s1 != 0 && s2 != 0);
  8723. #if JUCE_WINDOWS
  8724. return _wcsicmp (s1, s2);
  8725. #else
  8726. for (;;)
  8727. {
  8728. if (*s1 != *s2)
  8729. {
  8730. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8731. if (diff != 0)
  8732. return diff < 0 ? -1 : 1;
  8733. }
  8734. else if (*s1 == 0)
  8735. break;
  8736. ++s1;
  8737. ++s2;
  8738. }
  8739. return 0;
  8740. #endif
  8741. }
  8742. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8743. {
  8744. jassert (s1 != 0 && s2 != 0);
  8745. for (;;)
  8746. {
  8747. if (*s1 != *s2)
  8748. {
  8749. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8750. if (diff != 0)
  8751. return diff < 0 ? -1 : 1;
  8752. }
  8753. else if (*s1 == 0)
  8754. break;
  8755. ++s1;
  8756. ++s2;
  8757. }
  8758. return 0;
  8759. }
  8760. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8761. {
  8762. jassert (s1 != 0 && s2 != 0);
  8763. #if JUCE_WINDOWS
  8764. return strnicmp (s1, s2, maxChars);
  8765. #else
  8766. return strncasecmp (s1, s2, maxChars);
  8767. #endif
  8768. }
  8769. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8770. {
  8771. jassert (s1 != 0 && s2 != 0);
  8772. #if JUCE_WINDOWS
  8773. return _wcsnicmp (s1, s2, maxChars);
  8774. #else
  8775. while (--maxChars >= 0)
  8776. {
  8777. if (*s1 != *s2)
  8778. {
  8779. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8780. if (diff != 0)
  8781. return diff < 0 ? -1 : 1;
  8782. }
  8783. else if (*s1 == 0)
  8784. break;
  8785. ++s1;
  8786. ++s2;
  8787. }
  8788. return 0;
  8789. #endif
  8790. }
  8791. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8792. {
  8793. return strstr (haystack, needle);
  8794. }
  8795. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8796. {
  8797. return wcsstr (haystack, needle);
  8798. }
  8799. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8800. {
  8801. if (haystack != 0)
  8802. {
  8803. int i = 0;
  8804. if (ignoreCase)
  8805. {
  8806. const char n1 = toLowerCase (needle);
  8807. const char n2 = toUpperCase (needle);
  8808. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8809. {
  8810. while (haystack[i] != 0)
  8811. {
  8812. if (haystack[i] == n1 || haystack[i] == n2)
  8813. return i;
  8814. ++i;
  8815. }
  8816. return -1;
  8817. }
  8818. jassert (n1 == needle);
  8819. }
  8820. while (haystack[i] != 0)
  8821. {
  8822. if (haystack[i] == needle)
  8823. return i;
  8824. ++i;
  8825. }
  8826. }
  8827. return -1;
  8828. }
  8829. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8830. {
  8831. if (haystack != 0)
  8832. {
  8833. int i = 0;
  8834. if (ignoreCase)
  8835. {
  8836. const juce_wchar n1 = toLowerCase (needle);
  8837. const juce_wchar n2 = toUpperCase (needle);
  8838. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8839. {
  8840. while (haystack[i] != 0)
  8841. {
  8842. if (haystack[i] == n1 || haystack[i] == n2)
  8843. return i;
  8844. ++i;
  8845. }
  8846. return -1;
  8847. }
  8848. jassert (n1 == needle);
  8849. }
  8850. while (haystack[i] != 0)
  8851. {
  8852. if (haystack[i] == needle)
  8853. return i;
  8854. ++i;
  8855. }
  8856. }
  8857. return -1;
  8858. }
  8859. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8860. {
  8861. jassert (haystack != 0);
  8862. int i = 0;
  8863. while (haystack[i] != 0)
  8864. {
  8865. if (haystack[i] == needle)
  8866. return i;
  8867. ++i;
  8868. }
  8869. return -1;
  8870. }
  8871. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8872. {
  8873. jassert (haystack != 0);
  8874. int i = 0;
  8875. while (haystack[i] != 0)
  8876. {
  8877. if (haystack[i] == needle)
  8878. return i;
  8879. ++i;
  8880. }
  8881. return -1;
  8882. }
  8883. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8884. {
  8885. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8886. }
  8887. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8888. {
  8889. if (allowedChars == 0)
  8890. return 0;
  8891. int i = 0;
  8892. for (;;)
  8893. {
  8894. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8895. break;
  8896. ++i;
  8897. }
  8898. return i;
  8899. }
  8900. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8901. {
  8902. return (int) strftime (dest, maxChars, format, tm);
  8903. }
  8904. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8905. {
  8906. return (int) wcsftime (dest, maxChars, format, tm);
  8907. }
  8908. int CharacterFunctions::getIntValue (const char* const s) throw()
  8909. {
  8910. return atoi (s);
  8911. }
  8912. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8913. {
  8914. #if JUCE_WINDOWS
  8915. return _wtoi (s);
  8916. #else
  8917. int v = 0;
  8918. while (isWhitespace (*s))
  8919. ++s;
  8920. const bool isNeg = *s == '-';
  8921. if (isNeg)
  8922. ++s;
  8923. for (;;)
  8924. {
  8925. const wchar_t c = *s++;
  8926. if (c >= '0' && c <= '9')
  8927. v = v * 10 + (int) (c - '0');
  8928. else
  8929. break;
  8930. }
  8931. return isNeg ? -v : v;
  8932. #endif
  8933. }
  8934. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8935. {
  8936. #if JUCE_LINUX
  8937. return atoll (s);
  8938. #elif JUCE_WINDOWS
  8939. return _atoi64 (s);
  8940. #else
  8941. int64 v = 0;
  8942. while (isWhitespace (*s))
  8943. ++s;
  8944. const bool isNeg = *s == '-';
  8945. if (isNeg)
  8946. ++s;
  8947. for (;;)
  8948. {
  8949. const char c = *s++;
  8950. if (c >= '0' && c <= '9')
  8951. v = v * 10 + (int64) (c - '0');
  8952. else
  8953. break;
  8954. }
  8955. return isNeg ? -v : v;
  8956. #endif
  8957. }
  8958. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8959. {
  8960. #if JUCE_WINDOWS
  8961. return _wtoi64 (s);
  8962. #else
  8963. int64 v = 0;
  8964. while (isWhitespace (*s))
  8965. ++s;
  8966. const bool isNeg = *s == '-';
  8967. if (isNeg)
  8968. ++s;
  8969. for (;;)
  8970. {
  8971. const juce_wchar c = *s++;
  8972. if (c >= '0' && c <= '9')
  8973. v = v * 10 + (int64) (c - '0');
  8974. else
  8975. break;
  8976. }
  8977. return isNeg ? -v : v;
  8978. #endif
  8979. }
  8980. namespace
  8981. {
  8982. double juce_mulexp10 (const double value, int exponent) throw()
  8983. {
  8984. if (exponent == 0)
  8985. return value;
  8986. if (value == 0)
  8987. return 0;
  8988. const bool negative = (exponent < 0);
  8989. if (negative)
  8990. exponent = -exponent;
  8991. double result = 1.0, power = 10.0;
  8992. for (int bit = 1; exponent != 0; bit <<= 1)
  8993. {
  8994. if ((exponent & bit) != 0)
  8995. {
  8996. exponent ^= bit;
  8997. result *= power;
  8998. if (exponent == 0)
  8999. break;
  9000. }
  9001. power *= power;
  9002. }
  9003. return negative ? (value / result) : (value * result);
  9004. }
  9005. template <class CharType>
  9006. double juce_atof (const CharType* const original) throw()
  9007. {
  9008. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9009. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9010. int exponent = 0, decPointIndex = 0, digit = 0;
  9011. int lastDigit = 0, numSignificantDigits = 0;
  9012. bool isNegative = false, digitsFound = false;
  9013. const int maxSignificantDigits = 15 + 2;
  9014. const CharType* s = original;
  9015. while (CharacterFunctions::isWhitespace (*s))
  9016. ++s;
  9017. switch (*s)
  9018. {
  9019. case '-': isNegative = true; // fall-through..
  9020. case '+': ++s;
  9021. }
  9022. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9023. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9024. for (;;)
  9025. {
  9026. if (CharacterFunctions::isDigit (*s))
  9027. {
  9028. lastDigit = digit;
  9029. digit = *s++ - '0';
  9030. digitsFound = true;
  9031. if (decPointIndex != 0)
  9032. exponentAdjustment[1]++;
  9033. if (numSignificantDigits == 0 && digit == 0)
  9034. continue;
  9035. if (++numSignificantDigits > maxSignificantDigits)
  9036. {
  9037. if (digit > 5)
  9038. ++accumulator [decPointIndex];
  9039. else if (digit == 5 && (lastDigit & 1) != 0)
  9040. ++accumulator [decPointIndex];
  9041. if (decPointIndex > 0)
  9042. exponentAdjustment[1]--;
  9043. else
  9044. exponentAdjustment[0]++;
  9045. while (CharacterFunctions::isDigit (*s))
  9046. {
  9047. ++s;
  9048. if (decPointIndex == 0)
  9049. exponentAdjustment[0]++;
  9050. }
  9051. }
  9052. else
  9053. {
  9054. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9055. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9056. {
  9057. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9058. + accumulator [decPointIndex];
  9059. accumulator [decPointIndex] = 0;
  9060. exponentAccumulator [decPointIndex] = 0;
  9061. }
  9062. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9063. exponentAccumulator [decPointIndex]++;
  9064. }
  9065. }
  9066. else if (decPointIndex == 0 && *s == '.')
  9067. {
  9068. ++s;
  9069. decPointIndex = 1;
  9070. if (numSignificantDigits > maxSignificantDigits)
  9071. {
  9072. while (CharacterFunctions::isDigit (*s))
  9073. ++s;
  9074. break;
  9075. }
  9076. }
  9077. else
  9078. {
  9079. break;
  9080. }
  9081. }
  9082. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9083. if (decPointIndex != 0)
  9084. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9085. if ((*s == 'e' || *s == 'E') && digitsFound)
  9086. {
  9087. bool negativeExponent = false;
  9088. switch (*++s)
  9089. {
  9090. case '-': negativeExponent = true; // fall-through..
  9091. case '+': ++s;
  9092. }
  9093. while (CharacterFunctions::isDigit (*s))
  9094. exponent = (exponent * 10) + (*s++ - '0');
  9095. if (negativeExponent)
  9096. exponent = -exponent;
  9097. }
  9098. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9099. if (decPointIndex != 0)
  9100. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9101. return isNegative ? -r : r;
  9102. }
  9103. }
  9104. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9105. {
  9106. return juce_atof <char> (s);
  9107. }
  9108. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9109. {
  9110. return juce_atof <juce_wchar> (s);
  9111. }
  9112. char CharacterFunctions::toUpperCase (const char character) throw()
  9113. {
  9114. return (char) toupper (character);
  9115. }
  9116. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9117. {
  9118. return towupper (character);
  9119. }
  9120. void CharacterFunctions::toUpperCase (char* s) throw()
  9121. {
  9122. #if JUCE_WINDOWS
  9123. strupr (s);
  9124. #else
  9125. while (*s != 0)
  9126. {
  9127. *s = toUpperCase (*s);
  9128. ++s;
  9129. }
  9130. #endif
  9131. }
  9132. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9133. {
  9134. #if JUCE_WINDOWS
  9135. _wcsupr (s);
  9136. #else
  9137. while (*s != 0)
  9138. {
  9139. *s = toUpperCase (*s);
  9140. ++s;
  9141. }
  9142. #endif
  9143. }
  9144. bool CharacterFunctions::isUpperCase (const char character) throw()
  9145. {
  9146. return isupper (character) != 0;
  9147. }
  9148. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9149. {
  9150. #if JUCE_WINDOWS
  9151. return iswupper (character) != 0;
  9152. #else
  9153. return toLowerCase (character) != character;
  9154. #endif
  9155. }
  9156. char CharacterFunctions::toLowerCase (const char character) throw()
  9157. {
  9158. return (char) tolower (character);
  9159. }
  9160. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9161. {
  9162. return towlower (character);
  9163. }
  9164. void CharacterFunctions::toLowerCase (char* s) throw()
  9165. {
  9166. #if JUCE_WINDOWS
  9167. strlwr (s);
  9168. #else
  9169. while (*s != 0)
  9170. {
  9171. *s = toLowerCase (*s);
  9172. ++s;
  9173. }
  9174. #endif
  9175. }
  9176. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9177. {
  9178. #if JUCE_WINDOWS
  9179. _wcslwr (s);
  9180. #else
  9181. while (*s != 0)
  9182. {
  9183. *s = toLowerCase (*s);
  9184. ++s;
  9185. }
  9186. #endif
  9187. }
  9188. bool CharacterFunctions::isLowerCase (const char character) throw()
  9189. {
  9190. return islower (character) != 0;
  9191. }
  9192. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9193. {
  9194. #if JUCE_WINDOWS
  9195. return iswlower (character) != 0;
  9196. #else
  9197. return toUpperCase (character) != character;
  9198. #endif
  9199. }
  9200. bool CharacterFunctions::isWhitespace (const char character) throw()
  9201. {
  9202. return character == ' ' || (character <= 13 && character >= 9);
  9203. }
  9204. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9205. {
  9206. return iswspace (character) != 0;
  9207. }
  9208. bool CharacterFunctions::isDigit (const char character) throw()
  9209. {
  9210. return (character >= '0' && character <= '9');
  9211. }
  9212. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9213. {
  9214. return iswdigit (character) != 0;
  9215. }
  9216. bool CharacterFunctions::isLetter (const char character) throw()
  9217. {
  9218. return (character >= 'a' && character <= 'z')
  9219. || (character >= 'A' && character <= 'Z');
  9220. }
  9221. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9222. {
  9223. return iswalpha (character) != 0;
  9224. }
  9225. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9226. {
  9227. return (character >= 'a' && character <= 'z')
  9228. || (character >= 'A' && character <= 'Z')
  9229. || (character >= '0' && character <= '9');
  9230. }
  9231. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9232. {
  9233. return iswalnum (character) != 0;
  9234. }
  9235. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9236. {
  9237. unsigned int d = digit - '0';
  9238. if (d < (unsigned int) 10)
  9239. return (int) d;
  9240. d += (unsigned int) ('0' - 'a');
  9241. if (d < (unsigned int) 6)
  9242. return (int) d + 10;
  9243. d += (unsigned int) ('a' - 'A');
  9244. if (d < (unsigned int) 6)
  9245. return (int) d + 10;
  9246. return -1;
  9247. }
  9248. #if JUCE_MSVC
  9249. #pragma warning (pop)
  9250. #endif
  9251. END_JUCE_NAMESPACE
  9252. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9253. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9254. BEGIN_JUCE_NAMESPACE
  9255. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9256. {
  9257. loadFromText (fileContents);
  9258. }
  9259. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9260. {
  9261. loadFromText (fileToLoad.loadFileAsString());
  9262. }
  9263. LocalisedStrings::~LocalisedStrings()
  9264. {
  9265. }
  9266. const String LocalisedStrings::translate (const String& text) const
  9267. {
  9268. return translations.getValue (text, text);
  9269. }
  9270. namespace
  9271. {
  9272. CriticalSection currentMappingsLock;
  9273. LocalisedStrings* currentMappings = 0;
  9274. int findCloseQuote (const String& text, int startPos)
  9275. {
  9276. juce_wchar lastChar = 0;
  9277. for (;;)
  9278. {
  9279. const juce_wchar c = text [startPos];
  9280. if (c == 0 || (c == '"' && lastChar != '\\'))
  9281. break;
  9282. lastChar = c;
  9283. ++startPos;
  9284. }
  9285. return startPos;
  9286. }
  9287. const String unescapeString (const String& s)
  9288. {
  9289. return s.replace ("\\\"", "\"")
  9290. .replace ("\\\'", "\'")
  9291. .replace ("\\t", "\t")
  9292. .replace ("\\r", "\r")
  9293. .replace ("\\n", "\n");
  9294. }
  9295. }
  9296. void LocalisedStrings::loadFromText (const String& fileContents)
  9297. {
  9298. StringArray lines;
  9299. lines.addLines (fileContents);
  9300. for (int i = 0; i < lines.size(); ++i)
  9301. {
  9302. String line (lines[i].trim());
  9303. if (line.startsWithChar ('"'))
  9304. {
  9305. int closeQuote = findCloseQuote (line, 1);
  9306. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9307. if (originalText.isNotEmpty())
  9308. {
  9309. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9310. closeQuote = findCloseQuote (line, openingQuote + 1);
  9311. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9312. if (newText.isNotEmpty())
  9313. translations.set (originalText, newText);
  9314. }
  9315. }
  9316. else if (line.startsWithIgnoreCase ("language:"))
  9317. {
  9318. languageName = line.substring (9).trim();
  9319. }
  9320. else if (line.startsWithIgnoreCase ("countries:"))
  9321. {
  9322. countryCodes.addTokens (line.substring (10).trim(), true);
  9323. countryCodes.trim();
  9324. countryCodes.removeEmptyStrings();
  9325. }
  9326. }
  9327. }
  9328. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9329. {
  9330. translations.setIgnoresCase (shouldIgnoreCase);
  9331. }
  9332. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9333. {
  9334. const ScopedLock sl (currentMappingsLock);
  9335. delete currentMappings;
  9336. currentMappings = newTranslations;
  9337. }
  9338. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9339. {
  9340. return currentMappings;
  9341. }
  9342. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9343. {
  9344. const ScopedLock sl (currentMappingsLock);
  9345. if (currentMappings != 0)
  9346. return currentMappings->translate (text);
  9347. return text;
  9348. }
  9349. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9350. {
  9351. return translateWithCurrentMappings (String (text));
  9352. }
  9353. END_JUCE_NAMESPACE
  9354. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9355. /*** Start of inlined file: juce_String.cpp ***/
  9356. #if JUCE_MSVC
  9357. #pragma warning (push)
  9358. #pragma warning (disable: 4514)
  9359. #endif
  9360. #include <locale>
  9361. BEGIN_JUCE_NAMESPACE
  9362. #if JUCE_MSVC
  9363. #pragma warning (pop)
  9364. #endif
  9365. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9366. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9367. #endif
  9368. NewLine newLine;
  9369. class StringHolder
  9370. {
  9371. public:
  9372. StringHolder()
  9373. : refCount (0x3fffffff), allocatedNumChars (0)
  9374. {
  9375. text[0] = 0;
  9376. }
  9377. static juce_wchar* createUninitialised (const size_t numChars)
  9378. {
  9379. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9380. s->refCount.value = 0;
  9381. s->allocatedNumChars = numChars;
  9382. return &(s->text[0]);
  9383. }
  9384. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9385. {
  9386. juce_wchar* const dest = createUninitialised (numChars);
  9387. copyChars (dest, src, numChars);
  9388. return dest;
  9389. }
  9390. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9391. {
  9392. juce_wchar* const dest = createUninitialised (numChars);
  9393. CharacterFunctions::copy (dest, src, (int) numChars);
  9394. dest [numChars] = 0;
  9395. return dest;
  9396. }
  9397. static inline juce_wchar* getEmpty() throw()
  9398. {
  9399. return &(empty.text[0]);
  9400. }
  9401. static void retain (juce_wchar* const text) throw()
  9402. {
  9403. ++(bufferFromText (text)->refCount);
  9404. }
  9405. static inline void release (StringHolder* const b) throw()
  9406. {
  9407. if (--(b->refCount) == -1 && b != &empty)
  9408. delete[] reinterpret_cast <char*> (b);
  9409. }
  9410. static void release (juce_wchar* const text) throw()
  9411. {
  9412. release (bufferFromText (text));
  9413. }
  9414. static juce_wchar* makeUnique (juce_wchar* const text)
  9415. {
  9416. StringHolder* const b = bufferFromText (text);
  9417. if (b->refCount.get() <= 0)
  9418. return text;
  9419. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9420. release (b);
  9421. return newText;
  9422. }
  9423. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9424. {
  9425. StringHolder* const b = bufferFromText (text);
  9426. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9427. return text;
  9428. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9429. copyChars (newText, text, b->allocatedNumChars);
  9430. release (b);
  9431. return newText;
  9432. }
  9433. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9434. {
  9435. return bufferFromText (text)->allocatedNumChars;
  9436. }
  9437. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9438. {
  9439. jassert (src != 0 && dest != 0);
  9440. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9441. dest [numChars] = 0;
  9442. }
  9443. Atomic<int> refCount;
  9444. size_t allocatedNumChars;
  9445. juce_wchar text[1];
  9446. static StringHolder empty;
  9447. private:
  9448. static inline StringHolder* bufferFromText (void* const text) throw()
  9449. {
  9450. // (Can't use offsetof() here because of warnings about this not being a POD)
  9451. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9452. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9453. }
  9454. };
  9455. StringHolder StringHolder::empty;
  9456. const String String::empty;
  9457. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9458. {
  9459. jassert (t[numChars] == 0); // must have a null terminator
  9460. text = StringHolder::createCopy (t, numChars);
  9461. }
  9462. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9463. {
  9464. if (numExtraChars > 0)
  9465. {
  9466. const int oldLen = length();
  9467. const int newTotalLen = oldLen + numExtraChars;
  9468. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9469. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9470. }
  9471. }
  9472. void String::preallocateStorage (const size_t numChars)
  9473. {
  9474. text = StringHolder::makeUniqueWithSize (text, numChars);
  9475. }
  9476. String::String() throw()
  9477. : text (StringHolder::getEmpty())
  9478. {
  9479. }
  9480. String::~String() throw()
  9481. {
  9482. StringHolder::release (text);
  9483. }
  9484. String::String (const String& other) throw()
  9485. : text (other.text)
  9486. {
  9487. StringHolder::retain (text);
  9488. }
  9489. void String::swapWith (String& other) throw()
  9490. {
  9491. swapVariables (text, other.text);
  9492. }
  9493. String& String::operator= (const String& other) throw()
  9494. {
  9495. juce_wchar* const newText = other.text;
  9496. StringHolder::retain (newText);
  9497. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>&> (text).exchange (newText));
  9498. return *this;
  9499. }
  9500. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9501. String::String (const Preallocation& preallocationSize)
  9502. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9503. {
  9504. }
  9505. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9506. {
  9507. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9508. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9509. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9510. }
  9511. String::String (const char* const t)
  9512. {
  9513. if (t != 0 && *t != 0)
  9514. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9515. else
  9516. text = StringHolder::getEmpty();
  9517. }
  9518. String::String (const juce_wchar* const t)
  9519. {
  9520. if (t != 0 && *t != 0)
  9521. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9522. else
  9523. text = StringHolder::getEmpty();
  9524. }
  9525. String::String (const char* const t, const size_t maxChars)
  9526. {
  9527. int i;
  9528. for (i = 0; (size_t) i < maxChars; ++i)
  9529. if (t[i] == 0)
  9530. break;
  9531. if (i > 0)
  9532. text = StringHolder::createCopy (t, i);
  9533. else
  9534. text = StringHolder::getEmpty();
  9535. }
  9536. String::String (const juce_wchar* const t, const size_t maxChars)
  9537. {
  9538. int i;
  9539. for (i = 0; (size_t) i < maxChars; ++i)
  9540. if (t[i] == 0)
  9541. break;
  9542. if (i > 0)
  9543. text = StringHolder::createCopy (t, i);
  9544. else
  9545. text = StringHolder::getEmpty();
  9546. }
  9547. const String String::charToString (const juce_wchar character)
  9548. {
  9549. String result (Preallocation (1));
  9550. result.text[0] = character;
  9551. result.text[1] = 0;
  9552. return result;
  9553. }
  9554. namespace NumberToStringConverters
  9555. {
  9556. // pass in a pointer to the END of a buffer..
  9557. juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9558. {
  9559. *--t = 0;
  9560. int64 v = (n >= 0) ? n : -n;
  9561. do
  9562. {
  9563. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9564. v /= 10;
  9565. } while (v > 0);
  9566. if (n < 0)
  9567. *--t = '-';
  9568. return t;
  9569. }
  9570. juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9571. {
  9572. *--t = 0;
  9573. do
  9574. {
  9575. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9576. v /= 10;
  9577. } while (v > 0);
  9578. return t;
  9579. }
  9580. juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9581. {
  9582. if (n == (int) 0x80000000) // (would cause an overflow)
  9583. return int64ToString (t, n);
  9584. *--t = 0;
  9585. int v = abs (n);
  9586. do
  9587. {
  9588. *--t = (juce_wchar) ('0' + (v % 10));
  9589. v /= 10;
  9590. } while (v > 0);
  9591. if (n < 0)
  9592. *--t = '-';
  9593. return t;
  9594. }
  9595. juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9596. {
  9597. *--t = 0;
  9598. do
  9599. {
  9600. *--t = (juce_wchar) ('0' + (v % 10));
  9601. v /= 10;
  9602. } while (v > 0);
  9603. return t;
  9604. }
  9605. juce_wchar getDecimalPoint()
  9606. {
  9607. #if JUCE_VC7_OR_EARLIER
  9608. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9609. #else
  9610. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9611. #endif
  9612. return dp;
  9613. }
  9614. juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9615. {
  9616. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9617. {
  9618. juce_wchar* const end = buffer + numChars;
  9619. juce_wchar* t = end;
  9620. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9621. *--t = (juce_wchar) 0;
  9622. while (numDecPlaces >= 0 || v > 0)
  9623. {
  9624. if (numDecPlaces == 0)
  9625. *--t = getDecimalPoint();
  9626. *--t = (juce_wchar) ('0' + (v % 10));
  9627. v /= 10;
  9628. --numDecPlaces;
  9629. }
  9630. if (n < 0)
  9631. *--t = '-';
  9632. len = end - t - 1;
  9633. return t;
  9634. }
  9635. else
  9636. {
  9637. #if JUCE_WINDOWS
  9638. #if JUCE_VC7_OR_EARLIER || JUCE_MINGW
  9639. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9640. #else
  9641. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9642. #endif
  9643. #else
  9644. len = swprintf (buffer, numChars, L"%.9g", n);
  9645. #endif
  9646. return buffer;
  9647. }
  9648. }
  9649. }
  9650. String::String (const int number)
  9651. {
  9652. juce_wchar buffer [16];
  9653. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9654. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9655. createInternal (start, end - start - 1);
  9656. }
  9657. String::String (const unsigned int number)
  9658. {
  9659. juce_wchar buffer [16];
  9660. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9661. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9662. createInternal (start, end - start - 1);
  9663. }
  9664. String::String (const short number)
  9665. {
  9666. juce_wchar buffer [16];
  9667. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9668. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9669. createInternal (start, end - start - 1);
  9670. }
  9671. String::String (const unsigned short number)
  9672. {
  9673. juce_wchar buffer [16];
  9674. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9675. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9676. createInternal (start, end - start - 1);
  9677. }
  9678. String::String (const int64 number)
  9679. {
  9680. juce_wchar buffer [32];
  9681. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9682. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9683. createInternal (start, end - start - 1);
  9684. }
  9685. String::String (const uint64 number)
  9686. {
  9687. juce_wchar buffer [32];
  9688. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9689. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9690. createInternal (start, end - start - 1);
  9691. }
  9692. String::String (const float number, const int numberOfDecimalPlaces)
  9693. {
  9694. juce_wchar buffer [48];
  9695. size_t len;
  9696. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9697. createInternal (start, len);
  9698. }
  9699. String::String (const double number, const int numberOfDecimalPlaces)
  9700. {
  9701. juce_wchar buffer [48];
  9702. size_t len;
  9703. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9704. createInternal (start, len);
  9705. }
  9706. int String::length() const throw()
  9707. {
  9708. return CharacterFunctions::length (text);
  9709. }
  9710. int String::hashCode() const throw()
  9711. {
  9712. const juce_wchar* t = text;
  9713. int result = 0;
  9714. while (*t != (juce_wchar) 0)
  9715. result = 31 * result + *t++;
  9716. return result;
  9717. }
  9718. int64 String::hashCode64() const throw()
  9719. {
  9720. const juce_wchar* t = text;
  9721. int64 result = 0;
  9722. while (*t != (juce_wchar) 0)
  9723. result = 101 * result + *t++;
  9724. return result;
  9725. }
  9726. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9727. {
  9728. return string1.compare (string2) == 0;
  9729. }
  9730. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9731. {
  9732. return string1.compare (string2) == 0;
  9733. }
  9734. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9735. {
  9736. return string1.compare (string2) == 0;
  9737. }
  9738. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9739. {
  9740. return string1.compare (string2) != 0;
  9741. }
  9742. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9743. {
  9744. return string1.compare (string2) != 0;
  9745. }
  9746. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9747. {
  9748. return string1.compare (string2) != 0;
  9749. }
  9750. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9751. {
  9752. return string1.compare (string2) > 0;
  9753. }
  9754. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9755. {
  9756. return string1.compare (string2) < 0;
  9757. }
  9758. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9759. {
  9760. return string1.compare (string2) >= 0;
  9761. }
  9762. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9763. {
  9764. return string1.compare (string2) <= 0;
  9765. }
  9766. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9767. {
  9768. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9769. : isEmpty();
  9770. }
  9771. bool String::equalsIgnoreCase (const char* t) const throw()
  9772. {
  9773. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9774. : isEmpty();
  9775. }
  9776. bool String::equalsIgnoreCase (const String& other) const throw()
  9777. {
  9778. return text == other.text
  9779. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9780. }
  9781. int String::compare (const String& other) const throw()
  9782. {
  9783. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9784. }
  9785. int String::compare (const char* other) const throw()
  9786. {
  9787. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9788. }
  9789. int String::compare (const juce_wchar* other) const throw()
  9790. {
  9791. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9792. }
  9793. int String::compareIgnoreCase (const String& other) const throw()
  9794. {
  9795. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9796. }
  9797. int String::compareLexicographically (const String& other) const throw()
  9798. {
  9799. const juce_wchar* s1 = text;
  9800. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9801. ++s1;
  9802. const juce_wchar* s2 = other.text;
  9803. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9804. ++s2;
  9805. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9806. }
  9807. String& String::operator+= (const juce_wchar* const t)
  9808. {
  9809. if (t != 0)
  9810. appendInternal (t, CharacterFunctions::length (t));
  9811. return *this;
  9812. }
  9813. String& String::operator+= (const String& other)
  9814. {
  9815. if (isEmpty())
  9816. operator= (other);
  9817. else
  9818. appendInternal (other.text, other.length());
  9819. return *this;
  9820. }
  9821. String& String::operator+= (const char ch)
  9822. {
  9823. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9824. return operator+= (static_cast <const juce_wchar*> (asString));
  9825. }
  9826. String& String::operator+= (const juce_wchar ch)
  9827. {
  9828. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9829. return operator+= (static_cast <const juce_wchar*> (asString));
  9830. }
  9831. String& String::operator+= (const int number)
  9832. {
  9833. juce_wchar buffer [16];
  9834. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9835. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9836. appendInternal (start, (int) (end - start));
  9837. return *this;
  9838. }
  9839. String& String::operator+= (const unsigned int number)
  9840. {
  9841. juce_wchar buffer [16];
  9842. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9843. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9844. appendInternal (start, (int) (end - start));
  9845. return *this;
  9846. }
  9847. void String::append (const juce_wchar* const other, const int howMany)
  9848. {
  9849. if (howMany > 0)
  9850. {
  9851. int i;
  9852. for (i = 0; i < howMany; ++i)
  9853. if (other[i] == 0)
  9854. break;
  9855. appendInternal (other, i);
  9856. }
  9857. }
  9858. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9859. {
  9860. String s (string1);
  9861. return s += string2;
  9862. }
  9863. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9864. {
  9865. String s (string1);
  9866. return s += string2;
  9867. }
  9868. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9869. {
  9870. return String::charToString (string1) + string2;
  9871. }
  9872. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9873. {
  9874. return String::charToString (string1) + string2;
  9875. }
  9876. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9877. {
  9878. return string1 += string2;
  9879. }
  9880. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9881. {
  9882. return string1 += string2;
  9883. }
  9884. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9885. {
  9886. return string1 += string2;
  9887. }
  9888. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9889. {
  9890. return string1 += string2;
  9891. }
  9892. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9893. {
  9894. return string1 += string2;
  9895. }
  9896. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9897. {
  9898. return string1 += characterToAppend;
  9899. }
  9900. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9901. {
  9902. return string1 += characterToAppend;
  9903. }
  9904. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9905. {
  9906. return string1 += string2;
  9907. }
  9908. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9909. {
  9910. return string1 += string2;
  9911. }
  9912. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9913. {
  9914. return string1 += string2;
  9915. }
  9916. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9917. {
  9918. return string1 += (int) number;
  9919. }
  9920. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9921. {
  9922. return string1 += number;
  9923. }
  9924. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9925. {
  9926. return string1 += number;
  9927. }
  9928. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9929. {
  9930. return string1 += (int) number;
  9931. }
  9932. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9933. {
  9934. return string1 += (unsigned int) number;
  9935. }
  9936. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9937. {
  9938. return string1 += String (number);
  9939. }
  9940. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9941. {
  9942. return string1 += String (number);
  9943. }
  9944. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9945. {
  9946. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9947. // if lots of large, persistent strings were to be written to streams).
  9948. const int numBytes = text.getNumBytesAsUTF8();
  9949. HeapBlock<char> temp (numBytes + 1);
  9950. text.copyToUTF8 (temp, numBytes + 1);
  9951. stream.write (temp, numBytes);
  9952. return stream;
  9953. }
  9954. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9955. {
  9956. return string1 += NewLine::getDefault();
  9957. }
  9958. int String::indexOfChar (const juce_wchar character) const throw()
  9959. {
  9960. const juce_wchar* t = text;
  9961. for (;;)
  9962. {
  9963. if (*t == character)
  9964. return (int) (t - text);
  9965. if (*t++ == 0)
  9966. return -1;
  9967. }
  9968. }
  9969. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9970. {
  9971. for (int i = length(); --i >= 0;)
  9972. if (text[i] == character)
  9973. return i;
  9974. return -1;
  9975. }
  9976. int String::indexOf (const String& t) const throw()
  9977. {
  9978. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  9979. return r == 0 ? -1 : (int) (r - text);
  9980. }
  9981. int String::indexOfChar (const int startIndex,
  9982. const juce_wchar character) const throw()
  9983. {
  9984. if (startIndex > 0 && startIndex >= length())
  9985. return -1;
  9986. const juce_wchar* t = text + jmax (0, startIndex);
  9987. for (;;)
  9988. {
  9989. if (*t == character)
  9990. return (int) (t - text);
  9991. if (*t == 0)
  9992. return -1;
  9993. ++t;
  9994. }
  9995. }
  9996. int String::indexOfAnyOf (const String& charactersToLookFor,
  9997. const int startIndex,
  9998. const bool ignoreCase) const throw()
  9999. {
  10000. if (startIndex > 0 && startIndex >= length())
  10001. return -1;
  10002. const juce_wchar* t = text + jmax (0, startIndex);
  10003. while (*t != 0)
  10004. {
  10005. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10006. return (int) (t - text);
  10007. ++t;
  10008. }
  10009. return -1;
  10010. }
  10011. int String::indexOf (const int startIndex, const String& other) const throw()
  10012. {
  10013. if (startIndex > 0 && startIndex >= length())
  10014. return -1;
  10015. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10016. return found == 0 ? -1 : (int) (found - text);
  10017. }
  10018. int String::indexOfIgnoreCase (const String& other) const throw()
  10019. {
  10020. if (other.isNotEmpty())
  10021. {
  10022. const int len = other.length();
  10023. const int end = length() - len;
  10024. for (int i = 0; i <= end; ++i)
  10025. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10026. return i;
  10027. }
  10028. return -1;
  10029. }
  10030. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10031. {
  10032. if (other.isNotEmpty())
  10033. {
  10034. const int len = other.length();
  10035. const int end = length() - len;
  10036. for (int i = jmax (0, startIndex); i <= end; ++i)
  10037. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10038. return i;
  10039. }
  10040. return -1;
  10041. }
  10042. int String::lastIndexOf (const String& other) const throw()
  10043. {
  10044. if (other.isNotEmpty())
  10045. {
  10046. const int len = other.length();
  10047. int i = length() - len;
  10048. if (i >= 0)
  10049. {
  10050. const juce_wchar* n = text + i;
  10051. while (i >= 0)
  10052. {
  10053. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10054. return i;
  10055. --i;
  10056. }
  10057. }
  10058. }
  10059. return -1;
  10060. }
  10061. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10062. {
  10063. if (other.isNotEmpty())
  10064. {
  10065. const int len = other.length();
  10066. int i = length() - len;
  10067. if (i >= 0)
  10068. {
  10069. const juce_wchar* n = text + i;
  10070. while (i >= 0)
  10071. {
  10072. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10073. return i;
  10074. --i;
  10075. }
  10076. }
  10077. }
  10078. return -1;
  10079. }
  10080. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10081. {
  10082. for (int i = length(); --i >= 0;)
  10083. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10084. return i;
  10085. return -1;
  10086. }
  10087. bool String::contains (const String& other) const throw()
  10088. {
  10089. return indexOf (other) >= 0;
  10090. }
  10091. bool String::containsChar (const juce_wchar character) const throw()
  10092. {
  10093. const juce_wchar* t = text;
  10094. for (;;)
  10095. {
  10096. if (*t == 0)
  10097. return false;
  10098. if (*t == character)
  10099. return true;
  10100. ++t;
  10101. }
  10102. }
  10103. bool String::containsIgnoreCase (const String& t) const throw()
  10104. {
  10105. return indexOfIgnoreCase (t) >= 0;
  10106. }
  10107. int String::indexOfWholeWord (const String& word) const throw()
  10108. {
  10109. if (word.isNotEmpty())
  10110. {
  10111. const int wordLen = word.length();
  10112. const int end = length() - wordLen;
  10113. const juce_wchar* t = text;
  10114. for (int i = 0; i <= end; ++i)
  10115. {
  10116. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10117. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10118. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10119. {
  10120. return i;
  10121. }
  10122. ++t;
  10123. }
  10124. }
  10125. return -1;
  10126. }
  10127. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10128. {
  10129. if (word.isNotEmpty())
  10130. {
  10131. const int wordLen = word.length();
  10132. const int end = length() - wordLen;
  10133. const juce_wchar* t = text;
  10134. for (int i = 0; i <= end; ++i)
  10135. {
  10136. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10137. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10138. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10139. {
  10140. return i;
  10141. }
  10142. ++t;
  10143. }
  10144. }
  10145. return -1;
  10146. }
  10147. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10148. {
  10149. return indexOfWholeWord (wordToLookFor) >= 0;
  10150. }
  10151. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10152. {
  10153. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10154. }
  10155. namespace WildCardHelpers
  10156. {
  10157. int indexOfMatch (const juce_wchar* const wildcard,
  10158. const juce_wchar* const test,
  10159. const bool ignoreCase) throw()
  10160. {
  10161. int start = 0;
  10162. while (test [start] != 0)
  10163. {
  10164. int i = 0;
  10165. for (;;)
  10166. {
  10167. const juce_wchar wc = wildcard [i];
  10168. const juce_wchar c = test [i + start];
  10169. if (wc == c
  10170. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10171. || (wc == '?' && c != 0))
  10172. {
  10173. if (wc == 0)
  10174. return start;
  10175. ++i;
  10176. }
  10177. else
  10178. {
  10179. if (wc == '*' && (wildcard [i + 1] == 0
  10180. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10181. {
  10182. return start;
  10183. }
  10184. break;
  10185. }
  10186. }
  10187. ++start;
  10188. }
  10189. return -1;
  10190. }
  10191. }
  10192. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10193. {
  10194. int i = 0;
  10195. for (;;)
  10196. {
  10197. const juce_wchar wc = wildcard.text [i];
  10198. const juce_wchar c = text [i];
  10199. if (wc == c
  10200. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10201. || (wc == '?' && c != 0))
  10202. {
  10203. if (wc == 0)
  10204. return true;
  10205. ++i;
  10206. }
  10207. else
  10208. {
  10209. return wc == '*' && (wildcard [i + 1] == 0
  10210. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10211. }
  10212. }
  10213. }
  10214. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10215. {
  10216. const int len = stringToRepeat.length();
  10217. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10218. juce_wchar* n = result.text;
  10219. *n = 0;
  10220. while (--numberOfTimesToRepeat >= 0)
  10221. {
  10222. StringHolder::copyChars (n, stringToRepeat.text, len);
  10223. n += len;
  10224. }
  10225. return result;
  10226. }
  10227. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10228. {
  10229. jassert (padCharacter != 0);
  10230. const int len = length();
  10231. if (len >= minimumLength || padCharacter == 0)
  10232. return *this;
  10233. String result (Preallocation (minimumLength + 1));
  10234. juce_wchar* n = result.text;
  10235. minimumLength -= len;
  10236. while (--minimumLength >= 0)
  10237. *n++ = padCharacter;
  10238. StringHolder::copyChars (n, text, len);
  10239. return result;
  10240. }
  10241. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10242. {
  10243. jassert (padCharacter != 0);
  10244. const int len = length();
  10245. if (len >= minimumLength || padCharacter == 0)
  10246. return *this;
  10247. String result (*this, (size_t) minimumLength);
  10248. juce_wchar* n = result.text + len;
  10249. minimumLength -= len;
  10250. while (--minimumLength >= 0)
  10251. *n++ = padCharacter;
  10252. *n = 0;
  10253. return result;
  10254. }
  10255. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10256. {
  10257. if (index < 0)
  10258. {
  10259. // a negative index to replace from?
  10260. jassertfalse;
  10261. index = 0;
  10262. }
  10263. if (numCharsToReplace < 0)
  10264. {
  10265. // replacing a negative number of characters?
  10266. numCharsToReplace = 0;
  10267. jassertfalse;
  10268. }
  10269. const int len = length();
  10270. if (index + numCharsToReplace > len)
  10271. {
  10272. if (index > len)
  10273. {
  10274. // replacing beyond the end of the string?
  10275. index = len;
  10276. jassertfalse;
  10277. }
  10278. numCharsToReplace = len - index;
  10279. }
  10280. const int newStringLen = stringToInsert.length();
  10281. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10282. if (newTotalLen <= 0)
  10283. return String::empty;
  10284. String result (Preallocation ((size_t) newTotalLen));
  10285. StringHolder::copyChars (result.text, text, index);
  10286. if (newStringLen > 0)
  10287. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10288. const int endStringLen = newTotalLen - (index + newStringLen);
  10289. if (endStringLen > 0)
  10290. StringHolder::copyChars (result.text + (index + newStringLen),
  10291. text + (index + numCharsToReplace),
  10292. endStringLen);
  10293. return result;
  10294. }
  10295. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10296. {
  10297. const int stringToReplaceLen = stringToReplace.length();
  10298. const int stringToInsertLen = stringToInsert.length();
  10299. int i = 0;
  10300. String result (*this);
  10301. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10302. : result.indexOf (i, stringToReplace))) >= 0)
  10303. {
  10304. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10305. i += stringToInsertLen;
  10306. }
  10307. return result;
  10308. }
  10309. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10310. {
  10311. const int index = indexOfChar (charToReplace);
  10312. if (index < 0)
  10313. return *this;
  10314. String result (*this, size_t());
  10315. juce_wchar* t = result.text + index;
  10316. while (*t != 0)
  10317. {
  10318. if (*t == charToReplace)
  10319. *t = charToInsert;
  10320. ++t;
  10321. }
  10322. return result;
  10323. }
  10324. const String String::replaceCharacters (const String& charactersToReplace,
  10325. const String& charactersToInsertInstead) const
  10326. {
  10327. String result (*this, size_t());
  10328. juce_wchar* t = result.text;
  10329. const int len2 = charactersToInsertInstead.length();
  10330. // the two strings passed in are supposed to be the same length!
  10331. jassert (len2 == charactersToReplace.length());
  10332. while (*t != 0)
  10333. {
  10334. const int index = charactersToReplace.indexOfChar (*t);
  10335. if (isPositiveAndBelow (index, len2))
  10336. *t = charactersToInsertInstead [index];
  10337. ++t;
  10338. }
  10339. return result;
  10340. }
  10341. bool String::startsWith (const String& other) const throw()
  10342. {
  10343. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10344. }
  10345. bool String::startsWithIgnoreCase (const String& other) const throw()
  10346. {
  10347. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10348. }
  10349. bool String::startsWithChar (const juce_wchar character) const throw()
  10350. {
  10351. jassert (character != 0); // strings can't contain a null character!
  10352. return text[0] == character;
  10353. }
  10354. bool String::endsWithChar (const juce_wchar character) const throw()
  10355. {
  10356. jassert (character != 0); // strings can't contain a null character!
  10357. return text[0] != 0
  10358. && text [length() - 1] == character;
  10359. }
  10360. bool String::endsWith (const String& other) const throw()
  10361. {
  10362. const int thisLen = length();
  10363. const int otherLen = other.length();
  10364. return thisLen >= otherLen
  10365. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10366. }
  10367. bool String::endsWithIgnoreCase (const String& other) const throw()
  10368. {
  10369. const int thisLen = length();
  10370. const int otherLen = other.length();
  10371. return thisLen >= otherLen
  10372. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10373. }
  10374. const String String::toUpperCase() const
  10375. {
  10376. String result (*this, size_t());
  10377. CharacterFunctions::toUpperCase (result.text);
  10378. return result;
  10379. }
  10380. const String String::toLowerCase() const
  10381. {
  10382. String result (*this, size_t());
  10383. CharacterFunctions::toLowerCase (result.text);
  10384. return result;
  10385. }
  10386. juce_wchar& String::operator[] (const int index)
  10387. {
  10388. jassert (isPositiveAndNotGreaterThan (index, length()));
  10389. text = StringHolder::makeUnique (text);
  10390. return text [index];
  10391. }
  10392. juce_wchar String::getLastCharacter() const throw()
  10393. {
  10394. return isEmpty() ? juce_wchar() : text [length() - 1];
  10395. }
  10396. const String String::substring (int start, int end) const
  10397. {
  10398. if (start < 0)
  10399. start = 0;
  10400. else if (end <= start)
  10401. return empty;
  10402. int len = 0;
  10403. while (len <= end && text [len] != 0)
  10404. ++len;
  10405. if (end >= len)
  10406. {
  10407. if (start == 0)
  10408. return *this;
  10409. end = len;
  10410. }
  10411. return String (text + start, end - start);
  10412. }
  10413. const String String::substring (const int start) const
  10414. {
  10415. if (start <= 0)
  10416. return *this;
  10417. const int len = length();
  10418. if (start >= len)
  10419. return empty;
  10420. return String (text + start, len - start);
  10421. }
  10422. const String String::dropLastCharacters (const int numberToDrop) const
  10423. {
  10424. return String (text, jmax (0, length() - numberToDrop));
  10425. }
  10426. const String String::getLastCharacters (const int numCharacters) const
  10427. {
  10428. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10429. }
  10430. const String String::fromFirstOccurrenceOf (const String& sub,
  10431. const bool includeSubString,
  10432. const bool ignoreCase) const
  10433. {
  10434. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10435. : indexOf (sub);
  10436. if (i < 0)
  10437. return empty;
  10438. return substring (includeSubString ? i : i + sub.length());
  10439. }
  10440. const String String::fromLastOccurrenceOf (const String& sub,
  10441. const bool includeSubString,
  10442. const bool ignoreCase) const
  10443. {
  10444. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10445. : lastIndexOf (sub);
  10446. if (i < 0)
  10447. return *this;
  10448. return substring (includeSubString ? i : i + sub.length());
  10449. }
  10450. const String String::upToFirstOccurrenceOf (const String& sub,
  10451. const bool includeSubString,
  10452. const bool ignoreCase) const
  10453. {
  10454. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10455. : indexOf (sub);
  10456. if (i < 0)
  10457. return *this;
  10458. return substring (0, includeSubString ? i + sub.length() : i);
  10459. }
  10460. const String String::upToLastOccurrenceOf (const String& sub,
  10461. const bool includeSubString,
  10462. const bool ignoreCase) const
  10463. {
  10464. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10465. : lastIndexOf (sub);
  10466. if (i < 0)
  10467. return *this;
  10468. return substring (0, includeSubString ? i + sub.length() : i);
  10469. }
  10470. bool String::isQuotedString() const
  10471. {
  10472. const String trimmed (trimStart());
  10473. return trimmed[0] == '"'
  10474. || trimmed[0] == '\'';
  10475. }
  10476. const String String::unquoted() const
  10477. {
  10478. String s (*this);
  10479. if (s.text[0] == '"' || s.text[0] == '\'')
  10480. s = s.substring (1);
  10481. const int lastCharIndex = s.length() - 1;
  10482. if (lastCharIndex >= 0
  10483. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10484. s [lastCharIndex] = 0;
  10485. return s;
  10486. }
  10487. const String String::quoted (const juce_wchar quoteCharacter) const
  10488. {
  10489. if (isEmpty())
  10490. return charToString (quoteCharacter) + quoteCharacter;
  10491. String t (*this);
  10492. if (! t.startsWithChar (quoteCharacter))
  10493. t = charToString (quoteCharacter) + t;
  10494. if (! t.endsWithChar (quoteCharacter))
  10495. t += quoteCharacter;
  10496. return t;
  10497. }
  10498. const String String::trim() const
  10499. {
  10500. if (isEmpty())
  10501. return empty;
  10502. int start = 0;
  10503. while (CharacterFunctions::isWhitespace (text [start]))
  10504. ++start;
  10505. const int len = length();
  10506. int end = len - 1;
  10507. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10508. --end;
  10509. ++end;
  10510. if (end <= start)
  10511. return empty;
  10512. else if (start > 0 || end < len)
  10513. return String (text + start, end - start);
  10514. return *this;
  10515. }
  10516. const String String::trimStart() const
  10517. {
  10518. if (isEmpty())
  10519. return empty;
  10520. const juce_wchar* t = text;
  10521. while (CharacterFunctions::isWhitespace (*t))
  10522. ++t;
  10523. if (t == text)
  10524. return *this;
  10525. return String (t);
  10526. }
  10527. const String String::trimEnd() const
  10528. {
  10529. if (isEmpty())
  10530. return empty;
  10531. const juce_wchar* endT = text + (length() - 1);
  10532. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10533. --endT;
  10534. return String (text, (int) (++endT - text));
  10535. }
  10536. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10537. {
  10538. const juce_wchar* t = text;
  10539. while (charactersToTrim.containsChar (*t))
  10540. ++t;
  10541. return t == text ? *this : String (t);
  10542. }
  10543. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10544. {
  10545. if (isEmpty())
  10546. return empty;
  10547. const int len = length();
  10548. const juce_wchar* endT = text + (len - 1);
  10549. int numToRemove = 0;
  10550. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10551. {
  10552. ++numToRemove;
  10553. --endT;
  10554. }
  10555. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10556. }
  10557. const String String::retainCharacters (const String& charactersToRetain) const
  10558. {
  10559. if (isEmpty())
  10560. return empty;
  10561. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10562. juce_wchar* dst = result.text;
  10563. const juce_wchar* src = text;
  10564. while (*src != 0)
  10565. {
  10566. if (charactersToRetain.containsChar (*src))
  10567. *dst++ = *src;
  10568. ++src;
  10569. }
  10570. *dst = 0;
  10571. return result;
  10572. }
  10573. const String String::removeCharacters (const String& charactersToRemove) const
  10574. {
  10575. if (isEmpty())
  10576. return empty;
  10577. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10578. juce_wchar* dst = result.text;
  10579. const juce_wchar* src = text;
  10580. while (*src != 0)
  10581. {
  10582. if (! charactersToRemove.containsChar (*src))
  10583. *dst++ = *src;
  10584. ++src;
  10585. }
  10586. *dst = 0;
  10587. return result;
  10588. }
  10589. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10590. {
  10591. int i = 0;
  10592. for (;;)
  10593. {
  10594. if (! permittedCharacters.containsChar (text[i]))
  10595. break;
  10596. ++i;
  10597. }
  10598. return substring (0, i);
  10599. }
  10600. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10601. {
  10602. const juce_wchar* const t = text;
  10603. int i = 0;
  10604. while (t[i] != 0)
  10605. {
  10606. if (charactersToStopAt.containsChar (t[i]))
  10607. return String (text, i);
  10608. ++i;
  10609. }
  10610. return empty;
  10611. }
  10612. bool String::containsOnly (const String& chars) const throw()
  10613. {
  10614. const juce_wchar* t = text;
  10615. while (*t != 0)
  10616. if (! chars.containsChar (*t++))
  10617. return false;
  10618. return true;
  10619. }
  10620. bool String::containsAnyOf (const String& chars) const throw()
  10621. {
  10622. const juce_wchar* t = text;
  10623. while (*t != 0)
  10624. if (chars.containsChar (*t++))
  10625. return true;
  10626. return false;
  10627. }
  10628. bool String::containsNonWhitespaceChars() const throw()
  10629. {
  10630. const juce_wchar* t = text;
  10631. while (*t != 0)
  10632. if (! CharacterFunctions::isWhitespace (*t++))
  10633. return true;
  10634. return false;
  10635. }
  10636. const String String::formatted (const juce_wchar* const pf, ... )
  10637. {
  10638. jassert (pf != 0);
  10639. va_list args;
  10640. va_start (args, pf);
  10641. size_t bufferSize = 256;
  10642. String result (Preallocation ((size_t) bufferSize));
  10643. result.text[0] = 0;
  10644. for (;;)
  10645. {
  10646. #if JUCE_LINUX && JUCE_64BIT
  10647. va_list tempArgs;
  10648. va_copy (tempArgs, args);
  10649. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10650. va_end (tempArgs);
  10651. #elif JUCE_WINDOWS
  10652. #if JUCE_MSVC
  10653. #pragma warning (push)
  10654. #pragma warning (disable: 4996)
  10655. #endif
  10656. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10657. #if JUCE_MSVC
  10658. #pragma warning (pop)
  10659. #endif
  10660. #else
  10661. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10662. #endif
  10663. if (num > 0)
  10664. return result;
  10665. bufferSize += 256;
  10666. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10667. break; // returns -1 because of an error rather than because it needs more space.
  10668. result.preallocateStorage (bufferSize);
  10669. }
  10670. return empty;
  10671. }
  10672. int String::getIntValue() const throw()
  10673. {
  10674. return CharacterFunctions::getIntValue (text);
  10675. }
  10676. int String::getTrailingIntValue() const throw()
  10677. {
  10678. int n = 0;
  10679. int mult = 1;
  10680. const juce_wchar* t = text + length();
  10681. while (--t >= text)
  10682. {
  10683. const juce_wchar c = *t;
  10684. if (! CharacterFunctions::isDigit (c))
  10685. {
  10686. if (c == '-')
  10687. n = -n;
  10688. break;
  10689. }
  10690. n += mult * (c - '0');
  10691. mult *= 10;
  10692. }
  10693. return n;
  10694. }
  10695. int64 String::getLargeIntValue() const throw()
  10696. {
  10697. return CharacterFunctions::getInt64Value (text);
  10698. }
  10699. float String::getFloatValue() const throw()
  10700. {
  10701. return (float) CharacterFunctions::getDoubleValue (text);
  10702. }
  10703. double String::getDoubleValue() const throw()
  10704. {
  10705. return CharacterFunctions::getDoubleValue (text);
  10706. }
  10707. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10708. const String String::toHexString (const int number)
  10709. {
  10710. juce_wchar buffer[32];
  10711. juce_wchar* const end = buffer + 32;
  10712. juce_wchar* t = end;
  10713. *--t = 0;
  10714. unsigned int v = (unsigned int) number;
  10715. do
  10716. {
  10717. *--t = hexDigits [v & 15];
  10718. v >>= 4;
  10719. } while (v != 0);
  10720. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10721. }
  10722. const String String::toHexString (const int64 number)
  10723. {
  10724. juce_wchar buffer[32];
  10725. juce_wchar* const end = buffer + 32;
  10726. juce_wchar* t = end;
  10727. *--t = 0;
  10728. uint64 v = (uint64) number;
  10729. do
  10730. {
  10731. *--t = hexDigits [(int) (v & 15)];
  10732. v >>= 4;
  10733. } while (v != 0);
  10734. return String (t, (int) (((char*) end) - (char*) t));
  10735. }
  10736. const String String::toHexString (const short number)
  10737. {
  10738. return toHexString ((int) (unsigned short) number);
  10739. }
  10740. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10741. {
  10742. if (size <= 0)
  10743. return empty;
  10744. int numChars = (size * 2) + 2;
  10745. if (groupSize > 0)
  10746. numChars += size / groupSize;
  10747. String s (Preallocation ((size_t) numChars));
  10748. juce_wchar* d = s.text;
  10749. for (int i = 0; i < size; ++i)
  10750. {
  10751. *d++ = hexDigits [(*data) >> 4];
  10752. *d++ = hexDigits [(*data) & 0xf];
  10753. ++data;
  10754. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10755. *d++ = ' ';
  10756. }
  10757. *d = 0;
  10758. return s;
  10759. }
  10760. int String::getHexValue32() const throw()
  10761. {
  10762. int result = 0;
  10763. const juce_wchar* c = text;
  10764. for (;;)
  10765. {
  10766. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10767. if (hexValue >= 0)
  10768. result = (result << 4) | hexValue;
  10769. else if (*c == 0)
  10770. break;
  10771. ++c;
  10772. }
  10773. return result;
  10774. }
  10775. int64 String::getHexValue64() const throw()
  10776. {
  10777. int64 result = 0;
  10778. const juce_wchar* c = text;
  10779. for (;;)
  10780. {
  10781. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10782. if (hexValue >= 0)
  10783. result = (result << 4) | hexValue;
  10784. else if (*c == 0)
  10785. break;
  10786. ++c;
  10787. }
  10788. return result;
  10789. }
  10790. const String String::createStringFromData (const void* const data_, const int size)
  10791. {
  10792. const char* const data = static_cast <const char*> (data_);
  10793. if (size <= 0 || data == 0)
  10794. {
  10795. return empty;
  10796. }
  10797. else if (size < 2)
  10798. {
  10799. return charToString (data[0]);
  10800. }
  10801. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10802. || (data[0] == (char)-1 && data[1] == (char)-2))
  10803. {
  10804. // assume it's 16-bit unicode
  10805. const bool bigEndian = (data[0] == (char)-2);
  10806. const int numChars = size / 2 - 1;
  10807. String result;
  10808. result.preallocateStorage (numChars + 2);
  10809. const uint16* const src = (const uint16*) (data + 2);
  10810. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10811. if (bigEndian)
  10812. {
  10813. for (int i = 0; i < numChars; ++i)
  10814. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10815. }
  10816. else
  10817. {
  10818. for (int i = 0; i < numChars; ++i)
  10819. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10820. }
  10821. dst [numChars] = 0;
  10822. return result;
  10823. }
  10824. else
  10825. {
  10826. return String::fromUTF8 (data, size);
  10827. }
  10828. }
  10829. const char* String::toUTF8() const
  10830. {
  10831. if (isEmpty())
  10832. {
  10833. return reinterpret_cast <const char*> (text);
  10834. }
  10835. else
  10836. {
  10837. const int currentLen = length() + 1;
  10838. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10839. String* const mutableThis = const_cast <String*> (this);
  10840. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10841. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10842. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10843. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10844. #endif
  10845. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10846. return otherCopy;
  10847. }
  10848. }
  10849. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10850. {
  10851. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10852. int num = 0, index = 0;
  10853. for (;;)
  10854. {
  10855. const uint32 c = (uint32) text [index++];
  10856. if (c >= 0x80)
  10857. {
  10858. int numExtraBytes = 1;
  10859. if (c >= 0x800)
  10860. {
  10861. ++numExtraBytes;
  10862. if (c >= 0x10000)
  10863. {
  10864. ++numExtraBytes;
  10865. if (c >= 0x200000)
  10866. {
  10867. ++numExtraBytes;
  10868. if (c >= 0x4000000)
  10869. ++numExtraBytes;
  10870. }
  10871. }
  10872. }
  10873. if (buffer != 0)
  10874. {
  10875. if (num + numExtraBytes >= maxBufferSizeBytes)
  10876. {
  10877. buffer [num++] = 0;
  10878. break;
  10879. }
  10880. else
  10881. {
  10882. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10883. while (--numExtraBytes >= 0)
  10884. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10885. }
  10886. }
  10887. else
  10888. {
  10889. num += numExtraBytes + 1;
  10890. }
  10891. }
  10892. else
  10893. {
  10894. if (buffer != 0)
  10895. {
  10896. if (num + 1 >= maxBufferSizeBytes)
  10897. {
  10898. buffer [num++] = 0;
  10899. break;
  10900. }
  10901. buffer [num] = (uint8) c;
  10902. }
  10903. ++num;
  10904. }
  10905. if (c == 0)
  10906. break;
  10907. }
  10908. return num;
  10909. }
  10910. int String::getNumBytesAsUTF8() const throw()
  10911. {
  10912. int num = 0;
  10913. const juce_wchar* t = text;
  10914. for (;;)
  10915. {
  10916. const uint32 c = (uint32) *t;
  10917. if (c >= 0x80)
  10918. {
  10919. ++num;
  10920. if (c >= 0x800)
  10921. {
  10922. ++num;
  10923. if (c >= 0x10000)
  10924. {
  10925. ++num;
  10926. if (c >= 0x200000)
  10927. {
  10928. ++num;
  10929. if (c >= 0x4000000)
  10930. ++num;
  10931. }
  10932. }
  10933. }
  10934. }
  10935. else if (c == 0)
  10936. break;
  10937. ++num;
  10938. ++t;
  10939. }
  10940. return num;
  10941. }
  10942. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10943. {
  10944. if (buffer == 0)
  10945. return empty;
  10946. if (bufferSizeBytes < 0)
  10947. bufferSizeBytes = std::numeric_limits<int>::max();
  10948. size_t numBytes;
  10949. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10950. if (buffer [numBytes] == 0)
  10951. break;
  10952. String result (Preallocation (numBytes + 1));
  10953. juce_wchar* dest = result.text;
  10954. size_t i = 0;
  10955. while (i < numBytes)
  10956. {
  10957. const char c = buffer [i++];
  10958. if (c < 0)
  10959. {
  10960. unsigned int mask = 0x7f;
  10961. int bit = 0x40;
  10962. int numExtraValues = 0;
  10963. while (bit != 0 && (c & bit) != 0)
  10964. {
  10965. bit >>= 1;
  10966. mask >>= 1;
  10967. ++numExtraValues;
  10968. }
  10969. int n = (mask & (unsigned char) c);
  10970. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10971. {
  10972. const char nextByte = buffer[i];
  10973. if ((nextByte & 0xc0) != 0x80)
  10974. break;
  10975. n <<= 6;
  10976. n |= (nextByte & 0x3f);
  10977. ++i;
  10978. }
  10979. *dest++ = (juce_wchar) n;
  10980. }
  10981. else
  10982. {
  10983. *dest++ = (juce_wchar) c;
  10984. }
  10985. }
  10986. *dest = 0;
  10987. return result;
  10988. }
  10989. const char* String::toCString() const
  10990. {
  10991. if (isEmpty())
  10992. {
  10993. return reinterpret_cast <const char*> (text);
  10994. }
  10995. else
  10996. {
  10997. const int len = length();
  10998. String* const mutableThis = const_cast <String*> (this);
  10999. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11000. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11001. CharacterFunctions::copy (otherCopy, text, len);
  11002. otherCopy [len] = 0;
  11003. return otherCopy;
  11004. }
  11005. }
  11006. #if JUCE_MSVC
  11007. #pragma warning (push)
  11008. #pragma warning (disable: 4514 4996)
  11009. #endif
  11010. int String::getNumBytesAsCString() const throw()
  11011. {
  11012. return (int) wcstombs (0, text, 0);
  11013. }
  11014. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11015. {
  11016. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11017. if (destBuffer != 0 && numBytes >= 0)
  11018. destBuffer [numBytes] = 0;
  11019. return numBytes;
  11020. }
  11021. #if JUCE_MSVC
  11022. #pragma warning (pop)
  11023. #endif
  11024. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11025. {
  11026. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11027. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11028. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11029. }
  11030. String::Concatenator::Concatenator (String& stringToAppendTo)
  11031. : result (stringToAppendTo),
  11032. nextIndex (stringToAppendTo.length())
  11033. {
  11034. }
  11035. String::Concatenator::~Concatenator()
  11036. {
  11037. }
  11038. void String::Concatenator::append (const String& s)
  11039. {
  11040. const int len = s.length();
  11041. if (len > 0)
  11042. {
  11043. result.preallocateStorage (nextIndex + len);
  11044. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11045. nextIndex += len;
  11046. }
  11047. }
  11048. #if JUCE_UNIT_TESTS
  11049. class StringTests : public UnitTest
  11050. {
  11051. public:
  11052. StringTests() : UnitTest ("String class") {}
  11053. void runTest()
  11054. {
  11055. {
  11056. beginTest ("Basics");
  11057. expect (String().length() == 0);
  11058. expect (String() == String::empty);
  11059. String s1, s2 ("abcd");
  11060. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11061. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11062. expect (s2.length() == 4);
  11063. s1 = "abcd";
  11064. expect (s2 == s1 && s1 == s2);
  11065. expect (s1 == "abcd" && s1 == L"abcd");
  11066. expect (String ("abcd") == String (L"abcd"));
  11067. expect (String ("abcdefg", 4) == L"abcd");
  11068. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11069. expect (String::charToString ('x') == "x");
  11070. expect (String::charToString (0) == String::empty);
  11071. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11072. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11073. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11074. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11075. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11076. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11077. expect (s1.indexOf (String::empty) == 0);
  11078. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11079. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11080. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11081. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11082. }
  11083. {
  11084. beginTest ("Operations");
  11085. String s ("012345678");
  11086. expect (s.hashCode() != 0);
  11087. expect (s.hashCode64() != 0);
  11088. expect (s.hashCode() != (s + s).hashCode());
  11089. expect (s.hashCode64() != (s + s).hashCode64());
  11090. expect (s.compare (String ("012345678")) == 0);
  11091. expect (s.compare (String ("012345679")) < 0);
  11092. expect (s.compare (String ("012345676")) > 0);
  11093. expect (s.substring (2, 3) == String::charToString (s[2]));
  11094. expect (s.substring (0, 1) == String::charToString (s[0]));
  11095. expect (s.getLastCharacter() == s [s.length() - 1]);
  11096. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11097. expect (s.substring (0, 3) == L"012");
  11098. expect (s.substring (0, 100) == s);
  11099. expect (s.substring (-1, 100) == s);
  11100. expect (s.substring (3) == "345678");
  11101. expect (s.indexOf (L"45") == 4);
  11102. expect (String ("444445").indexOf ("45") == 4);
  11103. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11104. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11105. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11106. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11107. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11108. expect (s.indexOfChar (L'4') == 4);
  11109. expect (s + s == "012345678012345678");
  11110. expect (s.startsWith (s));
  11111. expect (s.startsWith (s.substring (0, 4)));
  11112. expect (s.startsWith (s.dropLastCharacters (4)));
  11113. expect (s.endsWith (s.substring (5)));
  11114. expect (s.endsWith (s));
  11115. expect (s.contains (s.substring (3, 6)));
  11116. expect (s.contains (s.substring (3)));
  11117. expect (s.startsWithChar (s[0]));
  11118. expect (s.endsWithChar (s.getLastCharacter()));
  11119. expect (s [s.length()] == 0);
  11120. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11121. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11122. String s2 ("123");
  11123. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11124. s2 += "xyz";
  11125. expect (s2 == "1234567890xyz");
  11126. beginTest ("Numeric conversions");
  11127. expect (String::empty.getIntValue() == 0);
  11128. expect (String::empty.getDoubleValue() == 0.0);
  11129. expect (String::empty.getFloatValue() == 0.0f);
  11130. expect (s.getIntValue() == 12345678);
  11131. expect (s.getLargeIntValue() == (int64) 12345678);
  11132. expect (s.getDoubleValue() == 12345678.0);
  11133. expect (s.getFloatValue() == 12345678.0f);
  11134. expect (String (-1234).getIntValue() == -1234);
  11135. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11136. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11137. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11138. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11139. expect (s.getHexValue32() == 0x12345678);
  11140. expect (s.getHexValue64() == (int64) 0x12345678);
  11141. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11142. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11143. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11144. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11145. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11146. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11147. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11148. beginTest ("Subsections");
  11149. String s3;
  11150. s3 = "abcdeFGHIJ";
  11151. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11152. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11153. expect (s3.containsIgnoreCase (s3.substring (3)));
  11154. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11155. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11156. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11157. expect (s3.containsAnyOf (L"zzzFs"));
  11158. expect (s3.startsWith ("abcd"));
  11159. expect (s3.startsWithIgnoreCase (L"abCD"));
  11160. expect (s3.startsWith (String::empty));
  11161. expect (s3.startsWithChar ('a'));
  11162. expect (s3.endsWith (String ("HIJ")));
  11163. expect (s3.endsWithIgnoreCase (L"Hij"));
  11164. expect (s3.endsWith (String::empty));
  11165. expect (s3.endsWithChar (L'J'));
  11166. expect (s3.indexOf ("HIJ") == 7);
  11167. expect (s3.indexOf (L"HIJK") == -1);
  11168. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11169. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11170. String s4 (s3);
  11171. s4.append (String ("xyz123"), 3);
  11172. expect (s4 == s3 + "xyz");
  11173. expect (String (1234) < String (1235));
  11174. expect (String (1235) > String (1234));
  11175. expect (String (1234) >= String (1234));
  11176. expect (String (1234) <= String (1234));
  11177. expect (String (1235) >= String (1234));
  11178. expect (String (1234) <= String (1235));
  11179. String s5 ("word word2 word3");
  11180. expect (s5.containsWholeWord (String ("word2")));
  11181. expect (s5.indexOfWholeWord ("word2") == 5);
  11182. expect (s5.containsWholeWord (L"word"));
  11183. expect (s5.containsWholeWord ("word3"));
  11184. expect (s5.containsWholeWord (s5));
  11185. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11186. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11187. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11188. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11189. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11190. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11191. expect (s5.containsNonWhitespaceChars());
  11192. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11193. expect (s5.matchesWildcard (L"wor*", false));
  11194. expect (s5.matchesWildcard ("wOr*", true));
  11195. expect (s5.matchesWildcard (L"*word3", true));
  11196. expect (s5.matchesWildcard ("*word?", true));
  11197. expect (s5.matchesWildcard (L"Word*3", true));
  11198. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11199. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11200. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11201. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11202. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11203. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11204. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11205. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11206. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11207. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11208. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11209. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11210. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11211. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11212. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11213. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11214. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11215. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11216. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11217. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11218. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11219. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11220. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11221. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11222. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11223. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11224. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11225. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11226. expect (s5.replace ("Word", "", true) == " 2 3");
  11227. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11228. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11229. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11230. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11231. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11232. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11233. expect (s5.retainCharacters (String::empty).isEmpty());
  11234. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11235. expect (s5.removeCharacters (String::empty) == s5);
  11236. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11237. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11238. expect (! s5.isQuotedString());
  11239. expect (s5.quoted().isQuotedString());
  11240. expect (! s5.quoted().unquoted().isQuotedString());
  11241. expect (! String ("x'").isQuotedString());
  11242. expect (String ("'x").isQuotedString());
  11243. String s6 (" \t xyz \t\r\n");
  11244. expect (s6.trim() == String ("xyz"));
  11245. expect (s6.trim().trim() == "xyz");
  11246. expect (s5.trim() == s5);
  11247. expect (s6.trimStart().trimEnd() == s6.trim());
  11248. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11249. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11250. expect (s6.trimStart() != s6.trimEnd());
  11251. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11252. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11253. }
  11254. {
  11255. beginTest ("UTF8");
  11256. String s ("word word2 word3");
  11257. {
  11258. char buffer [100];
  11259. memset (buffer, 0xff, sizeof (buffer));
  11260. s.copyToUTF8 (buffer, 100);
  11261. expect (String::fromUTF8 (buffer, 100) == s);
  11262. juce_wchar bufferUnicode [100];
  11263. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11264. s.copyToUnicode (bufferUnicode, 100);
  11265. expect (String (bufferUnicode, 100) == s);
  11266. }
  11267. {
  11268. juce_wchar wideBuffer [50];
  11269. zerostruct (wideBuffer);
  11270. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11271. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11272. String wide (wideBuffer);
  11273. expect (wide == (const juce_wchar*) wideBuffer);
  11274. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11275. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11276. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11277. }
  11278. }
  11279. }
  11280. };
  11281. static StringTests stringUnitTests;
  11282. #endif
  11283. END_JUCE_NAMESPACE
  11284. /*** End of inlined file: juce_String.cpp ***/
  11285. /*** Start of inlined file: juce_StringArray.cpp ***/
  11286. BEGIN_JUCE_NAMESPACE
  11287. StringArray::StringArray() throw()
  11288. {
  11289. }
  11290. StringArray::StringArray (const StringArray& other)
  11291. : strings (other.strings)
  11292. {
  11293. }
  11294. StringArray::StringArray (const String& firstValue)
  11295. {
  11296. strings.add (firstValue);
  11297. }
  11298. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11299. const int numberOfStrings)
  11300. {
  11301. for (int i = 0; i < numberOfStrings; ++i)
  11302. strings.add (initialStrings [i]);
  11303. }
  11304. StringArray::StringArray (const char* const* const initialStrings,
  11305. const int numberOfStrings)
  11306. {
  11307. for (int i = 0; i < numberOfStrings; ++i)
  11308. strings.add (initialStrings [i]);
  11309. }
  11310. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11311. {
  11312. int i = 0;
  11313. while (initialStrings[i] != 0)
  11314. strings.add (initialStrings [i++]);
  11315. }
  11316. StringArray::StringArray (const char* const* const initialStrings)
  11317. {
  11318. int i = 0;
  11319. while (initialStrings[i] != 0)
  11320. strings.add (initialStrings [i++]);
  11321. }
  11322. StringArray& StringArray::operator= (const StringArray& other)
  11323. {
  11324. strings = other.strings;
  11325. return *this;
  11326. }
  11327. StringArray::~StringArray()
  11328. {
  11329. }
  11330. bool StringArray::operator== (const StringArray& other) const throw()
  11331. {
  11332. if (other.size() != size())
  11333. return false;
  11334. for (int i = size(); --i >= 0;)
  11335. if (other.strings.getReference(i) != strings.getReference(i))
  11336. return false;
  11337. return true;
  11338. }
  11339. bool StringArray::operator!= (const StringArray& other) const throw()
  11340. {
  11341. return ! operator== (other);
  11342. }
  11343. void StringArray::clear()
  11344. {
  11345. strings.clear();
  11346. }
  11347. const String& StringArray::operator[] (const int index) const throw()
  11348. {
  11349. if (isPositiveAndBelow (index, strings.size()))
  11350. return strings.getReference (index);
  11351. return String::empty;
  11352. }
  11353. String& StringArray::getReference (const int index) throw()
  11354. {
  11355. jassert (isPositiveAndBelow (index, strings.size()));
  11356. return strings.getReference (index);
  11357. }
  11358. void StringArray::add (const String& newString)
  11359. {
  11360. strings.add (newString);
  11361. }
  11362. void StringArray::insert (const int index, const String& newString)
  11363. {
  11364. strings.insert (index, newString);
  11365. }
  11366. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11367. {
  11368. if (! contains (newString, ignoreCase))
  11369. add (newString);
  11370. }
  11371. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11372. {
  11373. if (startIndex < 0)
  11374. {
  11375. jassertfalse;
  11376. startIndex = 0;
  11377. }
  11378. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11379. numElementsToAdd = otherArray.size() - startIndex;
  11380. while (--numElementsToAdd >= 0)
  11381. strings.add (otherArray.strings.getReference (startIndex++));
  11382. }
  11383. void StringArray::set (const int index, const String& newString)
  11384. {
  11385. strings.set (index, newString);
  11386. }
  11387. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11388. {
  11389. if (ignoreCase)
  11390. {
  11391. for (int i = size(); --i >= 0;)
  11392. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11393. return true;
  11394. }
  11395. else
  11396. {
  11397. for (int i = size(); --i >= 0;)
  11398. if (stringToLookFor == strings.getReference(i))
  11399. return true;
  11400. }
  11401. return false;
  11402. }
  11403. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11404. {
  11405. if (i < 0)
  11406. i = 0;
  11407. const int numElements = size();
  11408. if (ignoreCase)
  11409. {
  11410. while (i < numElements)
  11411. {
  11412. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11413. return i;
  11414. ++i;
  11415. }
  11416. }
  11417. else
  11418. {
  11419. while (i < numElements)
  11420. {
  11421. if (stringToLookFor == strings.getReference (i))
  11422. return i;
  11423. ++i;
  11424. }
  11425. }
  11426. return -1;
  11427. }
  11428. void StringArray::remove (const int index)
  11429. {
  11430. strings.remove (index);
  11431. }
  11432. void StringArray::removeString (const String& stringToRemove,
  11433. const bool ignoreCase)
  11434. {
  11435. if (ignoreCase)
  11436. {
  11437. for (int i = size(); --i >= 0;)
  11438. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11439. strings.remove (i);
  11440. }
  11441. else
  11442. {
  11443. for (int i = size(); --i >= 0;)
  11444. if (stringToRemove == strings.getReference (i))
  11445. strings.remove (i);
  11446. }
  11447. }
  11448. void StringArray::removeRange (int startIndex, int numberToRemove)
  11449. {
  11450. strings.removeRange (startIndex, numberToRemove);
  11451. }
  11452. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11453. {
  11454. if (removeWhitespaceStrings)
  11455. {
  11456. for (int i = size(); --i >= 0;)
  11457. if (! strings.getReference(i).containsNonWhitespaceChars())
  11458. strings.remove (i);
  11459. }
  11460. else
  11461. {
  11462. for (int i = size(); --i >= 0;)
  11463. if (strings.getReference(i).isEmpty())
  11464. strings.remove (i);
  11465. }
  11466. }
  11467. void StringArray::trim()
  11468. {
  11469. for (int i = size(); --i >= 0;)
  11470. {
  11471. String& s = strings.getReference(i);
  11472. s = s.trim();
  11473. }
  11474. }
  11475. class InternalStringArrayComparator_CaseSensitive
  11476. {
  11477. public:
  11478. static int compareElements (String& first, String& second) { return first.compare (second); }
  11479. };
  11480. class InternalStringArrayComparator_CaseInsensitive
  11481. {
  11482. public:
  11483. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11484. };
  11485. void StringArray::sort (const bool ignoreCase)
  11486. {
  11487. if (ignoreCase)
  11488. {
  11489. InternalStringArrayComparator_CaseInsensitive comp;
  11490. strings.sort (comp);
  11491. }
  11492. else
  11493. {
  11494. InternalStringArrayComparator_CaseSensitive comp;
  11495. strings.sort (comp);
  11496. }
  11497. }
  11498. void StringArray::move (const int currentIndex, int newIndex) throw()
  11499. {
  11500. strings.move (currentIndex, newIndex);
  11501. }
  11502. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11503. {
  11504. const int last = (numberToJoin < 0) ? size()
  11505. : jmin (size(), start + numberToJoin);
  11506. if (start < 0)
  11507. start = 0;
  11508. if (start >= last)
  11509. return String::empty;
  11510. if (start == last - 1)
  11511. return strings.getReference (start);
  11512. const int separatorLen = separator.length();
  11513. int charsNeeded = separatorLen * (last - start - 1);
  11514. for (int i = start; i < last; ++i)
  11515. charsNeeded += strings.getReference(i).length();
  11516. String result;
  11517. result.preallocateStorage (charsNeeded);
  11518. juce_wchar* dest = result;
  11519. while (start < last)
  11520. {
  11521. const String& s = strings.getReference (start);
  11522. const int len = s.length();
  11523. if (len > 0)
  11524. {
  11525. s.copyToUnicode (dest, len);
  11526. dest += len;
  11527. }
  11528. if (++start < last && separatorLen > 0)
  11529. {
  11530. separator.copyToUnicode (dest, separatorLen);
  11531. dest += separatorLen;
  11532. }
  11533. }
  11534. *dest = 0;
  11535. return result;
  11536. }
  11537. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11538. {
  11539. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11540. }
  11541. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11542. {
  11543. int num = 0;
  11544. if (text.isNotEmpty())
  11545. {
  11546. bool insideQuotes = false;
  11547. juce_wchar currentQuoteChar = 0;
  11548. int i = 0;
  11549. int tokenStart = 0;
  11550. for (;;)
  11551. {
  11552. const juce_wchar c = text[i];
  11553. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11554. if (! isBreak)
  11555. {
  11556. if (quoteCharacters.containsChar (c))
  11557. {
  11558. if (insideQuotes)
  11559. {
  11560. // only break out of quotes-mode if we find a matching quote to the
  11561. // one that we opened with..
  11562. if (currentQuoteChar == c)
  11563. insideQuotes = false;
  11564. }
  11565. else
  11566. {
  11567. insideQuotes = true;
  11568. currentQuoteChar = c;
  11569. }
  11570. }
  11571. }
  11572. else
  11573. {
  11574. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11575. ++num;
  11576. tokenStart = i + 1;
  11577. }
  11578. if (c == 0)
  11579. break;
  11580. ++i;
  11581. }
  11582. }
  11583. return num;
  11584. }
  11585. int StringArray::addLines (const String& sourceText)
  11586. {
  11587. int numLines = 0;
  11588. const juce_wchar* text = sourceText;
  11589. while (*text != 0)
  11590. {
  11591. const juce_wchar* const startOfLine = text;
  11592. while (*text != 0)
  11593. {
  11594. if (*text == '\r')
  11595. {
  11596. ++text;
  11597. if (*text == '\n')
  11598. ++text;
  11599. break;
  11600. }
  11601. if (*text == '\n')
  11602. {
  11603. ++text;
  11604. break;
  11605. }
  11606. ++text;
  11607. }
  11608. const juce_wchar* endOfLine = text;
  11609. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11610. --endOfLine;
  11611. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11612. --endOfLine;
  11613. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11614. ++numLines;
  11615. }
  11616. return numLines;
  11617. }
  11618. void StringArray::removeDuplicates (const bool ignoreCase)
  11619. {
  11620. for (int i = 0; i < size() - 1; ++i)
  11621. {
  11622. const String s (strings.getReference(i));
  11623. int nextIndex = i + 1;
  11624. for (;;)
  11625. {
  11626. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11627. if (nextIndex < 0)
  11628. break;
  11629. strings.remove (nextIndex);
  11630. }
  11631. }
  11632. }
  11633. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11634. const bool appendNumberToFirstInstance,
  11635. const juce_wchar* preNumberString,
  11636. const juce_wchar* postNumberString)
  11637. {
  11638. if (preNumberString == 0)
  11639. preNumberString = L" (";
  11640. if (postNumberString == 0)
  11641. postNumberString = L")";
  11642. for (int i = 0; i < size() - 1; ++i)
  11643. {
  11644. String& s = strings.getReference(i);
  11645. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11646. if (nextIndex >= 0)
  11647. {
  11648. const String original (s);
  11649. int number = 0;
  11650. if (appendNumberToFirstInstance)
  11651. s = original + preNumberString + String (++number) + postNumberString;
  11652. else
  11653. ++number;
  11654. while (nextIndex >= 0)
  11655. {
  11656. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11657. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11658. }
  11659. }
  11660. }
  11661. }
  11662. void StringArray::minimiseStorageOverheads()
  11663. {
  11664. strings.minimiseStorageOverheads();
  11665. }
  11666. END_JUCE_NAMESPACE
  11667. /*** End of inlined file: juce_StringArray.cpp ***/
  11668. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11669. BEGIN_JUCE_NAMESPACE
  11670. StringPairArray::StringPairArray (const bool ignoreCase_)
  11671. : ignoreCase (ignoreCase_)
  11672. {
  11673. }
  11674. StringPairArray::StringPairArray (const StringPairArray& other)
  11675. : keys (other.keys),
  11676. values (other.values),
  11677. ignoreCase (other.ignoreCase)
  11678. {
  11679. }
  11680. StringPairArray::~StringPairArray()
  11681. {
  11682. }
  11683. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11684. {
  11685. keys = other.keys;
  11686. values = other.values;
  11687. return *this;
  11688. }
  11689. bool StringPairArray::operator== (const StringPairArray& other) const
  11690. {
  11691. for (int i = keys.size(); --i >= 0;)
  11692. if (other [keys[i]] != values[i])
  11693. return false;
  11694. return true;
  11695. }
  11696. bool StringPairArray::operator!= (const StringPairArray& other) const
  11697. {
  11698. return ! operator== (other);
  11699. }
  11700. const String& StringPairArray::operator[] (const String& key) const
  11701. {
  11702. return values [keys.indexOf (key, ignoreCase)];
  11703. }
  11704. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11705. {
  11706. const int i = keys.indexOf (key, ignoreCase);
  11707. if (i >= 0)
  11708. return values[i];
  11709. return defaultReturnValue;
  11710. }
  11711. void StringPairArray::set (const String& key, const String& value)
  11712. {
  11713. const int i = keys.indexOf (key, ignoreCase);
  11714. if (i >= 0)
  11715. {
  11716. values.set (i, value);
  11717. }
  11718. else
  11719. {
  11720. keys.add (key);
  11721. values.add (value);
  11722. }
  11723. }
  11724. void StringPairArray::addArray (const StringPairArray& other)
  11725. {
  11726. for (int i = 0; i < other.size(); ++i)
  11727. set (other.keys[i], other.values[i]);
  11728. }
  11729. void StringPairArray::clear()
  11730. {
  11731. keys.clear();
  11732. values.clear();
  11733. }
  11734. void StringPairArray::remove (const String& key)
  11735. {
  11736. remove (keys.indexOf (key, ignoreCase));
  11737. }
  11738. void StringPairArray::remove (const int index)
  11739. {
  11740. keys.remove (index);
  11741. values.remove (index);
  11742. }
  11743. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11744. {
  11745. ignoreCase = shouldIgnoreCase;
  11746. }
  11747. const String StringPairArray::getDescription() const
  11748. {
  11749. String s;
  11750. for (int i = 0; i < keys.size(); ++i)
  11751. {
  11752. s << keys[i] << " = " << values[i];
  11753. if (i < keys.size())
  11754. s << ", ";
  11755. }
  11756. return s;
  11757. }
  11758. void StringPairArray::minimiseStorageOverheads()
  11759. {
  11760. keys.minimiseStorageOverheads();
  11761. values.minimiseStorageOverheads();
  11762. }
  11763. END_JUCE_NAMESPACE
  11764. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11765. /*** Start of inlined file: juce_StringPool.cpp ***/
  11766. BEGIN_JUCE_NAMESPACE
  11767. StringPool::StringPool() throw() {}
  11768. StringPool::~StringPool() {}
  11769. namespace StringPoolHelpers
  11770. {
  11771. template <class StringType>
  11772. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11773. {
  11774. int start = 0;
  11775. int end = strings.size();
  11776. for (;;)
  11777. {
  11778. if (start >= end)
  11779. {
  11780. jassert (start <= end);
  11781. strings.insert (start, newString);
  11782. return strings.getReference (start);
  11783. }
  11784. else
  11785. {
  11786. const String& startString = strings.getReference (start);
  11787. if (startString == newString)
  11788. return startString;
  11789. const int halfway = (start + end) >> 1;
  11790. if (halfway == start)
  11791. {
  11792. if (startString.compare (newString) < 0)
  11793. ++start;
  11794. strings.insert (start, newString);
  11795. return strings.getReference (start);
  11796. }
  11797. const int comp = strings.getReference (halfway).compare (newString);
  11798. if (comp == 0)
  11799. return strings.getReference (halfway);
  11800. else if (comp < 0)
  11801. start = halfway;
  11802. else
  11803. end = halfway;
  11804. }
  11805. }
  11806. }
  11807. }
  11808. const juce_wchar* StringPool::getPooledString (const String& s)
  11809. {
  11810. if (s.isEmpty())
  11811. return String::empty;
  11812. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11813. }
  11814. const juce_wchar* StringPool::getPooledString (const char* const s)
  11815. {
  11816. if (s == 0 || *s == 0)
  11817. return String::empty;
  11818. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11819. }
  11820. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11821. {
  11822. if (s == 0 || *s == 0)
  11823. return String::empty;
  11824. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11825. }
  11826. int StringPool::size() const throw()
  11827. {
  11828. return strings.size();
  11829. }
  11830. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11831. {
  11832. return strings [index];
  11833. }
  11834. END_JUCE_NAMESPACE
  11835. /*** End of inlined file: juce_StringPool.cpp ***/
  11836. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11837. BEGIN_JUCE_NAMESPACE
  11838. XmlDocument::XmlDocument (const String& documentText)
  11839. : originalText (documentText),
  11840. ignoreEmptyTextElements (true)
  11841. {
  11842. }
  11843. XmlDocument::XmlDocument (const File& file)
  11844. : ignoreEmptyTextElements (true),
  11845. inputSource (new FileInputSource (file))
  11846. {
  11847. }
  11848. XmlDocument::~XmlDocument()
  11849. {
  11850. }
  11851. XmlElement* XmlDocument::parse (const File& file)
  11852. {
  11853. XmlDocument doc (file);
  11854. return doc.getDocumentElement();
  11855. }
  11856. XmlElement* XmlDocument::parse (const String& xmlData)
  11857. {
  11858. XmlDocument doc (xmlData);
  11859. return doc.getDocumentElement();
  11860. }
  11861. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11862. {
  11863. inputSource = newSource;
  11864. }
  11865. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11866. {
  11867. ignoreEmptyTextElements = shouldBeIgnored;
  11868. }
  11869. namespace XmlIdentifierChars
  11870. {
  11871. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11872. {
  11873. return CharacterFunctions::isLetterOrDigit (c)
  11874. || c == '_' || c == '-' || c == ':' || c == '.';
  11875. }
  11876. bool isIdentifierChar (const juce_wchar c) throw()
  11877. {
  11878. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11879. return (c < numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11880. : isIdentifierCharSlow (c);
  11881. }
  11882. /*static void generateIdentifierCharConstants()
  11883. {
  11884. uint32 n[8];
  11885. zerostruct (n);
  11886. for (int i = 0; i < 256; ++i)
  11887. if (isIdentifierCharSlow (i))
  11888. n[i >> 5] |= (1 << (i & 31));
  11889. String s;
  11890. for (int i = 0; i < 8; ++i)
  11891. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11892. DBG (s);
  11893. }*/
  11894. }
  11895. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11896. {
  11897. String textToParse (originalText);
  11898. if (textToParse.isEmpty() && inputSource != 0)
  11899. {
  11900. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11901. if (in != 0)
  11902. {
  11903. MemoryOutputStream data;
  11904. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11905. textToParse = data.toString();
  11906. if (! onlyReadOuterDocumentElement)
  11907. originalText = textToParse;
  11908. }
  11909. }
  11910. input = textToParse;
  11911. lastError = String::empty;
  11912. errorOccurred = false;
  11913. outOfData = false;
  11914. needToLoadDTD = true;
  11915. if (textToParse.isEmpty())
  11916. {
  11917. lastError = "not enough input";
  11918. }
  11919. else
  11920. {
  11921. skipHeader();
  11922. if (input != 0)
  11923. {
  11924. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11925. if (! errorOccurred)
  11926. return result.release();
  11927. }
  11928. else
  11929. {
  11930. lastError = "incorrect xml header";
  11931. }
  11932. }
  11933. return 0;
  11934. }
  11935. const String& XmlDocument::getLastParseError() const throw()
  11936. {
  11937. return lastError;
  11938. }
  11939. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11940. {
  11941. lastError = desc;
  11942. errorOccurred = ! carryOn;
  11943. }
  11944. const String XmlDocument::getFileContents (const String& filename) const
  11945. {
  11946. if (inputSource != 0)
  11947. {
  11948. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11949. if (in != 0)
  11950. return in->readEntireStreamAsString();
  11951. }
  11952. return String::empty;
  11953. }
  11954. juce_wchar XmlDocument::readNextChar() throw()
  11955. {
  11956. if (*input != 0)
  11957. return *input++;
  11958. outOfData = true;
  11959. return 0;
  11960. }
  11961. int XmlDocument::findNextTokenLength() throw()
  11962. {
  11963. int len = 0;
  11964. juce_wchar c = *input;
  11965. while (XmlIdentifierChars::isIdentifierChar (c))
  11966. c = input [++len];
  11967. return len;
  11968. }
  11969. void XmlDocument::skipHeader()
  11970. {
  11971. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11972. if (found != 0)
  11973. {
  11974. input = found;
  11975. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11976. if (input == 0)
  11977. return;
  11978. #if JUCE_DEBUG
  11979. const String header (found, input - found);
  11980. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11981. .fromFirstOccurrenceOf ("=", false, false)
  11982. .fromFirstOccurrenceOf ("\"", false, false)
  11983. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11984. /* If you load an XML document with a non-UTF encoding type, it may have been
  11985. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11986. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11987. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11988. read, use your own code to convert them to a unicode String, and pass that to the
  11989. XML parser.
  11990. */
  11991. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11992. #endif
  11993. input += 2;
  11994. }
  11995. skipNextWhiteSpace();
  11996. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11997. if (docType == 0)
  11998. return;
  11999. input = docType + 9;
  12000. int n = 1;
  12001. while (n > 0)
  12002. {
  12003. const juce_wchar c = readNextChar();
  12004. if (outOfData)
  12005. return;
  12006. if (c == '<')
  12007. ++n;
  12008. else if (c == '>')
  12009. --n;
  12010. }
  12011. docType += 9;
  12012. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12013. }
  12014. void XmlDocument::skipNextWhiteSpace()
  12015. {
  12016. for (;;)
  12017. {
  12018. juce_wchar c = *input;
  12019. while (CharacterFunctions::isWhitespace (c))
  12020. c = *++input;
  12021. if (c == 0)
  12022. {
  12023. outOfData = true;
  12024. break;
  12025. }
  12026. else if (c == '<')
  12027. {
  12028. if (input[1] == '!'
  12029. && input[2] == '-'
  12030. && input[3] == '-')
  12031. {
  12032. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12033. if (closeComment == 0)
  12034. {
  12035. outOfData = true;
  12036. break;
  12037. }
  12038. input = closeComment + 3;
  12039. continue;
  12040. }
  12041. else if (input[1] == '?')
  12042. {
  12043. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12044. if (closeBracket == 0)
  12045. {
  12046. outOfData = true;
  12047. break;
  12048. }
  12049. input = closeBracket + 2;
  12050. continue;
  12051. }
  12052. }
  12053. break;
  12054. }
  12055. }
  12056. void XmlDocument::readQuotedString (String& result)
  12057. {
  12058. const juce_wchar quote = readNextChar();
  12059. while (! outOfData)
  12060. {
  12061. const juce_wchar c = readNextChar();
  12062. if (c == quote)
  12063. break;
  12064. if (c == '&')
  12065. {
  12066. --input;
  12067. readEntity (result);
  12068. }
  12069. else
  12070. {
  12071. --input;
  12072. const juce_wchar* const start = input;
  12073. for (;;)
  12074. {
  12075. const juce_wchar character = *input;
  12076. if (character == quote)
  12077. {
  12078. result.append (start, (int) (input - start));
  12079. ++input;
  12080. return;
  12081. }
  12082. else if (character == '&')
  12083. {
  12084. result.append (start, (int) (input - start));
  12085. break;
  12086. }
  12087. else if (character == 0)
  12088. {
  12089. outOfData = true;
  12090. setLastError ("unmatched quotes", false);
  12091. break;
  12092. }
  12093. ++input;
  12094. }
  12095. }
  12096. }
  12097. }
  12098. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12099. {
  12100. XmlElement* node = 0;
  12101. skipNextWhiteSpace();
  12102. if (outOfData)
  12103. return 0;
  12104. input = CharacterFunctions::find (input, JUCE_T("<"));
  12105. if (input != 0)
  12106. {
  12107. ++input;
  12108. int tagLen = findNextTokenLength();
  12109. if (tagLen == 0)
  12110. {
  12111. // no tag name - but allow for a gap after the '<' before giving an error
  12112. skipNextWhiteSpace();
  12113. tagLen = findNextTokenLength();
  12114. if (tagLen == 0)
  12115. {
  12116. setLastError ("tag name missing", false);
  12117. return node;
  12118. }
  12119. }
  12120. node = new XmlElement (String (input, tagLen));
  12121. input += tagLen;
  12122. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  12123. // look for attributes
  12124. for (;;)
  12125. {
  12126. skipNextWhiteSpace();
  12127. const juce_wchar c = *input;
  12128. // empty tag..
  12129. if (c == '/' && input[1] == '>')
  12130. {
  12131. input += 2;
  12132. break;
  12133. }
  12134. // parse the guts of the element..
  12135. if (c == '>')
  12136. {
  12137. ++input;
  12138. if (alsoParseSubElements)
  12139. readChildElements (node);
  12140. break;
  12141. }
  12142. // get an attribute..
  12143. if (XmlIdentifierChars::isIdentifierChar (c))
  12144. {
  12145. const int attNameLen = findNextTokenLength();
  12146. if (attNameLen > 0)
  12147. {
  12148. const juce_wchar* attNameStart = input;
  12149. input += attNameLen;
  12150. skipNextWhiteSpace();
  12151. if (readNextChar() == '=')
  12152. {
  12153. skipNextWhiteSpace();
  12154. const juce_wchar nextChar = *input;
  12155. if (nextChar == '"' || nextChar == '\'')
  12156. {
  12157. XmlElement::XmlAttributeNode* const newAtt
  12158. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12159. String::empty);
  12160. readQuotedString (newAtt->value);
  12161. attributeAppender.append (newAtt);
  12162. continue;
  12163. }
  12164. }
  12165. }
  12166. }
  12167. else
  12168. {
  12169. if (! outOfData)
  12170. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12171. }
  12172. break;
  12173. }
  12174. }
  12175. return node;
  12176. }
  12177. void XmlDocument::readChildElements (XmlElement* parent)
  12178. {
  12179. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  12180. for (;;)
  12181. {
  12182. const juce_wchar* const preWhitespaceInput = input;
  12183. skipNextWhiteSpace();
  12184. if (outOfData)
  12185. {
  12186. setLastError ("unmatched tags", false);
  12187. break;
  12188. }
  12189. if (*input == '<')
  12190. {
  12191. if (input[1] == '/')
  12192. {
  12193. // our close tag..
  12194. input = CharacterFunctions::find (input, JUCE_T(">"));
  12195. ++input;
  12196. break;
  12197. }
  12198. else if (input[1] == '!'
  12199. && input[2] == '['
  12200. && input[3] == 'C'
  12201. && input[4] == 'D'
  12202. && input[5] == 'A'
  12203. && input[6] == 'T'
  12204. && input[7] == 'A'
  12205. && input[8] == '[')
  12206. {
  12207. input += 9;
  12208. const juce_wchar* const inputStart = input;
  12209. int len = 0;
  12210. for (;;)
  12211. {
  12212. if (*input == 0)
  12213. {
  12214. setLastError ("unterminated CDATA section", false);
  12215. outOfData = true;
  12216. break;
  12217. }
  12218. else if (input[0] == ']'
  12219. && input[1] == ']'
  12220. && input[2] == '>')
  12221. {
  12222. input += 3;
  12223. break;
  12224. }
  12225. ++input;
  12226. ++len;
  12227. }
  12228. childAppender.append (XmlElement::createTextElement (String (inputStart, len)));
  12229. }
  12230. else
  12231. {
  12232. // this is some other element, so parse and add it..
  12233. XmlElement* const n = readNextElement (true);
  12234. if (n != 0)
  12235. childAppender.append (n);
  12236. else
  12237. return;
  12238. }
  12239. }
  12240. else // must be a character block
  12241. {
  12242. input = preWhitespaceInput; // roll back to include the leading whitespace
  12243. String textElementContent;
  12244. for (;;)
  12245. {
  12246. const juce_wchar c = *input;
  12247. if (c == '<')
  12248. break;
  12249. if (c == 0)
  12250. {
  12251. setLastError ("unmatched tags", false);
  12252. outOfData = true;
  12253. return;
  12254. }
  12255. if (c == '&')
  12256. {
  12257. String entity;
  12258. readEntity (entity);
  12259. if (entity.startsWithChar ('<') && entity [1] != 0)
  12260. {
  12261. const juce_wchar* const oldInput = input;
  12262. const bool oldOutOfData = outOfData;
  12263. input = entity;
  12264. outOfData = false;
  12265. for (;;)
  12266. {
  12267. XmlElement* const n = readNextElement (true);
  12268. if (n == 0)
  12269. break;
  12270. childAppender.append (n);
  12271. }
  12272. input = oldInput;
  12273. outOfData = oldOutOfData;
  12274. }
  12275. else
  12276. {
  12277. textElementContent += entity;
  12278. }
  12279. }
  12280. else
  12281. {
  12282. const juce_wchar* start = input;
  12283. int len = 0;
  12284. for (;;)
  12285. {
  12286. const juce_wchar nextChar = *input;
  12287. if (nextChar == '<' || nextChar == '&')
  12288. {
  12289. break;
  12290. }
  12291. else if (nextChar == 0)
  12292. {
  12293. setLastError ("unmatched tags", false);
  12294. outOfData = true;
  12295. return;
  12296. }
  12297. ++input;
  12298. ++len;
  12299. }
  12300. textElementContent.append (start, len);
  12301. }
  12302. }
  12303. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12304. {
  12305. childAppender.append (XmlElement::createTextElement (textElementContent));
  12306. }
  12307. }
  12308. }
  12309. }
  12310. void XmlDocument::readEntity (String& result)
  12311. {
  12312. // skip over the ampersand
  12313. ++input;
  12314. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12315. {
  12316. input += 4;
  12317. result += '&';
  12318. }
  12319. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12320. {
  12321. input += 5;
  12322. result += '"';
  12323. }
  12324. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12325. {
  12326. input += 5;
  12327. result += '\'';
  12328. }
  12329. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12330. {
  12331. input += 3;
  12332. result += '<';
  12333. }
  12334. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12335. {
  12336. input += 3;
  12337. result += '>';
  12338. }
  12339. else if (*input == '#')
  12340. {
  12341. int charCode = 0;
  12342. ++input;
  12343. if (*input == 'x' || *input == 'X')
  12344. {
  12345. ++input;
  12346. int numChars = 0;
  12347. while (input[0] != ';')
  12348. {
  12349. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12350. if (hexValue < 0 || ++numChars > 8)
  12351. {
  12352. setLastError ("illegal escape sequence", true);
  12353. break;
  12354. }
  12355. charCode = (charCode << 4) | hexValue;
  12356. ++input;
  12357. }
  12358. ++input;
  12359. }
  12360. else if (input[0] >= '0' && input[0] <= '9')
  12361. {
  12362. int numChars = 0;
  12363. while (input[0] != ';')
  12364. {
  12365. if (++numChars > 12)
  12366. {
  12367. setLastError ("illegal escape sequence", true);
  12368. break;
  12369. }
  12370. charCode = charCode * 10 + (input[0] - '0');
  12371. ++input;
  12372. }
  12373. ++input;
  12374. }
  12375. else
  12376. {
  12377. setLastError ("illegal escape sequence", true);
  12378. result += '&';
  12379. return;
  12380. }
  12381. result << (juce_wchar) charCode;
  12382. }
  12383. else
  12384. {
  12385. const juce_wchar* const entityNameStart = input;
  12386. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12387. if (closingSemiColon == 0)
  12388. {
  12389. outOfData = true;
  12390. result += '&';
  12391. }
  12392. else
  12393. {
  12394. input = closingSemiColon + 1;
  12395. result += expandExternalEntity (String (entityNameStart,
  12396. (int) (closingSemiColon - entityNameStart)));
  12397. }
  12398. }
  12399. }
  12400. const String XmlDocument::expandEntity (const String& ent)
  12401. {
  12402. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12403. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12404. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12405. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12406. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12407. if (ent[0] == '#')
  12408. {
  12409. if (ent[1] == 'x' || ent[1] == 'X')
  12410. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12411. if (ent[1] >= '0' && ent[1] <= '9')
  12412. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12413. setLastError ("illegal escape sequence", false);
  12414. return String::charToString ('&');
  12415. }
  12416. return expandExternalEntity (ent);
  12417. }
  12418. const String XmlDocument::expandExternalEntity (const String& entity)
  12419. {
  12420. if (needToLoadDTD)
  12421. {
  12422. if (dtdText.isNotEmpty())
  12423. {
  12424. dtdText = dtdText.trimCharactersAtEnd (">");
  12425. tokenisedDTD.addTokens (dtdText, true);
  12426. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12427. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12428. {
  12429. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12430. tokenisedDTD.clear();
  12431. tokenisedDTD.addTokens (getFileContents (fn), true);
  12432. }
  12433. else
  12434. {
  12435. tokenisedDTD.clear();
  12436. const int openBracket = dtdText.indexOfChar ('[');
  12437. if (openBracket > 0)
  12438. {
  12439. const int closeBracket = dtdText.lastIndexOfChar (']');
  12440. if (closeBracket > openBracket)
  12441. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12442. closeBracket), true);
  12443. }
  12444. }
  12445. for (int i = tokenisedDTD.size(); --i >= 0;)
  12446. {
  12447. if (tokenisedDTD[i].startsWithChar ('%')
  12448. && tokenisedDTD[i].endsWithChar (';'))
  12449. {
  12450. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12451. StringArray newToks;
  12452. newToks.addTokens (parsed, true);
  12453. tokenisedDTD.remove (i);
  12454. for (int j = newToks.size(); --j >= 0;)
  12455. tokenisedDTD.insert (i, newToks[j]);
  12456. }
  12457. }
  12458. }
  12459. needToLoadDTD = false;
  12460. }
  12461. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12462. {
  12463. if (tokenisedDTD[i] == entity)
  12464. {
  12465. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12466. {
  12467. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12468. // check for sub-entities..
  12469. int ampersand = ent.indexOfChar ('&');
  12470. while (ampersand >= 0)
  12471. {
  12472. const int semiColon = ent.indexOf (i + 1, ";");
  12473. if (semiColon < 0)
  12474. {
  12475. setLastError ("entity without terminating semi-colon", false);
  12476. break;
  12477. }
  12478. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12479. ent = ent.substring (0, ampersand)
  12480. + resolved
  12481. + ent.substring (semiColon + 1);
  12482. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12483. }
  12484. return ent;
  12485. }
  12486. }
  12487. }
  12488. setLastError ("unknown entity", true);
  12489. return entity;
  12490. }
  12491. const String XmlDocument::getParameterEntity (const String& entity)
  12492. {
  12493. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12494. {
  12495. if (tokenisedDTD[i] == entity
  12496. && tokenisedDTD [i - 1] == "%"
  12497. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12498. {
  12499. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12500. if (ent.equalsIgnoreCase ("system"))
  12501. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12502. else
  12503. return ent.trim().unquoted();
  12504. }
  12505. }
  12506. return entity;
  12507. }
  12508. END_JUCE_NAMESPACE
  12509. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12510. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12511. BEGIN_JUCE_NAMESPACE
  12512. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12513. : name (other.name),
  12514. value (other.value)
  12515. {
  12516. }
  12517. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12518. : name (name_),
  12519. value (value_)
  12520. {
  12521. #if JUCE_DEBUG
  12522. // this checks whether the attribute name string contains any illegals characters..
  12523. for (const juce_wchar* t = name; *t != 0; ++t)
  12524. jassert (CharacterFunctions::isLetterOrDigit (*t) || *t == '_' || *t == '-' || *t == ':');
  12525. #endif
  12526. }
  12527. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12528. {
  12529. return name.equalsIgnoreCase (nameToMatch);
  12530. }
  12531. XmlElement::XmlElement (const String& tagName_) throw()
  12532. : tagName (tagName_)
  12533. {
  12534. // the tag name mustn't be empty, or it'll look like a text element!
  12535. jassert (tagName_.containsNonWhitespaceChars())
  12536. // The tag can't contain spaces or other characters that would create invalid XML!
  12537. jassert (! tagName_.containsAnyOf (" <>/&"));
  12538. }
  12539. XmlElement::XmlElement (int /*dummy*/) throw()
  12540. {
  12541. }
  12542. XmlElement::XmlElement (const XmlElement& other)
  12543. : tagName (other.tagName)
  12544. {
  12545. copyChildrenAndAttributesFrom (other);
  12546. }
  12547. XmlElement& XmlElement::operator= (const XmlElement& other)
  12548. {
  12549. if (this != &other)
  12550. {
  12551. removeAllAttributes();
  12552. deleteAllChildElements();
  12553. tagName = other.tagName;
  12554. copyChildrenAndAttributesFrom (other);
  12555. }
  12556. return *this;
  12557. }
  12558. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12559. {
  12560. jassert (firstChildElement.get() == 0);
  12561. firstChildElement.addCopyOfList (other.firstChildElement);
  12562. jassert (attributes.get() == 0);
  12563. attributes.addCopyOfList (other.attributes);
  12564. }
  12565. XmlElement::~XmlElement() throw()
  12566. {
  12567. firstChildElement.deleteAll();
  12568. attributes.deleteAll();
  12569. }
  12570. namespace XmlOutputFunctions
  12571. {
  12572. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12573. {
  12574. if ((character >= 'a' && character <= 'z')
  12575. || (character >= 'A' && character <= 'Z')
  12576. || (character >= '0' && character <= '9'))
  12577. return true;
  12578. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12579. do
  12580. {
  12581. if (((juce_wchar) (uint8) *t) == character)
  12582. return true;
  12583. }
  12584. while (*++t != 0);
  12585. return false;
  12586. }
  12587. void generateLegalCharConstants()
  12588. {
  12589. uint8 n[32];
  12590. zerostruct (n);
  12591. for (int i = 0; i < 256; ++i)
  12592. if (isLegalXmlCharSlow (i))
  12593. n[i >> 3] |= (1 << (i & 7));
  12594. String s;
  12595. for (int i = 0; i < 32; ++i)
  12596. s << (int) n[i] << ", ";
  12597. DBG (s);
  12598. }*/
  12599. bool isLegalXmlChar (const uint32 c) throw()
  12600. {
  12601. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12602. return c < sizeof (legalChars) * 8
  12603. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12604. }
  12605. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12606. {
  12607. const juce_wchar* t = text;
  12608. for (;;)
  12609. {
  12610. const juce_wchar character = *t++;
  12611. if (character == 0)
  12612. break;
  12613. if (isLegalXmlChar ((uint32) character))
  12614. {
  12615. outputStream << (char) character;
  12616. }
  12617. else
  12618. {
  12619. switch (character)
  12620. {
  12621. case '&': outputStream << "&amp;"; break;
  12622. case '"': outputStream << "&quot;"; break;
  12623. case '>': outputStream << "&gt;"; break;
  12624. case '<': outputStream << "&lt;"; break;
  12625. case '\n':
  12626. case '\r':
  12627. if (! changeNewLines)
  12628. {
  12629. outputStream << (char) character;
  12630. break;
  12631. }
  12632. // Note: deliberate fall-through here!
  12633. default:
  12634. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12635. break;
  12636. }
  12637. }
  12638. }
  12639. }
  12640. void writeSpaces (OutputStream& out, int numSpaces)
  12641. {
  12642. if (numSpaces > 0)
  12643. {
  12644. const char blanks[] = " ";
  12645. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12646. while (numSpaces > blankSize)
  12647. {
  12648. out.write (blanks, blankSize);
  12649. numSpaces -= blankSize;
  12650. }
  12651. out.write (blanks, numSpaces);
  12652. }
  12653. }
  12654. }
  12655. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12656. const int indentationLevel,
  12657. const int lineWrapLength) const
  12658. {
  12659. using namespace XmlOutputFunctions;
  12660. writeSpaces (outputStream, indentationLevel);
  12661. if (! isTextElement())
  12662. {
  12663. outputStream.writeByte ('<');
  12664. outputStream << tagName;
  12665. {
  12666. const int attIndent = indentationLevel + tagName.length() + 1;
  12667. int lineLen = 0;
  12668. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12669. {
  12670. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12671. {
  12672. outputStream << newLine;
  12673. writeSpaces (outputStream, attIndent);
  12674. lineLen = 0;
  12675. }
  12676. const int64 startPos = outputStream.getPosition();
  12677. outputStream.writeByte (' ');
  12678. outputStream << att->name;
  12679. outputStream.write ("=\"", 2);
  12680. escapeIllegalXmlChars (outputStream, att->value, true);
  12681. outputStream.writeByte ('"');
  12682. lineLen += (int) (outputStream.getPosition() - startPos);
  12683. }
  12684. }
  12685. if (firstChildElement != 0)
  12686. {
  12687. outputStream.writeByte ('>');
  12688. XmlElement* child = firstChildElement;
  12689. bool lastWasTextNode = false;
  12690. while (child != 0)
  12691. {
  12692. if (child->isTextElement())
  12693. {
  12694. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12695. lastWasTextNode = true;
  12696. }
  12697. else
  12698. {
  12699. if (indentationLevel >= 0 && ! lastWasTextNode)
  12700. outputStream << newLine;
  12701. child->writeElementAsText (outputStream,
  12702. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12703. lastWasTextNode = false;
  12704. }
  12705. child = child->getNextElement();
  12706. }
  12707. if (indentationLevel >= 0 && ! lastWasTextNode)
  12708. {
  12709. outputStream << newLine;
  12710. writeSpaces (outputStream, indentationLevel);
  12711. }
  12712. outputStream.write ("</", 2);
  12713. outputStream << tagName;
  12714. outputStream.writeByte ('>');
  12715. }
  12716. else
  12717. {
  12718. outputStream.write ("/>", 2);
  12719. }
  12720. }
  12721. else
  12722. {
  12723. escapeIllegalXmlChars (outputStream, getText(), false);
  12724. }
  12725. }
  12726. const String XmlElement::createDocument (const String& dtdToUse,
  12727. const bool allOnOneLine,
  12728. const bool includeXmlHeader,
  12729. const String& encodingType,
  12730. const int lineWrapLength) const
  12731. {
  12732. MemoryOutputStream mem (2048);
  12733. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12734. return mem.toUTF8();
  12735. }
  12736. void XmlElement::writeToStream (OutputStream& output,
  12737. const String& dtdToUse,
  12738. const bool allOnOneLine,
  12739. const bool includeXmlHeader,
  12740. const String& encodingType,
  12741. const int lineWrapLength) const
  12742. {
  12743. using namespace XmlOutputFunctions;
  12744. if (includeXmlHeader)
  12745. {
  12746. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12747. if (allOnOneLine)
  12748. output.writeByte (' ');
  12749. else
  12750. output << newLine << newLine;
  12751. }
  12752. if (dtdToUse.isNotEmpty())
  12753. {
  12754. output << dtdToUse;
  12755. if (allOnOneLine)
  12756. output.writeByte (' ');
  12757. else
  12758. output << newLine;
  12759. }
  12760. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12761. if (! allOnOneLine)
  12762. output << newLine;
  12763. }
  12764. bool XmlElement::writeToFile (const File& file,
  12765. const String& dtdToUse,
  12766. const String& encodingType,
  12767. const int lineWrapLength) const
  12768. {
  12769. if (file.hasWriteAccess())
  12770. {
  12771. TemporaryFile tempFile (file);
  12772. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12773. if (out != 0)
  12774. {
  12775. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12776. out = 0;
  12777. return tempFile.overwriteTargetFileWithTemporary();
  12778. }
  12779. }
  12780. return false;
  12781. }
  12782. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12783. {
  12784. #if JUCE_DEBUG
  12785. // if debugging, check that the case is actually the same, because
  12786. // valid xml is case-sensitive, and although this lets it pass, it's
  12787. // better not to..
  12788. if (tagName.equalsIgnoreCase (tagNameWanted))
  12789. {
  12790. jassert (tagName == tagNameWanted);
  12791. return true;
  12792. }
  12793. else
  12794. {
  12795. return false;
  12796. }
  12797. #else
  12798. return tagName.equalsIgnoreCase (tagNameWanted);
  12799. #endif
  12800. }
  12801. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12802. {
  12803. XmlElement* e = nextListItem;
  12804. while (e != 0 && ! e->hasTagName (requiredTagName))
  12805. e = e->nextListItem;
  12806. return e;
  12807. }
  12808. int XmlElement::getNumAttributes() const throw()
  12809. {
  12810. return attributes.size();
  12811. }
  12812. const String& XmlElement::getAttributeName (const int index) const throw()
  12813. {
  12814. const XmlAttributeNode* const att = attributes [index];
  12815. return att != 0 ? att->name : String::empty;
  12816. }
  12817. const String& XmlElement::getAttributeValue (const int index) const throw()
  12818. {
  12819. const XmlAttributeNode* const att = attributes [index];
  12820. return att != 0 ? att->value : String::empty;
  12821. }
  12822. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12823. {
  12824. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12825. if (att->hasName (attributeName))
  12826. return true;
  12827. return false;
  12828. }
  12829. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12830. {
  12831. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12832. if (att->hasName (attributeName))
  12833. return att->value;
  12834. return String::empty;
  12835. }
  12836. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12837. {
  12838. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12839. if (att->hasName (attributeName))
  12840. return att->value;
  12841. return defaultReturnValue;
  12842. }
  12843. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12844. {
  12845. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12846. if (att->hasName (attributeName))
  12847. return att->value.getIntValue();
  12848. return defaultReturnValue;
  12849. }
  12850. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12851. {
  12852. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12853. if (att->hasName (attributeName))
  12854. return att->value.getDoubleValue();
  12855. return defaultReturnValue;
  12856. }
  12857. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12858. {
  12859. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12860. {
  12861. if (att->hasName (attributeName))
  12862. {
  12863. juce_wchar firstChar = att->value[0];
  12864. if (CharacterFunctions::isWhitespace (firstChar))
  12865. firstChar = att->value.trimStart() [0];
  12866. return firstChar == '1'
  12867. || firstChar == 't'
  12868. || firstChar == 'y'
  12869. || firstChar == 'T'
  12870. || firstChar == 'Y';
  12871. }
  12872. }
  12873. return defaultReturnValue;
  12874. }
  12875. bool XmlElement::compareAttribute (const String& attributeName,
  12876. const String& stringToCompareAgainst,
  12877. const bool ignoreCase) const throw()
  12878. {
  12879. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12880. if (att->hasName (attributeName))
  12881. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12882. : att->value == stringToCompareAgainst;
  12883. return false;
  12884. }
  12885. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12886. {
  12887. if (attributes == 0)
  12888. {
  12889. attributes = new XmlAttributeNode (attributeName, value);
  12890. }
  12891. else
  12892. {
  12893. XmlAttributeNode* att = attributes;
  12894. for (;;)
  12895. {
  12896. if (att->hasName (attributeName))
  12897. {
  12898. att->value = value;
  12899. break;
  12900. }
  12901. else if (att->nextListItem == 0)
  12902. {
  12903. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12904. break;
  12905. }
  12906. att = att->nextListItem;
  12907. }
  12908. }
  12909. }
  12910. void XmlElement::setAttribute (const String& attributeName, const int number)
  12911. {
  12912. setAttribute (attributeName, String (number));
  12913. }
  12914. void XmlElement::setAttribute (const String& attributeName, const double number)
  12915. {
  12916. setAttribute (attributeName, String (number));
  12917. }
  12918. void XmlElement::removeAttribute (const String& attributeName) throw()
  12919. {
  12920. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12921. while (att->get() != 0)
  12922. {
  12923. if (att->get()->hasName (attributeName))
  12924. {
  12925. delete att->removeNext();
  12926. break;
  12927. }
  12928. att = &(att->get()->nextListItem);
  12929. }
  12930. }
  12931. void XmlElement::removeAllAttributes() throw()
  12932. {
  12933. attributes.deleteAll();
  12934. }
  12935. int XmlElement::getNumChildElements() const throw()
  12936. {
  12937. return firstChildElement.size();
  12938. }
  12939. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12940. {
  12941. return firstChildElement [index].get();
  12942. }
  12943. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12944. {
  12945. XmlElement* child = firstChildElement;
  12946. while (child != 0)
  12947. {
  12948. if (child->hasTagName (childName))
  12949. break;
  12950. child = child->nextListItem;
  12951. }
  12952. return child;
  12953. }
  12954. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12955. {
  12956. if (newNode != 0)
  12957. firstChildElement.append (newNode);
  12958. }
  12959. void XmlElement::insertChildElement (XmlElement* const newNode,
  12960. int indexToInsertAt) throw()
  12961. {
  12962. if (newNode != 0)
  12963. {
  12964. removeChildElement (newNode, false);
  12965. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12966. }
  12967. }
  12968. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12969. {
  12970. XmlElement* const newElement = new XmlElement (childTagName);
  12971. addChildElement (newElement);
  12972. return newElement;
  12973. }
  12974. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12975. XmlElement* const newNode) throw()
  12976. {
  12977. if (newNode != 0)
  12978. {
  12979. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12980. if (p != 0)
  12981. {
  12982. if (currentChildElement != newNode)
  12983. delete p->replaceNext (newNode);
  12984. return true;
  12985. }
  12986. }
  12987. return false;
  12988. }
  12989. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12990. const bool shouldDeleteTheChild) throw()
  12991. {
  12992. if (childToRemove != 0)
  12993. {
  12994. firstChildElement.remove (childToRemove);
  12995. if (shouldDeleteTheChild)
  12996. delete childToRemove;
  12997. }
  12998. }
  12999. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13000. const bool ignoreOrderOfAttributes) const throw()
  13001. {
  13002. if (this != other)
  13003. {
  13004. if (other == 0 || tagName != other->tagName)
  13005. return false;
  13006. if (ignoreOrderOfAttributes)
  13007. {
  13008. int totalAtts = 0;
  13009. const XmlAttributeNode* att = attributes;
  13010. while (att != 0)
  13011. {
  13012. if (! other->compareAttribute (att->name, att->value))
  13013. return false;
  13014. att = att->nextListItem;
  13015. ++totalAtts;
  13016. }
  13017. if (totalAtts != other->getNumAttributes())
  13018. return false;
  13019. }
  13020. else
  13021. {
  13022. const XmlAttributeNode* thisAtt = attributes;
  13023. const XmlAttributeNode* otherAtt = other->attributes;
  13024. for (;;)
  13025. {
  13026. if (thisAtt == 0 || otherAtt == 0)
  13027. {
  13028. if (thisAtt == otherAtt) // both 0, so it's a match
  13029. break;
  13030. return false;
  13031. }
  13032. if (thisAtt->name != otherAtt->name
  13033. || thisAtt->value != otherAtt->value)
  13034. {
  13035. return false;
  13036. }
  13037. thisAtt = thisAtt->nextListItem;
  13038. otherAtt = otherAtt->nextListItem;
  13039. }
  13040. }
  13041. const XmlElement* thisChild = firstChildElement;
  13042. const XmlElement* otherChild = other->firstChildElement;
  13043. for (;;)
  13044. {
  13045. if (thisChild == 0 || otherChild == 0)
  13046. {
  13047. if (thisChild == otherChild) // both 0, so it's a match
  13048. break;
  13049. return false;
  13050. }
  13051. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13052. return false;
  13053. thisChild = thisChild->nextListItem;
  13054. otherChild = otherChild->nextListItem;
  13055. }
  13056. }
  13057. return true;
  13058. }
  13059. void XmlElement::deleteAllChildElements() throw()
  13060. {
  13061. firstChildElement.deleteAll();
  13062. }
  13063. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13064. {
  13065. XmlElement* child = firstChildElement;
  13066. while (child != 0)
  13067. {
  13068. XmlElement* const nextChild = child->nextListItem;
  13069. if (child->hasTagName (name))
  13070. removeChildElement (child, true);
  13071. child = nextChild;
  13072. }
  13073. }
  13074. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13075. {
  13076. return firstChildElement.contains (possibleChild);
  13077. }
  13078. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13079. {
  13080. if (this == elementToLookFor || elementToLookFor == 0)
  13081. return 0;
  13082. XmlElement* child = firstChildElement;
  13083. while (child != 0)
  13084. {
  13085. if (elementToLookFor == child)
  13086. return this;
  13087. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13088. if (found != 0)
  13089. return found;
  13090. child = child->nextListItem;
  13091. }
  13092. return 0;
  13093. }
  13094. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13095. {
  13096. firstChildElement.copyToArray (elems);
  13097. }
  13098. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13099. {
  13100. XmlElement* e = firstChildElement = elems[0];
  13101. for (int i = 1; i < num; ++i)
  13102. {
  13103. e->nextListItem = elems[i];
  13104. e = e->nextListItem;
  13105. }
  13106. e->nextListItem = 0;
  13107. }
  13108. bool XmlElement::isTextElement() const throw()
  13109. {
  13110. return tagName.isEmpty();
  13111. }
  13112. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13113. const String& XmlElement::getText() const throw()
  13114. {
  13115. jassert (isTextElement()); // you're trying to get the text from an element that
  13116. // isn't actually a text element.. If this contains text sub-nodes, you
  13117. // probably want to use getAllSubText instead.
  13118. return getStringAttribute (juce_xmltextContentAttributeName);
  13119. }
  13120. void XmlElement::setText (const String& newText)
  13121. {
  13122. if (isTextElement())
  13123. setAttribute (juce_xmltextContentAttributeName, newText);
  13124. else
  13125. jassertfalse; // you can only change the text in a text element, not a normal one.
  13126. }
  13127. const String XmlElement::getAllSubText() const
  13128. {
  13129. if (isTextElement())
  13130. return getText();
  13131. String result;
  13132. String::Concatenator concatenator (result);
  13133. const XmlElement* child = firstChildElement;
  13134. while (child != 0)
  13135. {
  13136. concatenator.append (child->getAllSubText());
  13137. child = child->nextListItem;
  13138. }
  13139. return result;
  13140. }
  13141. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13142. const String& defaultReturnValue) const
  13143. {
  13144. const XmlElement* const child = getChildByName (childTagName);
  13145. if (child != 0)
  13146. return child->getAllSubText();
  13147. return defaultReturnValue;
  13148. }
  13149. XmlElement* XmlElement::createTextElement (const String& text)
  13150. {
  13151. XmlElement* const e = new XmlElement ((int) 0);
  13152. e->setAttribute (juce_xmltextContentAttributeName, text);
  13153. return e;
  13154. }
  13155. void XmlElement::addTextElement (const String& text)
  13156. {
  13157. addChildElement (createTextElement (text));
  13158. }
  13159. void XmlElement::deleteAllTextElements() throw()
  13160. {
  13161. XmlElement* child = firstChildElement;
  13162. while (child != 0)
  13163. {
  13164. XmlElement* const next = child->nextListItem;
  13165. if (child->isTextElement())
  13166. removeChildElement (child, true);
  13167. child = next;
  13168. }
  13169. }
  13170. END_JUCE_NAMESPACE
  13171. /*** End of inlined file: juce_XmlElement.cpp ***/
  13172. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13173. BEGIN_JUCE_NAMESPACE
  13174. ReadWriteLock::ReadWriteLock() throw()
  13175. : numWaitingWriters (0),
  13176. numWriters (0),
  13177. writerThreadId (0)
  13178. {
  13179. }
  13180. ReadWriteLock::~ReadWriteLock() throw()
  13181. {
  13182. jassert (readerThreads.size() == 0);
  13183. jassert (numWriters == 0);
  13184. }
  13185. void ReadWriteLock::enterRead() const throw()
  13186. {
  13187. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13188. const ScopedLock sl (accessLock);
  13189. for (;;)
  13190. {
  13191. jassert (readerThreads.size() % 2 == 0);
  13192. int i;
  13193. for (i = 0; i < readerThreads.size(); i += 2)
  13194. if (readerThreads.getUnchecked(i) == threadId)
  13195. break;
  13196. if (i < readerThreads.size()
  13197. || numWriters + numWaitingWriters == 0
  13198. || (threadId == writerThreadId && numWriters > 0))
  13199. {
  13200. if (i < readerThreads.size())
  13201. {
  13202. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13203. }
  13204. else
  13205. {
  13206. readerThreads.add (threadId);
  13207. readerThreads.add ((Thread::ThreadID) 1);
  13208. }
  13209. return;
  13210. }
  13211. const ScopedUnlock ul (accessLock);
  13212. waitEvent.wait (100);
  13213. }
  13214. }
  13215. void ReadWriteLock::exitRead() const throw()
  13216. {
  13217. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13218. const ScopedLock sl (accessLock);
  13219. for (int i = 0; i < readerThreads.size(); i += 2)
  13220. {
  13221. if (readerThreads.getUnchecked(i) == threadId)
  13222. {
  13223. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13224. if (newCount == 0)
  13225. {
  13226. readerThreads.removeRange (i, 2);
  13227. waitEvent.signal();
  13228. }
  13229. else
  13230. {
  13231. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13232. }
  13233. return;
  13234. }
  13235. }
  13236. jassertfalse; // unlocking a lock that wasn't locked..
  13237. }
  13238. void ReadWriteLock::enterWrite() const throw()
  13239. {
  13240. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13241. const ScopedLock sl (accessLock);
  13242. for (;;)
  13243. {
  13244. if (readerThreads.size() + numWriters == 0
  13245. || threadId == writerThreadId
  13246. || (readerThreads.size() == 2
  13247. && readerThreads.getUnchecked(0) == threadId))
  13248. {
  13249. writerThreadId = threadId;
  13250. ++numWriters;
  13251. break;
  13252. }
  13253. ++numWaitingWriters;
  13254. accessLock.exit();
  13255. waitEvent.wait (100);
  13256. accessLock.enter();
  13257. --numWaitingWriters;
  13258. }
  13259. }
  13260. bool ReadWriteLock::tryEnterWrite() const throw()
  13261. {
  13262. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13263. const ScopedLock sl (accessLock);
  13264. if (readerThreads.size() + numWriters == 0
  13265. || threadId == writerThreadId
  13266. || (readerThreads.size() == 2
  13267. && readerThreads.getUnchecked(0) == threadId))
  13268. {
  13269. writerThreadId = threadId;
  13270. ++numWriters;
  13271. return true;
  13272. }
  13273. return false;
  13274. }
  13275. void ReadWriteLock::exitWrite() const throw()
  13276. {
  13277. const ScopedLock sl (accessLock);
  13278. // check this thread actually had the lock..
  13279. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13280. if (--numWriters == 0)
  13281. {
  13282. writerThreadId = 0;
  13283. waitEvent.signal();
  13284. }
  13285. }
  13286. END_JUCE_NAMESPACE
  13287. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13288. /*** Start of inlined file: juce_Thread.cpp ***/
  13289. BEGIN_JUCE_NAMESPACE
  13290. class RunningThreadsList
  13291. {
  13292. public:
  13293. RunningThreadsList()
  13294. {
  13295. }
  13296. void add (Thread* const thread)
  13297. {
  13298. const ScopedLock sl (lock);
  13299. jassert (! threads.contains (thread));
  13300. threads.add (thread);
  13301. }
  13302. void remove (Thread* const thread)
  13303. {
  13304. const ScopedLock sl (lock);
  13305. jassert (threads.contains (thread));
  13306. threads.removeValue (thread);
  13307. }
  13308. int size() const throw()
  13309. {
  13310. return threads.size();
  13311. }
  13312. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13313. {
  13314. const ScopedLock sl (lock);
  13315. for (int i = threads.size(); --i >= 0;)
  13316. {
  13317. Thread* const t = threads.getUnchecked(i);
  13318. if (t->getThreadId() == targetID)
  13319. return t;
  13320. }
  13321. return 0;
  13322. }
  13323. void stopAll (const int timeOutMilliseconds)
  13324. {
  13325. signalAllThreadsToStop();
  13326. for (;;)
  13327. {
  13328. Thread* firstThread = getFirstThread();
  13329. if (firstThread != 0)
  13330. firstThread->stopThread (timeOutMilliseconds);
  13331. else
  13332. break;
  13333. }
  13334. }
  13335. static RunningThreadsList& getInstance()
  13336. {
  13337. static RunningThreadsList runningThreads;
  13338. return runningThreads;
  13339. }
  13340. private:
  13341. Array<Thread*> threads;
  13342. CriticalSection lock;
  13343. void signalAllThreadsToStop()
  13344. {
  13345. const ScopedLock sl (lock);
  13346. for (int i = threads.size(); --i >= 0;)
  13347. threads.getUnchecked(i)->signalThreadShouldExit();
  13348. }
  13349. Thread* getFirstThread() const
  13350. {
  13351. const ScopedLock sl (lock);
  13352. return threads.getFirst();
  13353. }
  13354. };
  13355. void Thread::threadEntryPoint()
  13356. {
  13357. RunningThreadsList::getInstance().add (this);
  13358. JUCE_TRY
  13359. {
  13360. if (threadName_.isNotEmpty())
  13361. setCurrentThreadName (threadName_);
  13362. if (startSuspensionEvent_.wait (10000))
  13363. {
  13364. jassert (getCurrentThreadId() == threadId_);
  13365. if (affinityMask_ != 0)
  13366. setCurrentThreadAffinityMask (affinityMask_);
  13367. run();
  13368. }
  13369. }
  13370. JUCE_CATCH_ALL_ASSERT
  13371. RunningThreadsList::getInstance().remove (this);
  13372. closeThreadHandle();
  13373. }
  13374. // used to wrap the incoming call from the platform-specific code
  13375. void JUCE_API juce_threadEntryPoint (void* userData)
  13376. {
  13377. static_cast <Thread*> (userData)->threadEntryPoint();
  13378. }
  13379. Thread::Thread (const String& threadName)
  13380. : threadName_ (threadName),
  13381. threadHandle_ (0),
  13382. threadId_ (0),
  13383. threadPriority_ (5),
  13384. affinityMask_ (0),
  13385. threadShouldExit_ (false)
  13386. {
  13387. }
  13388. Thread::~Thread()
  13389. {
  13390. /* If your thread class's destructor has been called without first stopping the thread, that
  13391. means that this partially destructed object is still performing some work - and that's
  13392. probably a Bad Thing!
  13393. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13394. your subclass's destructor.
  13395. */
  13396. jassert (! isThreadRunning());
  13397. stopThread (100);
  13398. }
  13399. void Thread::startThread()
  13400. {
  13401. const ScopedLock sl (startStopLock);
  13402. threadShouldExit_ = false;
  13403. if (threadHandle_ == 0)
  13404. {
  13405. launchThread();
  13406. setThreadPriority (threadHandle_, threadPriority_);
  13407. startSuspensionEvent_.signal();
  13408. }
  13409. }
  13410. void Thread::startThread (const int priority)
  13411. {
  13412. const ScopedLock sl (startStopLock);
  13413. if (threadHandle_ == 0)
  13414. {
  13415. threadPriority_ = priority;
  13416. startThread();
  13417. }
  13418. else
  13419. {
  13420. setPriority (priority);
  13421. }
  13422. }
  13423. bool Thread::isThreadRunning() const
  13424. {
  13425. return threadHandle_ != 0;
  13426. }
  13427. void Thread::signalThreadShouldExit()
  13428. {
  13429. threadShouldExit_ = true;
  13430. }
  13431. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13432. {
  13433. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13434. jassert (getThreadId() != getCurrentThreadId());
  13435. const int sleepMsPerIteration = 5;
  13436. int count = timeOutMilliseconds / sleepMsPerIteration;
  13437. while (isThreadRunning())
  13438. {
  13439. if (timeOutMilliseconds > 0 && --count < 0)
  13440. return false;
  13441. sleep (sleepMsPerIteration);
  13442. }
  13443. return true;
  13444. }
  13445. void Thread::stopThread (const int timeOutMilliseconds)
  13446. {
  13447. // agh! You can't stop the thread that's calling this method! How on earth
  13448. // would that work??
  13449. jassert (getCurrentThreadId() != getThreadId());
  13450. const ScopedLock sl (startStopLock);
  13451. if (isThreadRunning())
  13452. {
  13453. signalThreadShouldExit();
  13454. notify();
  13455. if (timeOutMilliseconds != 0)
  13456. waitForThreadToExit (timeOutMilliseconds);
  13457. if (isThreadRunning())
  13458. {
  13459. // very bad karma if this point is reached, as there are bound to be
  13460. // locks and events left in silly states when a thread is killed by force..
  13461. jassertfalse;
  13462. Logger::writeToLog ("!! killing thread by force !!");
  13463. killThread();
  13464. RunningThreadsList::getInstance().remove (this);
  13465. threadHandle_ = 0;
  13466. threadId_ = 0;
  13467. }
  13468. }
  13469. }
  13470. bool Thread::setPriority (const int priority)
  13471. {
  13472. const ScopedLock sl (startStopLock);
  13473. if (setThreadPriority (threadHandle_, priority))
  13474. {
  13475. threadPriority_ = priority;
  13476. return true;
  13477. }
  13478. return false;
  13479. }
  13480. bool Thread::setCurrentThreadPriority (const int priority)
  13481. {
  13482. return setThreadPriority (0, priority);
  13483. }
  13484. void Thread::setAffinityMask (const uint32 affinityMask)
  13485. {
  13486. affinityMask_ = affinityMask;
  13487. }
  13488. bool Thread::wait (const int timeOutMilliseconds) const
  13489. {
  13490. return defaultEvent_.wait (timeOutMilliseconds);
  13491. }
  13492. void Thread::notify() const
  13493. {
  13494. defaultEvent_.signal();
  13495. }
  13496. int Thread::getNumRunningThreads()
  13497. {
  13498. return RunningThreadsList::getInstance().size();
  13499. }
  13500. Thread* Thread::getCurrentThread()
  13501. {
  13502. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13503. }
  13504. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13505. {
  13506. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13507. }
  13508. END_JUCE_NAMESPACE
  13509. /*** End of inlined file: juce_Thread.cpp ***/
  13510. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13511. BEGIN_JUCE_NAMESPACE
  13512. ThreadPoolJob::ThreadPoolJob (const String& name)
  13513. : jobName (name),
  13514. pool (0),
  13515. shouldStop (false),
  13516. isActive (false),
  13517. shouldBeDeleted (false)
  13518. {
  13519. }
  13520. ThreadPoolJob::~ThreadPoolJob()
  13521. {
  13522. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13523. // to remove it first!
  13524. jassert (pool == 0 || ! pool->contains (this));
  13525. }
  13526. const String ThreadPoolJob::getJobName() const
  13527. {
  13528. return jobName;
  13529. }
  13530. void ThreadPoolJob::setJobName (const String& newName)
  13531. {
  13532. jobName = newName;
  13533. }
  13534. void ThreadPoolJob::signalJobShouldExit()
  13535. {
  13536. shouldStop = true;
  13537. }
  13538. class ThreadPool::ThreadPoolThread : public Thread
  13539. {
  13540. public:
  13541. ThreadPoolThread (ThreadPool& pool_)
  13542. : Thread ("Pool"),
  13543. pool (pool_),
  13544. busy (false)
  13545. {
  13546. }
  13547. void run()
  13548. {
  13549. while (! threadShouldExit())
  13550. {
  13551. if (! pool.runNextJob())
  13552. wait (500);
  13553. }
  13554. }
  13555. private:
  13556. ThreadPool& pool;
  13557. bool volatile busy;
  13558. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13559. };
  13560. ThreadPool::ThreadPool (const int numThreads,
  13561. const bool startThreadsOnlyWhenNeeded,
  13562. const int stopThreadsWhenNotUsedTimeoutMs)
  13563. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13564. priority (5)
  13565. {
  13566. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13567. for (int i = jmax (1, numThreads); --i >= 0;)
  13568. threads.add (new ThreadPoolThread (*this));
  13569. if (! startThreadsOnlyWhenNeeded)
  13570. for (int i = threads.size(); --i >= 0;)
  13571. threads.getUnchecked(i)->startThread (priority);
  13572. }
  13573. ThreadPool::~ThreadPool()
  13574. {
  13575. removeAllJobs (true, 4000);
  13576. int i;
  13577. for (i = threads.size(); --i >= 0;)
  13578. threads.getUnchecked(i)->signalThreadShouldExit();
  13579. for (i = threads.size(); --i >= 0;)
  13580. threads.getUnchecked(i)->stopThread (500);
  13581. }
  13582. void ThreadPool::addJob (ThreadPoolJob* const job)
  13583. {
  13584. jassert (job != 0);
  13585. jassert (job->pool == 0);
  13586. if (job->pool == 0)
  13587. {
  13588. job->pool = this;
  13589. job->shouldStop = false;
  13590. job->isActive = false;
  13591. {
  13592. const ScopedLock sl (lock);
  13593. jobs.add (job);
  13594. int numRunning = 0;
  13595. for (int i = threads.size(); --i >= 0;)
  13596. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13597. ++numRunning;
  13598. if (numRunning < threads.size())
  13599. {
  13600. bool startedOne = false;
  13601. int n = 1000;
  13602. while (--n >= 0 && ! startedOne)
  13603. {
  13604. for (int i = threads.size(); --i >= 0;)
  13605. {
  13606. if (! threads.getUnchecked(i)->isThreadRunning())
  13607. {
  13608. threads.getUnchecked(i)->startThread (priority);
  13609. startedOne = true;
  13610. break;
  13611. }
  13612. }
  13613. if (! startedOne)
  13614. Thread::sleep (2);
  13615. }
  13616. }
  13617. }
  13618. for (int i = threads.size(); --i >= 0;)
  13619. threads.getUnchecked(i)->notify();
  13620. }
  13621. }
  13622. int ThreadPool::getNumJobs() const
  13623. {
  13624. return jobs.size();
  13625. }
  13626. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13627. {
  13628. const ScopedLock sl (lock);
  13629. return jobs [index];
  13630. }
  13631. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13632. {
  13633. const ScopedLock sl (lock);
  13634. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13635. }
  13636. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13637. {
  13638. const ScopedLock sl (lock);
  13639. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13640. }
  13641. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13642. const int timeOutMs) const
  13643. {
  13644. if (job != 0)
  13645. {
  13646. const uint32 start = Time::getMillisecondCounter();
  13647. while (contains (job))
  13648. {
  13649. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13650. return false;
  13651. jobFinishedSignal.wait (2);
  13652. }
  13653. }
  13654. return true;
  13655. }
  13656. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13657. const bool interruptIfRunning,
  13658. const int timeOutMs)
  13659. {
  13660. bool dontWait = true;
  13661. if (job != 0)
  13662. {
  13663. const ScopedLock sl (lock);
  13664. if (jobs.contains (job))
  13665. {
  13666. if (job->isActive)
  13667. {
  13668. if (interruptIfRunning)
  13669. job->signalJobShouldExit();
  13670. dontWait = false;
  13671. }
  13672. else
  13673. {
  13674. jobs.removeValue (job);
  13675. job->pool = 0;
  13676. }
  13677. }
  13678. }
  13679. return dontWait || waitForJobToFinish (job, timeOutMs);
  13680. }
  13681. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13682. const int timeOutMs,
  13683. const bool deleteInactiveJobs,
  13684. ThreadPool::JobSelector* selectedJobsToRemove)
  13685. {
  13686. Array <ThreadPoolJob*> jobsToWaitFor;
  13687. {
  13688. const ScopedLock sl (lock);
  13689. for (int i = jobs.size(); --i >= 0;)
  13690. {
  13691. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13692. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13693. {
  13694. if (job->isActive)
  13695. {
  13696. jobsToWaitFor.add (job);
  13697. if (interruptRunningJobs)
  13698. job->signalJobShouldExit();
  13699. }
  13700. else
  13701. {
  13702. jobs.remove (i);
  13703. if (deleteInactiveJobs)
  13704. delete job;
  13705. else
  13706. job->pool = 0;
  13707. }
  13708. }
  13709. }
  13710. }
  13711. const uint32 start = Time::getMillisecondCounter();
  13712. for (;;)
  13713. {
  13714. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13715. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13716. jobsToWaitFor.remove (i);
  13717. if (jobsToWaitFor.size() == 0)
  13718. break;
  13719. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13720. return false;
  13721. jobFinishedSignal.wait (20);
  13722. }
  13723. return true;
  13724. }
  13725. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13726. {
  13727. StringArray s;
  13728. const ScopedLock sl (lock);
  13729. for (int i = 0; i < jobs.size(); ++i)
  13730. {
  13731. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13732. if (job->isActive || ! onlyReturnActiveJobs)
  13733. s.add (job->getJobName());
  13734. }
  13735. return s;
  13736. }
  13737. bool ThreadPool::setThreadPriorities (const int newPriority)
  13738. {
  13739. bool ok = true;
  13740. if (priority != newPriority)
  13741. {
  13742. priority = newPriority;
  13743. for (int i = threads.size(); --i >= 0;)
  13744. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13745. ok = false;
  13746. }
  13747. return ok;
  13748. }
  13749. bool ThreadPool::runNextJob()
  13750. {
  13751. ThreadPoolJob* job = 0;
  13752. {
  13753. const ScopedLock sl (lock);
  13754. for (int i = 0; i < jobs.size(); ++i)
  13755. {
  13756. job = jobs[i];
  13757. if (job != 0 && ! (job->isActive || job->shouldStop))
  13758. break;
  13759. job = 0;
  13760. }
  13761. if (job != 0)
  13762. job->isActive = true;
  13763. }
  13764. if (job != 0)
  13765. {
  13766. JUCE_TRY
  13767. {
  13768. ThreadPoolJob::JobStatus result = job->runJob();
  13769. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13770. const ScopedLock sl (lock);
  13771. if (jobs.contains (job))
  13772. {
  13773. job->isActive = false;
  13774. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13775. {
  13776. job->pool = 0;
  13777. job->shouldStop = true;
  13778. jobs.removeValue (job);
  13779. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13780. delete job;
  13781. jobFinishedSignal.signal();
  13782. }
  13783. else
  13784. {
  13785. // move the job to the end of the queue if it wants another go
  13786. jobs.move (jobs.indexOf (job), -1);
  13787. }
  13788. }
  13789. }
  13790. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13791. catch (...)
  13792. {
  13793. const ScopedLock sl (lock);
  13794. jobs.removeValue (job);
  13795. }
  13796. #endif
  13797. }
  13798. else
  13799. {
  13800. if (threadStopTimeout > 0
  13801. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13802. {
  13803. const ScopedLock sl (lock);
  13804. if (jobs.size() == 0)
  13805. for (int i = threads.size(); --i >= 0;)
  13806. threads.getUnchecked(i)->signalThreadShouldExit();
  13807. }
  13808. else
  13809. {
  13810. return false;
  13811. }
  13812. }
  13813. return true;
  13814. }
  13815. END_JUCE_NAMESPACE
  13816. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13817. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13818. BEGIN_JUCE_NAMESPACE
  13819. TimeSliceThread::TimeSliceThread (const String& threadName)
  13820. : Thread (threadName),
  13821. index (0),
  13822. clientBeingCalled (0),
  13823. clientsChanged (false)
  13824. {
  13825. }
  13826. TimeSliceThread::~TimeSliceThread()
  13827. {
  13828. stopThread (2000);
  13829. }
  13830. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  13831. {
  13832. const ScopedLock sl (listLock);
  13833. clients.addIfNotAlreadyThere (client);
  13834. clientsChanged = true;
  13835. notify();
  13836. }
  13837. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13838. {
  13839. const ScopedLock sl1 (listLock);
  13840. clientsChanged = true;
  13841. // if there's a chance we're in the middle of calling this client, we need to
  13842. // also lock the outer lock..
  13843. if (clientBeingCalled == client)
  13844. {
  13845. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13846. const ScopedLock sl2 (callbackLock);
  13847. const ScopedLock sl3 (listLock);
  13848. clients.removeValue (client);
  13849. }
  13850. else
  13851. {
  13852. clients.removeValue (client);
  13853. }
  13854. }
  13855. int TimeSliceThread::getNumClients() const
  13856. {
  13857. return clients.size();
  13858. }
  13859. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13860. {
  13861. const ScopedLock sl (listLock);
  13862. return clients [i];
  13863. }
  13864. void TimeSliceThread::run()
  13865. {
  13866. int numCallsSinceBusy = 0;
  13867. while (! threadShouldExit())
  13868. {
  13869. int timeToWait = 500;
  13870. {
  13871. const ScopedLock sl (callbackLock);
  13872. {
  13873. const ScopedLock sl2 (listLock);
  13874. if (clients.size() > 0)
  13875. {
  13876. index = (index + 1) % clients.size();
  13877. clientBeingCalled = clients [index];
  13878. }
  13879. else
  13880. {
  13881. index = 0;
  13882. clientBeingCalled = 0;
  13883. }
  13884. if (clientsChanged)
  13885. {
  13886. clientsChanged = false;
  13887. numCallsSinceBusy = 0;
  13888. }
  13889. }
  13890. if (clientBeingCalled != 0)
  13891. {
  13892. if (clientBeingCalled->useTimeSlice())
  13893. numCallsSinceBusy = 0;
  13894. else
  13895. ++numCallsSinceBusy;
  13896. if (numCallsSinceBusy >= clients.size())
  13897. timeToWait = 500;
  13898. else if (index == 0)
  13899. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  13900. else
  13901. timeToWait = 0;
  13902. }
  13903. }
  13904. if (timeToWait > 0)
  13905. wait (timeToWait);
  13906. }
  13907. }
  13908. END_JUCE_NAMESPACE
  13909. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13910. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13911. BEGIN_JUCE_NAMESPACE
  13912. DeletedAtShutdown::DeletedAtShutdown()
  13913. {
  13914. const ScopedLock sl (getLock());
  13915. getObjects().add (this);
  13916. }
  13917. DeletedAtShutdown::~DeletedAtShutdown()
  13918. {
  13919. const ScopedLock sl (getLock());
  13920. getObjects().removeValue (this);
  13921. }
  13922. void DeletedAtShutdown::deleteAll()
  13923. {
  13924. // make a local copy of the array, so it can't get into a loop if something
  13925. // creates another DeletedAtShutdown object during its destructor.
  13926. Array <DeletedAtShutdown*> localCopy;
  13927. {
  13928. const ScopedLock sl (getLock());
  13929. localCopy = getObjects();
  13930. }
  13931. for (int i = localCopy.size(); --i >= 0;)
  13932. {
  13933. JUCE_TRY
  13934. {
  13935. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13936. // double-check that it's not already been deleted during another object's destructor.
  13937. {
  13938. const ScopedLock sl (getLock());
  13939. if (! getObjects().contains (deletee))
  13940. deletee = 0;
  13941. }
  13942. delete deletee;
  13943. }
  13944. JUCE_CATCH_EXCEPTION
  13945. }
  13946. // if no objects got re-created during shutdown, this should have been emptied by their
  13947. // destructors
  13948. jassert (getObjects().size() == 0);
  13949. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13950. }
  13951. CriticalSection& DeletedAtShutdown::getLock()
  13952. {
  13953. static CriticalSection lock;
  13954. return lock;
  13955. }
  13956. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13957. {
  13958. static Array <DeletedAtShutdown*> objects;
  13959. return objects;
  13960. }
  13961. END_JUCE_NAMESPACE
  13962. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13963. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13964. BEGIN_JUCE_NAMESPACE
  13965. UnitTest::UnitTest (const String& name_)
  13966. : name (name_), runner (0)
  13967. {
  13968. getAllTests().add (this);
  13969. }
  13970. UnitTest::~UnitTest()
  13971. {
  13972. getAllTests().removeValue (this);
  13973. }
  13974. Array<UnitTest*>& UnitTest::getAllTests()
  13975. {
  13976. static Array<UnitTest*> tests;
  13977. return tests;
  13978. }
  13979. void UnitTest::initialise() {}
  13980. void UnitTest::shutdown() {}
  13981. void UnitTest::performTest (UnitTestRunner* const runner_)
  13982. {
  13983. jassert (runner_ != 0);
  13984. runner = runner_;
  13985. initialise();
  13986. runTest();
  13987. shutdown();
  13988. }
  13989. void UnitTest::logMessage (const String& message)
  13990. {
  13991. runner->logMessage (message);
  13992. }
  13993. void UnitTest::beginTest (const String& testName)
  13994. {
  13995. runner->beginNewTest (this, testName);
  13996. }
  13997. void UnitTest::expect (const bool result, const String& failureMessage)
  13998. {
  13999. if (result)
  14000. runner->addPass();
  14001. else
  14002. runner->addFail (failureMessage);
  14003. }
  14004. UnitTestRunner::UnitTestRunner()
  14005. : currentTest (0), assertOnFailure (false)
  14006. {
  14007. }
  14008. UnitTestRunner::~UnitTestRunner()
  14009. {
  14010. }
  14011. int UnitTestRunner::getNumResults() const throw()
  14012. {
  14013. return results.size();
  14014. }
  14015. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14016. {
  14017. return results [index];
  14018. }
  14019. void UnitTestRunner::resultsUpdated()
  14020. {
  14021. }
  14022. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14023. {
  14024. results.clear();
  14025. assertOnFailure = assertOnFailure_;
  14026. resultsUpdated();
  14027. for (int i = 0; i < tests.size(); ++i)
  14028. {
  14029. try
  14030. {
  14031. tests.getUnchecked(i)->performTest (this);
  14032. }
  14033. catch (...)
  14034. {
  14035. addFail ("An unhandled exception was thrown!");
  14036. }
  14037. }
  14038. endTest();
  14039. }
  14040. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14041. {
  14042. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14043. }
  14044. void UnitTestRunner::logMessage (const String& message)
  14045. {
  14046. Logger::writeToLog (message);
  14047. }
  14048. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14049. {
  14050. endTest();
  14051. currentTest = test;
  14052. TestResult* const r = new TestResult();
  14053. r->unitTestName = test->getName();
  14054. r->subcategoryName = subCategory;
  14055. r->passes = 0;
  14056. r->failures = 0;
  14057. results.add (r);
  14058. logMessage ("-----------------------------------------------------------------");
  14059. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14060. resultsUpdated();
  14061. }
  14062. void UnitTestRunner::endTest()
  14063. {
  14064. if (results.size() > 0)
  14065. {
  14066. TestResult* const r = results.getLast();
  14067. if (r->failures > 0)
  14068. {
  14069. String m ("FAILED!!");
  14070. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14071. << " failed, out of a total of " << (r->passes + r->failures);
  14072. logMessage (String::empty);
  14073. logMessage (m);
  14074. logMessage (String::empty);
  14075. }
  14076. else
  14077. {
  14078. logMessage ("All tests completed successfully");
  14079. }
  14080. }
  14081. }
  14082. void UnitTestRunner::addPass()
  14083. {
  14084. {
  14085. const ScopedLock sl (results.getLock());
  14086. TestResult* const r = results.getLast();
  14087. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14088. r->passes++;
  14089. String message ("Test ");
  14090. message << (r->failures + r->passes) << " passed";
  14091. logMessage (message);
  14092. }
  14093. resultsUpdated();
  14094. }
  14095. void UnitTestRunner::addFail (const String& failureMessage)
  14096. {
  14097. {
  14098. const ScopedLock sl (results.getLock());
  14099. TestResult* const r = results.getLast();
  14100. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14101. r->failures++;
  14102. String message ("!!! Test ");
  14103. message << (r->failures + r->passes) << " failed";
  14104. if (failureMessage.isNotEmpty())
  14105. message << ": " << failureMessage;
  14106. r->messages.add (message);
  14107. logMessage (message);
  14108. }
  14109. resultsUpdated();
  14110. if (assertOnFailure) { jassertfalse }
  14111. }
  14112. END_JUCE_NAMESPACE
  14113. /*** End of inlined file: juce_UnitTest.cpp ***/
  14114. #endif
  14115. #if JUCE_BUILD_MISC
  14116. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14117. BEGIN_JUCE_NAMESPACE
  14118. class ValueTree::SetPropertyAction : public UndoableAction
  14119. {
  14120. public:
  14121. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14122. const var& newValue_, const var& oldValue_,
  14123. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14124. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14125. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14126. {
  14127. }
  14128. bool perform()
  14129. {
  14130. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14131. if (isDeletingProperty)
  14132. target->removeProperty (name, 0);
  14133. else
  14134. target->setProperty (name, newValue, 0);
  14135. return true;
  14136. }
  14137. bool undo()
  14138. {
  14139. if (isAddingNewProperty)
  14140. target->removeProperty (name, 0);
  14141. else
  14142. target->setProperty (name, oldValue, 0);
  14143. return true;
  14144. }
  14145. int getSizeInUnits()
  14146. {
  14147. return (int) sizeof (*this); //xxx should be more accurate
  14148. }
  14149. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14150. {
  14151. if (! (isAddingNewProperty || isDeletingProperty))
  14152. {
  14153. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14154. if (next != 0 && next->target == target && next->name == name
  14155. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14156. {
  14157. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14158. }
  14159. }
  14160. return 0;
  14161. }
  14162. private:
  14163. const SharedObjectPtr target;
  14164. const Identifier name;
  14165. const var newValue;
  14166. var oldValue;
  14167. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14168. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  14169. };
  14170. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14171. {
  14172. public:
  14173. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14174. const SharedObjectPtr& newChild_)
  14175. : target (target_),
  14176. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14177. childIndex (childIndex_),
  14178. isDeleting (newChild_ == 0)
  14179. {
  14180. jassert (child != 0);
  14181. }
  14182. bool perform()
  14183. {
  14184. if (isDeleting)
  14185. target->removeChild (childIndex, 0);
  14186. else
  14187. target->addChild (child, childIndex, 0);
  14188. return true;
  14189. }
  14190. bool undo()
  14191. {
  14192. if (isDeleting)
  14193. {
  14194. target->addChild (child, childIndex, 0);
  14195. }
  14196. else
  14197. {
  14198. // If you hit this, it seems that your object's state is getting confused - probably
  14199. // because you've interleaved some undoable and non-undoable operations?
  14200. jassert (childIndex < target->children.size());
  14201. target->removeChild (childIndex, 0);
  14202. }
  14203. return true;
  14204. }
  14205. int getSizeInUnits()
  14206. {
  14207. return (int) sizeof (*this); //xxx should be more accurate
  14208. }
  14209. private:
  14210. const SharedObjectPtr target, child;
  14211. const int childIndex;
  14212. const bool isDeleting;
  14213. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  14214. };
  14215. class ValueTree::MoveChildAction : public UndoableAction
  14216. {
  14217. public:
  14218. MoveChildAction (const SharedObjectPtr& parent_,
  14219. const int startIndex_, const int endIndex_)
  14220. : parent (parent_),
  14221. startIndex (startIndex_),
  14222. endIndex (endIndex_)
  14223. {
  14224. }
  14225. bool perform()
  14226. {
  14227. parent->moveChild (startIndex, endIndex, 0);
  14228. return true;
  14229. }
  14230. bool undo()
  14231. {
  14232. parent->moveChild (endIndex, startIndex, 0);
  14233. return true;
  14234. }
  14235. int getSizeInUnits()
  14236. {
  14237. return (int) sizeof (*this); //xxx should be more accurate
  14238. }
  14239. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14240. {
  14241. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14242. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14243. return new MoveChildAction (parent, startIndex, next->endIndex);
  14244. return 0;
  14245. }
  14246. private:
  14247. const SharedObjectPtr parent;
  14248. const int startIndex, endIndex;
  14249. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  14250. };
  14251. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14252. : type (type_), parent (0)
  14253. {
  14254. }
  14255. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14256. : type (other.type), properties (other.properties), parent (0)
  14257. {
  14258. for (int i = 0; i < other.children.size(); ++i)
  14259. {
  14260. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14261. child->parent = this;
  14262. children.add (child);
  14263. }
  14264. }
  14265. ValueTree::SharedObject::~SharedObject()
  14266. {
  14267. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14268. for (int i = children.size(); --i >= 0;)
  14269. {
  14270. const SharedObjectPtr c (children.getUnchecked(i));
  14271. c->parent = 0;
  14272. children.remove (i);
  14273. c->sendParentChangeMessage();
  14274. }
  14275. }
  14276. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14277. {
  14278. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14279. {
  14280. ValueTree* const v = valueTreesWithListeners[i];
  14281. if (v != 0)
  14282. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14283. }
  14284. }
  14285. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14286. {
  14287. ValueTree tree (this);
  14288. ValueTree::SharedObject* t = this;
  14289. while (t != 0)
  14290. {
  14291. t->sendPropertyChangeMessage (tree, property);
  14292. t = t->parent;
  14293. }
  14294. }
  14295. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14296. {
  14297. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14298. {
  14299. ValueTree* const v = valueTreesWithListeners[i];
  14300. if (v != 0)
  14301. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14302. }
  14303. }
  14304. void ValueTree::SharedObject::sendChildChangeMessage()
  14305. {
  14306. ValueTree tree (this);
  14307. ValueTree::SharedObject* t = this;
  14308. while (t != 0)
  14309. {
  14310. t->sendChildChangeMessage (tree);
  14311. t = t->parent;
  14312. }
  14313. }
  14314. void ValueTree::SharedObject::sendParentChangeMessage()
  14315. {
  14316. ValueTree tree (this);
  14317. int i;
  14318. for (i = children.size(); --i >= 0;)
  14319. {
  14320. SharedObject* const t = children[i];
  14321. if (t != 0)
  14322. t->sendParentChangeMessage();
  14323. }
  14324. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14325. {
  14326. ValueTree* const v = valueTreesWithListeners[i];
  14327. if (v != 0)
  14328. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14329. }
  14330. }
  14331. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14332. {
  14333. return properties [name];
  14334. }
  14335. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14336. {
  14337. return properties.getWithDefault (name, defaultReturnValue);
  14338. }
  14339. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14340. {
  14341. if (undoManager == 0)
  14342. {
  14343. if (properties.set (name, newValue))
  14344. sendPropertyChangeMessage (name);
  14345. }
  14346. else
  14347. {
  14348. var* const existingValue = properties.getVarPointer (name);
  14349. if (existingValue != 0)
  14350. {
  14351. if (*existingValue != newValue)
  14352. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14353. }
  14354. else
  14355. {
  14356. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14357. }
  14358. }
  14359. }
  14360. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14361. {
  14362. return properties.contains (name);
  14363. }
  14364. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14365. {
  14366. if (undoManager == 0)
  14367. {
  14368. if (properties.remove (name))
  14369. sendPropertyChangeMessage (name);
  14370. }
  14371. else
  14372. {
  14373. if (properties.contains (name))
  14374. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14375. }
  14376. }
  14377. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14378. {
  14379. if (undoManager == 0)
  14380. {
  14381. while (properties.size() > 0)
  14382. {
  14383. const Identifier name (properties.getName (properties.size() - 1));
  14384. properties.remove (name);
  14385. sendPropertyChangeMessage (name);
  14386. }
  14387. }
  14388. else
  14389. {
  14390. for (int i = properties.size(); --i >= 0;)
  14391. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14392. }
  14393. }
  14394. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14395. {
  14396. for (int i = 0; i < children.size(); ++i)
  14397. if (children.getUnchecked(i)->type == typeToMatch)
  14398. return ValueTree (children.getUnchecked(i).getObject());
  14399. return ValueTree::invalid;
  14400. }
  14401. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14402. {
  14403. for (int i = 0; i < children.size(); ++i)
  14404. if (children.getUnchecked(i)->type == typeToMatch)
  14405. return ValueTree (children.getUnchecked(i).getObject());
  14406. SharedObject* const newObject = new SharedObject (typeToMatch);
  14407. addChild (newObject, -1, undoManager);
  14408. return ValueTree (newObject);
  14409. }
  14410. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14411. {
  14412. for (int i = 0; i < children.size(); ++i)
  14413. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14414. return ValueTree (children.getUnchecked(i).getObject());
  14415. return ValueTree::invalid;
  14416. }
  14417. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14418. {
  14419. const SharedObject* p = parent;
  14420. while (p != 0)
  14421. {
  14422. if (p == possibleParent)
  14423. return true;
  14424. p = p->parent;
  14425. }
  14426. return false;
  14427. }
  14428. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14429. {
  14430. return children.indexOf (child.object);
  14431. }
  14432. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14433. {
  14434. if (child != 0 && child->parent != this)
  14435. {
  14436. if (child != this && ! isAChildOf (child))
  14437. {
  14438. // You should always make sure that a child is removed from its previous parent before
  14439. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14440. // undomanager should be used when removing it from its current parent..
  14441. jassert (child->parent == 0);
  14442. if (child->parent != 0)
  14443. {
  14444. jassert (child->parent->children.indexOf (child) >= 0);
  14445. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14446. }
  14447. if (undoManager == 0)
  14448. {
  14449. children.insert (index, child);
  14450. child->parent = this;
  14451. sendChildChangeMessage();
  14452. child->sendParentChangeMessage();
  14453. }
  14454. else
  14455. {
  14456. if (index < 0)
  14457. index = children.size();
  14458. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14459. }
  14460. }
  14461. else
  14462. {
  14463. // You're attempting to create a recursive loop! A node
  14464. // can't be a child of one of its own children!
  14465. jassertfalse;
  14466. }
  14467. }
  14468. }
  14469. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14470. {
  14471. const SharedObjectPtr child (children [childIndex]);
  14472. if (child != 0)
  14473. {
  14474. if (undoManager == 0)
  14475. {
  14476. children.remove (childIndex);
  14477. child->parent = 0;
  14478. sendChildChangeMessage();
  14479. child->sendParentChangeMessage();
  14480. }
  14481. else
  14482. {
  14483. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14484. }
  14485. }
  14486. }
  14487. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14488. {
  14489. while (children.size() > 0)
  14490. removeChild (children.size() - 1, undoManager);
  14491. }
  14492. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14493. {
  14494. // The source index must be a valid index!
  14495. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14496. if (currentIndex != newIndex
  14497. && isPositiveAndBelow (currentIndex, children.size()))
  14498. {
  14499. if (undoManager == 0)
  14500. {
  14501. children.move (currentIndex, newIndex);
  14502. sendChildChangeMessage();
  14503. }
  14504. else
  14505. {
  14506. if (! isPositiveAndBelow (newIndex, children.size()))
  14507. newIndex = children.size() - 1;
  14508. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14509. }
  14510. }
  14511. }
  14512. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14513. {
  14514. jassert (newOrder.size() == children.size());
  14515. if (undoManager == 0)
  14516. {
  14517. children = newOrder;
  14518. sendChildChangeMessage();
  14519. }
  14520. else
  14521. {
  14522. for (int i = 0; i < children.size(); ++i)
  14523. {
  14524. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14525. {
  14526. jassert (children.contains (newOrder.getUnchecked(i)));
  14527. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14528. }
  14529. }
  14530. }
  14531. }
  14532. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14533. {
  14534. if (type != other.type
  14535. || properties.size() != other.properties.size()
  14536. || children.size() != other.children.size()
  14537. || properties != other.properties)
  14538. return false;
  14539. for (int i = 0; i < children.size(); ++i)
  14540. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14541. return false;
  14542. return true;
  14543. }
  14544. ValueTree::ValueTree() throw()
  14545. : object (0)
  14546. {
  14547. }
  14548. const ValueTree ValueTree::invalid;
  14549. ValueTree::ValueTree (const Identifier& type_)
  14550. : object (new ValueTree::SharedObject (type_))
  14551. {
  14552. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14553. }
  14554. ValueTree::ValueTree (SharedObject* const object_)
  14555. : object (object_)
  14556. {
  14557. }
  14558. ValueTree::ValueTree (const ValueTree& other)
  14559. : object (other.object)
  14560. {
  14561. }
  14562. ValueTree& ValueTree::operator= (const ValueTree& other)
  14563. {
  14564. if (listeners.size() > 0)
  14565. {
  14566. if (object != 0)
  14567. object->valueTreesWithListeners.removeValue (this);
  14568. if (other.object != 0)
  14569. other.object->valueTreesWithListeners.add (this);
  14570. }
  14571. object = other.object;
  14572. return *this;
  14573. }
  14574. ValueTree::~ValueTree()
  14575. {
  14576. if (listeners.size() > 0 && object != 0)
  14577. object->valueTreesWithListeners.removeValue (this);
  14578. }
  14579. bool ValueTree::operator== (const ValueTree& other) const throw()
  14580. {
  14581. return object == other.object;
  14582. }
  14583. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14584. {
  14585. return object != other.object;
  14586. }
  14587. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14588. {
  14589. return object == other.object
  14590. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14591. }
  14592. ValueTree ValueTree::createCopy() const
  14593. {
  14594. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14595. }
  14596. bool ValueTree::hasType (const Identifier& typeName) const
  14597. {
  14598. return object != 0 && object->type == typeName;
  14599. }
  14600. const Identifier ValueTree::getType() const
  14601. {
  14602. return object != 0 ? object->type : Identifier();
  14603. }
  14604. ValueTree ValueTree::getParent() const
  14605. {
  14606. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14607. }
  14608. ValueTree ValueTree::getSibling (const int delta) const
  14609. {
  14610. if (object == 0 || object->parent == 0)
  14611. return invalid;
  14612. const int index = object->parent->indexOf (*this) + delta;
  14613. return ValueTree (object->parent->children [index].getObject());
  14614. }
  14615. const var& ValueTree::operator[] (const Identifier& name) const
  14616. {
  14617. return object == 0 ? var::null : object->getProperty (name);
  14618. }
  14619. const var& ValueTree::getProperty (const Identifier& name) const
  14620. {
  14621. return object == 0 ? var::null : object->getProperty (name);
  14622. }
  14623. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14624. {
  14625. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14626. }
  14627. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14628. {
  14629. jassert (name.toString().isNotEmpty());
  14630. if (object != 0 && name.toString().isNotEmpty())
  14631. object->setProperty (name, newValue, undoManager);
  14632. }
  14633. bool ValueTree::hasProperty (const Identifier& name) const
  14634. {
  14635. return object != 0 && object->hasProperty (name);
  14636. }
  14637. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14638. {
  14639. if (object != 0)
  14640. object->removeProperty (name, undoManager);
  14641. }
  14642. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14643. {
  14644. if (object != 0)
  14645. object->removeAllProperties (undoManager);
  14646. }
  14647. int ValueTree::getNumProperties() const
  14648. {
  14649. return object == 0 ? 0 : object->properties.size();
  14650. }
  14651. const Identifier ValueTree::getPropertyName (const int index) const
  14652. {
  14653. return object == 0 ? Identifier()
  14654. : object->properties.getName (index);
  14655. }
  14656. class ValueTreePropertyValueSource : public Value::ValueSource,
  14657. public ValueTree::Listener
  14658. {
  14659. public:
  14660. ValueTreePropertyValueSource (const ValueTree& tree_,
  14661. const Identifier& property_,
  14662. UndoManager* const undoManager_)
  14663. : tree (tree_),
  14664. property (property_),
  14665. undoManager (undoManager_)
  14666. {
  14667. tree.addListener (this);
  14668. }
  14669. ~ValueTreePropertyValueSource()
  14670. {
  14671. tree.removeListener (this);
  14672. }
  14673. const var getValue() const
  14674. {
  14675. return tree [property];
  14676. }
  14677. void setValue (const var& newValue)
  14678. {
  14679. tree.setProperty (property, newValue, undoManager);
  14680. }
  14681. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14682. {
  14683. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14684. sendChangeMessage (false);
  14685. }
  14686. void valueTreeChildrenChanged (ValueTree&) {}
  14687. void valueTreeParentChanged (ValueTree&) {}
  14688. private:
  14689. ValueTree tree;
  14690. const Identifier property;
  14691. UndoManager* const undoManager;
  14692. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14693. };
  14694. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14695. {
  14696. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14697. }
  14698. int ValueTree::getNumChildren() const
  14699. {
  14700. return object == 0 ? 0 : object->children.size();
  14701. }
  14702. ValueTree ValueTree::getChild (int index) const
  14703. {
  14704. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14705. }
  14706. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14707. {
  14708. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14709. }
  14710. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14711. {
  14712. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14713. }
  14714. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14715. {
  14716. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14717. }
  14718. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14719. {
  14720. return object != 0 && object->isAChildOf (possibleParent.object);
  14721. }
  14722. int ValueTree::indexOf (const ValueTree& child) const
  14723. {
  14724. return object != 0 ? object->indexOf (child) : -1;
  14725. }
  14726. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14727. {
  14728. if (object != 0)
  14729. object->addChild (child.object, index, undoManager);
  14730. }
  14731. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14732. {
  14733. if (object != 0)
  14734. object->removeChild (childIndex, undoManager);
  14735. }
  14736. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14737. {
  14738. if (object != 0)
  14739. object->removeChild (object->children.indexOf (child.object), undoManager);
  14740. }
  14741. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14742. {
  14743. if (object != 0)
  14744. object->removeAllChildren (undoManager);
  14745. }
  14746. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14747. {
  14748. if (object != 0)
  14749. object->moveChild (currentIndex, newIndex, undoManager);
  14750. }
  14751. void ValueTree::addListener (Listener* listener)
  14752. {
  14753. if (listener != 0)
  14754. {
  14755. if (listeners.size() == 0 && object != 0)
  14756. object->valueTreesWithListeners.add (this);
  14757. listeners.add (listener);
  14758. }
  14759. }
  14760. void ValueTree::removeListener (Listener* listener)
  14761. {
  14762. listeners.remove (listener);
  14763. if (listeners.size() == 0 && object != 0)
  14764. object->valueTreesWithListeners.removeValue (this);
  14765. }
  14766. XmlElement* ValueTree::SharedObject::createXml() const
  14767. {
  14768. XmlElement* const xml = new XmlElement (type.toString());
  14769. properties.copyToXmlAttributes (*xml);
  14770. for (int i = 0; i < children.size(); ++i)
  14771. xml->addChildElement (children.getUnchecked(i)->createXml());
  14772. return xml;
  14773. }
  14774. XmlElement* ValueTree::createXml() const
  14775. {
  14776. return object != 0 ? object->createXml() : 0;
  14777. }
  14778. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14779. {
  14780. ValueTree v (xml.getTagName());
  14781. v.object->properties.setFromXmlAttributes (xml);
  14782. forEachXmlChildElement (xml, e)
  14783. v.addChild (fromXml (*e), -1, 0);
  14784. return v;
  14785. }
  14786. void ValueTree::writeToStream (OutputStream& output)
  14787. {
  14788. output.writeString (getType().toString());
  14789. const int numProps = getNumProperties();
  14790. output.writeCompressedInt (numProps);
  14791. int i;
  14792. for (i = 0; i < numProps; ++i)
  14793. {
  14794. const Identifier name (getPropertyName(i));
  14795. output.writeString (name.toString());
  14796. getProperty(name).writeToStream (output);
  14797. }
  14798. const int numChildren = getNumChildren();
  14799. output.writeCompressedInt (numChildren);
  14800. for (i = 0; i < numChildren; ++i)
  14801. getChild (i).writeToStream (output);
  14802. }
  14803. ValueTree ValueTree::readFromStream (InputStream& input)
  14804. {
  14805. const String type (input.readString());
  14806. if (type.isEmpty())
  14807. return ValueTree::invalid;
  14808. ValueTree v (type);
  14809. const int numProps = input.readCompressedInt();
  14810. if (numProps < 0)
  14811. {
  14812. jassertfalse; // trying to read corrupted data!
  14813. return v;
  14814. }
  14815. int i;
  14816. for (i = 0; i < numProps; ++i)
  14817. {
  14818. const String name (input.readString());
  14819. jassert (name.isNotEmpty());
  14820. const var value (var::readFromStream (input));
  14821. v.object->properties.set (name, value);
  14822. }
  14823. const int numChildren = input.readCompressedInt();
  14824. for (i = 0; i < numChildren; ++i)
  14825. {
  14826. ValueTree child (readFromStream (input));
  14827. v.object->children.add (child.object);
  14828. child.object->parent = v.object;
  14829. }
  14830. return v;
  14831. }
  14832. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14833. {
  14834. MemoryInputStream in (data, numBytes, false);
  14835. return readFromStream (in);
  14836. }
  14837. END_JUCE_NAMESPACE
  14838. /*** End of inlined file: juce_ValueTree.cpp ***/
  14839. /*** Start of inlined file: juce_Value.cpp ***/
  14840. BEGIN_JUCE_NAMESPACE
  14841. Value::ValueSource::ValueSource()
  14842. {
  14843. }
  14844. Value::ValueSource::~ValueSource()
  14845. {
  14846. }
  14847. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14848. {
  14849. if (synchronous)
  14850. {
  14851. for (int i = valuesWithListeners.size(); --i >= 0;)
  14852. {
  14853. Value* const v = valuesWithListeners[i];
  14854. if (v != 0)
  14855. v->callListeners();
  14856. }
  14857. }
  14858. else
  14859. {
  14860. triggerAsyncUpdate();
  14861. }
  14862. }
  14863. void Value::ValueSource::handleAsyncUpdate()
  14864. {
  14865. sendChangeMessage (true);
  14866. }
  14867. class SimpleValueSource : public Value::ValueSource
  14868. {
  14869. public:
  14870. SimpleValueSource()
  14871. {
  14872. }
  14873. SimpleValueSource (const var& initialValue)
  14874. : value (initialValue)
  14875. {
  14876. }
  14877. ~SimpleValueSource()
  14878. {
  14879. }
  14880. const var getValue() const
  14881. {
  14882. return value;
  14883. }
  14884. void setValue (const var& newValue)
  14885. {
  14886. if (newValue != value)
  14887. {
  14888. value = newValue;
  14889. sendChangeMessage (false);
  14890. }
  14891. }
  14892. private:
  14893. var value;
  14894. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14895. };
  14896. Value::Value()
  14897. : value (new SimpleValueSource())
  14898. {
  14899. }
  14900. Value::Value (ValueSource* const value_)
  14901. : value (value_)
  14902. {
  14903. jassert (value_ != 0);
  14904. }
  14905. Value::Value (const var& initialValue)
  14906. : value (new SimpleValueSource (initialValue))
  14907. {
  14908. }
  14909. Value::Value (const Value& other)
  14910. : value (other.value)
  14911. {
  14912. }
  14913. Value& Value::operator= (const Value& other)
  14914. {
  14915. value = other.value;
  14916. return *this;
  14917. }
  14918. Value::~Value()
  14919. {
  14920. if (listeners.size() > 0)
  14921. value->valuesWithListeners.removeValue (this);
  14922. }
  14923. const var Value::getValue() const
  14924. {
  14925. return value->getValue();
  14926. }
  14927. Value::operator const var() const
  14928. {
  14929. return getValue();
  14930. }
  14931. void Value::setValue (const var& newValue)
  14932. {
  14933. value->setValue (newValue);
  14934. }
  14935. const String Value::toString() const
  14936. {
  14937. return value->getValue().toString();
  14938. }
  14939. Value& Value::operator= (const var& newValue)
  14940. {
  14941. value->setValue (newValue);
  14942. return *this;
  14943. }
  14944. void Value::referTo (const Value& valueToReferTo)
  14945. {
  14946. if (valueToReferTo.value != value)
  14947. {
  14948. if (listeners.size() > 0)
  14949. {
  14950. value->valuesWithListeners.removeValue (this);
  14951. valueToReferTo.value->valuesWithListeners.add (this);
  14952. }
  14953. value = valueToReferTo.value;
  14954. callListeners();
  14955. }
  14956. }
  14957. bool Value::refersToSameSourceAs (const Value& other) const
  14958. {
  14959. return value == other.value;
  14960. }
  14961. bool Value::operator== (const Value& other) const
  14962. {
  14963. return value == other.value || value->getValue() == other.getValue();
  14964. }
  14965. bool Value::operator!= (const Value& other) const
  14966. {
  14967. return value != other.value && value->getValue() != other.getValue();
  14968. }
  14969. void Value::addListener (ValueListener* const listener)
  14970. {
  14971. if (listener != 0)
  14972. {
  14973. if (listeners.size() == 0)
  14974. value->valuesWithListeners.add (this);
  14975. listeners.add (listener);
  14976. }
  14977. }
  14978. void Value::removeListener (ValueListener* const listener)
  14979. {
  14980. listeners.remove (listener);
  14981. if (listeners.size() == 0)
  14982. value->valuesWithListeners.removeValue (this);
  14983. }
  14984. void Value::callListeners()
  14985. {
  14986. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14987. listeners.call (&ValueListener::valueChanged, v);
  14988. }
  14989. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14990. {
  14991. return stream << value.toString();
  14992. }
  14993. END_JUCE_NAMESPACE
  14994. /*** End of inlined file: juce_Value.cpp ***/
  14995. /*** Start of inlined file: juce_Application.cpp ***/
  14996. BEGIN_JUCE_NAMESPACE
  14997. #if JUCE_MAC
  14998. extern void juce_initialiseMacMainMenu();
  14999. #endif
  15000. JUCEApplication::JUCEApplication()
  15001. : appReturnValue (0),
  15002. stillInitialising (true)
  15003. {
  15004. jassert (isStandaloneApp() && appInstance == 0);
  15005. appInstance = this;
  15006. }
  15007. JUCEApplication::~JUCEApplication()
  15008. {
  15009. if (appLock != 0)
  15010. {
  15011. appLock->exit();
  15012. appLock = 0;
  15013. }
  15014. jassert (appInstance == this);
  15015. appInstance = 0;
  15016. }
  15017. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15018. JUCEApplication* JUCEApplication::appInstance = 0;
  15019. bool JUCEApplication::moreThanOneInstanceAllowed()
  15020. {
  15021. return true;
  15022. }
  15023. void JUCEApplication::anotherInstanceStarted (const String&)
  15024. {
  15025. }
  15026. void JUCEApplication::systemRequestedQuit()
  15027. {
  15028. quit();
  15029. }
  15030. void JUCEApplication::quit()
  15031. {
  15032. MessageManager::getInstance()->stopDispatchLoop();
  15033. }
  15034. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15035. {
  15036. appReturnValue = newReturnValue;
  15037. }
  15038. void JUCEApplication::actionListenerCallback (const String& message)
  15039. {
  15040. if (message.startsWith (getApplicationName() + "/"))
  15041. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15042. }
  15043. void JUCEApplication::unhandledException (const std::exception*,
  15044. const String&,
  15045. const int)
  15046. {
  15047. jassertfalse;
  15048. }
  15049. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15050. const char* const sourceFile,
  15051. const int lineNumber)
  15052. {
  15053. if (appInstance != 0)
  15054. appInstance->unhandledException (e, sourceFile, lineNumber);
  15055. }
  15056. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15057. {
  15058. return 0;
  15059. }
  15060. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15061. {
  15062. commands.add (StandardApplicationCommandIDs::quit);
  15063. }
  15064. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15065. {
  15066. if (commandID == StandardApplicationCommandIDs::quit)
  15067. {
  15068. result.setInfo (TRANS("Quit"),
  15069. TRANS("Quits the application"),
  15070. "Application",
  15071. 0);
  15072. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15073. }
  15074. }
  15075. bool JUCEApplication::perform (const InvocationInfo& info)
  15076. {
  15077. if (info.commandID == StandardApplicationCommandIDs::quit)
  15078. {
  15079. systemRequestedQuit();
  15080. return true;
  15081. }
  15082. return false;
  15083. }
  15084. bool JUCEApplication::initialiseApp (const String& commandLine)
  15085. {
  15086. commandLineParameters = commandLine.trim();
  15087. #if ! JUCE_IOS
  15088. jassert (appLock == 0); // initialiseApp must only be called once!
  15089. if (! moreThanOneInstanceAllowed())
  15090. {
  15091. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15092. if (! appLock->enter(0))
  15093. {
  15094. appLock = 0;
  15095. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15096. DBG ("Another instance is running - quitting...");
  15097. return false;
  15098. }
  15099. }
  15100. #endif
  15101. // let the app do its setting-up..
  15102. initialise (commandLineParameters);
  15103. #if JUCE_MAC
  15104. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15105. #endif
  15106. // register for broadcast new app messages
  15107. MessageManager::getInstance()->registerBroadcastListener (this);
  15108. stillInitialising = false;
  15109. return true;
  15110. }
  15111. int JUCEApplication::shutdownApp()
  15112. {
  15113. jassert (appInstance == this);
  15114. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15115. JUCE_TRY
  15116. {
  15117. // give the app a chance to clean up..
  15118. shutdown();
  15119. }
  15120. JUCE_CATCH_EXCEPTION
  15121. return getApplicationReturnValue();
  15122. }
  15123. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15124. void JUCEApplication::appWillTerminateByForce()
  15125. {
  15126. {
  15127. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15128. if (app != 0)
  15129. app->shutdownApp();
  15130. }
  15131. shutdownJuce_GUI();
  15132. }
  15133. int JUCEApplication::main (const String& commandLine)
  15134. {
  15135. ScopedJuceInitialiser_GUI libraryInitialiser;
  15136. jassert (createInstance != 0);
  15137. int returnCode = 0;
  15138. {
  15139. const ScopedPointer<JUCEApplication> app (createInstance());
  15140. if (! app->initialiseApp (commandLine))
  15141. return 0;
  15142. JUCE_TRY
  15143. {
  15144. // loop until a quit message is received..
  15145. MessageManager::getInstance()->runDispatchLoop();
  15146. }
  15147. JUCE_CATCH_EXCEPTION
  15148. returnCode = app->shutdownApp();
  15149. }
  15150. return returnCode;
  15151. }
  15152. #if JUCE_IOS
  15153. extern int juce_iOSMain (int argc, const char* argv[]);
  15154. #endif
  15155. #if ! JUCE_WINDOWS
  15156. extern const char* juce_Argv0;
  15157. #endif
  15158. int JUCEApplication::main (int argc, const char* argv[])
  15159. {
  15160. JUCE_AUTORELEASEPOOL
  15161. #if ! JUCE_WINDOWS
  15162. jassert (createInstance != 0);
  15163. juce_Argv0 = argv[0];
  15164. #endif
  15165. #if JUCE_IOS
  15166. return juce_iOSMain (argc, argv);
  15167. #else
  15168. String cmd;
  15169. for (int i = 1; i < argc; ++i)
  15170. cmd << argv[i] << ' ';
  15171. return JUCEApplication::main (cmd);
  15172. #endif
  15173. }
  15174. END_JUCE_NAMESPACE
  15175. /*** End of inlined file: juce_Application.cpp ***/
  15176. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15177. BEGIN_JUCE_NAMESPACE
  15178. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15179. : commandID (commandID_),
  15180. flags (0)
  15181. {
  15182. }
  15183. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15184. const String& description_,
  15185. const String& categoryName_,
  15186. const int flags_) throw()
  15187. {
  15188. shortName = shortName_;
  15189. description = description_;
  15190. categoryName = categoryName_;
  15191. flags = flags_;
  15192. }
  15193. void ApplicationCommandInfo::setActive (const bool b) throw()
  15194. {
  15195. if (b)
  15196. flags &= ~isDisabled;
  15197. else
  15198. flags |= isDisabled;
  15199. }
  15200. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15201. {
  15202. if (b)
  15203. flags |= isTicked;
  15204. else
  15205. flags &= ~isTicked;
  15206. }
  15207. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15208. {
  15209. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15210. }
  15211. END_JUCE_NAMESPACE
  15212. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15213. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15214. BEGIN_JUCE_NAMESPACE
  15215. ApplicationCommandManager::ApplicationCommandManager()
  15216. : firstTarget (0)
  15217. {
  15218. keyMappings = new KeyPressMappingSet (this);
  15219. Desktop::getInstance().addFocusChangeListener (this);
  15220. }
  15221. ApplicationCommandManager::~ApplicationCommandManager()
  15222. {
  15223. Desktop::getInstance().removeFocusChangeListener (this);
  15224. keyMappings = 0;
  15225. }
  15226. void ApplicationCommandManager::clearCommands()
  15227. {
  15228. commands.clear();
  15229. keyMappings->clearAllKeyPresses();
  15230. triggerAsyncUpdate();
  15231. }
  15232. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15233. {
  15234. // zero isn't a valid command ID!
  15235. jassert (newCommand.commandID != 0);
  15236. // the name isn't optional!
  15237. jassert (newCommand.shortName.isNotEmpty());
  15238. if (getCommandForID (newCommand.commandID) == 0)
  15239. {
  15240. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15241. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15242. commands.add (newInfo);
  15243. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15244. triggerAsyncUpdate();
  15245. }
  15246. else
  15247. {
  15248. // trying to re-register the same command with different parameters?
  15249. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15250. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15251. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15252. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15253. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15254. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15255. }
  15256. }
  15257. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15258. {
  15259. if (target != 0)
  15260. {
  15261. Array <CommandID> commandIDs;
  15262. target->getAllCommands (commandIDs);
  15263. for (int i = 0; i < commandIDs.size(); ++i)
  15264. {
  15265. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15266. target->getCommandInfo (info.commandID, info);
  15267. registerCommand (info);
  15268. }
  15269. }
  15270. }
  15271. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15272. {
  15273. for (int i = commands.size(); --i >= 0;)
  15274. {
  15275. if (commands.getUnchecked (i)->commandID == commandID)
  15276. {
  15277. commands.remove (i);
  15278. triggerAsyncUpdate();
  15279. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15280. for (int j = keys.size(); --j >= 0;)
  15281. keyMappings->removeKeyPress (keys.getReference (j));
  15282. }
  15283. }
  15284. }
  15285. void ApplicationCommandManager::commandStatusChanged()
  15286. {
  15287. triggerAsyncUpdate();
  15288. }
  15289. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15290. {
  15291. for (int i = commands.size(); --i >= 0;)
  15292. if (commands.getUnchecked(i)->commandID == commandID)
  15293. return commands.getUnchecked(i);
  15294. return 0;
  15295. }
  15296. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15297. {
  15298. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15299. return (ci != 0) ? ci->shortName : String::empty;
  15300. }
  15301. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15302. {
  15303. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15304. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15305. : String::empty;
  15306. }
  15307. const StringArray ApplicationCommandManager::getCommandCategories() const
  15308. {
  15309. StringArray s;
  15310. for (int i = 0; i < commands.size(); ++i)
  15311. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15312. return s;
  15313. }
  15314. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15315. {
  15316. Array <CommandID> results;
  15317. for (int i = 0; i < commands.size(); ++i)
  15318. if (commands.getUnchecked(i)->categoryName == categoryName)
  15319. results.add (commands.getUnchecked(i)->commandID);
  15320. return results;
  15321. }
  15322. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15323. {
  15324. ApplicationCommandTarget::InvocationInfo info (commandID);
  15325. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15326. return invoke (info, asynchronously);
  15327. }
  15328. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15329. {
  15330. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15331. // manager first..
  15332. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15333. ApplicationCommandInfo commandInfo (0);
  15334. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15335. if (target == 0)
  15336. return false;
  15337. ApplicationCommandTarget::InvocationInfo info (info_);
  15338. info.commandFlags = commandInfo.flags;
  15339. sendListenerInvokeCallback (info);
  15340. const bool ok = target->invoke (info, asynchronously);
  15341. commandStatusChanged();
  15342. return ok;
  15343. }
  15344. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15345. {
  15346. return firstTarget != 0 ? firstTarget
  15347. : findDefaultComponentTarget();
  15348. }
  15349. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15350. {
  15351. firstTarget = newTarget;
  15352. }
  15353. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15354. ApplicationCommandInfo& upToDateInfo)
  15355. {
  15356. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15357. if (target == 0)
  15358. target = JUCEApplication::getInstance();
  15359. if (target != 0)
  15360. target = target->getTargetForCommand (commandID);
  15361. if (target != 0)
  15362. target->getCommandInfo (commandID, upToDateInfo);
  15363. return target;
  15364. }
  15365. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15366. {
  15367. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15368. if (target == 0 && c != 0)
  15369. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15370. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15371. return target;
  15372. }
  15373. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15374. {
  15375. Component* c = Component::getCurrentlyFocusedComponent();
  15376. if (c == 0)
  15377. {
  15378. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15379. if (activeWindow != 0)
  15380. {
  15381. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15382. if (c == 0)
  15383. c = activeWindow;
  15384. }
  15385. }
  15386. if (c == 0 && Process::isForegroundProcess())
  15387. {
  15388. // getting a bit desperate now - try all desktop comps..
  15389. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15390. {
  15391. ApplicationCommandTarget* const target
  15392. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15393. ->getPeer()->getLastFocusedSubcomponent());
  15394. if (target != 0)
  15395. return target;
  15396. }
  15397. }
  15398. if (c != 0)
  15399. {
  15400. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15401. // if we're focused on a ResizableWindow, chances are that it's the content
  15402. // component that really should get the event. And if not, the event will
  15403. // still be passed up to the top level window anyway, so let's send it to the
  15404. // content comp.
  15405. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15406. c = resizableWindow->getContentComponent();
  15407. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15408. if (target != 0)
  15409. return target;
  15410. }
  15411. return JUCEApplication::getInstance();
  15412. }
  15413. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15414. {
  15415. listeners.add (listener);
  15416. }
  15417. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15418. {
  15419. listeners.remove (listener);
  15420. }
  15421. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15422. {
  15423. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15424. }
  15425. void ApplicationCommandManager::handleAsyncUpdate()
  15426. {
  15427. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15428. }
  15429. void ApplicationCommandManager::globalFocusChanged (Component*)
  15430. {
  15431. commandStatusChanged();
  15432. }
  15433. END_JUCE_NAMESPACE
  15434. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15435. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15436. BEGIN_JUCE_NAMESPACE
  15437. ApplicationCommandTarget::ApplicationCommandTarget()
  15438. {
  15439. }
  15440. ApplicationCommandTarget::~ApplicationCommandTarget()
  15441. {
  15442. messageInvoker = 0;
  15443. }
  15444. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15445. {
  15446. if (isCommandActive (info.commandID))
  15447. {
  15448. if (async)
  15449. {
  15450. if (messageInvoker == 0)
  15451. messageInvoker = new CommandTargetMessageInvoker (this);
  15452. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15453. return true;
  15454. }
  15455. else
  15456. {
  15457. const bool success = perform (info);
  15458. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15459. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15460. // returns the command's info.
  15461. return success;
  15462. }
  15463. }
  15464. return false;
  15465. }
  15466. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15467. {
  15468. Component* c = dynamic_cast <Component*> (this);
  15469. if (c != 0)
  15470. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15471. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15472. return 0;
  15473. }
  15474. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15475. {
  15476. ApplicationCommandTarget* target = this;
  15477. int depth = 0;
  15478. while (target != 0)
  15479. {
  15480. Array <CommandID> commandIDs;
  15481. target->getAllCommands (commandIDs);
  15482. if (commandIDs.contains (commandID))
  15483. return target;
  15484. target = target->getNextCommandTarget();
  15485. ++depth;
  15486. jassert (depth < 100); // could be a recursive command chain??
  15487. jassert (target != this); // definitely a recursive command chain!
  15488. if (depth > 100 || target == this)
  15489. break;
  15490. }
  15491. if (target == 0)
  15492. {
  15493. target = JUCEApplication::getInstance();
  15494. if (target != 0)
  15495. {
  15496. Array <CommandID> commandIDs;
  15497. target->getAllCommands (commandIDs);
  15498. if (commandIDs.contains (commandID))
  15499. return target;
  15500. }
  15501. }
  15502. return 0;
  15503. }
  15504. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15505. {
  15506. ApplicationCommandInfo info (commandID);
  15507. info.flags = ApplicationCommandInfo::isDisabled;
  15508. getCommandInfo (commandID, info);
  15509. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15510. }
  15511. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15512. {
  15513. ApplicationCommandTarget* target = this;
  15514. int depth = 0;
  15515. while (target != 0)
  15516. {
  15517. if (target->tryToInvoke (info, async))
  15518. return true;
  15519. target = target->getNextCommandTarget();
  15520. ++depth;
  15521. jassert (depth < 100); // could be a recursive command chain??
  15522. jassert (target != this); // definitely a recursive command chain!
  15523. if (depth > 100 || target == this)
  15524. break;
  15525. }
  15526. if (target == 0)
  15527. {
  15528. target = JUCEApplication::getInstance();
  15529. if (target != 0)
  15530. return target->tryToInvoke (info, async);
  15531. }
  15532. return false;
  15533. }
  15534. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15535. {
  15536. ApplicationCommandTarget::InvocationInfo info (commandID);
  15537. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15538. return invoke (info, asynchronously);
  15539. }
  15540. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15541. : commandID (commandID_),
  15542. commandFlags (0),
  15543. invocationMethod (direct),
  15544. originatingComponent (0),
  15545. isKeyDown (false),
  15546. millisecsSinceKeyPressed (0)
  15547. {
  15548. }
  15549. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15550. : owner (owner_)
  15551. {
  15552. }
  15553. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15554. {
  15555. }
  15556. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15557. {
  15558. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15559. owner->tryToInvoke (*info, false);
  15560. }
  15561. END_JUCE_NAMESPACE
  15562. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15563. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15564. BEGIN_JUCE_NAMESPACE
  15565. juce_ImplementSingleton (ApplicationProperties)
  15566. ApplicationProperties::ApplicationProperties()
  15567. : msBeforeSaving (3000),
  15568. options (PropertiesFile::storeAsBinary),
  15569. commonSettingsAreReadOnly (0),
  15570. processLock (0)
  15571. {
  15572. }
  15573. ApplicationProperties::~ApplicationProperties()
  15574. {
  15575. closeFiles();
  15576. clearSingletonInstance();
  15577. }
  15578. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15579. const String& fileNameSuffix,
  15580. const String& folderName_,
  15581. const int millisecondsBeforeSaving,
  15582. const int propertiesFileOptions,
  15583. InterProcessLock* processLock_)
  15584. {
  15585. appName = applicationName;
  15586. fileSuffix = fileNameSuffix;
  15587. folderName = folderName_;
  15588. msBeforeSaving = millisecondsBeforeSaving;
  15589. options = propertiesFileOptions;
  15590. processLock = processLock_;
  15591. }
  15592. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15593. const bool testCommonSettings,
  15594. const bool showWarningDialogOnFailure)
  15595. {
  15596. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15597. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15598. if (! (userOk && commonOk))
  15599. {
  15600. if (showWarningDialogOnFailure)
  15601. {
  15602. String filenames;
  15603. if (userProps != 0 && ! userOk)
  15604. filenames << '\n' << userProps->getFile().getFullPathName();
  15605. if (commonProps != 0 && ! commonOk)
  15606. filenames << '\n' << commonProps->getFile().getFullPathName();
  15607. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15608. appName + TRANS(" - Unable to save settings"),
  15609. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15610. + appName + TRANS(" needs to be able to write to the following files:\n")
  15611. + filenames
  15612. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15613. }
  15614. return false;
  15615. }
  15616. return true;
  15617. }
  15618. void ApplicationProperties::openFiles()
  15619. {
  15620. // You need to call setStorageParameters() before trying to get hold of the
  15621. // properties!
  15622. jassert (appName.isNotEmpty());
  15623. if (appName.isNotEmpty())
  15624. {
  15625. if (userProps == 0)
  15626. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15627. false, msBeforeSaving, options, processLock);
  15628. if (commonProps == 0)
  15629. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15630. true, msBeforeSaving, options, processLock);
  15631. userProps->setFallbackPropertySet (commonProps);
  15632. }
  15633. }
  15634. PropertiesFile* ApplicationProperties::getUserSettings()
  15635. {
  15636. if (userProps == 0)
  15637. openFiles();
  15638. return userProps;
  15639. }
  15640. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15641. {
  15642. if (commonProps == 0)
  15643. openFiles();
  15644. if (returnUserPropsIfReadOnly)
  15645. {
  15646. if (commonSettingsAreReadOnly == 0)
  15647. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15648. if (commonSettingsAreReadOnly > 0)
  15649. return userProps;
  15650. }
  15651. return commonProps;
  15652. }
  15653. bool ApplicationProperties::saveIfNeeded()
  15654. {
  15655. return (userProps == 0 || userProps->saveIfNeeded())
  15656. && (commonProps == 0 || commonProps->saveIfNeeded());
  15657. }
  15658. void ApplicationProperties::closeFiles()
  15659. {
  15660. userProps = 0;
  15661. commonProps = 0;
  15662. }
  15663. END_JUCE_NAMESPACE
  15664. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15665. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15666. BEGIN_JUCE_NAMESPACE
  15667. namespace PropertyFileConstants
  15668. {
  15669. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15670. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15671. static const char* const fileTag = "PROPERTIES";
  15672. static const char* const valueTag = "VALUE";
  15673. static const char* const nameAttribute = "name";
  15674. static const char* const valueAttribute = "val";
  15675. }
  15676. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15677. const int options_, InterProcessLock* const processLock_)
  15678. : PropertySet (ignoreCaseOfKeyNames),
  15679. file (f),
  15680. timerInterval (millisecondsBeforeSaving),
  15681. options (options_),
  15682. loadedOk (false),
  15683. needsWriting (false),
  15684. processLock (processLock_)
  15685. {
  15686. // You need to correctly specify just one storage format for the file
  15687. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15688. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15689. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15690. ProcessScopedLock pl (createProcessLock());
  15691. if (pl != 0 && ! pl->isLocked())
  15692. return; // locking failure..
  15693. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15694. if (fileStream != 0)
  15695. {
  15696. int magicNumber = fileStream->readInt();
  15697. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15698. {
  15699. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15700. magicNumber = PropertyFileConstants::magicNumber;
  15701. }
  15702. if (magicNumber == PropertyFileConstants::magicNumber)
  15703. {
  15704. loadedOk = true;
  15705. BufferedInputStream in (fileStream.release(), 2048, true);
  15706. int numValues = in.readInt();
  15707. while (--numValues >= 0 && ! in.isExhausted())
  15708. {
  15709. const String key (in.readString());
  15710. const String value (in.readString());
  15711. jassert (key.isNotEmpty());
  15712. if (key.isNotEmpty())
  15713. getAllProperties().set (key, value);
  15714. }
  15715. }
  15716. else
  15717. {
  15718. // Not a binary props file - let's see if it's XML..
  15719. fileStream = 0;
  15720. XmlDocument parser (f);
  15721. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15722. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15723. {
  15724. doc = parser.getDocumentElement();
  15725. if (doc != 0)
  15726. {
  15727. loadedOk = true;
  15728. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15729. {
  15730. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15731. if (name.isNotEmpty())
  15732. {
  15733. getAllProperties().set (name,
  15734. e->getFirstChildElement() != 0
  15735. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15736. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15737. }
  15738. }
  15739. }
  15740. else
  15741. {
  15742. // must be a pretty broken XML file we're trying to parse here,
  15743. // or a sign that this object needs an InterProcessLock,
  15744. // or just a failure reading the file. This last reason is why
  15745. // we don't jassertfalse here.
  15746. }
  15747. }
  15748. }
  15749. }
  15750. else
  15751. {
  15752. loadedOk = ! f.exists();
  15753. }
  15754. }
  15755. PropertiesFile::~PropertiesFile()
  15756. {
  15757. if (! saveIfNeeded())
  15758. jassertfalse;
  15759. }
  15760. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15761. {
  15762. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15763. }
  15764. bool PropertiesFile::saveIfNeeded()
  15765. {
  15766. const ScopedLock sl (getLock());
  15767. return (! needsWriting) || save();
  15768. }
  15769. bool PropertiesFile::needsToBeSaved() const
  15770. {
  15771. const ScopedLock sl (getLock());
  15772. return needsWriting;
  15773. }
  15774. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15775. {
  15776. const ScopedLock sl (getLock());
  15777. needsWriting = needsToBeSaved_;
  15778. }
  15779. bool PropertiesFile::save()
  15780. {
  15781. const ScopedLock sl (getLock());
  15782. stopTimer();
  15783. if (file == File::nonexistent
  15784. || file.isDirectory()
  15785. || ! file.getParentDirectory().createDirectory())
  15786. return false;
  15787. if ((options & storeAsXML) != 0)
  15788. {
  15789. XmlElement doc (PropertyFileConstants::fileTag);
  15790. for (int i = 0; i < getAllProperties().size(); ++i)
  15791. {
  15792. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15793. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15794. // if the value seems to contain xml, store it as such..
  15795. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15796. if (childElement != 0)
  15797. e->addChildElement (childElement);
  15798. else
  15799. e->setAttribute (PropertyFileConstants::valueAttribute,
  15800. getAllProperties().getAllValues() [i]);
  15801. }
  15802. ProcessScopedLock pl (createProcessLock());
  15803. if (pl != 0 && ! pl->isLocked())
  15804. return false; // locking failure..
  15805. if (doc.writeToFile (file, String::empty))
  15806. {
  15807. needsWriting = false;
  15808. return true;
  15809. }
  15810. }
  15811. else
  15812. {
  15813. ProcessScopedLock pl (createProcessLock());
  15814. if (pl != 0 && ! pl->isLocked())
  15815. return false; // locking failure..
  15816. TemporaryFile tempFile (file);
  15817. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15818. if (out != 0)
  15819. {
  15820. if ((options & storeAsCompressedBinary) != 0)
  15821. {
  15822. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15823. out->flush();
  15824. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15825. }
  15826. else
  15827. {
  15828. // have you set up the storage option flags correctly?
  15829. jassert ((options & storeAsBinary) != 0);
  15830. out->writeInt (PropertyFileConstants::magicNumber);
  15831. }
  15832. const int numProperties = getAllProperties().size();
  15833. out->writeInt (numProperties);
  15834. for (int i = 0; i < numProperties; ++i)
  15835. {
  15836. out->writeString (getAllProperties().getAllKeys() [i]);
  15837. out->writeString (getAllProperties().getAllValues() [i]);
  15838. }
  15839. out = 0;
  15840. if (tempFile.overwriteTargetFileWithTemporary())
  15841. {
  15842. needsWriting = false;
  15843. return true;
  15844. }
  15845. }
  15846. }
  15847. return false;
  15848. }
  15849. void PropertiesFile::timerCallback()
  15850. {
  15851. saveIfNeeded();
  15852. }
  15853. void PropertiesFile::propertyChanged()
  15854. {
  15855. sendChangeMessage();
  15856. needsWriting = true;
  15857. if (timerInterval > 0)
  15858. startTimer (timerInterval);
  15859. else if (timerInterval == 0)
  15860. saveIfNeeded();
  15861. }
  15862. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15863. const String& fileNameSuffix,
  15864. const String& folderName,
  15865. const bool commonToAllUsers)
  15866. {
  15867. // mustn't have illegal characters in this name..
  15868. jassert (applicationName == File::createLegalFileName (applicationName));
  15869. #if JUCE_MAC || JUCE_IOS
  15870. File dir (commonToAllUsers ? "/Library/Preferences"
  15871. : "~/Library/Preferences");
  15872. if (folderName.isNotEmpty())
  15873. dir = dir.getChildFile (folderName);
  15874. #endif
  15875. #ifdef JUCE_LINUX
  15876. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15877. + (folderName.isNotEmpty() ? folderName
  15878. : ("." + applicationName)));
  15879. #endif
  15880. #if JUCE_WINDOWS
  15881. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15882. : File::userApplicationDataDirectory));
  15883. if (dir == File::nonexistent)
  15884. return File::nonexistent;
  15885. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15886. : applicationName);
  15887. #endif
  15888. return dir.getChildFile (applicationName)
  15889. .withFileExtension (fileNameSuffix);
  15890. }
  15891. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15892. const String& fileNameSuffix,
  15893. const String& folderName,
  15894. const bool commonToAllUsers,
  15895. const int millisecondsBeforeSaving,
  15896. const int propertiesFileOptions,
  15897. InterProcessLock* processLock_)
  15898. {
  15899. const File file (getDefaultAppSettingsFile (applicationName,
  15900. fileNameSuffix,
  15901. folderName,
  15902. commonToAllUsers));
  15903. jassert (file != File::nonexistent);
  15904. if (file == File::nonexistent)
  15905. return 0;
  15906. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15907. }
  15908. END_JUCE_NAMESPACE
  15909. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15910. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15911. BEGIN_JUCE_NAMESPACE
  15912. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15913. const String& fileWildcard_,
  15914. const String& openFileDialogTitle_,
  15915. const String& saveFileDialogTitle_)
  15916. : changedSinceSave (false),
  15917. fileExtension (fileExtension_),
  15918. fileWildcard (fileWildcard_),
  15919. openFileDialogTitle (openFileDialogTitle_),
  15920. saveFileDialogTitle (saveFileDialogTitle_)
  15921. {
  15922. }
  15923. FileBasedDocument::~FileBasedDocument()
  15924. {
  15925. }
  15926. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15927. {
  15928. if (changedSinceSave != hasChanged)
  15929. {
  15930. changedSinceSave = hasChanged;
  15931. sendChangeMessage();
  15932. }
  15933. }
  15934. void FileBasedDocument::changed()
  15935. {
  15936. changedSinceSave = true;
  15937. sendChangeMessage();
  15938. }
  15939. void FileBasedDocument::setFile (const File& newFile)
  15940. {
  15941. if (documentFile != newFile)
  15942. {
  15943. documentFile = newFile;
  15944. changed();
  15945. }
  15946. }
  15947. bool FileBasedDocument::loadFrom (const File& newFile,
  15948. const bool showMessageOnFailure)
  15949. {
  15950. MouseCursor::showWaitCursor();
  15951. const File oldFile (documentFile);
  15952. documentFile = newFile;
  15953. String error;
  15954. if (newFile.existsAsFile())
  15955. {
  15956. error = loadDocument (newFile);
  15957. if (error.isEmpty())
  15958. {
  15959. setChangedFlag (false);
  15960. MouseCursor::hideWaitCursor();
  15961. setLastDocumentOpened (newFile);
  15962. return true;
  15963. }
  15964. }
  15965. else
  15966. {
  15967. error = "The file doesn't exist";
  15968. }
  15969. documentFile = oldFile;
  15970. MouseCursor::hideWaitCursor();
  15971. if (showMessageOnFailure)
  15972. {
  15973. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15974. TRANS("Failed to open file..."),
  15975. TRANS("There was an error while trying to load the file:\n\n")
  15976. + newFile.getFullPathName()
  15977. + "\n\n"
  15978. + error);
  15979. }
  15980. return false;
  15981. }
  15982. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15983. {
  15984. FileChooser fc (openFileDialogTitle,
  15985. getLastDocumentOpened(),
  15986. fileWildcard);
  15987. if (fc.browseForFileToOpen())
  15988. return loadFrom (fc.getResult(), showMessageOnFailure);
  15989. return false;
  15990. }
  15991. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15992. const bool showMessageOnFailure)
  15993. {
  15994. return saveAs (documentFile,
  15995. false,
  15996. askUserForFileIfNotSpecified,
  15997. showMessageOnFailure);
  15998. }
  15999. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16000. const bool warnAboutOverwritingExistingFiles,
  16001. const bool askUserForFileIfNotSpecified,
  16002. const bool showMessageOnFailure)
  16003. {
  16004. if (newFile == File::nonexistent)
  16005. {
  16006. if (askUserForFileIfNotSpecified)
  16007. {
  16008. return saveAsInteractive (true);
  16009. }
  16010. else
  16011. {
  16012. // can't save to an unspecified file
  16013. jassertfalse;
  16014. return failedToWriteToFile;
  16015. }
  16016. }
  16017. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16018. {
  16019. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16020. TRANS("File already exists"),
  16021. TRANS("There's already a file called:\n\n")
  16022. + newFile.getFullPathName()
  16023. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16024. TRANS("overwrite"),
  16025. TRANS("cancel")))
  16026. {
  16027. return userCancelledSave;
  16028. }
  16029. }
  16030. MouseCursor::showWaitCursor();
  16031. const File oldFile (documentFile);
  16032. documentFile = newFile;
  16033. String error (saveDocument (newFile));
  16034. if (error.isEmpty())
  16035. {
  16036. setChangedFlag (false);
  16037. MouseCursor::hideWaitCursor();
  16038. return savedOk;
  16039. }
  16040. documentFile = oldFile;
  16041. MouseCursor::hideWaitCursor();
  16042. if (showMessageOnFailure)
  16043. {
  16044. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16045. TRANS("Error writing to file..."),
  16046. TRANS("An error occurred while trying to save \"")
  16047. + getDocumentTitle()
  16048. + TRANS("\" to the file:\n\n")
  16049. + newFile.getFullPathName()
  16050. + "\n\n"
  16051. + error);
  16052. }
  16053. return failedToWriteToFile;
  16054. }
  16055. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16056. {
  16057. if (! hasChangedSinceSaved())
  16058. return savedOk;
  16059. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16060. TRANS("Closing document..."),
  16061. TRANS("Do you want to save the changes to \"")
  16062. + getDocumentTitle() + "\"?",
  16063. TRANS("save"),
  16064. TRANS("discard changes"),
  16065. TRANS("cancel"));
  16066. if (r == 1)
  16067. {
  16068. // save changes
  16069. return save (true, true);
  16070. }
  16071. else if (r == 2)
  16072. {
  16073. // discard changes
  16074. return savedOk;
  16075. }
  16076. return userCancelledSave;
  16077. }
  16078. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16079. {
  16080. File f;
  16081. if (documentFile.existsAsFile())
  16082. f = documentFile;
  16083. else
  16084. f = getLastDocumentOpened();
  16085. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16086. if (legalFilename.isEmpty())
  16087. legalFilename = "unnamed";
  16088. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16089. f = f.getSiblingFile (legalFilename);
  16090. else
  16091. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16092. f = f.withFileExtension (fileExtension)
  16093. .getNonexistentSibling (true);
  16094. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16095. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16096. {
  16097. File chosen (fc.getResult());
  16098. if (chosen.getFileExtension().isEmpty())
  16099. {
  16100. chosen = chosen.withFileExtension (fileExtension);
  16101. if (chosen.exists())
  16102. {
  16103. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16104. TRANS("File already exists"),
  16105. TRANS("There's already a file called:")
  16106. + "\n\n" + chosen.getFullPathName()
  16107. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16108. TRANS("overwrite"),
  16109. TRANS("cancel")))
  16110. {
  16111. return userCancelledSave;
  16112. }
  16113. }
  16114. }
  16115. setLastDocumentOpened (chosen);
  16116. return saveAs (chosen, false, false, true);
  16117. }
  16118. return userCancelledSave;
  16119. }
  16120. END_JUCE_NAMESPACE
  16121. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16122. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16123. BEGIN_JUCE_NAMESPACE
  16124. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16125. : maxNumberOfItems (10)
  16126. {
  16127. }
  16128. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16129. {
  16130. }
  16131. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16132. {
  16133. maxNumberOfItems = jmax (1, newMaxNumber);
  16134. while (getNumFiles() > maxNumberOfItems)
  16135. files.remove (getNumFiles() - 1);
  16136. }
  16137. int RecentlyOpenedFilesList::getNumFiles() const
  16138. {
  16139. return files.size();
  16140. }
  16141. const File RecentlyOpenedFilesList::getFile (const int index) const
  16142. {
  16143. return File (files [index]);
  16144. }
  16145. void RecentlyOpenedFilesList::clear()
  16146. {
  16147. files.clear();
  16148. }
  16149. void RecentlyOpenedFilesList::addFile (const File& file)
  16150. {
  16151. const String path (file.getFullPathName());
  16152. files.removeString (path, true);
  16153. files.insert (0, path);
  16154. setMaxNumberOfItems (maxNumberOfItems);
  16155. }
  16156. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16157. {
  16158. for (int i = getNumFiles(); --i >= 0;)
  16159. if (! getFile(i).exists())
  16160. files.remove (i);
  16161. }
  16162. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16163. const int baseItemId,
  16164. const bool showFullPaths,
  16165. const bool dontAddNonExistentFiles,
  16166. const File** filesToAvoid)
  16167. {
  16168. int num = 0;
  16169. for (int i = 0; i < getNumFiles(); ++i)
  16170. {
  16171. const File f (getFile(i));
  16172. if ((! dontAddNonExistentFiles) || f.exists())
  16173. {
  16174. bool needsAvoiding = false;
  16175. if (filesToAvoid != 0)
  16176. {
  16177. const File** avoid = filesToAvoid;
  16178. while (*avoid != 0)
  16179. {
  16180. if (f == **avoid)
  16181. {
  16182. needsAvoiding = true;
  16183. break;
  16184. }
  16185. ++avoid;
  16186. }
  16187. }
  16188. if (! needsAvoiding)
  16189. {
  16190. menuToAddTo.addItem (baseItemId + i,
  16191. showFullPaths ? f.getFullPathName()
  16192. : f.getFileName());
  16193. ++num;
  16194. }
  16195. }
  16196. }
  16197. return num;
  16198. }
  16199. const String RecentlyOpenedFilesList::toString() const
  16200. {
  16201. return files.joinIntoString ("\n");
  16202. }
  16203. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16204. {
  16205. clear();
  16206. files.addLines (stringifiedVersion);
  16207. setMaxNumberOfItems (maxNumberOfItems);
  16208. }
  16209. END_JUCE_NAMESPACE
  16210. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16211. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16212. BEGIN_JUCE_NAMESPACE
  16213. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16214. const int minimumTransactions)
  16215. : totalUnitsStored (0),
  16216. nextIndex (0),
  16217. newTransaction (true),
  16218. reentrancyCheck (false)
  16219. {
  16220. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16221. minimumTransactions);
  16222. }
  16223. UndoManager::~UndoManager()
  16224. {
  16225. clearUndoHistory();
  16226. }
  16227. void UndoManager::clearUndoHistory()
  16228. {
  16229. transactions.clear();
  16230. transactionNames.clear();
  16231. totalUnitsStored = 0;
  16232. nextIndex = 0;
  16233. sendChangeMessage();
  16234. }
  16235. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16236. {
  16237. return totalUnitsStored;
  16238. }
  16239. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16240. const int minimumTransactions)
  16241. {
  16242. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16243. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16244. }
  16245. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16246. {
  16247. if (command_ != 0)
  16248. {
  16249. ScopedPointer<UndoableAction> command (command_);
  16250. if (actionName.isNotEmpty())
  16251. currentTransactionName = actionName;
  16252. if (reentrancyCheck)
  16253. {
  16254. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16255. // undo() methods, or else these actions won't actually get done.
  16256. return false;
  16257. }
  16258. else if (command->perform())
  16259. {
  16260. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16261. if (commandSet != 0 && ! newTransaction)
  16262. {
  16263. UndoableAction* lastAction = commandSet->getLast();
  16264. if (lastAction != 0)
  16265. {
  16266. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16267. if (coalescedAction != 0)
  16268. {
  16269. command = coalescedAction;
  16270. totalUnitsStored -= lastAction->getSizeInUnits();
  16271. commandSet->removeLast();
  16272. }
  16273. }
  16274. }
  16275. else
  16276. {
  16277. commandSet = new OwnedArray<UndoableAction>();
  16278. transactions.insert (nextIndex, commandSet);
  16279. transactionNames.insert (nextIndex, currentTransactionName);
  16280. ++nextIndex;
  16281. }
  16282. totalUnitsStored += command->getSizeInUnits();
  16283. commandSet->add (command.release());
  16284. newTransaction = false;
  16285. while (nextIndex < transactions.size())
  16286. {
  16287. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16288. for (int i = lastSet->size(); --i >= 0;)
  16289. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16290. transactions.removeLast();
  16291. transactionNames.remove (transactionNames.size() - 1);
  16292. }
  16293. while (nextIndex > 0
  16294. && totalUnitsStored > maxNumUnitsToKeep
  16295. && transactions.size() > minimumTransactionsToKeep)
  16296. {
  16297. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16298. for (int i = firstSet->size(); --i >= 0;)
  16299. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16300. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16301. transactions.remove (0);
  16302. transactionNames.remove (0);
  16303. --nextIndex;
  16304. }
  16305. sendChangeMessage();
  16306. return true;
  16307. }
  16308. }
  16309. return false;
  16310. }
  16311. void UndoManager::beginNewTransaction (const String& actionName)
  16312. {
  16313. newTransaction = true;
  16314. currentTransactionName = actionName;
  16315. }
  16316. void UndoManager::setCurrentTransactionName (const String& newName)
  16317. {
  16318. currentTransactionName = newName;
  16319. }
  16320. bool UndoManager::canUndo() const
  16321. {
  16322. return nextIndex > 0;
  16323. }
  16324. bool UndoManager::canRedo() const
  16325. {
  16326. return nextIndex < transactions.size();
  16327. }
  16328. const String UndoManager::getUndoDescription() const
  16329. {
  16330. return transactionNames [nextIndex - 1];
  16331. }
  16332. const String UndoManager::getRedoDescription() const
  16333. {
  16334. return transactionNames [nextIndex];
  16335. }
  16336. bool UndoManager::undo()
  16337. {
  16338. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16339. if (commandSet == 0)
  16340. return false;
  16341. reentrancyCheck = true;
  16342. bool failed = false;
  16343. for (int i = commandSet->size(); --i >= 0;)
  16344. {
  16345. if (! commandSet->getUnchecked(i)->undo())
  16346. {
  16347. jassertfalse;
  16348. failed = true;
  16349. break;
  16350. }
  16351. }
  16352. reentrancyCheck = false;
  16353. if (failed)
  16354. clearUndoHistory();
  16355. else
  16356. --nextIndex;
  16357. beginNewTransaction();
  16358. sendChangeMessage();
  16359. return true;
  16360. }
  16361. bool UndoManager::redo()
  16362. {
  16363. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16364. if (commandSet == 0)
  16365. return false;
  16366. reentrancyCheck = true;
  16367. bool failed = false;
  16368. for (int i = 0; i < commandSet->size(); ++i)
  16369. {
  16370. if (! commandSet->getUnchecked(i)->perform())
  16371. {
  16372. jassertfalse;
  16373. failed = true;
  16374. break;
  16375. }
  16376. }
  16377. reentrancyCheck = false;
  16378. if (failed)
  16379. clearUndoHistory();
  16380. else
  16381. ++nextIndex;
  16382. beginNewTransaction();
  16383. sendChangeMessage();
  16384. return true;
  16385. }
  16386. bool UndoManager::undoCurrentTransactionOnly()
  16387. {
  16388. return newTransaction ? false : undo();
  16389. }
  16390. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16391. {
  16392. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16393. if (commandSet != 0 && ! newTransaction)
  16394. {
  16395. for (int i = 0; i < commandSet->size(); ++i)
  16396. actionsFound.add (commandSet->getUnchecked(i));
  16397. }
  16398. }
  16399. int UndoManager::getNumActionsInCurrentTransaction() const
  16400. {
  16401. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16402. if (commandSet != 0 && ! newTransaction)
  16403. return commandSet->size();
  16404. return 0;
  16405. }
  16406. END_JUCE_NAMESPACE
  16407. /*** End of inlined file: juce_UndoManager.cpp ***/
  16408. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16409. BEGIN_JUCE_NAMESPACE
  16410. static const char* const aiffFormatName = "AIFF file";
  16411. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16412. class AiffAudioFormatReader : public AudioFormatReader
  16413. {
  16414. public:
  16415. int bytesPerFrame;
  16416. int64 dataChunkStart;
  16417. bool littleEndian;
  16418. AiffAudioFormatReader (InputStream* in)
  16419. : AudioFormatReader (in, TRANS (aiffFormatName))
  16420. {
  16421. if (input->readInt() == chunkName ("FORM"))
  16422. {
  16423. const int len = input->readIntBigEndian();
  16424. const int64 end = input->getPosition() + len;
  16425. const int nextType = input->readInt();
  16426. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16427. {
  16428. bool hasGotVer = false;
  16429. bool hasGotData = false;
  16430. bool hasGotType = false;
  16431. while (input->getPosition() < end)
  16432. {
  16433. const int type = input->readInt();
  16434. const uint32 length = (uint32) input->readIntBigEndian();
  16435. const int64 chunkEnd = input->getPosition() + length;
  16436. if (type == chunkName ("FVER"))
  16437. {
  16438. hasGotVer = true;
  16439. const int ver = input->readIntBigEndian();
  16440. if (ver != 0 && ver != (int) 0xa2805140)
  16441. break;
  16442. }
  16443. else if (type == chunkName ("COMM"))
  16444. {
  16445. hasGotType = true;
  16446. numChannels = (unsigned int) input->readShortBigEndian();
  16447. lengthInSamples = input->readIntBigEndian();
  16448. bitsPerSample = input->readShortBigEndian();
  16449. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16450. unsigned char sampleRateBytes[10];
  16451. input->read (sampleRateBytes, 10);
  16452. const int byte0 = sampleRateBytes[0];
  16453. if ((byte0 & 0x80) != 0
  16454. || byte0 <= 0x3F || byte0 > 0x40
  16455. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16456. break;
  16457. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16458. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16459. sampleRate = (int) sampRate;
  16460. if (length <= 18)
  16461. {
  16462. // some types don't have a chunk large enough to include a compression
  16463. // type, so assume it's just big-endian pcm
  16464. littleEndian = false;
  16465. }
  16466. else
  16467. {
  16468. const int compType = input->readInt();
  16469. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16470. {
  16471. littleEndian = false;
  16472. }
  16473. else if (compType == chunkName ("sowt"))
  16474. {
  16475. littleEndian = true;
  16476. }
  16477. else
  16478. {
  16479. sampleRate = 0;
  16480. break;
  16481. }
  16482. }
  16483. }
  16484. else if (type == chunkName ("SSND"))
  16485. {
  16486. hasGotData = true;
  16487. const int offset = input->readIntBigEndian();
  16488. dataChunkStart = input->getPosition() + 4 + offset;
  16489. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16490. }
  16491. else if ((hasGotVer && hasGotData && hasGotType)
  16492. || chunkEnd < input->getPosition()
  16493. || input->isExhausted())
  16494. {
  16495. break;
  16496. }
  16497. input->setPosition (chunkEnd);
  16498. }
  16499. }
  16500. }
  16501. }
  16502. ~AiffAudioFormatReader()
  16503. {
  16504. }
  16505. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16506. int64 startSampleInFile, int numSamples)
  16507. {
  16508. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16509. if (samplesAvailable < numSamples)
  16510. {
  16511. for (int i = numDestChannels; --i >= 0;)
  16512. if (destSamples[i] != 0)
  16513. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16514. numSamples = (int) samplesAvailable;
  16515. }
  16516. if (numSamples <= 0)
  16517. return true;
  16518. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16519. while (numSamples > 0)
  16520. {
  16521. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16522. char tempBuffer [tempBufSize];
  16523. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16524. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16525. if (bytesRead < numThisTime * bytesPerFrame)
  16526. {
  16527. jassert (bytesRead >= 0);
  16528. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16529. }
  16530. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16531. if (littleEndian)
  16532. {
  16533. switch (bitsPerSample)
  16534. {
  16535. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16536. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16537. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16538. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16539. default: jassertfalse; break;
  16540. }
  16541. }
  16542. else
  16543. {
  16544. switch (bitsPerSample)
  16545. {
  16546. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16547. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16548. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16549. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16550. default: jassertfalse; break;
  16551. }
  16552. }
  16553. startOffsetInDestBuffer += numThisTime;
  16554. numSamples -= numThisTime;
  16555. }
  16556. return true;
  16557. }
  16558. private:
  16559. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16560. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16561. };
  16562. class AiffAudioFormatWriter : public AudioFormatWriter
  16563. {
  16564. public:
  16565. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16566. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16567. lengthInSamples (0),
  16568. bytesWritten (0),
  16569. writeFailed (false)
  16570. {
  16571. headerPosition = out->getPosition();
  16572. writeHeader();
  16573. }
  16574. ~AiffAudioFormatWriter()
  16575. {
  16576. if ((bytesWritten & 1) != 0)
  16577. output->writeByte (0);
  16578. writeHeader();
  16579. }
  16580. bool write (const int** data, int numSamples)
  16581. {
  16582. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16583. if (writeFailed)
  16584. return false;
  16585. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16586. tempBlock.ensureSize (bytes, false);
  16587. switch (bitsPerSample)
  16588. {
  16589. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16590. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16591. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16592. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16593. default: jassertfalse; break;
  16594. }
  16595. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16596. || ! output->write (tempBlock.getData(), bytes))
  16597. {
  16598. // failed to write to disk, so let's try writing the header.
  16599. // If it's just run out of disk space, then if it does manage
  16600. // to write the header, we'll still have a useable file..
  16601. writeHeader();
  16602. writeFailed = true;
  16603. return false;
  16604. }
  16605. else
  16606. {
  16607. bytesWritten += bytes;
  16608. lengthInSamples += numSamples;
  16609. return true;
  16610. }
  16611. }
  16612. private:
  16613. MemoryBlock tempBlock;
  16614. uint32 lengthInSamples, bytesWritten;
  16615. int64 headerPosition;
  16616. bool writeFailed;
  16617. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16618. void writeHeader()
  16619. {
  16620. const bool couldSeekOk = output->setPosition (headerPosition);
  16621. (void) couldSeekOk;
  16622. // if this fails, you've given it an output stream that can't seek! It needs
  16623. // to be able to seek back to write the header
  16624. jassert (couldSeekOk);
  16625. const int headerLen = 54;
  16626. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16627. audioBytes += (audioBytes & 1);
  16628. output->writeInt (chunkName ("FORM"));
  16629. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16630. output->writeInt (chunkName ("AIFF"));
  16631. output->writeInt (chunkName ("COMM"));
  16632. output->writeIntBigEndian (18);
  16633. output->writeShortBigEndian ((short) numChannels);
  16634. output->writeIntBigEndian (lengthInSamples);
  16635. output->writeShortBigEndian ((short) bitsPerSample);
  16636. uint8 sampleRateBytes[10];
  16637. zeromem (sampleRateBytes, 10);
  16638. if (sampleRate <= 1)
  16639. {
  16640. sampleRateBytes[0] = 0x3f;
  16641. sampleRateBytes[1] = 0xff;
  16642. sampleRateBytes[2] = 0x80;
  16643. }
  16644. else
  16645. {
  16646. int mask = 0x40000000;
  16647. sampleRateBytes[0] = 0x40;
  16648. if (sampleRate >= mask)
  16649. {
  16650. jassertfalse;
  16651. sampleRateBytes[1] = 0x1d;
  16652. }
  16653. else
  16654. {
  16655. int n = (int) sampleRate;
  16656. int i;
  16657. for (i = 0; i <= 32 ; ++i)
  16658. {
  16659. if ((n & mask) != 0)
  16660. break;
  16661. mask >>= 1;
  16662. }
  16663. n = n << (i + 1);
  16664. sampleRateBytes[1] = (uint8) (29 - i);
  16665. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16666. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16667. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16668. sampleRateBytes[5] = (uint8) (n & 0xff);
  16669. }
  16670. }
  16671. output->write (sampleRateBytes, 10);
  16672. output->writeInt (chunkName ("SSND"));
  16673. output->writeIntBigEndian (audioBytes + 8);
  16674. output->writeInt (0);
  16675. output->writeInt (0);
  16676. jassert (output->getPosition() == headerLen);
  16677. }
  16678. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16679. };
  16680. AiffAudioFormat::AiffAudioFormat()
  16681. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16682. {
  16683. }
  16684. AiffAudioFormat::~AiffAudioFormat()
  16685. {
  16686. }
  16687. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16688. {
  16689. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16690. return Array <int> (rates);
  16691. }
  16692. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16693. {
  16694. const int depths[] = { 8, 16, 24, 0 };
  16695. return Array <int> (depths);
  16696. }
  16697. bool AiffAudioFormat::canDoStereo() { return true; }
  16698. bool AiffAudioFormat::canDoMono() { return true; }
  16699. #if JUCE_MAC
  16700. bool AiffAudioFormat::canHandleFile (const File& f)
  16701. {
  16702. if (AudioFormat::canHandleFile (f))
  16703. return true;
  16704. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16705. return type == 'AIFF' || type == 'AIFC'
  16706. || type == 'aiff' || type == 'aifc';
  16707. }
  16708. #endif
  16709. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16710. {
  16711. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16712. if (w->sampleRate != 0)
  16713. return w.release();
  16714. if (! deleteStreamIfOpeningFails)
  16715. w->input = 0;
  16716. return 0;
  16717. }
  16718. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16719. double sampleRate,
  16720. unsigned int numberOfChannels,
  16721. int bitsPerSample,
  16722. const StringPairArray& /*metadataValues*/,
  16723. int /*qualityOptionIndex*/)
  16724. {
  16725. if (getPossibleBitDepths().contains (bitsPerSample))
  16726. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16727. return 0;
  16728. }
  16729. END_JUCE_NAMESPACE
  16730. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16731. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16732. BEGIN_JUCE_NAMESPACE
  16733. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16734. : formatName (name),
  16735. fileExtensions (extensions)
  16736. {
  16737. }
  16738. AudioFormat::~AudioFormat()
  16739. {
  16740. }
  16741. bool AudioFormat::canHandleFile (const File& f)
  16742. {
  16743. for (int i = 0; i < fileExtensions.size(); ++i)
  16744. if (f.hasFileExtension (fileExtensions[i]))
  16745. return true;
  16746. return false;
  16747. }
  16748. const String& AudioFormat::getFormatName() const { return formatName; }
  16749. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16750. bool AudioFormat::isCompressed() { return false; }
  16751. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16752. END_JUCE_NAMESPACE
  16753. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16754. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16755. BEGIN_JUCE_NAMESPACE
  16756. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16757. const String& formatName_)
  16758. : sampleRate (0),
  16759. bitsPerSample (0),
  16760. lengthInSamples (0),
  16761. numChannels (0),
  16762. usesFloatingPointData (false),
  16763. input (in),
  16764. formatName (formatName_)
  16765. {
  16766. }
  16767. AudioFormatReader::~AudioFormatReader()
  16768. {
  16769. delete input;
  16770. }
  16771. bool AudioFormatReader::read (int* const* destSamples,
  16772. int numDestChannels,
  16773. int64 startSampleInSource,
  16774. int numSamplesToRead,
  16775. const bool fillLeftoverChannelsWithCopies)
  16776. {
  16777. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16778. int startOffsetInDestBuffer = 0;
  16779. if (startSampleInSource < 0)
  16780. {
  16781. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16782. for (int i = numDestChannels; --i >= 0;)
  16783. if (destSamples[i] != 0)
  16784. zeromem (destSamples[i], sizeof (int) * silence);
  16785. startOffsetInDestBuffer += silence;
  16786. numSamplesToRead -= silence;
  16787. startSampleInSource = 0;
  16788. }
  16789. if (numSamplesToRead <= 0)
  16790. return true;
  16791. if (! readSamples (const_cast<int**> (destSamples),
  16792. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16793. startSampleInSource, numSamplesToRead))
  16794. return false;
  16795. if (numDestChannels > (int) numChannels)
  16796. {
  16797. if (fillLeftoverChannelsWithCopies)
  16798. {
  16799. int* lastFullChannel = destSamples[0];
  16800. for (int i = (int) numChannels; --i > 0;)
  16801. {
  16802. if (destSamples[i] != 0)
  16803. {
  16804. lastFullChannel = destSamples[i];
  16805. break;
  16806. }
  16807. }
  16808. if (lastFullChannel != 0)
  16809. for (int i = numChannels; i < numDestChannels; ++i)
  16810. if (destSamples[i] != 0)
  16811. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16812. }
  16813. else
  16814. {
  16815. for (int i = numChannels; i < numDestChannels; ++i)
  16816. if (destSamples[i] != 0)
  16817. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16818. }
  16819. }
  16820. return true;
  16821. }
  16822. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16823. int64 numSamples,
  16824. float& lowestLeft, float& highestLeft,
  16825. float& lowestRight, float& highestRight)
  16826. {
  16827. if (numSamples <= 0)
  16828. {
  16829. lowestLeft = 0;
  16830. lowestRight = 0;
  16831. highestLeft = 0;
  16832. highestRight = 0;
  16833. return;
  16834. }
  16835. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16836. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16837. int* tempBuffer[3];
  16838. tempBuffer[0] = tempSpace.getData();
  16839. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16840. tempBuffer[2] = 0;
  16841. if (usesFloatingPointData)
  16842. {
  16843. float lmin = 1.0e6f;
  16844. float lmax = -lmin;
  16845. float rmin = lmin;
  16846. float rmax = lmax;
  16847. while (numSamples > 0)
  16848. {
  16849. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16850. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16851. numSamples -= numToDo;
  16852. startSampleInFile += numToDo;
  16853. float bufMin, bufMax;
  16854. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16855. lmin = jmin (lmin, bufMin);
  16856. lmax = jmax (lmax, bufMax);
  16857. if (numChannels > 1)
  16858. {
  16859. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16860. rmin = jmin (rmin, bufMin);
  16861. rmax = jmax (rmax, bufMax);
  16862. }
  16863. }
  16864. if (numChannels <= 1)
  16865. {
  16866. rmax = lmax;
  16867. rmin = lmin;
  16868. }
  16869. lowestLeft = lmin;
  16870. highestLeft = lmax;
  16871. lowestRight = rmin;
  16872. highestRight = rmax;
  16873. }
  16874. else
  16875. {
  16876. int lmax = std::numeric_limits<int>::min();
  16877. int lmin = std::numeric_limits<int>::max();
  16878. int rmax = std::numeric_limits<int>::min();
  16879. int rmin = std::numeric_limits<int>::max();
  16880. while (numSamples > 0)
  16881. {
  16882. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16883. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16884. break;
  16885. numSamples -= numToDo;
  16886. startSampleInFile += numToDo;
  16887. for (int j = numChannels; --j >= 0;)
  16888. {
  16889. int bufMin, bufMax;
  16890. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16891. if (j == 0)
  16892. {
  16893. lmax = jmax (lmax, bufMax);
  16894. lmin = jmin (lmin, bufMin);
  16895. }
  16896. else
  16897. {
  16898. rmax = jmax (rmax, bufMax);
  16899. rmin = jmin (rmin, bufMin);
  16900. }
  16901. }
  16902. }
  16903. if (numChannels <= 1)
  16904. {
  16905. rmax = lmax;
  16906. rmin = lmin;
  16907. }
  16908. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16909. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16910. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16911. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16912. }
  16913. }
  16914. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16915. int64 numSamplesToSearch,
  16916. const double magnitudeRangeMinimum,
  16917. const double magnitudeRangeMaximum,
  16918. const int minimumConsecutiveSamples)
  16919. {
  16920. if (numSamplesToSearch == 0)
  16921. return -1;
  16922. const int bufferSize = 4096;
  16923. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16924. int* tempBuffer[3];
  16925. tempBuffer[0] = tempSpace.getData();
  16926. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16927. tempBuffer[2] = 0;
  16928. int consecutive = 0;
  16929. int64 firstMatchPos = -1;
  16930. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16931. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16932. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16933. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16934. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16935. while (numSamplesToSearch != 0)
  16936. {
  16937. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16938. int64 bufferStart = startSample;
  16939. if (numSamplesToSearch < 0)
  16940. bufferStart -= numThisTime;
  16941. if (bufferStart >= (int) lengthInSamples)
  16942. break;
  16943. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16944. int num = numThisTime;
  16945. while (--num >= 0)
  16946. {
  16947. if (numSamplesToSearch < 0)
  16948. --startSample;
  16949. bool matches = false;
  16950. const int index = (int) (startSample - bufferStart);
  16951. if (usesFloatingPointData)
  16952. {
  16953. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16954. if (sample1 >= magnitudeRangeMinimum
  16955. && sample1 <= magnitudeRangeMaximum)
  16956. {
  16957. matches = true;
  16958. }
  16959. else if (numChannels > 1)
  16960. {
  16961. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16962. matches = (sample2 >= magnitudeRangeMinimum
  16963. && sample2 <= magnitudeRangeMaximum);
  16964. }
  16965. }
  16966. else
  16967. {
  16968. const int sample1 = abs (tempBuffer[0] [index]);
  16969. if (sample1 >= intMagnitudeRangeMinimum
  16970. && sample1 <= intMagnitudeRangeMaximum)
  16971. {
  16972. matches = true;
  16973. }
  16974. else if (numChannels > 1)
  16975. {
  16976. const int sample2 = abs (tempBuffer[1][index]);
  16977. matches = (sample2 >= intMagnitudeRangeMinimum
  16978. && sample2 <= intMagnitudeRangeMaximum);
  16979. }
  16980. }
  16981. if (matches)
  16982. {
  16983. if (firstMatchPos < 0)
  16984. firstMatchPos = startSample;
  16985. if (++consecutive >= minimumConsecutiveSamples)
  16986. {
  16987. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16988. return -1;
  16989. return firstMatchPos;
  16990. }
  16991. }
  16992. else
  16993. {
  16994. consecutive = 0;
  16995. firstMatchPos = -1;
  16996. }
  16997. if (numSamplesToSearch > 0)
  16998. ++startSample;
  16999. }
  17000. if (numSamplesToSearch > 0)
  17001. numSamplesToSearch -= numThisTime;
  17002. else
  17003. numSamplesToSearch += numThisTime;
  17004. }
  17005. return -1;
  17006. }
  17007. END_JUCE_NAMESPACE
  17008. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17009. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17010. BEGIN_JUCE_NAMESPACE
  17011. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17012. const String& formatName_,
  17013. const double rate,
  17014. const unsigned int numChannels_,
  17015. const unsigned int bitsPerSample_)
  17016. : sampleRate (rate),
  17017. numChannels (numChannels_),
  17018. bitsPerSample (bitsPerSample_),
  17019. usesFloatingPointData (false),
  17020. output (out),
  17021. formatName (formatName_)
  17022. {
  17023. }
  17024. AudioFormatWriter::~AudioFormatWriter()
  17025. {
  17026. delete output;
  17027. }
  17028. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17029. int64 startSample,
  17030. int64 numSamplesToRead)
  17031. {
  17032. const int bufferSize = 16384;
  17033. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17034. int* buffers [128];
  17035. zerostruct (buffers);
  17036. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17037. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17038. if (numSamplesToRead < 0)
  17039. numSamplesToRead = reader.lengthInSamples;
  17040. while (numSamplesToRead > 0)
  17041. {
  17042. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17043. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17044. return false;
  17045. if (reader.usesFloatingPointData != isFloatingPoint())
  17046. {
  17047. int** bufferChan = buffers;
  17048. while (*bufferChan != 0)
  17049. {
  17050. int* b = *bufferChan++;
  17051. if (isFloatingPoint())
  17052. {
  17053. // int -> float
  17054. const double factor = 1.0 / std::numeric_limits<int>::max();
  17055. for (int i = 0; i < numToDo; ++i)
  17056. ((float*) b)[i] = (float) (factor * b[i]);
  17057. }
  17058. else
  17059. {
  17060. // float -> int
  17061. for (int i = 0; i < numToDo; ++i)
  17062. {
  17063. const double samp = *(const float*) b;
  17064. if (samp <= -1.0)
  17065. *b++ = std::numeric_limits<int>::min();
  17066. else if (samp >= 1.0)
  17067. *b++ = std::numeric_limits<int>::max();
  17068. else
  17069. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17070. }
  17071. }
  17072. }
  17073. }
  17074. if (! write (const_cast<const int**> (buffers), numToDo))
  17075. return false;
  17076. numSamplesToRead -= numToDo;
  17077. startSample += numToDo;
  17078. }
  17079. return true;
  17080. }
  17081. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17082. {
  17083. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17084. while (numSamplesToRead > 0)
  17085. {
  17086. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17087. AudioSourceChannelInfo info;
  17088. info.buffer = &tempBuffer;
  17089. info.startSample = 0;
  17090. info.numSamples = numToDo;
  17091. info.clearActiveBufferRegion();
  17092. source.getNextAudioBlock (info);
  17093. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17094. return false;
  17095. numSamplesToRead -= numToDo;
  17096. }
  17097. return true;
  17098. }
  17099. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17100. {
  17101. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17102. if (numSamples <= 0)
  17103. return true;
  17104. HeapBlock<int> tempBuffer;
  17105. HeapBlock<int*> chans (numChannels + 1);
  17106. chans [numChannels] = 0;
  17107. if (isFloatingPoint())
  17108. {
  17109. for (int i = numChannels; --i >= 0;)
  17110. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17111. }
  17112. else
  17113. {
  17114. tempBuffer.malloc (numSamples * numChannels);
  17115. for (unsigned int i = 0; i < numChannels; ++i)
  17116. {
  17117. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17118. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17119. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17120. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17121. destData.convertSamples (sourceData, numSamples);
  17122. }
  17123. }
  17124. return write ((const int**) chans.getData(), numSamples);
  17125. }
  17126. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17127. public AbstractFifo
  17128. {
  17129. public:
  17130. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  17131. : AbstractFifo (bufferSize_),
  17132. buffer (numChannels, bufferSize_),
  17133. timeSliceThread (timeSliceThread_),
  17134. writer (writer_),
  17135. thumbnailToUpdate (0),
  17136. samplesWritten (0),
  17137. isRunning (true)
  17138. {
  17139. timeSliceThread.addTimeSliceClient (this);
  17140. }
  17141. ~Buffer()
  17142. {
  17143. isRunning = false;
  17144. timeSliceThread.removeTimeSliceClient (this);
  17145. while (useTimeSlice())
  17146. {}
  17147. }
  17148. bool write (const float** data, int numSamples)
  17149. {
  17150. if (numSamples <= 0 || ! isRunning)
  17151. return true;
  17152. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17153. int start1, size1, start2, size2;
  17154. prepareToWrite (numSamples, start1, size1, start2, size2);
  17155. if (size1 + size2 < numSamples)
  17156. return false;
  17157. for (int i = buffer.getNumChannels(); --i >= 0;)
  17158. {
  17159. buffer.copyFrom (i, start1, data[i], size1);
  17160. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17161. }
  17162. finishedWrite (size1 + size2);
  17163. timeSliceThread.notify();
  17164. return true;
  17165. }
  17166. bool useTimeSlice()
  17167. {
  17168. const int numToDo = getTotalSize() / 4;
  17169. int start1, size1, start2, size2;
  17170. prepareToRead (numToDo, start1, size1, start2, size2);
  17171. if (size1 <= 0)
  17172. return false;
  17173. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17174. const ScopedLock sl (thumbnailLock);
  17175. if (thumbnailToUpdate != 0)
  17176. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  17177. samplesWritten += size1;
  17178. if (size2 > 0)
  17179. {
  17180. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17181. if (thumbnailToUpdate != 0)
  17182. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  17183. samplesWritten += size2;
  17184. }
  17185. finishedRead (size1 + size2);
  17186. return true;
  17187. }
  17188. void setThumbnail (AudioThumbnail* thumb)
  17189. {
  17190. if (thumb != 0)
  17191. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  17192. const ScopedLock sl (thumbnailLock);
  17193. thumbnailToUpdate = thumb;
  17194. samplesWritten = 0;
  17195. }
  17196. private:
  17197. AudioSampleBuffer buffer;
  17198. TimeSliceThread& timeSliceThread;
  17199. ScopedPointer<AudioFormatWriter> writer;
  17200. CriticalSection thumbnailLock;
  17201. AudioThumbnail* thumbnailToUpdate;
  17202. int64 samplesWritten;
  17203. volatile bool isRunning;
  17204. JUCE_DECLARE_NON_COPYABLE (Buffer);
  17205. };
  17206. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17207. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17208. {
  17209. }
  17210. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17211. {
  17212. }
  17213. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17214. {
  17215. return buffer->write (data, numSamples);
  17216. }
  17217. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  17218. {
  17219. buffer->setThumbnail (thumb);
  17220. }
  17221. END_JUCE_NAMESPACE
  17222. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17223. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17224. BEGIN_JUCE_NAMESPACE
  17225. AudioFormatManager::AudioFormatManager()
  17226. : defaultFormatIndex (0)
  17227. {
  17228. }
  17229. AudioFormatManager::~AudioFormatManager()
  17230. {
  17231. }
  17232. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17233. {
  17234. jassert (newFormat != 0);
  17235. if (newFormat != 0)
  17236. {
  17237. #if JUCE_DEBUG
  17238. for (int i = getNumKnownFormats(); --i >= 0;)
  17239. {
  17240. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17241. {
  17242. jassertfalse; // trying to add the same format twice!
  17243. }
  17244. }
  17245. #endif
  17246. if (makeThisTheDefaultFormat)
  17247. defaultFormatIndex = getNumKnownFormats();
  17248. knownFormats.add (newFormat);
  17249. }
  17250. }
  17251. void AudioFormatManager::registerBasicFormats()
  17252. {
  17253. #if JUCE_MAC
  17254. registerFormat (new AiffAudioFormat(), true);
  17255. registerFormat (new WavAudioFormat(), false);
  17256. #else
  17257. registerFormat (new WavAudioFormat(), true);
  17258. registerFormat (new AiffAudioFormat(), false);
  17259. #endif
  17260. #if JUCE_USE_FLAC
  17261. registerFormat (new FlacAudioFormat(), false);
  17262. #endif
  17263. #if JUCE_USE_OGGVORBIS
  17264. registerFormat (new OggVorbisAudioFormat(), false);
  17265. #endif
  17266. }
  17267. void AudioFormatManager::clearFormats()
  17268. {
  17269. knownFormats.clear();
  17270. defaultFormatIndex = 0;
  17271. }
  17272. int AudioFormatManager::getNumKnownFormats() const
  17273. {
  17274. return knownFormats.size();
  17275. }
  17276. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17277. {
  17278. return knownFormats [index];
  17279. }
  17280. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17281. {
  17282. return getKnownFormat (defaultFormatIndex);
  17283. }
  17284. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17285. {
  17286. String e (fileExtension);
  17287. if (! e.startsWithChar ('.'))
  17288. e = "." + e;
  17289. for (int i = 0; i < getNumKnownFormats(); ++i)
  17290. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17291. return getKnownFormat(i);
  17292. return 0;
  17293. }
  17294. const String AudioFormatManager::getWildcardForAllFormats() const
  17295. {
  17296. StringArray allExtensions;
  17297. int i;
  17298. for (i = 0; i < getNumKnownFormats(); ++i)
  17299. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17300. allExtensions.trim();
  17301. allExtensions.removeEmptyStrings();
  17302. String s;
  17303. for (i = 0; i < allExtensions.size(); ++i)
  17304. {
  17305. s << '*';
  17306. if (! allExtensions[i].startsWithChar ('.'))
  17307. s << '.';
  17308. s << allExtensions[i];
  17309. if (i < allExtensions.size() - 1)
  17310. s << ';';
  17311. }
  17312. return s;
  17313. }
  17314. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17315. {
  17316. // you need to actually register some formats before the manager can
  17317. // use them to open a file!
  17318. jassert (getNumKnownFormats() > 0);
  17319. for (int i = 0; i < getNumKnownFormats(); ++i)
  17320. {
  17321. AudioFormat* const af = getKnownFormat(i);
  17322. if (af->canHandleFile (file))
  17323. {
  17324. InputStream* const in = file.createInputStream();
  17325. if (in != 0)
  17326. {
  17327. AudioFormatReader* const r = af->createReaderFor (in, true);
  17328. if (r != 0)
  17329. return r;
  17330. }
  17331. }
  17332. }
  17333. return 0;
  17334. }
  17335. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17336. {
  17337. // you need to actually register some formats before the manager can
  17338. // use them to open a file!
  17339. jassert (getNumKnownFormats() > 0);
  17340. ScopedPointer <InputStream> in (audioFileStream);
  17341. if (in != 0)
  17342. {
  17343. const int64 originalStreamPos = in->getPosition();
  17344. for (int i = 0; i < getNumKnownFormats(); ++i)
  17345. {
  17346. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17347. if (r != 0)
  17348. {
  17349. in.release();
  17350. return r;
  17351. }
  17352. in->setPosition (originalStreamPos);
  17353. // the stream that is passed-in must be capable of being repositioned so
  17354. // that all the formats can have a go at opening it.
  17355. jassert (in->getPosition() == originalStreamPos);
  17356. }
  17357. }
  17358. return 0;
  17359. }
  17360. END_JUCE_NAMESPACE
  17361. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17362. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17363. BEGIN_JUCE_NAMESPACE
  17364. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17365. const int64 startSample_,
  17366. const int64 length_,
  17367. const bool deleteSourceWhenDeleted_)
  17368. : AudioFormatReader (0, source_->getFormatName()),
  17369. source (source_),
  17370. startSample (startSample_),
  17371. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17372. {
  17373. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17374. sampleRate = source->sampleRate;
  17375. bitsPerSample = source->bitsPerSample;
  17376. lengthInSamples = length;
  17377. numChannels = source->numChannels;
  17378. usesFloatingPointData = source->usesFloatingPointData;
  17379. }
  17380. AudioSubsectionReader::~AudioSubsectionReader()
  17381. {
  17382. if (deleteSourceWhenDeleted)
  17383. delete source;
  17384. }
  17385. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17386. int64 startSampleInFile, int numSamples)
  17387. {
  17388. if (startSampleInFile + numSamples > length)
  17389. {
  17390. for (int i = numDestChannels; --i >= 0;)
  17391. if (destSamples[i] != 0)
  17392. zeromem (destSamples[i], sizeof (int) * numSamples);
  17393. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17394. if (numSamples <= 0)
  17395. return true;
  17396. }
  17397. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17398. startSampleInFile + startSample, numSamples);
  17399. }
  17400. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17401. int64 numSamples,
  17402. float& lowestLeft,
  17403. float& highestLeft,
  17404. float& lowestRight,
  17405. float& highestRight)
  17406. {
  17407. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17408. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17409. source->readMaxLevels (startSampleInFile + startSample,
  17410. numSamples,
  17411. lowestLeft,
  17412. highestLeft,
  17413. lowestRight,
  17414. highestRight);
  17415. }
  17416. END_JUCE_NAMESPACE
  17417. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17418. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17419. BEGIN_JUCE_NAMESPACE
  17420. struct AudioThumbnail::MinMaxValue
  17421. {
  17422. char minValue;
  17423. char maxValue;
  17424. MinMaxValue() : minValue (0), maxValue (0)
  17425. {
  17426. }
  17427. inline void set (const char newMin, const char newMax) throw()
  17428. {
  17429. minValue = newMin;
  17430. maxValue = newMax;
  17431. }
  17432. inline void setFloat (const float newMin, const float newMax) throw()
  17433. {
  17434. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17435. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17436. if (maxValue == minValue)
  17437. maxValue = (char) jmin (127, maxValue + 1);
  17438. }
  17439. inline bool isNonZero() const throw()
  17440. {
  17441. return maxValue > minValue;
  17442. }
  17443. inline int getPeak() const throw()
  17444. {
  17445. return jmax (std::abs ((int) minValue),
  17446. std::abs ((int) maxValue));
  17447. }
  17448. inline void read (InputStream& input)
  17449. {
  17450. minValue = input.readByte();
  17451. maxValue = input.readByte();
  17452. }
  17453. inline void write (OutputStream& output)
  17454. {
  17455. output.writeByte (minValue);
  17456. output.writeByte (maxValue);
  17457. }
  17458. };
  17459. class AudioThumbnail::LevelDataSource : public TimeSliceClient,
  17460. public Timer
  17461. {
  17462. public:
  17463. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17464. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17465. hashCode (hash), owner (owner_), reader (newReader)
  17466. {
  17467. }
  17468. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17469. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17470. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17471. {
  17472. }
  17473. ~LevelDataSource()
  17474. {
  17475. owner.cache.removeTimeSliceClient (this);
  17476. }
  17477. enum { timeBeforeDeletingReader = 2000 };
  17478. void initialise (int64 numSamplesFinished_)
  17479. {
  17480. const ScopedLock sl (readerLock);
  17481. numSamplesFinished = numSamplesFinished_;
  17482. createReader();
  17483. if (reader != 0)
  17484. {
  17485. lengthInSamples = reader->lengthInSamples;
  17486. numChannels = reader->numChannels;
  17487. sampleRate = reader->sampleRate;
  17488. if (lengthInSamples <= 0)
  17489. reader = 0;
  17490. else if (! isFullyLoaded())
  17491. owner.cache.addTimeSliceClient (this);
  17492. }
  17493. }
  17494. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17495. {
  17496. const ScopedLock sl (readerLock);
  17497. createReader();
  17498. if (reader != 0)
  17499. {
  17500. float l[4] = { 0 };
  17501. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17502. levels.clearQuick();
  17503. levels.addArray ((const float*) l, 4);
  17504. }
  17505. }
  17506. void releaseResources()
  17507. {
  17508. const ScopedLock sl (readerLock);
  17509. reader = 0;
  17510. }
  17511. bool useTimeSlice()
  17512. {
  17513. if (isFullyLoaded())
  17514. {
  17515. if (reader != 0 && source != 0)
  17516. startTimer (timeBeforeDeletingReader);
  17517. owner.cache.removeTimeSliceClient (this);
  17518. return false;
  17519. }
  17520. stopTimer();
  17521. bool justFinished = false;
  17522. {
  17523. const ScopedLock sl (readerLock);
  17524. createReader();
  17525. if (reader != 0)
  17526. {
  17527. if (! readNextBlock())
  17528. return true;
  17529. justFinished = true;
  17530. }
  17531. }
  17532. if (justFinished)
  17533. owner.cache.storeThumb (owner, hashCode);
  17534. return false;
  17535. }
  17536. void timerCallback()
  17537. {
  17538. stopTimer();
  17539. releaseResources();
  17540. }
  17541. bool isFullyLoaded() const throw()
  17542. {
  17543. return numSamplesFinished >= lengthInSamples;
  17544. }
  17545. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17546. {
  17547. return (int) (originalSample / owner.samplesPerThumbSample);
  17548. }
  17549. int64 lengthInSamples, numSamplesFinished;
  17550. double sampleRate;
  17551. int numChannels;
  17552. int64 hashCode;
  17553. private:
  17554. AudioThumbnail& owner;
  17555. ScopedPointer <InputSource> source;
  17556. ScopedPointer <AudioFormatReader> reader;
  17557. CriticalSection readerLock;
  17558. void createReader()
  17559. {
  17560. if (reader == 0 && source != 0)
  17561. {
  17562. InputStream* audioFileStream = source->createInputStream();
  17563. if (audioFileStream != 0)
  17564. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17565. }
  17566. }
  17567. bool readNextBlock()
  17568. {
  17569. jassert (reader != 0);
  17570. if (! isFullyLoaded())
  17571. {
  17572. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17573. if (numToDo > 0)
  17574. {
  17575. int64 startSample = numSamplesFinished;
  17576. const int firstThumbIndex = sampleToThumbSample (startSample);
  17577. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17578. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17579. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17580. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17581. for (int i = 0; i < numThumbSamps; ++i)
  17582. {
  17583. float lowestLeft, highestLeft, lowestRight, highestRight;
  17584. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17585. lowestLeft, highestLeft, lowestRight, highestRight);
  17586. levels[0][i].setFloat (lowestLeft, highestLeft);
  17587. levels[1][i].setFloat (lowestRight, highestRight);
  17588. }
  17589. {
  17590. const ScopedUnlock su (readerLock);
  17591. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17592. }
  17593. numSamplesFinished += numToDo;
  17594. }
  17595. }
  17596. return isFullyLoaded();
  17597. }
  17598. };
  17599. class AudioThumbnail::ThumbData
  17600. {
  17601. public:
  17602. ThumbData (const int numThumbSamples)
  17603. : peakLevel (-1)
  17604. {
  17605. ensureSize (numThumbSamples);
  17606. }
  17607. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17608. {
  17609. jassert (thumbSampleIndex < data.size());
  17610. return data.getRawDataPointer() + thumbSampleIndex;
  17611. }
  17612. int getSize() const throw()
  17613. {
  17614. return data.size();
  17615. }
  17616. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17617. {
  17618. if (startSample >= 0)
  17619. {
  17620. endSample = jmin (endSample, data.size() - 1);
  17621. char mx = -128;
  17622. char mn = 127;
  17623. while (startSample <= endSample)
  17624. {
  17625. const MinMaxValue& v = data.getReference (startSample);
  17626. if (v.minValue < mn) mn = v.minValue;
  17627. if (v.maxValue > mx) mx = v.maxValue;
  17628. ++startSample;
  17629. }
  17630. if (mn <= mx)
  17631. {
  17632. result.set (mn, mx);
  17633. return;
  17634. }
  17635. }
  17636. result.set (1, 0);
  17637. }
  17638. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17639. {
  17640. resetPeak();
  17641. if (startIndex + numValues > data.size())
  17642. ensureSize (startIndex + numValues);
  17643. MinMaxValue* const dest = getData (startIndex);
  17644. for (int i = 0; i < numValues; ++i)
  17645. dest[i] = source[i];
  17646. }
  17647. void resetPeak()
  17648. {
  17649. peakLevel = -1;
  17650. }
  17651. int getPeak()
  17652. {
  17653. if (peakLevel < 0)
  17654. {
  17655. for (int i = 0; i < data.size(); ++i)
  17656. {
  17657. const int peak = data[i].getPeak();
  17658. if (peak > peakLevel)
  17659. peakLevel = peak;
  17660. }
  17661. }
  17662. return peakLevel;
  17663. }
  17664. private:
  17665. Array <MinMaxValue> data;
  17666. int peakLevel;
  17667. void ensureSize (const int thumbSamples)
  17668. {
  17669. const int extraNeeded = thumbSamples - data.size();
  17670. if (extraNeeded > 0)
  17671. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17672. }
  17673. };
  17674. class AudioThumbnail::CachedWindow
  17675. {
  17676. public:
  17677. CachedWindow()
  17678. : cachedStart (0), cachedTimePerPixel (0),
  17679. numChannelsCached (0), numSamplesCached (0),
  17680. cacheNeedsRefilling (true)
  17681. {
  17682. }
  17683. void invalidate()
  17684. {
  17685. cacheNeedsRefilling = true;
  17686. }
  17687. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17688. const double startTime, const double endTime,
  17689. const int channelNum, const float verticalZoomFactor,
  17690. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17691. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17692. {
  17693. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17694. numChannels, samplesPerThumbSample, levelData, channels);
  17695. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17696. {
  17697. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17698. if (! clip.isEmpty())
  17699. {
  17700. const float topY = (float) area.getY();
  17701. const float bottomY = (float) area.getBottom();
  17702. const float midY = (topY + bottomY) * 0.5f;
  17703. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17704. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17705. int x = clip.getX();
  17706. for (int w = clip.getWidth(); --w >= 0;)
  17707. {
  17708. if (cacheData->isNonZero())
  17709. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17710. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17711. ++x;
  17712. ++cacheData;
  17713. }
  17714. }
  17715. }
  17716. }
  17717. private:
  17718. Array <MinMaxValue> data;
  17719. double cachedStart, cachedTimePerPixel;
  17720. int numChannelsCached, numSamplesCached;
  17721. bool cacheNeedsRefilling;
  17722. void refillCache (const int numSamples, double startTime, const double endTime,
  17723. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17724. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17725. {
  17726. const double timePerPixel = (endTime - startTime) / numSamples;
  17727. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17728. {
  17729. invalidate();
  17730. return;
  17731. }
  17732. if (numSamples == numSamplesCached
  17733. && numChannelsCached == numChannels
  17734. && startTime == cachedStart
  17735. && timePerPixel == cachedTimePerPixel
  17736. && ! cacheNeedsRefilling)
  17737. {
  17738. return;
  17739. }
  17740. numSamplesCached = numSamples;
  17741. numChannelsCached = numChannels;
  17742. cachedStart = startTime;
  17743. cachedTimePerPixel = timePerPixel;
  17744. cacheNeedsRefilling = false;
  17745. ensureSize (numSamples);
  17746. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17747. {
  17748. int sample = roundToInt (startTime * sampleRate);
  17749. Array<float> levels;
  17750. int i;
  17751. for (i = 0; i < numSamples; ++i)
  17752. {
  17753. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17754. if (sample >= 0)
  17755. {
  17756. if (sample >= levelData->lengthInSamples)
  17757. break;
  17758. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17759. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17760. for (int chan = 0; chan < numChans; ++chan)
  17761. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17762. levels.getUnchecked (chan * 2 + 1));
  17763. }
  17764. startTime += timePerPixel;
  17765. sample = nextSample;
  17766. }
  17767. numSamplesCached = i;
  17768. }
  17769. else
  17770. {
  17771. jassert (channels.size() == numChannelsCached);
  17772. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17773. {
  17774. ThumbData* channelData = channels.getUnchecked (channelNum);
  17775. MinMaxValue* cacheData = getData (channelNum, 0);
  17776. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17777. startTime = cachedStart;
  17778. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17779. for (int i = numSamples; --i >= 0;)
  17780. {
  17781. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17782. channelData->getMinMax (sample, nextSample, *cacheData);
  17783. ++cacheData;
  17784. startTime += timePerPixel;
  17785. sample = nextSample;
  17786. }
  17787. }
  17788. }
  17789. }
  17790. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17791. {
  17792. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17793. return data.getRawDataPointer() + channelNum * numSamplesCached
  17794. + cacheIndex;
  17795. }
  17796. void ensureSize (const int numSamples)
  17797. {
  17798. const int itemsRequired = numSamples * numChannelsCached;
  17799. if (data.size() < itemsRequired)
  17800. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17801. }
  17802. };
  17803. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17804. AudioFormatManager& formatManagerToUse_,
  17805. AudioThumbnailCache& cacheToUse)
  17806. : formatManagerToUse (formatManagerToUse_),
  17807. cache (cacheToUse),
  17808. window (new CachedWindow()),
  17809. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17810. totalSamples (0),
  17811. numChannels (0),
  17812. sampleRate (0)
  17813. {
  17814. }
  17815. AudioThumbnail::~AudioThumbnail()
  17816. {
  17817. clear();
  17818. }
  17819. void AudioThumbnail::clear()
  17820. {
  17821. source = 0;
  17822. const ScopedLock sl (lock);
  17823. window->invalidate();
  17824. channels.clear();
  17825. totalSamples = numSamplesFinished = 0;
  17826. numChannels = 0;
  17827. sampleRate = 0;
  17828. sendChangeMessage();
  17829. }
  17830. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17831. {
  17832. clear();
  17833. numChannels = newNumChannels;
  17834. sampleRate = newSampleRate;
  17835. totalSamples = totalSamplesInSource;
  17836. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17837. }
  17838. void AudioThumbnail::createChannels (const int length)
  17839. {
  17840. while (channels.size() < numChannels)
  17841. channels.add (new ThumbData (length));
  17842. }
  17843. void AudioThumbnail::loadFrom (InputStream& input)
  17844. {
  17845. clear();
  17846. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17847. return;
  17848. samplesPerThumbSample = input.readInt();
  17849. totalSamples = input.readInt64(); // Total number of source samples.
  17850. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17851. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17852. numChannels = input.readInt(); // Number of audio channels.
  17853. sampleRate = input.readInt(); // Source sample rate.
  17854. input.skipNextBytes (16); // reserved area
  17855. createChannels (numThumbnailSamples);
  17856. for (int i = 0; i < numThumbnailSamples; ++i)
  17857. for (int chan = 0; chan < numChannels; ++chan)
  17858. channels.getUnchecked(chan)->getData(i)->read (input);
  17859. }
  17860. void AudioThumbnail::saveTo (OutputStream& output) const
  17861. {
  17862. const ScopedLock sl (lock);
  17863. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17864. output.write ("jatm", 4);
  17865. output.writeInt (samplesPerThumbSample);
  17866. output.writeInt64 (totalSamples);
  17867. output.writeInt64 (numSamplesFinished);
  17868. output.writeInt (numThumbnailSamples);
  17869. output.writeInt (numChannels);
  17870. output.writeInt ((int) sampleRate);
  17871. output.writeInt64 (0);
  17872. output.writeInt64 (0);
  17873. for (int i = 0; i < numThumbnailSamples; ++i)
  17874. for (int chan = 0; chan < numChannels; ++chan)
  17875. channels.getUnchecked(chan)->getData(i)->write (output);
  17876. }
  17877. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17878. {
  17879. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17880. numSamplesFinished = 0;
  17881. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17882. {
  17883. source = newSource; // (make sure this isn't done before loadThumb is called)
  17884. source->lengthInSamples = totalSamples;
  17885. source->sampleRate = sampleRate;
  17886. source->numChannels = numChannels;
  17887. source->numSamplesFinished = numSamplesFinished;
  17888. }
  17889. else
  17890. {
  17891. source = newSource; // (make sure this isn't done before loadThumb is called)
  17892. const ScopedLock sl (lock);
  17893. source->initialise (numSamplesFinished);
  17894. totalSamples = source->lengthInSamples;
  17895. sampleRate = source->sampleRate;
  17896. numChannels = source->numChannels;
  17897. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17898. }
  17899. return sampleRate > 0 && totalSamples > 0;
  17900. }
  17901. bool AudioThumbnail::setSource (InputSource* const newSource)
  17902. {
  17903. clear();
  17904. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17905. }
  17906. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17907. {
  17908. clear();
  17909. if (newReader != 0)
  17910. setDataSource (new LevelDataSource (*this, newReader, hash));
  17911. }
  17912. int64 AudioThumbnail::getHashCode() const
  17913. {
  17914. return source == 0 ? 0 : source->hashCode;
  17915. }
  17916. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17917. int startOffsetInBuffer, int numSamples)
  17918. {
  17919. jassert (startSample >= 0);
  17920. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17921. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17922. const int numToDo = lastThumbIndex - firstThumbIndex;
  17923. if (numToDo > 0)
  17924. {
  17925. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17926. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17927. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17928. for (int chan = 0; chan < numChans; ++chan)
  17929. {
  17930. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17931. MinMaxValue* const dest = thumbData + numToDo * chan;
  17932. thumbChannels [chan] = dest;
  17933. for (int i = 0; i < numToDo; ++i)
  17934. {
  17935. float low, high;
  17936. const int start = i * samplesPerThumbSample;
  17937. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17938. dest[i].setFloat (low, high);
  17939. }
  17940. }
  17941. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17942. }
  17943. }
  17944. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17945. {
  17946. const ScopedLock sl (lock);
  17947. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17948. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17949. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17950. totalSamples = jmax (numSamplesFinished, totalSamples);
  17951. window->invalidate();
  17952. sendChangeMessage();
  17953. }
  17954. int AudioThumbnail::getNumChannels() const throw()
  17955. {
  17956. return numChannels;
  17957. }
  17958. double AudioThumbnail::getTotalLength() const throw()
  17959. {
  17960. return totalSamples / sampleRate;
  17961. }
  17962. bool AudioThumbnail::isFullyLoaded() const throw()
  17963. {
  17964. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17965. }
  17966. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17967. {
  17968. return numSamplesFinished;
  17969. }
  17970. float AudioThumbnail::getApproximatePeak() const
  17971. {
  17972. int peak = 0;
  17973. for (int i = channels.size(); --i >= 0;)
  17974. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17975. return jlimit (0, 127, peak) / 127.0f;
  17976. }
  17977. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17978. double endTime, int channelNum, float verticalZoomFactor)
  17979. {
  17980. const ScopedLock sl (lock);
  17981. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17982. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17983. }
  17984. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17985. double endTimeSeconds, float verticalZoomFactor)
  17986. {
  17987. for (int i = 0; i < numChannels; ++i)
  17988. {
  17989. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17990. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17991. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17992. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17993. }
  17994. }
  17995. END_JUCE_NAMESPACE
  17996. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17997. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17998. BEGIN_JUCE_NAMESPACE
  17999. struct ThumbnailCacheEntry
  18000. {
  18001. int64 hash;
  18002. uint32 lastUsed;
  18003. MemoryBlock data;
  18004. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  18005. };
  18006. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18007. : TimeSliceThread ("thumb cache"),
  18008. maxNumThumbsToStore (maxNumThumbsToStore_)
  18009. {
  18010. startThread (2);
  18011. }
  18012. AudioThumbnailCache::~AudioThumbnailCache()
  18013. {
  18014. }
  18015. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  18016. {
  18017. for (int i = thumbs.size(); --i >= 0;)
  18018. if (thumbs.getUnchecked(i)->hash == hash)
  18019. return thumbs.getUnchecked(i);
  18020. return 0;
  18021. }
  18022. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18023. {
  18024. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18025. if (te != 0)
  18026. {
  18027. te->lastUsed = Time::getMillisecondCounter();
  18028. MemoryInputStream in (te->data, false);
  18029. thumb.loadFrom (in);
  18030. return true;
  18031. }
  18032. return false;
  18033. }
  18034. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18035. const int64 hashCode)
  18036. {
  18037. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  18038. if (te == 0)
  18039. {
  18040. te = new ThumbnailCacheEntry();
  18041. te->hash = hashCode;
  18042. if (thumbs.size() < maxNumThumbsToStore)
  18043. {
  18044. thumbs.add (te);
  18045. }
  18046. else
  18047. {
  18048. int oldest = 0;
  18049. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  18050. for (int i = thumbs.size(); --i >= 0;)
  18051. {
  18052. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  18053. {
  18054. oldest = i;
  18055. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  18056. }
  18057. }
  18058. thumbs.set (oldest, te);
  18059. }
  18060. }
  18061. te->lastUsed = Time::getMillisecondCounter();
  18062. MemoryOutputStream out (te->data, false);
  18063. thumb.saveTo (out);
  18064. }
  18065. void AudioThumbnailCache::clear()
  18066. {
  18067. thumbs.clear();
  18068. }
  18069. END_JUCE_NAMESPACE
  18070. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18071. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18072. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18073. #if ! JUCE_WINDOWS
  18074. #include <QuickTime/Movies.h>
  18075. #include <QuickTime/QTML.h>
  18076. #include <QuickTime/QuickTimeComponents.h>
  18077. #include <QuickTime/MediaHandlers.h>
  18078. #include <QuickTime/ImageCodec.h>
  18079. #else
  18080. #if JUCE_MSVC
  18081. #pragma warning (push)
  18082. #pragma warning (disable : 4100)
  18083. #endif
  18084. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18085. add its header directory to your include path.
  18086. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18087. flag in juce_Config.h
  18088. */
  18089. #include <Movies.h>
  18090. #include <QTML.h>
  18091. #include <QuickTimeComponents.h>
  18092. #include <MediaHandlers.h>
  18093. #include <ImageCodec.h>
  18094. #if JUCE_MSVC
  18095. #pragma warning (pop)
  18096. #endif
  18097. #endif
  18098. BEGIN_JUCE_NAMESPACE
  18099. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18100. static const char* const quickTimeFormatName = "QuickTime file";
  18101. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18102. class QTAudioReader : public AudioFormatReader
  18103. {
  18104. public:
  18105. QTAudioReader (InputStream* const input_, const int trackNum_)
  18106. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18107. ok (false),
  18108. movie (0),
  18109. trackNum (trackNum_),
  18110. lastSampleRead (0),
  18111. lastThreadId (0),
  18112. extractor (0),
  18113. dataHandle (0)
  18114. {
  18115. JUCE_AUTORELEASEPOOL
  18116. bufferList.calloc (256, 1);
  18117. #if JUCE_WINDOWS
  18118. if (InitializeQTML (0) != noErr)
  18119. return;
  18120. #endif
  18121. if (EnterMovies() != noErr)
  18122. return;
  18123. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18124. if (! opened)
  18125. return;
  18126. {
  18127. const int numTracks = GetMovieTrackCount (movie);
  18128. int trackCount = 0;
  18129. for (int i = 1; i <= numTracks; ++i)
  18130. {
  18131. track = GetMovieIndTrack (movie, i);
  18132. media = GetTrackMedia (track);
  18133. OSType mediaType;
  18134. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18135. if (mediaType == SoundMediaType
  18136. && trackCount++ == trackNum_)
  18137. {
  18138. ok = true;
  18139. break;
  18140. }
  18141. }
  18142. }
  18143. if (! ok)
  18144. return;
  18145. ok = false;
  18146. lengthInSamples = GetMediaDecodeDuration (media);
  18147. usesFloatingPointData = false;
  18148. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18149. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18150. / GetMediaTimeScale (media);
  18151. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18152. unsigned long output_layout_size;
  18153. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18154. kQTPropertyClass_MovieAudioExtraction_Audio,
  18155. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18156. 0, &output_layout_size, 0);
  18157. if (err != noErr)
  18158. return;
  18159. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18160. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18161. err = MovieAudioExtractionGetProperty (extractor,
  18162. kQTPropertyClass_MovieAudioExtraction_Audio,
  18163. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18164. output_layout_size, qt_audio_channel_layout, 0);
  18165. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18166. err = MovieAudioExtractionSetProperty (extractor,
  18167. kQTPropertyClass_MovieAudioExtraction_Audio,
  18168. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18169. output_layout_size,
  18170. qt_audio_channel_layout);
  18171. err = MovieAudioExtractionGetProperty (extractor,
  18172. kQTPropertyClass_MovieAudioExtraction_Audio,
  18173. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18174. sizeof (inputStreamDesc),
  18175. &inputStreamDesc, 0);
  18176. if (err != noErr)
  18177. return;
  18178. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18179. | kAudioFormatFlagIsPacked
  18180. | kAudioFormatFlagsNativeEndian;
  18181. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18182. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18183. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18184. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18185. err = MovieAudioExtractionSetProperty (extractor,
  18186. kQTPropertyClass_MovieAudioExtraction_Audio,
  18187. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18188. sizeof (inputStreamDesc),
  18189. &inputStreamDesc);
  18190. if (err != noErr)
  18191. return;
  18192. Boolean allChannelsDiscrete = false;
  18193. err = MovieAudioExtractionSetProperty (extractor,
  18194. kQTPropertyClass_MovieAudioExtraction_Movie,
  18195. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18196. sizeof (allChannelsDiscrete),
  18197. &allChannelsDiscrete);
  18198. if (err != noErr)
  18199. return;
  18200. bufferList->mNumberBuffers = 1;
  18201. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18202. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18203. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18204. bufferList->mBuffers[0].mData = dataBuffer;
  18205. sampleRate = inputStreamDesc.mSampleRate;
  18206. bitsPerSample = 16;
  18207. numChannels = inputStreamDesc.mChannelsPerFrame;
  18208. detachThread();
  18209. ok = true;
  18210. }
  18211. ~QTAudioReader()
  18212. {
  18213. JUCE_AUTORELEASEPOOL
  18214. checkThreadIsAttached();
  18215. if (dataHandle != 0)
  18216. DisposeHandle (dataHandle);
  18217. if (extractor != 0)
  18218. {
  18219. MovieAudioExtractionEnd (extractor);
  18220. extractor = 0;
  18221. }
  18222. DisposeMovie (movie);
  18223. #if JUCE_MAC
  18224. ExitMoviesOnThread ();
  18225. #endif
  18226. }
  18227. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18228. int64 startSampleInFile, int numSamples)
  18229. {
  18230. JUCE_AUTORELEASEPOOL
  18231. checkThreadIsAttached();
  18232. bool ok = true;
  18233. while (numSamples > 0)
  18234. {
  18235. if (lastSampleRead != startSampleInFile)
  18236. {
  18237. TimeRecord time;
  18238. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18239. time.base = 0;
  18240. time.value.hi = 0;
  18241. time.value.lo = (UInt32) startSampleInFile;
  18242. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18243. kQTPropertyClass_MovieAudioExtraction_Movie,
  18244. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18245. sizeof (time), &time);
  18246. if (err != noErr)
  18247. {
  18248. ok = false;
  18249. break;
  18250. }
  18251. }
  18252. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18253. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18254. UInt32 outFlags = 0;
  18255. UInt32 actualNumFrames = framesToDo;
  18256. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18257. if (err != noErr)
  18258. {
  18259. ok = false;
  18260. break;
  18261. }
  18262. lastSampleRead = startSampleInFile + actualNumFrames;
  18263. const int samplesReceived = actualNumFrames;
  18264. for (int j = numDestChannels; --j >= 0;)
  18265. {
  18266. if (destSamples[j] != 0)
  18267. {
  18268. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18269. for (int i = 0; i < samplesReceived; ++i)
  18270. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18271. }
  18272. }
  18273. startOffsetInDestBuffer += samplesReceived;
  18274. startSampleInFile += samplesReceived;
  18275. numSamples -= samplesReceived;
  18276. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18277. {
  18278. for (int j = numDestChannels; --j >= 0;)
  18279. if (destSamples[j] != 0)
  18280. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18281. break;
  18282. }
  18283. }
  18284. detachThread();
  18285. return ok;
  18286. }
  18287. bool ok;
  18288. private:
  18289. Movie movie;
  18290. Media media;
  18291. Track track;
  18292. const int trackNum;
  18293. double trackUnitsPerFrame;
  18294. int samplesPerFrame;
  18295. int64 lastSampleRead;
  18296. Thread::ThreadID lastThreadId;
  18297. MovieAudioExtractionRef extractor;
  18298. AudioStreamBasicDescription inputStreamDesc;
  18299. HeapBlock <AudioBufferList> bufferList;
  18300. HeapBlock <char> dataBuffer;
  18301. Handle dataHandle;
  18302. void checkThreadIsAttached()
  18303. {
  18304. #if JUCE_MAC
  18305. if (Thread::getCurrentThreadId() != lastThreadId)
  18306. EnterMoviesOnThread (0);
  18307. AttachMovieToCurrentThread (movie);
  18308. #endif
  18309. }
  18310. void detachThread()
  18311. {
  18312. #if JUCE_MAC
  18313. DetachMovieFromCurrentThread (movie);
  18314. #endif
  18315. }
  18316. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18317. };
  18318. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18319. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18320. {
  18321. }
  18322. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18323. {
  18324. }
  18325. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18326. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18327. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18328. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18329. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18330. const bool deleteStreamIfOpeningFails)
  18331. {
  18332. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18333. if (r->ok)
  18334. return r.release();
  18335. if (! deleteStreamIfOpeningFails)
  18336. r->input = 0;
  18337. return 0;
  18338. }
  18339. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18340. double /*sampleRateToUse*/,
  18341. unsigned int /*numberOfChannels*/,
  18342. int /*bitsPerSample*/,
  18343. const StringPairArray& /*metadataValues*/,
  18344. int /*qualityOptionIndex*/)
  18345. {
  18346. jassertfalse; // not yet implemented!
  18347. return 0;
  18348. }
  18349. END_JUCE_NAMESPACE
  18350. #endif
  18351. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18352. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18353. BEGIN_JUCE_NAMESPACE
  18354. static const char* const wavFormatName = "WAV file";
  18355. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18356. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18357. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18358. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18359. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18360. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18361. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18362. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18363. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18364. const String& originator,
  18365. const String& originatorRef,
  18366. const Time& date,
  18367. const int64 timeReferenceSamples,
  18368. const String& codingHistory)
  18369. {
  18370. StringPairArray m;
  18371. m.set (bwavDescription, description);
  18372. m.set (bwavOriginator, originator);
  18373. m.set (bwavOriginatorRef, originatorRef);
  18374. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18375. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18376. m.set (bwavTimeReference, String (timeReferenceSamples));
  18377. m.set (bwavCodingHistory, codingHistory);
  18378. return m;
  18379. }
  18380. #if JUCE_MSVC
  18381. #pragma pack (push, 1)
  18382. #define PACKED
  18383. #elif JUCE_GCC
  18384. #define PACKED __attribute__((packed))
  18385. #else
  18386. #define PACKED
  18387. #endif
  18388. struct BWAVChunk
  18389. {
  18390. char description [256];
  18391. char originator [32];
  18392. char originatorRef [32];
  18393. char originationDate [10];
  18394. char originationTime [8];
  18395. uint32 timeRefLow;
  18396. uint32 timeRefHigh;
  18397. uint16 version;
  18398. uint8 umid[64];
  18399. uint8 reserved[190];
  18400. char codingHistory[1];
  18401. void copyTo (StringPairArray& values) const
  18402. {
  18403. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18404. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18405. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18406. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18407. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18408. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18409. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18410. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18411. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18412. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18413. }
  18414. static MemoryBlock createFrom (const StringPairArray& values)
  18415. {
  18416. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18417. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18418. data.fillWith (0);
  18419. BWAVChunk* b = (BWAVChunk*) data.getData();
  18420. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18421. // as they get called in the right order..
  18422. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18423. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18424. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18425. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18426. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18427. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18428. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18429. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18430. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18431. if (b->description[0] != 0
  18432. || b->originator[0] != 0
  18433. || b->originationDate[0] != 0
  18434. || b->originationTime[0] != 0
  18435. || b->codingHistory[0] != 0
  18436. || time != 0)
  18437. {
  18438. return data;
  18439. }
  18440. return MemoryBlock();
  18441. }
  18442. } PACKED;
  18443. struct SMPLChunk
  18444. {
  18445. struct SampleLoop
  18446. {
  18447. uint32 identifier;
  18448. uint32 type;
  18449. uint32 start;
  18450. uint32 end;
  18451. uint32 fraction;
  18452. uint32 playCount;
  18453. } PACKED;
  18454. uint32 manufacturer;
  18455. uint32 product;
  18456. uint32 samplePeriod;
  18457. uint32 midiUnityNote;
  18458. uint32 midiPitchFraction;
  18459. uint32 smpteFormat;
  18460. uint32 smpteOffset;
  18461. uint32 numSampleLoops;
  18462. uint32 samplerData;
  18463. SampleLoop loops[1];
  18464. void copyTo (StringPairArray& values, const int totalSize) const
  18465. {
  18466. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18467. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18468. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18469. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18470. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18471. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18472. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18473. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18474. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18475. for (uint32 i = 0; i < numSampleLoops; ++i)
  18476. {
  18477. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18478. break;
  18479. const String prefix ("Loop" + String(i));
  18480. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18481. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18482. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18483. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18484. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18485. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18486. }
  18487. }
  18488. static MemoryBlock createFrom (const StringPairArray& values)
  18489. {
  18490. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18491. if (numLoops <= 0)
  18492. return MemoryBlock();
  18493. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18494. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18495. data.fillWith (0);
  18496. SMPLChunk* s = (SMPLChunk*) data.getData();
  18497. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18498. // as they get called in the right order..
  18499. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18500. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18501. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18502. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18503. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18504. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18505. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18506. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18507. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18508. for (int i = 0; i < numLoops; ++i)
  18509. {
  18510. const String prefix ("Loop" + String(i));
  18511. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18512. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18513. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18514. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18515. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18516. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18517. }
  18518. return data;
  18519. }
  18520. } PACKED;
  18521. struct ExtensibleWavSubFormat
  18522. {
  18523. uint32 data1;
  18524. uint16 data2;
  18525. uint16 data3;
  18526. uint8 data4[8];
  18527. } PACKED;
  18528. #if JUCE_MSVC
  18529. #pragma pack (pop)
  18530. #endif
  18531. #undef PACKED
  18532. class WavAudioFormatReader : public AudioFormatReader
  18533. {
  18534. public:
  18535. WavAudioFormatReader (InputStream* const in)
  18536. : AudioFormatReader (in, TRANS (wavFormatName)),
  18537. bwavChunkStart (0),
  18538. bwavSize (0),
  18539. dataLength (0)
  18540. {
  18541. if (input->readInt() == chunkName ("RIFF"))
  18542. {
  18543. const uint32 len = (uint32) input->readInt();
  18544. const int64 end = input->getPosition() + len;
  18545. bool hasGotType = false;
  18546. bool hasGotData = false;
  18547. if (input->readInt() == chunkName ("WAVE"))
  18548. {
  18549. while (input->getPosition() < end
  18550. && ! input->isExhausted())
  18551. {
  18552. const int chunkType = input->readInt();
  18553. uint32 length = (uint32) input->readInt();
  18554. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18555. if (chunkType == chunkName ("fmt "))
  18556. {
  18557. // read the format chunk
  18558. const unsigned short format = input->readShort();
  18559. const short numChans = input->readShort();
  18560. sampleRate = input->readInt();
  18561. const int bytesPerSec = input->readInt();
  18562. numChannels = numChans;
  18563. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18564. bitsPerSample = 8 * bytesPerFrame / numChans;
  18565. if (format == 3)
  18566. {
  18567. usesFloatingPointData = true;
  18568. }
  18569. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18570. {
  18571. if (length < 40) // too short
  18572. {
  18573. bytesPerFrame = 0;
  18574. }
  18575. else
  18576. {
  18577. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18578. ExtensibleWavSubFormat subFormat;
  18579. subFormat.data1 = input->readInt();
  18580. subFormat.data2 = input->readShort();
  18581. subFormat.data3 = input->readShort();
  18582. input->read (subFormat.data4, sizeof (subFormat.data4));
  18583. const ExtensibleWavSubFormat pcmFormat
  18584. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18585. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18586. {
  18587. const ExtensibleWavSubFormat ambisonicFormat
  18588. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18589. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18590. bytesPerFrame = 0;
  18591. }
  18592. }
  18593. }
  18594. else if (format != 1)
  18595. {
  18596. bytesPerFrame = 0;
  18597. }
  18598. hasGotType = true;
  18599. }
  18600. else if (chunkType == chunkName ("data"))
  18601. {
  18602. // get the data chunk's position
  18603. dataLength = length;
  18604. dataChunkStart = input->getPosition();
  18605. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18606. hasGotData = true;
  18607. }
  18608. else if (chunkType == chunkName ("bext"))
  18609. {
  18610. bwavChunkStart = input->getPosition();
  18611. bwavSize = length;
  18612. // Broadcast-wav extension chunk..
  18613. HeapBlock <BWAVChunk> bwav;
  18614. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18615. input->read (bwav, length);
  18616. bwav->copyTo (metadataValues);
  18617. }
  18618. else if (chunkType == chunkName ("smpl"))
  18619. {
  18620. HeapBlock <SMPLChunk> smpl;
  18621. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18622. input->read (smpl, length);
  18623. smpl->copyTo (metadataValues, length);
  18624. }
  18625. else if (chunkEnd <= input->getPosition())
  18626. {
  18627. break;
  18628. }
  18629. input->setPosition (chunkEnd);
  18630. }
  18631. }
  18632. }
  18633. }
  18634. ~WavAudioFormatReader()
  18635. {
  18636. }
  18637. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18638. int64 startSampleInFile, int numSamples)
  18639. {
  18640. jassert (destSamples != 0);
  18641. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18642. if (samplesAvailable < numSamples)
  18643. {
  18644. for (int i = numDestChannels; --i >= 0;)
  18645. if (destSamples[i] != 0)
  18646. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18647. numSamples = (int) samplesAvailable;
  18648. }
  18649. if (numSamples <= 0)
  18650. return true;
  18651. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18652. while (numSamples > 0)
  18653. {
  18654. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18655. char tempBuffer [tempBufSize];
  18656. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18657. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18658. if (bytesRead < numThisTime * bytesPerFrame)
  18659. {
  18660. jassert (bytesRead >= 0);
  18661. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18662. }
  18663. switch (bitsPerSample)
  18664. {
  18665. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18666. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18667. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18668. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18669. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18670. default: jassertfalse; break;
  18671. }
  18672. startOffsetInDestBuffer += numThisTime;
  18673. numSamples -= numThisTime;
  18674. }
  18675. return true;
  18676. }
  18677. int64 bwavChunkStart, bwavSize;
  18678. private:
  18679. ScopedPointer<AudioData::Converter> converter;
  18680. int bytesPerFrame;
  18681. int64 dataChunkStart, dataLength;
  18682. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18683. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18684. };
  18685. class WavAudioFormatWriter : public AudioFormatWriter
  18686. {
  18687. public:
  18688. WavAudioFormatWriter (OutputStream* const out,
  18689. const double sampleRate_,
  18690. const unsigned int numChannels_,
  18691. const int bits,
  18692. const StringPairArray& metadataValues)
  18693. : AudioFormatWriter (out,
  18694. TRANS (wavFormatName),
  18695. sampleRate_,
  18696. numChannels_,
  18697. bits),
  18698. lengthInSamples (0),
  18699. bytesWritten (0),
  18700. writeFailed (false)
  18701. {
  18702. if (metadataValues.size() > 0)
  18703. {
  18704. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18705. smplChunk = SMPLChunk::createFrom (metadataValues);
  18706. }
  18707. headerPosition = out->getPosition();
  18708. writeHeader();
  18709. }
  18710. ~WavAudioFormatWriter()
  18711. {
  18712. writeHeader();
  18713. }
  18714. bool write (const int** data, int numSamples)
  18715. {
  18716. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18717. if (writeFailed)
  18718. return false;
  18719. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18720. tempBlock.ensureSize (bytes, false);
  18721. switch (bitsPerSample)
  18722. {
  18723. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18724. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18725. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18726. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18727. default: jassertfalse; break;
  18728. }
  18729. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18730. || ! output->write (tempBlock.getData(), bytes))
  18731. {
  18732. // failed to write to disk, so let's try writing the header.
  18733. // If it's just run out of disk space, then if it does manage
  18734. // to write the header, we'll still have a useable file..
  18735. writeHeader();
  18736. writeFailed = true;
  18737. return false;
  18738. }
  18739. else
  18740. {
  18741. bytesWritten += bytes;
  18742. lengthInSamples += numSamples;
  18743. return true;
  18744. }
  18745. }
  18746. private:
  18747. ScopedPointer<AudioData::Converter> converter;
  18748. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18749. uint32 lengthInSamples, bytesWritten;
  18750. int64 headerPosition;
  18751. bool writeFailed;
  18752. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18753. void writeHeader()
  18754. {
  18755. const bool seekedOk = output->setPosition (headerPosition);
  18756. (void) seekedOk;
  18757. // if this fails, you've given it an output stream that can't seek! It needs
  18758. // to be able to seek back to write the header
  18759. jassert (seekedOk);
  18760. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18761. output->writeInt (chunkName ("RIFF"));
  18762. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18763. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18764. output->writeInt (chunkName ("WAVE"));
  18765. output->writeInt (chunkName ("fmt "));
  18766. output->writeInt (16);
  18767. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18768. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18769. output->writeShort ((short) numChannels);
  18770. output->writeInt ((int) sampleRate);
  18771. output->writeInt (bytesPerFrame * (int) sampleRate);
  18772. output->writeShort ((short) bytesPerFrame);
  18773. output->writeShort ((short) bitsPerSample);
  18774. if (bwavChunk.getSize() > 0)
  18775. {
  18776. output->writeInt (chunkName ("bext"));
  18777. output->writeInt ((int) bwavChunk.getSize());
  18778. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18779. }
  18780. if (smplChunk.getSize() > 0)
  18781. {
  18782. output->writeInt (chunkName ("smpl"));
  18783. output->writeInt ((int) smplChunk.getSize());
  18784. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18785. }
  18786. output->writeInt (chunkName ("data"));
  18787. output->writeInt (lengthInSamples * bytesPerFrame);
  18788. usesFloatingPointData = (bitsPerSample == 32);
  18789. }
  18790. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18791. };
  18792. WavAudioFormat::WavAudioFormat()
  18793. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18794. {
  18795. }
  18796. WavAudioFormat::~WavAudioFormat()
  18797. {
  18798. }
  18799. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18800. {
  18801. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18802. return Array <int> (rates);
  18803. }
  18804. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18805. {
  18806. const int depths[] = { 8, 16, 24, 32, 0 };
  18807. return Array <int> (depths);
  18808. }
  18809. bool WavAudioFormat::canDoStereo() { return true; }
  18810. bool WavAudioFormat::canDoMono() { return true; }
  18811. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18812. const bool deleteStreamIfOpeningFails)
  18813. {
  18814. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18815. if (r->sampleRate != 0)
  18816. return r.release();
  18817. if (! deleteStreamIfOpeningFails)
  18818. r->input = 0;
  18819. return 0;
  18820. }
  18821. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18822. double sampleRate,
  18823. unsigned int numChannels,
  18824. int bitsPerSample,
  18825. const StringPairArray& metadataValues,
  18826. int /*qualityOptionIndex*/)
  18827. {
  18828. if (getPossibleBitDepths().contains (bitsPerSample))
  18829. {
  18830. return new WavAudioFormatWriter (out,
  18831. sampleRate,
  18832. numChannels,
  18833. bitsPerSample,
  18834. metadataValues);
  18835. }
  18836. return 0;
  18837. }
  18838. namespace
  18839. {
  18840. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18841. {
  18842. TemporaryFile tempFile (file);
  18843. WavAudioFormat wav;
  18844. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18845. if (reader != 0)
  18846. {
  18847. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18848. if (outStream != 0)
  18849. {
  18850. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18851. reader->numChannels, reader->bitsPerSample,
  18852. metadata, 0));
  18853. if (writer != 0)
  18854. {
  18855. outStream.release();
  18856. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18857. writer = 0;
  18858. reader = 0;
  18859. return ok && tempFile.overwriteTargetFileWithTemporary();
  18860. }
  18861. }
  18862. }
  18863. return false;
  18864. }
  18865. }
  18866. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18867. {
  18868. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18869. if (reader != 0)
  18870. {
  18871. const int64 bwavPos = reader->bwavChunkStart;
  18872. const int64 bwavSize = reader->bwavSize;
  18873. reader = 0;
  18874. if (bwavSize > 0)
  18875. {
  18876. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18877. if (chunk.getSize() <= (size_t) bwavSize)
  18878. {
  18879. // the new one will fit in the space available, so write it directly..
  18880. const int64 oldSize = wavFile.getSize();
  18881. {
  18882. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18883. out->setPosition (bwavPos);
  18884. out->write (chunk.getData(), (int) chunk.getSize());
  18885. out->setPosition (oldSize);
  18886. }
  18887. jassert (wavFile.getSize() == oldSize);
  18888. return true;
  18889. }
  18890. }
  18891. }
  18892. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18893. }
  18894. END_JUCE_NAMESPACE
  18895. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18896. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18897. #if JUCE_USE_CDREADER
  18898. BEGIN_JUCE_NAMESPACE
  18899. int AudioCDReader::getNumTracks() const
  18900. {
  18901. return trackStartSamples.size() - 1;
  18902. }
  18903. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18904. {
  18905. return trackStartSamples [trackNum];
  18906. }
  18907. const Array<int>& AudioCDReader::getTrackOffsets() const
  18908. {
  18909. return trackStartSamples;
  18910. }
  18911. int AudioCDReader::getCDDBId()
  18912. {
  18913. int checksum = 0;
  18914. const int numTracks = getNumTracks();
  18915. for (int i = 0; i < numTracks; ++i)
  18916. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18917. checksum += offset % 10;
  18918. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18919. // CCLLLLTT: checksum, length, tracks
  18920. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18921. }
  18922. END_JUCE_NAMESPACE
  18923. #endif
  18924. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18925. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18926. BEGIN_JUCE_NAMESPACE
  18927. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18928. const bool deleteReaderWhenThisIsDeleted)
  18929. : reader (reader_),
  18930. deleteReader (deleteReaderWhenThisIsDeleted),
  18931. nextPlayPos (0),
  18932. looping (false)
  18933. {
  18934. jassert (reader != 0);
  18935. }
  18936. AudioFormatReaderSource::~AudioFormatReaderSource()
  18937. {
  18938. releaseResources();
  18939. if (deleteReader)
  18940. delete reader;
  18941. }
  18942. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18943. {
  18944. nextPlayPos = newPosition;
  18945. }
  18946. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18947. {
  18948. looping = shouldLoop;
  18949. }
  18950. int AudioFormatReaderSource::getNextReadPosition() const
  18951. {
  18952. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18953. : nextPlayPos;
  18954. }
  18955. int AudioFormatReaderSource::getTotalLength() const
  18956. {
  18957. return (int) reader->lengthInSamples;
  18958. }
  18959. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18960. double /*sampleRate*/)
  18961. {
  18962. }
  18963. void AudioFormatReaderSource::releaseResources()
  18964. {
  18965. }
  18966. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18967. {
  18968. if (info.numSamples > 0)
  18969. {
  18970. const int start = nextPlayPos;
  18971. if (looping)
  18972. {
  18973. const int newStart = start % (int) reader->lengthInSamples;
  18974. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18975. if (newEnd > newStart)
  18976. {
  18977. info.buffer->readFromAudioReader (reader,
  18978. info.startSample,
  18979. newEnd - newStart,
  18980. newStart,
  18981. true, true);
  18982. }
  18983. else
  18984. {
  18985. const int endSamps = (int) reader->lengthInSamples - newStart;
  18986. info.buffer->readFromAudioReader (reader,
  18987. info.startSample,
  18988. endSamps,
  18989. newStart,
  18990. true, true);
  18991. info.buffer->readFromAudioReader (reader,
  18992. info.startSample + endSamps,
  18993. newEnd,
  18994. 0,
  18995. true, true);
  18996. }
  18997. nextPlayPos = newEnd;
  18998. }
  18999. else
  19000. {
  19001. info.buffer->readFromAudioReader (reader,
  19002. info.startSample,
  19003. info.numSamples,
  19004. start,
  19005. true, true);
  19006. nextPlayPos += info.numSamples;
  19007. }
  19008. }
  19009. }
  19010. END_JUCE_NAMESPACE
  19011. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19012. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19013. BEGIN_JUCE_NAMESPACE
  19014. AudioSourcePlayer::AudioSourcePlayer()
  19015. : source (0),
  19016. sampleRate (0),
  19017. bufferSize (0),
  19018. tempBuffer (2, 8),
  19019. lastGain (1.0f),
  19020. gain (1.0f)
  19021. {
  19022. }
  19023. AudioSourcePlayer::~AudioSourcePlayer()
  19024. {
  19025. setSource (0);
  19026. }
  19027. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19028. {
  19029. if (source != newSource)
  19030. {
  19031. AudioSource* const oldSource = source;
  19032. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19033. newSource->prepareToPlay (bufferSize, sampleRate);
  19034. {
  19035. const ScopedLock sl (readLock);
  19036. source = newSource;
  19037. }
  19038. if (oldSource != 0)
  19039. oldSource->releaseResources();
  19040. }
  19041. }
  19042. void AudioSourcePlayer::setGain (const float newGain) throw()
  19043. {
  19044. gain = newGain;
  19045. }
  19046. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19047. int totalNumInputChannels,
  19048. float** outputChannelData,
  19049. int totalNumOutputChannels,
  19050. int numSamples)
  19051. {
  19052. // these should have been prepared by audioDeviceAboutToStart()...
  19053. jassert (sampleRate > 0 && bufferSize > 0);
  19054. const ScopedLock sl (readLock);
  19055. if (source != 0)
  19056. {
  19057. AudioSourceChannelInfo info;
  19058. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19059. // messy stuff needed to compact the channels down into an array
  19060. // of non-zero pointers..
  19061. for (i = 0; i < totalNumInputChannels; ++i)
  19062. {
  19063. if (inputChannelData[i] != 0)
  19064. {
  19065. inputChans [numInputs++] = inputChannelData[i];
  19066. if (numInputs >= numElementsInArray (inputChans))
  19067. break;
  19068. }
  19069. }
  19070. for (i = 0; i < totalNumOutputChannels; ++i)
  19071. {
  19072. if (outputChannelData[i] != 0)
  19073. {
  19074. outputChans [numOutputs++] = outputChannelData[i];
  19075. if (numOutputs >= numElementsInArray (outputChans))
  19076. break;
  19077. }
  19078. }
  19079. if (numInputs > numOutputs)
  19080. {
  19081. // if there aren't enough output channels for the number of
  19082. // inputs, we need to create some temporary extra ones (can't
  19083. // use the input data in case it gets written to)
  19084. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19085. false, false, true);
  19086. for (i = 0; i < numOutputs; ++i)
  19087. {
  19088. channels[numActiveChans] = outputChans[i];
  19089. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19090. ++numActiveChans;
  19091. }
  19092. for (i = numOutputs; i < numInputs; ++i)
  19093. {
  19094. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19095. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19096. ++numActiveChans;
  19097. }
  19098. }
  19099. else
  19100. {
  19101. for (i = 0; i < numInputs; ++i)
  19102. {
  19103. channels[numActiveChans] = outputChans[i];
  19104. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19105. ++numActiveChans;
  19106. }
  19107. for (i = numInputs; i < numOutputs; ++i)
  19108. {
  19109. channels[numActiveChans] = outputChans[i];
  19110. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19111. ++numActiveChans;
  19112. }
  19113. }
  19114. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19115. info.buffer = &buffer;
  19116. info.startSample = 0;
  19117. info.numSamples = numSamples;
  19118. source->getNextAudioBlock (info);
  19119. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19120. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19121. lastGain = gain;
  19122. }
  19123. else
  19124. {
  19125. for (int i = 0; i < totalNumOutputChannels; ++i)
  19126. if (outputChannelData[i] != 0)
  19127. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19128. }
  19129. }
  19130. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19131. {
  19132. sampleRate = device->getCurrentSampleRate();
  19133. bufferSize = device->getCurrentBufferSizeSamples();
  19134. zeromem (channels, sizeof (channels));
  19135. if (source != 0)
  19136. source->prepareToPlay (bufferSize, sampleRate);
  19137. }
  19138. void AudioSourcePlayer::audioDeviceStopped()
  19139. {
  19140. if (source != 0)
  19141. source->releaseResources();
  19142. sampleRate = 0.0;
  19143. bufferSize = 0;
  19144. tempBuffer.setSize (2, 8);
  19145. }
  19146. END_JUCE_NAMESPACE
  19147. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19148. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19149. BEGIN_JUCE_NAMESPACE
  19150. AudioTransportSource::AudioTransportSource()
  19151. : source (0),
  19152. resamplerSource (0),
  19153. bufferingSource (0),
  19154. positionableSource (0),
  19155. masterSource (0),
  19156. gain (1.0f),
  19157. lastGain (1.0f),
  19158. playing (false),
  19159. stopped (true),
  19160. sampleRate (44100.0),
  19161. sourceSampleRate (0.0),
  19162. blockSize (128),
  19163. readAheadBufferSize (0),
  19164. isPrepared (false),
  19165. inputStreamEOF (false)
  19166. {
  19167. }
  19168. AudioTransportSource::~AudioTransportSource()
  19169. {
  19170. setSource (0);
  19171. releaseResources();
  19172. }
  19173. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19174. int readAheadBufferSize_,
  19175. double sourceSampleRateToCorrectFor)
  19176. {
  19177. if (source == newSource)
  19178. {
  19179. if (source == 0)
  19180. return;
  19181. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19182. }
  19183. readAheadBufferSize = readAheadBufferSize_;
  19184. sourceSampleRate = sourceSampleRateToCorrectFor;
  19185. ResamplingAudioSource* newResamplerSource = 0;
  19186. BufferingAudioSource* newBufferingSource = 0;
  19187. PositionableAudioSource* newPositionableSource = 0;
  19188. AudioSource* newMasterSource = 0;
  19189. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19190. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19191. AudioSource* oldMasterSource = masterSource;
  19192. if (newSource != 0)
  19193. {
  19194. newPositionableSource = newSource;
  19195. if (readAheadBufferSize_ > 0)
  19196. newPositionableSource = newBufferingSource
  19197. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19198. newPositionableSource->setNextReadPosition (0);
  19199. if (sourceSampleRateToCorrectFor != 0)
  19200. newMasterSource = newResamplerSource
  19201. = new ResamplingAudioSource (newPositionableSource, false);
  19202. else
  19203. newMasterSource = newPositionableSource;
  19204. if (isPrepared)
  19205. {
  19206. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19207. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19208. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19209. }
  19210. }
  19211. {
  19212. const ScopedLock sl (callbackLock);
  19213. source = newSource;
  19214. resamplerSource = newResamplerSource;
  19215. bufferingSource = newBufferingSource;
  19216. masterSource = newMasterSource;
  19217. positionableSource = newPositionableSource;
  19218. playing = false;
  19219. }
  19220. if (oldMasterSource != 0)
  19221. oldMasterSource->releaseResources();
  19222. }
  19223. void AudioTransportSource::start()
  19224. {
  19225. if ((! playing) && masterSource != 0)
  19226. {
  19227. {
  19228. const ScopedLock sl (callbackLock);
  19229. playing = true;
  19230. stopped = false;
  19231. inputStreamEOF = false;
  19232. }
  19233. sendChangeMessage();
  19234. }
  19235. }
  19236. void AudioTransportSource::stop()
  19237. {
  19238. if (playing)
  19239. {
  19240. {
  19241. const ScopedLock sl (callbackLock);
  19242. playing = false;
  19243. }
  19244. int n = 500;
  19245. while (--n >= 0 && ! stopped)
  19246. Thread::sleep (2);
  19247. sendChangeMessage();
  19248. }
  19249. }
  19250. void AudioTransportSource::setPosition (double newPosition)
  19251. {
  19252. if (sampleRate > 0.0)
  19253. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19254. }
  19255. double AudioTransportSource::getCurrentPosition() const
  19256. {
  19257. if (sampleRate > 0.0)
  19258. return getNextReadPosition() / sampleRate;
  19259. else
  19260. return 0.0;
  19261. }
  19262. double AudioTransportSource::getLengthInSeconds() const
  19263. {
  19264. return getTotalLength() / sampleRate;
  19265. }
  19266. void AudioTransportSource::setNextReadPosition (int newPosition)
  19267. {
  19268. if (positionableSource != 0)
  19269. {
  19270. if (sampleRate > 0 && sourceSampleRate > 0)
  19271. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19272. positionableSource->setNextReadPosition (newPosition);
  19273. }
  19274. }
  19275. int AudioTransportSource::getNextReadPosition() const
  19276. {
  19277. if (positionableSource != 0)
  19278. {
  19279. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19280. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19281. }
  19282. return 0;
  19283. }
  19284. int AudioTransportSource::getTotalLength() const
  19285. {
  19286. const ScopedLock sl (callbackLock);
  19287. if (positionableSource != 0)
  19288. {
  19289. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19290. return roundToInt (positionableSource->getTotalLength() * ratio);
  19291. }
  19292. return 0;
  19293. }
  19294. bool AudioTransportSource::isLooping() const
  19295. {
  19296. const ScopedLock sl (callbackLock);
  19297. return positionableSource != 0
  19298. && positionableSource->isLooping();
  19299. }
  19300. void AudioTransportSource::setGain (const float newGain) throw()
  19301. {
  19302. gain = newGain;
  19303. }
  19304. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19305. double sampleRate_)
  19306. {
  19307. const ScopedLock sl (callbackLock);
  19308. sampleRate = sampleRate_;
  19309. blockSize = samplesPerBlockExpected;
  19310. if (masterSource != 0)
  19311. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19312. if (resamplerSource != 0 && sourceSampleRate != 0)
  19313. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19314. isPrepared = true;
  19315. }
  19316. void AudioTransportSource::releaseResources()
  19317. {
  19318. const ScopedLock sl (callbackLock);
  19319. if (masterSource != 0)
  19320. masterSource->releaseResources();
  19321. isPrepared = false;
  19322. }
  19323. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19324. {
  19325. const ScopedLock sl (callbackLock);
  19326. inputStreamEOF = false;
  19327. if (masterSource != 0 && ! stopped)
  19328. {
  19329. masterSource->getNextAudioBlock (info);
  19330. if (! playing)
  19331. {
  19332. // just stopped playing, so fade out the last block..
  19333. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19334. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19335. if (info.numSamples > 256)
  19336. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19337. }
  19338. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19339. && ! positionableSource->isLooping())
  19340. {
  19341. playing = false;
  19342. inputStreamEOF = true;
  19343. sendChangeMessage();
  19344. }
  19345. stopped = ! playing;
  19346. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19347. {
  19348. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19349. lastGain, gain);
  19350. }
  19351. }
  19352. else
  19353. {
  19354. info.clearActiveBufferRegion();
  19355. stopped = true;
  19356. }
  19357. lastGain = gain;
  19358. }
  19359. END_JUCE_NAMESPACE
  19360. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19361. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19362. BEGIN_JUCE_NAMESPACE
  19363. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19364. public Thread,
  19365. private Timer
  19366. {
  19367. public:
  19368. SharedBufferingAudioSourceThread()
  19369. : Thread ("Audio Buffer")
  19370. {
  19371. }
  19372. ~SharedBufferingAudioSourceThread()
  19373. {
  19374. stopThread (10000);
  19375. clearSingletonInstance();
  19376. }
  19377. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19378. void addSource (BufferingAudioSource* source)
  19379. {
  19380. const ScopedLock sl (lock);
  19381. if (! sources.contains (source))
  19382. {
  19383. sources.add (source);
  19384. startThread();
  19385. stopTimer();
  19386. }
  19387. notify();
  19388. }
  19389. void removeSource (BufferingAudioSource* source)
  19390. {
  19391. const ScopedLock sl (lock);
  19392. sources.removeValue (source);
  19393. if (sources.size() == 0)
  19394. startTimer (5000);
  19395. }
  19396. private:
  19397. Array <BufferingAudioSource*> sources;
  19398. CriticalSection lock;
  19399. void run()
  19400. {
  19401. while (! threadShouldExit())
  19402. {
  19403. bool busy = false;
  19404. for (int i = sources.size(); --i >= 0;)
  19405. {
  19406. if (threadShouldExit())
  19407. return;
  19408. const ScopedLock sl (lock);
  19409. BufferingAudioSource* const b = sources[i];
  19410. if (b != 0 && b->readNextBufferChunk())
  19411. busy = true;
  19412. }
  19413. if (! busy)
  19414. wait (500);
  19415. }
  19416. }
  19417. void timerCallback()
  19418. {
  19419. stopTimer();
  19420. if (sources.size() == 0)
  19421. deleteInstance();
  19422. }
  19423. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19424. };
  19425. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19426. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19427. const bool deleteSourceWhenDeleted_,
  19428. int numberOfSamplesToBuffer_)
  19429. : source (source_),
  19430. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19431. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19432. buffer (2, 0),
  19433. bufferValidStart (0),
  19434. bufferValidEnd (0),
  19435. nextPlayPos (0),
  19436. wasSourceLooping (false)
  19437. {
  19438. jassert (source_ != 0);
  19439. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19440. // not using a larger buffer..
  19441. }
  19442. BufferingAudioSource::~BufferingAudioSource()
  19443. {
  19444. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19445. if (thread != 0)
  19446. thread->removeSource (this);
  19447. if (deleteSourceWhenDeleted)
  19448. delete source;
  19449. }
  19450. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19451. {
  19452. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19453. sampleRate = sampleRate_;
  19454. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19455. buffer.clear();
  19456. bufferValidStart = 0;
  19457. bufferValidEnd = 0;
  19458. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19459. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19460. buffer.getNumSamples() / 2))
  19461. {
  19462. SharedBufferingAudioSourceThread::getInstance()->notify();
  19463. Thread::sleep (5);
  19464. }
  19465. }
  19466. void BufferingAudioSource::releaseResources()
  19467. {
  19468. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19469. if (thread != 0)
  19470. thread->removeSource (this);
  19471. buffer.setSize (2, 0);
  19472. source->releaseResources();
  19473. }
  19474. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19475. {
  19476. const ScopedLock sl (bufferStartPosLock);
  19477. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19478. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19479. if (validStart == validEnd)
  19480. {
  19481. // total cache miss
  19482. info.clearActiveBufferRegion();
  19483. }
  19484. else
  19485. {
  19486. if (validStart > 0)
  19487. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19488. if (validEnd < info.numSamples)
  19489. info.buffer->clear (info.startSample + validEnd,
  19490. info.numSamples - validEnd); // partial cache miss at end
  19491. if (validStart < validEnd)
  19492. {
  19493. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19494. {
  19495. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19496. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19497. if (startBufferIndex < endBufferIndex)
  19498. {
  19499. info.buffer->copyFrom (chan, info.startSample + validStart,
  19500. buffer,
  19501. chan, startBufferIndex,
  19502. validEnd - validStart);
  19503. }
  19504. else
  19505. {
  19506. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19507. info.buffer->copyFrom (chan, info.startSample + validStart,
  19508. buffer,
  19509. chan, startBufferIndex,
  19510. initialSize);
  19511. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19512. buffer,
  19513. chan, 0,
  19514. (validEnd - validStart) - initialSize);
  19515. }
  19516. }
  19517. }
  19518. nextPlayPos += info.numSamples;
  19519. if (source->isLooping() && nextPlayPos > 0)
  19520. nextPlayPos %= source->getTotalLength();
  19521. }
  19522. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19523. if (thread != 0)
  19524. thread->notify();
  19525. }
  19526. int BufferingAudioSource::getNextReadPosition() const
  19527. {
  19528. return (source->isLooping() && nextPlayPos > 0)
  19529. ? nextPlayPos % source->getTotalLength()
  19530. : nextPlayPos;
  19531. }
  19532. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19533. {
  19534. const ScopedLock sl (bufferStartPosLock);
  19535. nextPlayPos = newPosition;
  19536. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19537. if (thread != 0)
  19538. thread->notify();
  19539. }
  19540. bool BufferingAudioSource::readNextBufferChunk()
  19541. {
  19542. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19543. {
  19544. const ScopedLock sl (bufferStartPosLock);
  19545. if (wasSourceLooping != isLooping())
  19546. {
  19547. wasSourceLooping = isLooping();
  19548. bufferValidStart = 0;
  19549. bufferValidEnd = 0;
  19550. }
  19551. newBVS = jmax (0, nextPlayPos);
  19552. newBVE = newBVS + buffer.getNumSamples() - 4;
  19553. sectionToReadStart = 0;
  19554. sectionToReadEnd = 0;
  19555. const int maxChunkSize = 2048;
  19556. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19557. {
  19558. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19559. sectionToReadStart = newBVS;
  19560. sectionToReadEnd = newBVE;
  19561. bufferValidStart = 0;
  19562. bufferValidEnd = 0;
  19563. }
  19564. else if (abs (newBVS - bufferValidStart) > 512
  19565. || abs (newBVE - bufferValidEnd) > 512)
  19566. {
  19567. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19568. sectionToReadStart = bufferValidEnd;
  19569. sectionToReadEnd = newBVE;
  19570. bufferValidStart = newBVS;
  19571. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19572. }
  19573. }
  19574. if (sectionToReadStart != sectionToReadEnd)
  19575. {
  19576. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19577. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19578. if (bufferIndexStart < bufferIndexEnd)
  19579. {
  19580. readBufferSection (sectionToReadStart,
  19581. sectionToReadEnd - sectionToReadStart,
  19582. bufferIndexStart);
  19583. }
  19584. else
  19585. {
  19586. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19587. readBufferSection (sectionToReadStart,
  19588. initialSize,
  19589. bufferIndexStart);
  19590. readBufferSection (sectionToReadStart + initialSize,
  19591. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19592. 0);
  19593. }
  19594. const ScopedLock sl2 (bufferStartPosLock);
  19595. bufferValidStart = newBVS;
  19596. bufferValidEnd = newBVE;
  19597. return true;
  19598. }
  19599. else
  19600. {
  19601. return false;
  19602. }
  19603. }
  19604. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19605. {
  19606. if (source->getNextReadPosition() != start)
  19607. source->setNextReadPosition (start);
  19608. AudioSourceChannelInfo info;
  19609. info.buffer = &buffer;
  19610. info.startSample = bufferOffset;
  19611. info.numSamples = length;
  19612. source->getNextAudioBlock (info);
  19613. }
  19614. END_JUCE_NAMESPACE
  19615. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19616. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19617. BEGIN_JUCE_NAMESPACE
  19618. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19619. const bool deleteSourceWhenDeleted_)
  19620. : requiredNumberOfChannels (2),
  19621. source (source_),
  19622. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19623. buffer (2, 16)
  19624. {
  19625. remappedInfo.buffer = &buffer;
  19626. remappedInfo.startSample = 0;
  19627. }
  19628. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19629. {
  19630. if (deleteSourceWhenDeleted)
  19631. delete source;
  19632. }
  19633. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19634. {
  19635. const ScopedLock sl (lock);
  19636. requiredNumberOfChannels = requiredNumberOfChannels_;
  19637. }
  19638. void ChannelRemappingAudioSource::clearAllMappings()
  19639. {
  19640. const ScopedLock sl (lock);
  19641. remappedInputs.clear();
  19642. remappedOutputs.clear();
  19643. }
  19644. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19645. {
  19646. const ScopedLock sl (lock);
  19647. while (remappedInputs.size() < destIndex)
  19648. remappedInputs.add (-1);
  19649. remappedInputs.set (destIndex, sourceIndex);
  19650. }
  19651. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19652. {
  19653. const ScopedLock sl (lock);
  19654. while (remappedOutputs.size() < sourceIndex)
  19655. remappedOutputs.add (-1);
  19656. remappedOutputs.set (sourceIndex, destIndex);
  19657. }
  19658. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19659. {
  19660. const ScopedLock sl (lock);
  19661. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19662. return remappedInputs.getUnchecked (inputChannelIndex);
  19663. return -1;
  19664. }
  19665. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19666. {
  19667. const ScopedLock sl (lock);
  19668. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19669. return remappedOutputs .getUnchecked (outputChannelIndex);
  19670. return -1;
  19671. }
  19672. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19673. {
  19674. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19675. }
  19676. void ChannelRemappingAudioSource::releaseResources()
  19677. {
  19678. source->releaseResources();
  19679. }
  19680. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19681. {
  19682. const ScopedLock sl (lock);
  19683. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19684. const int numChans = bufferToFill.buffer->getNumChannels();
  19685. int i;
  19686. for (i = 0; i < buffer.getNumChannels(); ++i)
  19687. {
  19688. const int remappedChan = getRemappedInputChannel (i);
  19689. if (remappedChan >= 0 && remappedChan < numChans)
  19690. {
  19691. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19692. remappedChan,
  19693. bufferToFill.startSample,
  19694. bufferToFill.numSamples);
  19695. }
  19696. else
  19697. {
  19698. buffer.clear (i, 0, bufferToFill.numSamples);
  19699. }
  19700. }
  19701. remappedInfo.numSamples = bufferToFill.numSamples;
  19702. source->getNextAudioBlock (remappedInfo);
  19703. bufferToFill.clearActiveBufferRegion();
  19704. for (i = 0; i < requiredNumberOfChannels; ++i)
  19705. {
  19706. const int remappedChan = getRemappedOutputChannel (i);
  19707. if (remappedChan >= 0 && remappedChan < numChans)
  19708. {
  19709. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19710. buffer, i, 0, bufferToFill.numSamples);
  19711. }
  19712. }
  19713. }
  19714. XmlElement* ChannelRemappingAudioSource::createXml() const
  19715. {
  19716. XmlElement* e = new XmlElement ("MAPPINGS");
  19717. String ins, outs;
  19718. int i;
  19719. const ScopedLock sl (lock);
  19720. for (i = 0; i < remappedInputs.size(); ++i)
  19721. ins << remappedInputs.getUnchecked(i) << ' ';
  19722. for (i = 0; i < remappedOutputs.size(); ++i)
  19723. outs << remappedOutputs.getUnchecked(i) << ' ';
  19724. e->setAttribute ("inputs", ins.trimEnd());
  19725. e->setAttribute ("outputs", outs.trimEnd());
  19726. return e;
  19727. }
  19728. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19729. {
  19730. if (e.hasTagName ("MAPPINGS"))
  19731. {
  19732. const ScopedLock sl (lock);
  19733. clearAllMappings();
  19734. StringArray ins, outs;
  19735. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19736. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19737. int i;
  19738. for (i = 0; i < ins.size(); ++i)
  19739. remappedInputs.add (ins[i].getIntValue());
  19740. for (i = 0; i < outs.size(); ++i)
  19741. remappedOutputs.add (outs[i].getIntValue());
  19742. }
  19743. }
  19744. END_JUCE_NAMESPACE
  19745. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19746. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19747. BEGIN_JUCE_NAMESPACE
  19748. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19749. const bool deleteInputWhenDeleted_)
  19750. : input (inputSource),
  19751. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19752. {
  19753. jassert (inputSource != 0);
  19754. for (int i = 2; --i >= 0;)
  19755. iirFilters.add (new IIRFilter());
  19756. }
  19757. IIRFilterAudioSource::~IIRFilterAudioSource()
  19758. {
  19759. if (deleteInputWhenDeleted)
  19760. delete input;
  19761. }
  19762. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19763. {
  19764. for (int i = iirFilters.size(); --i >= 0;)
  19765. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19766. }
  19767. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19768. {
  19769. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19770. for (int i = iirFilters.size(); --i >= 0;)
  19771. iirFilters.getUnchecked(i)->reset();
  19772. }
  19773. void IIRFilterAudioSource::releaseResources()
  19774. {
  19775. input->releaseResources();
  19776. }
  19777. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19778. {
  19779. input->getNextAudioBlock (bufferToFill);
  19780. const int numChannels = bufferToFill.buffer->getNumChannels();
  19781. while (numChannels > iirFilters.size())
  19782. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19783. for (int i = 0; i < numChannels; ++i)
  19784. iirFilters.getUnchecked(i)
  19785. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19786. bufferToFill.numSamples);
  19787. }
  19788. END_JUCE_NAMESPACE
  19789. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19790. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19791. BEGIN_JUCE_NAMESPACE
  19792. MixerAudioSource::MixerAudioSource()
  19793. : tempBuffer (2, 0),
  19794. currentSampleRate (0.0),
  19795. bufferSizeExpected (0)
  19796. {
  19797. }
  19798. MixerAudioSource::~MixerAudioSource()
  19799. {
  19800. removeAllInputs();
  19801. }
  19802. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19803. {
  19804. if (input != 0 && ! inputs.contains (input))
  19805. {
  19806. double localRate;
  19807. int localBufferSize;
  19808. {
  19809. const ScopedLock sl (lock);
  19810. localRate = currentSampleRate;
  19811. localBufferSize = bufferSizeExpected;
  19812. }
  19813. if (localRate != 0.0)
  19814. input->prepareToPlay (localBufferSize, localRate);
  19815. const ScopedLock sl (lock);
  19816. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19817. inputs.add (input);
  19818. }
  19819. }
  19820. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19821. {
  19822. if (input != 0)
  19823. {
  19824. int index;
  19825. {
  19826. const ScopedLock sl (lock);
  19827. index = inputs.indexOf (input);
  19828. if (index >= 0)
  19829. {
  19830. inputsToDelete.shiftBits (index, 1);
  19831. inputs.remove (index);
  19832. }
  19833. }
  19834. if (index >= 0)
  19835. {
  19836. input->releaseResources();
  19837. if (deleteInput)
  19838. delete input;
  19839. }
  19840. }
  19841. }
  19842. void MixerAudioSource::removeAllInputs()
  19843. {
  19844. OwnedArray<AudioSource> toDelete;
  19845. {
  19846. const ScopedLock sl (lock);
  19847. for (int i = inputs.size(); --i >= 0;)
  19848. if (inputsToDelete[i])
  19849. toDelete.add (inputs.getUnchecked(i));
  19850. }
  19851. }
  19852. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19853. {
  19854. tempBuffer.setSize (2, samplesPerBlockExpected);
  19855. const ScopedLock sl (lock);
  19856. currentSampleRate = sampleRate;
  19857. bufferSizeExpected = samplesPerBlockExpected;
  19858. for (int i = inputs.size(); --i >= 0;)
  19859. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19860. }
  19861. void MixerAudioSource::releaseResources()
  19862. {
  19863. const ScopedLock sl (lock);
  19864. for (int i = inputs.size(); --i >= 0;)
  19865. inputs.getUnchecked(i)->releaseResources();
  19866. tempBuffer.setSize (2, 0);
  19867. currentSampleRate = 0;
  19868. bufferSizeExpected = 0;
  19869. }
  19870. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19871. {
  19872. const ScopedLock sl (lock);
  19873. if (inputs.size() > 0)
  19874. {
  19875. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19876. if (inputs.size() > 1)
  19877. {
  19878. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19879. info.buffer->getNumSamples());
  19880. AudioSourceChannelInfo info2;
  19881. info2.buffer = &tempBuffer;
  19882. info2.numSamples = info.numSamples;
  19883. info2.startSample = 0;
  19884. for (int i = 1; i < inputs.size(); ++i)
  19885. {
  19886. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19887. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19888. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19889. }
  19890. }
  19891. }
  19892. else
  19893. {
  19894. info.clearActiveBufferRegion();
  19895. }
  19896. }
  19897. END_JUCE_NAMESPACE
  19898. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19899. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19900. BEGIN_JUCE_NAMESPACE
  19901. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19902. const bool deleteInputWhenDeleted_,
  19903. const int numChannels_)
  19904. : input (inputSource),
  19905. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19906. ratio (1.0),
  19907. lastRatio (1.0),
  19908. buffer (numChannels_, 0),
  19909. sampsInBuffer (0),
  19910. numChannels (numChannels_)
  19911. {
  19912. jassert (input != 0);
  19913. }
  19914. ResamplingAudioSource::~ResamplingAudioSource()
  19915. {
  19916. if (deleteInputWhenDeleted)
  19917. delete input;
  19918. }
  19919. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19920. {
  19921. jassert (samplesInPerOutputSample > 0);
  19922. const ScopedLock sl (ratioLock);
  19923. ratio = jmax (0.0, samplesInPerOutputSample);
  19924. }
  19925. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19926. double sampleRate)
  19927. {
  19928. const ScopedLock sl (ratioLock);
  19929. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19930. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19931. buffer.clear();
  19932. sampsInBuffer = 0;
  19933. bufferPos = 0;
  19934. subSampleOffset = 0.0;
  19935. filterStates.calloc (numChannels);
  19936. srcBuffers.calloc (numChannels);
  19937. destBuffers.calloc (numChannels);
  19938. createLowPass (ratio);
  19939. resetFilters();
  19940. }
  19941. void ResamplingAudioSource::releaseResources()
  19942. {
  19943. input->releaseResources();
  19944. buffer.setSize (numChannels, 0);
  19945. }
  19946. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19947. {
  19948. double localRatio;
  19949. {
  19950. const ScopedLock sl (ratioLock);
  19951. localRatio = ratio;
  19952. }
  19953. if (lastRatio != localRatio)
  19954. {
  19955. createLowPass (localRatio);
  19956. lastRatio = localRatio;
  19957. }
  19958. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19959. int bufferSize = buffer.getNumSamples();
  19960. if (bufferSize < sampsNeeded + 8)
  19961. {
  19962. bufferPos %= bufferSize;
  19963. bufferSize = sampsNeeded + 32;
  19964. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19965. }
  19966. bufferPos %= bufferSize;
  19967. int endOfBufferPos = bufferPos + sampsInBuffer;
  19968. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19969. while (sampsNeeded > sampsInBuffer)
  19970. {
  19971. endOfBufferPos %= bufferSize;
  19972. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19973. bufferSize - endOfBufferPos);
  19974. AudioSourceChannelInfo readInfo;
  19975. readInfo.buffer = &buffer;
  19976. readInfo.numSamples = numToDo;
  19977. readInfo.startSample = endOfBufferPos;
  19978. input->getNextAudioBlock (readInfo);
  19979. if (localRatio > 1.0001)
  19980. {
  19981. // for down-sampling, pre-apply the filter..
  19982. for (int i = channelsToProcess; --i >= 0;)
  19983. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19984. }
  19985. sampsInBuffer += numToDo;
  19986. endOfBufferPos += numToDo;
  19987. }
  19988. for (int channel = 0; channel < channelsToProcess; ++channel)
  19989. {
  19990. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19991. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19992. }
  19993. int nextPos = (bufferPos + 1) % bufferSize;
  19994. for (int m = info.numSamples; --m >= 0;)
  19995. {
  19996. const float alpha = (float) subSampleOffset;
  19997. const float invAlpha = 1.0f - alpha;
  19998. for (int channel = 0; channel < channelsToProcess; ++channel)
  19999. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20000. subSampleOffset += localRatio;
  20001. jassert (sampsInBuffer > 0);
  20002. while (subSampleOffset >= 1.0)
  20003. {
  20004. if (++bufferPos >= bufferSize)
  20005. bufferPos = 0;
  20006. --sampsInBuffer;
  20007. nextPos = (bufferPos + 1) % bufferSize;
  20008. subSampleOffset -= 1.0;
  20009. }
  20010. }
  20011. if (localRatio < 0.9999)
  20012. {
  20013. // for up-sampling, apply the filter after transposing..
  20014. for (int i = channelsToProcess; --i >= 0;)
  20015. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20016. }
  20017. else if (localRatio <= 1.0001)
  20018. {
  20019. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20020. for (int i = channelsToProcess; --i >= 0;)
  20021. {
  20022. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20023. FilterState& fs = filterStates[i];
  20024. if (info.numSamples > 1)
  20025. {
  20026. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20027. }
  20028. else
  20029. {
  20030. fs.y2 = fs.y1;
  20031. fs.x2 = fs.x1;
  20032. }
  20033. fs.y1 = fs.x1 = *endOfBuffer;
  20034. }
  20035. }
  20036. jassert (sampsInBuffer >= 0);
  20037. }
  20038. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20039. {
  20040. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20041. : 0.5 * frequencyRatio;
  20042. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  20043. const double nSquared = n * n;
  20044. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20045. setFilterCoefficients (c1,
  20046. c1 * 2.0f,
  20047. c1,
  20048. 1.0,
  20049. c1 * 2.0 * (1.0 - nSquared),
  20050. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20051. }
  20052. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20053. {
  20054. const double a = 1.0 / c4;
  20055. c1 *= a;
  20056. c2 *= a;
  20057. c3 *= a;
  20058. c5 *= a;
  20059. c6 *= a;
  20060. coefficients[0] = c1;
  20061. coefficients[1] = c2;
  20062. coefficients[2] = c3;
  20063. coefficients[3] = c4;
  20064. coefficients[4] = c5;
  20065. coefficients[5] = c6;
  20066. }
  20067. void ResamplingAudioSource::resetFilters()
  20068. {
  20069. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20070. }
  20071. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20072. {
  20073. while (--num >= 0)
  20074. {
  20075. const double in = *samples;
  20076. double out = coefficients[0] * in
  20077. + coefficients[1] * fs.x1
  20078. + coefficients[2] * fs.x2
  20079. - coefficients[4] * fs.y1
  20080. - coefficients[5] * fs.y2;
  20081. #if JUCE_INTEL
  20082. if (! (out < -1.0e-8 || out > 1.0e-8))
  20083. out = 0;
  20084. #endif
  20085. fs.x2 = fs.x1;
  20086. fs.x1 = in;
  20087. fs.y2 = fs.y1;
  20088. fs.y1 = out;
  20089. *samples++ = (float) out;
  20090. }
  20091. }
  20092. END_JUCE_NAMESPACE
  20093. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20094. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20095. BEGIN_JUCE_NAMESPACE
  20096. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20097. : frequency (1000.0),
  20098. sampleRate (44100.0),
  20099. currentPhase (0.0),
  20100. phasePerSample (0.0),
  20101. amplitude (0.5f)
  20102. {
  20103. }
  20104. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20105. {
  20106. }
  20107. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20108. {
  20109. amplitude = newAmplitude;
  20110. }
  20111. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20112. {
  20113. frequency = newFrequencyHz;
  20114. phasePerSample = 0.0;
  20115. }
  20116. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20117. double sampleRate_)
  20118. {
  20119. currentPhase = 0.0;
  20120. phasePerSample = 0.0;
  20121. sampleRate = sampleRate_;
  20122. }
  20123. void ToneGeneratorAudioSource::releaseResources()
  20124. {
  20125. }
  20126. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20127. {
  20128. if (phasePerSample == 0.0)
  20129. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20130. for (int i = 0; i < info.numSamples; ++i)
  20131. {
  20132. const float sample = amplitude * (float) std::sin (currentPhase);
  20133. currentPhase += phasePerSample;
  20134. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20135. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20136. }
  20137. }
  20138. END_JUCE_NAMESPACE
  20139. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20140. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20141. BEGIN_JUCE_NAMESPACE
  20142. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20143. : sampleRate (0),
  20144. bufferSize (0),
  20145. useDefaultInputChannels (true),
  20146. useDefaultOutputChannels (true)
  20147. {
  20148. }
  20149. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20150. {
  20151. return outputDeviceName == other.outputDeviceName
  20152. && inputDeviceName == other.inputDeviceName
  20153. && sampleRate == other.sampleRate
  20154. && bufferSize == other.bufferSize
  20155. && inputChannels == other.inputChannels
  20156. && useDefaultInputChannels == other.useDefaultInputChannels
  20157. && outputChannels == other.outputChannels
  20158. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20159. }
  20160. AudioDeviceManager::AudioDeviceManager()
  20161. : currentAudioDevice (0),
  20162. numInputChansNeeded (0),
  20163. numOutputChansNeeded (2),
  20164. listNeedsScanning (true),
  20165. useInputNames (false),
  20166. inputLevelMeasurementEnabledCount (0),
  20167. inputLevel (0),
  20168. tempBuffer (2, 2),
  20169. defaultMidiOutput (0),
  20170. cpuUsageMs (0),
  20171. timeToCpuScale (0)
  20172. {
  20173. callbackHandler.owner = this;
  20174. }
  20175. AudioDeviceManager::~AudioDeviceManager()
  20176. {
  20177. currentAudioDevice = 0;
  20178. defaultMidiOutput = 0;
  20179. }
  20180. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20181. {
  20182. if (availableDeviceTypes.size() == 0)
  20183. {
  20184. createAudioDeviceTypes (availableDeviceTypes);
  20185. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20186. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20187. if (availableDeviceTypes.size() > 0)
  20188. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20189. }
  20190. }
  20191. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20192. {
  20193. scanDevicesIfNeeded();
  20194. return availableDeviceTypes;
  20195. }
  20196. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20197. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20198. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20199. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20200. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20201. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20202. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20203. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20204. {
  20205. (void) list; // (to avoid 'unused param' warnings)
  20206. #if JUCE_WINDOWS
  20207. #if JUCE_WASAPI
  20208. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20209. list.add (juce_createAudioIODeviceType_WASAPI());
  20210. #endif
  20211. #if JUCE_DIRECTSOUND
  20212. list.add (juce_createAudioIODeviceType_DirectSound());
  20213. #endif
  20214. #if JUCE_ASIO
  20215. list.add (juce_createAudioIODeviceType_ASIO());
  20216. #endif
  20217. #endif
  20218. #if JUCE_MAC
  20219. list.add (juce_createAudioIODeviceType_CoreAudio());
  20220. #endif
  20221. #if JUCE_IOS
  20222. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20223. #endif
  20224. #if JUCE_LINUX && JUCE_ALSA
  20225. list.add (juce_createAudioIODeviceType_ALSA());
  20226. #endif
  20227. #if JUCE_LINUX && JUCE_JACK
  20228. list.add (juce_createAudioIODeviceType_JACK());
  20229. #endif
  20230. }
  20231. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20232. const int numOutputChannelsNeeded,
  20233. const XmlElement* const e,
  20234. const bool selectDefaultDeviceOnFailure,
  20235. const String& preferredDefaultDeviceName,
  20236. const AudioDeviceSetup* preferredSetupOptions)
  20237. {
  20238. scanDevicesIfNeeded();
  20239. numInputChansNeeded = numInputChannelsNeeded;
  20240. numOutputChansNeeded = numOutputChannelsNeeded;
  20241. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20242. {
  20243. lastExplicitSettings = new XmlElement (*e);
  20244. String error;
  20245. AudioDeviceSetup setup;
  20246. if (preferredSetupOptions != 0)
  20247. setup = *preferredSetupOptions;
  20248. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20249. {
  20250. setup.inputDeviceName = setup.outputDeviceName
  20251. = e->getStringAttribute ("audioDeviceName");
  20252. }
  20253. else
  20254. {
  20255. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20256. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20257. }
  20258. currentDeviceType = e->getStringAttribute ("deviceType");
  20259. if (currentDeviceType.isEmpty())
  20260. {
  20261. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20262. if (type != 0)
  20263. currentDeviceType = type->getTypeName();
  20264. else if (availableDeviceTypes.size() > 0)
  20265. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20266. }
  20267. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20268. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20269. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20270. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20271. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20272. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20273. error = setAudioDeviceSetup (setup, true);
  20274. midiInsFromXml.clear();
  20275. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20276. midiInsFromXml.add (c->getStringAttribute ("name"));
  20277. const StringArray allMidiIns (MidiInput::getDevices());
  20278. for (int i = allMidiIns.size(); --i >= 0;)
  20279. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20280. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20281. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20282. false, preferredDefaultDeviceName);
  20283. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20284. return error;
  20285. }
  20286. else
  20287. {
  20288. AudioDeviceSetup setup;
  20289. if (preferredSetupOptions != 0)
  20290. {
  20291. setup = *preferredSetupOptions;
  20292. }
  20293. else if (preferredDefaultDeviceName.isNotEmpty())
  20294. {
  20295. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20296. {
  20297. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20298. StringArray outs (type->getDeviceNames (false));
  20299. int i;
  20300. for (i = 0; i < outs.size(); ++i)
  20301. {
  20302. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20303. {
  20304. setup.outputDeviceName = outs[i];
  20305. break;
  20306. }
  20307. }
  20308. StringArray ins (type->getDeviceNames (true));
  20309. for (i = 0; i < ins.size(); ++i)
  20310. {
  20311. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20312. {
  20313. setup.inputDeviceName = ins[i];
  20314. break;
  20315. }
  20316. }
  20317. }
  20318. }
  20319. insertDefaultDeviceNames (setup);
  20320. return setAudioDeviceSetup (setup, false);
  20321. }
  20322. }
  20323. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20324. {
  20325. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20326. if (type != 0)
  20327. {
  20328. if (setup.outputDeviceName.isEmpty())
  20329. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20330. if (setup.inputDeviceName.isEmpty())
  20331. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20332. }
  20333. }
  20334. XmlElement* AudioDeviceManager::createStateXml() const
  20335. {
  20336. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20337. }
  20338. void AudioDeviceManager::scanDevicesIfNeeded()
  20339. {
  20340. if (listNeedsScanning)
  20341. {
  20342. listNeedsScanning = false;
  20343. createDeviceTypesIfNeeded();
  20344. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20345. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20346. }
  20347. }
  20348. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20349. {
  20350. scanDevicesIfNeeded();
  20351. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20352. {
  20353. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20354. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20355. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20356. {
  20357. return type;
  20358. }
  20359. }
  20360. return 0;
  20361. }
  20362. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20363. {
  20364. setup = currentSetup;
  20365. }
  20366. void AudioDeviceManager::deleteCurrentDevice()
  20367. {
  20368. currentAudioDevice = 0;
  20369. currentSetup.inputDeviceName = String::empty;
  20370. currentSetup.outputDeviceName = String::empty;
  20371. }
  20372. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20373. const bool treatAsChosenDevice)
  20374. {
  20375. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20376. {
  20377. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20378. && currentDeviceType != type)
  20379. {
  20380. currentDeviceType = type;
  20381. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20382. insertDefaultDeviceNames (s);
  20383. setAudioDeviceSetup (s, treatAsChosenDevice);
  20384. sendChangeMessage();
  20385. break;
  20386. }
  20387. }
  20388. }
  20389. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20390. {
  20391. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20392. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20393. return availableDeviceTypes[i];
  20394. return availableDeviceTypes[0];
  20395. }
  20396. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20397. const bool treatAsChosenDevice)
  20398. {
  20399. jassert (&newSetup != &currentSetup); // this will have no effect
  20400. if (newSetup == currentSetup && currentAudioDevice != 0)
  20401. return String::empty;
  20402. if (! (newSetup == currentSetup))
  20403. sendChangeMessage();
  20404. stopDevice();
  20405. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20406. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20407. String error;
  20408. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20409. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20410. {
  20411. deleteCurrentDevice();
  20412. if (treatAsChosenDevice)
  20413. updateXml();
  20414. return String::empty;
  20415. }
  20416. if (currentSetup.inputDeviceName != newInputDeviceName
  20417. || currentSetup.outputDeviceName != newOutputDeviceName
  20418. || currentAudioDevice == 0)
  20419. {
  20420. deleteCurrentDevice();
  20421. scanDevicesIfNeeded();
  20422. if (newOutputDeviceName.isNotEmpty()
  20423. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20424. {
  20425. return "No such device: " + newOutputDeviceName;
  20426. }
  20427. if (newInputDeviceName.isNotEmpty()
  20428. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20429. {
  20430. return "No such device: " + newInputDeviceName;
  20431. }
  20432. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20433. if (currentAudioDevice == 0)
  20434. 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!";
  20435. else
  20436. error = currentAudioDevice->getLastError();
  20437. if (error.isNotEmpty())
  20438. {
  20439. deleteCurrentDevice();
  20440. return error;
  20441. }
  20442. if (newSetup.useDefaultInputChannels)
  20443. {
  20444. inputChannels.clear();
  20445. inputChannels.setRange (0, numInputChansNeeded, true);
  20446. }
  20447. if (newSetup.useDefaultOutputChannels)
  20448. {
  20449. outputChannels.clear();
  20450. outputChannels.setRange (0, numOutputChansNeeded, true);
  20451. }
  20452. if (newInputDeviceName.isEmpty())
  20453. inputChannels.clear();
  20454. if (newOutputDeviceName.isEmpty())
  20455. outputChannels.clear();
  20456. }
  20457. if (! newSetup.useDefaultInputChannels)
  20458. inputChannels = newSetup.inputChannels;
  20459. if (! newSetup.useDefaultOutputChannels)
  20460. outputChannels = newSetup.outputChannels;
  20461. currentSetup = newSetup;
  20462. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20463. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20464. error = currentAudioDevice->open (inputChannels,
  20465. outputChannels,
  20466. currentSetup.sampleRate,
  20467. currentSetup.bufferSize);
  20468. if (error.isEmpty())
  20469. {
  20470. currentDeviceType = currentAudioDevice->getTypeName();
  20471. currentAudioDevice->start (&callbackHandler);
  20472. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20473. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20474. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20475. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20476. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20477. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20478. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20479. if (treatAsChosenDevice)
  20480. updateXml();
  20481. }
  20482. else
  20483. {
  20484. deleteCurrentDevice();
  20485. }
  20486. return error;
  20487. }
  20488. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20489. {
  20490. jassert (currentAudioDevice != 0);
  20491. if (rate > 0)
  20492. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20493. if (currentAudioDevice->getSampleRate (i) == rate)
  20494. return rate;
  20495. double lowestAbove44 = 0.0;
  20496. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20497. {
  20498. const double sr = currentAudioDevice->getSampleRate (i);
  20499. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20500. lowestAbove44 = sr;
  20501. }
  20502. if (lowestAbove44 > 0.0)
  20503. return lowestAbove44;
  20504. return currentAudioDevice->getSampleRate (0);
  20505. }
  20506. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20507. {
  20508. jassert (currentAudioDevice != 0);
  20509. if (bufferSize > 0)
  20510. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20511. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20512. return bufferSize;
  20513. return currentAudioDevice->getDefaultBufferSize();
  20514. }
  20515. void AudioDeviceManager::stopDevice()
  20516. {
  20517. if (currentAudioDevice != 0)
  20518. currentAudioDevice->stop();
  20519. testSound = 0;
  20520. }
  20521. void AudioDeviceManager::closeAudioDevice()
  20522. {
  20523. stopDevice();
  20524. currentAudioDevice = 0;
  20525. }
  20526. void AudioDeviceManager::restartLastAudioDevice()
  20527. {
  20528. if (currentAudioDevice == 0)
  20529. {
  20530. if (currentSetup.inputDeviceName.isEmpty()
  20531. && currentSetup.outputDeviceName.isEmpty())
  20532. {
  20533. // This method will only reload the last device that was running
  20534. // before closeAudioDevice() was called - you need to actually open
  20535. // one first, with setAudioDevice().
  20536. jassertfalse;
  20537. return;
  20538. }
  20539. AudioDeviceSetup s (currentSetup);
  20540. setAudioDeviceSetup (s, false);
  20541. }
  20542. }
  20543. void AudioDeviceManager::updateXml()
  20544. {
  20545. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20546. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20547. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20548. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20549. if (currentAudioDevice != 0)
  20550. {
  20551. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20552. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20553. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20554. if (! currentSetup.useDefaultInputChannels)
  20555. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20556. if (! currentSetup.useDefaultOutputChannels)
  20557. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20558. }
  20559. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20560. {
  20561. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20562. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20563. }
  20564. if (midiInsFromXml.size() > 0)
  20565. {
  20566. // Add any midi devices that have been enabled before, but which aren't currently
  20567. // open because the device has been disconnected.
  20568. const StringArray availableMidiDevices (MidiInput::getDevices());
  20569. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20570. {
  20571. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20572. {
  20573. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20574. m->setAttribute ("name", midiInsFromXml[i]);
  20575. }
  20576. }
  20577. }
  20578. if (defaultMidiOutputName.isNotEmpty())
  20579. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20580. }
  20581. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20582. {
  20583. {
  20584. const ScopedLock sl (audioCallbackLock);
  20585. if (callbacks.contains (newCallback))
  20586. return;
  20587. }
  20588. if (currentAudioDevice != 0 && newCallback != 0)
  20589. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20590. const ScopedLock sl (audioCallbackLock);
  20591. callbacks.add (newCallback);
  20592. }
  20593. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20594. {
  20595. if (callbackToRemove != 0)
  20596. {
  20597. bool needsDeinitialising = currentAudioDevice != 0;
  20598. {
  20599. const ScopedLock sl (audioCallbackLock);
  20600. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20601. callbacks.removeValue (callbackToRemove);
  20602. }
  20603. if (needsDeinitialising)
  20604. callbackToRemove->audioDeviceStopped();
  20605. }
  20606. }
  20607. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20608. int numInputChannels,
  20609. float** outputChannelData,
  20610. int numOutputChannels,
  20611. int numSamples)
  20612. {
  20613. const ScopedLock sl (audioCallbackLock);
  20614. if (inputLevelMeasurementEnabledCount > 0)
  20615. {
  20616. for (int j = 0; j < numSamples; ++j)
  20617. {
  20618. float s = 0;
  20619. for (int i = 0; i < numInputChannels; ++i)
  20620. s += std::abs (inputChannelData[i][j]);
  20621. s /= numInputChannels;
  20622. const double decayFactor = 0.99992;
  20623. if (s > inputLevel)
  20624. inputLevel = s;
  20625. else if (inputLevel > 0.001f)
  20626. inputLevel *= decayFactor;
  20627. else
  20628. inputLevel = 0;
  20629. }
  20630. }
  20631. if (callbacks.size() > 0)
  20632. {
  20633. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20634. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20635. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20636. outputChannelData, numOutputChannels, numSamples);
  20637. float** const tempChans = tempBuffer.getArrayOfChannels();
  20638. for (int i = callbacks.size(); --i > 0;)
  20639. {
  20640. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20641. tempChans, numOutputChannels, numSamples);
  20642. for (int chan = 0; chan < numOutputChannels; ++chan)
  20643. {
  20644. const float* const src = tempChans [chan];
  20645. float* const dst = outputChannelData [chan];
  20646. if (src != 0 && dst != 0)
  20647. for (int j = 0; j < numSamples; ++j)
  20648. dst[j] += src[j];
  20649. }
  20650. }
  20651. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20652. const double filterAmount = 0.2;
  20653. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20654. }
  20655. else
  20656. {
  20657. for (int i = 0; i < numOutputChannels; ++i)
  20658. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20659. }
  20660. if (testSound != 0)
  20661. {
  20662. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20663. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20664. for (int i = 0; i < numOutputChannels; ++i)
  20665. for (int j = 0; j < numSamps; ++j)
  20666. outputChannelData [i][j] += src[j];
  20667. testSoundPosition += numSamps;
  20668. if (testSoundPosition >= testSound->getNumSamples())
  20669. testSound = 0;
  20670. }
  20671. }
  20672. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20673. {
  20674. cpuUsageMs = 0;
  20675. const double sampleRate = device->getCurrentSampleRate();
  20676. const int blockSize = device->getCurrentBufferSizeSamples();
  20677. if (sampleRate > 0.0 && blockSize > 0)
  20678. {
  20679. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20680. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20681. }
  20682. {
  20683. const ScopedLock sl (audioCallbackLock);
  20684. for (int i = callbacks.size(); --i >= 0;)
  20685. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20686. }
  20687. sendChangeMessage();
  20688. }
  20689. void AudioDeviceManager::audioDeviceStoppedInt()
  20690. {
  20691. cpuUsageMs = 0;
  20692. timeToCpuScale = 0;
  20693. sendChangeMessage();
  20694. const ScopedLock sl (audioCallbackLock);
  20695. for (int i = callbacks.size(); --i >= 0;)
  20696. callbacks.getUnchecked(i)->audioDeviceStopped();
  20697. }
  20698. double AudioDeviceManager::getCpuUsage() const
  20699. {
  20700. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20701. }
  20702. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20703. const bool enabled)
  20704. {
  20705. if (enabled != isMidiInputEnabled (name))
  20706. {
  20707. if (enabled)
  20708. {
  20709. const int index = MidiInput::getDevices().indexOf (name);
  20710. if (index >= 0)
  20711. {
  20712. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20713. if (min != 0)
  20714. {
  20715. enabledMidiInputs.add (min);
  20716. min->start();
  20717. }
  20718. }
  20719. }
  20720. else
  20721. {
  20722. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20723. if (enabledMidiInputs[i]->getName() == name)
  20724. enabledMidiInputs.remove (i);
  20725. }
  20726. updateXml();
  20727. sendChangeMessage();
  20728. }
  20729. }
  20730. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20731. {
  20732. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20733. if (enabledMidiInputs[i]->getName() == name)
  20734. return true;
  20735. return false;
  20736. }
  20737. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20738. MidiInputCallback* callbackToAdd)
  20739. {
  20740. removeMidiInputCallback (name, callbackToAdd);
  20741. if (name.isEmpty())
  20742. {
  20743. midiCallbacks.add (callbackToAdd);
  20744. midiCallbackDevices.add (0);
  20745. }
  20746. else
  20747. {
  20748. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20749. {
  20750. if (enabledMidiInputs[i]->getName() == name)
  20751. {
  20752. const ScopedLock sl (midiCallbackLock);
  20753. midiCallbacks.add (callbackToAdd);
  20754. midiCallbackDevices.add (enabledMidiInputs[i]);
  20755. break;
  20756. }
  20757. }
  20758. }
  20759. }
  20760. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* /*callback*/)
  20761. {
  20762. const ScopedLock sl (midiCallbackLock);
  20763. for (int i = midiCallbacks.size(); --i >= 0;)
  20764. {
  20765. String devName;
  20766. if (midiCallbackDevices.getUnchecked(i) != 0)
  20767. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20768. if (devName == name)
  20769. {
  20770. midiCallbacks.remove (i);
  20771. midiCallbackDevices.remove (i);
  20772. }
  20773. }
  20774. }
  20775. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20776. const MidiMessage& message)
  20777. {
  20778. if (! message.isActiveSense())
  20779. {
  20780. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20781. const ScopedLock sl (midiCallbackLock);
  20782. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20783. {
  20784. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20785. if (md == source || (md == 0 && isDefaultSource))
  20786. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20787. }
  20788. }
  20789. }
  20790. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20791. {
  20792. if (defaultMidiOutputName != deviceName)
  20793. {
  20794. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20795. {
  20796. const ScopedLock sl (audioCallbackLock);
  20797. oldCallbacks = callbacks;
  20798. callbacks.clear();
  20799. }
  20800. if (currentAudioDevice != 0)
  20801. for (int i = oldCallbacks.size(); --i >= 0;)
  20802. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20803. defaultMidiOutput = 0;
  20804. defaultMidiOutputName = deviceName;
  20805. if (deviceName.isNotEmpty())
  20806. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20807. if (currentAudioDevice != 0)
  20808. for (int i = oldCallbacks.size(); --i >= 0;)
  20809. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20810. {
  20811. const ScopedLock sl (audioCallbackLock);
  20812. callbacks = oldCallbacks;
  20813. }
  20814. updateXml();
  20815. sendChangeMessage();
  20816. }
  20817. }
  20818. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20819. int numInputChannels,
  20820. float** outputChannelData,
  20821. int numOutputChannels,
  20822. int numSamples)
  20823. {
  20824. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20825. }
  20826. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20827. {
  20828. owner->audioDeviceAboutToStartInt (device);
  20829. }
  20830. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20831. {
  20832. owner->audioDeviceStoppedInt();
  20833. }
  20834. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20835. {
  20836. owner->handleIncomingMidiMessageInt (source, message);
  20837. }
  20838. void AudioDeviceManager::playTestSound()
  20839. {
  20840. { // cunningly nested to swap, unlock and delete in that order.
  20841. ScopedPointer <AudioSampleBuffer> oldSound;
  20842. {
  20843. const ScopedLock sl (audioCallbackLock);
  20844. oldSound = testSound;
  20845. }
  20846. }
  20847. testSoundPosition = 0;
  20848. if (currentAudioDevice != 0)
  20849. {
  20850. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20851. const int soundLength = (int) sampleRate;
  20852. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20853. float* samples = newSound->getSampleData (0);
  20854. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20855. const float amplitude = 0.5f;
  20856. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20857. for (int i = 0; i < soundLength; ++i)
  20858. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20859. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20860. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20861. const ScopedLock sl (audioCallbackLock);
  20862. testSound = newSound;
  20863. }
  20864. }
  20865. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20866. {
  20867. const ScopedLock sl (audioCallbackLock);
  20868. if (enableMeasurement)
  20869. ++inputLevelMeasurementEnabledCount;
  20870. else
  20871. --inputLevelMeasurementEnabledCount;
  20872. inputLevel = 0;
  20873. }
  20874. double AudioDeviceManager::getCurrentInputLevel() const
  20875. {
  20876. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20877. return inputLevel;
  20878. }
  20879. END_JUCE_NAMESPACE
  20880. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20881. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20882. BEGIN_JUCE_NAMESPACE
  20883. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20884. : name (deviceName),
  20885. typeName (typeName_)
  20886. {
  20887. }
  20888. AudioIODevice::~AudioIODevice()
  20889. {
  20890. }
  20891. bool AudioIODevice::hasControlPanel() const
  20892. {
  20893. return false;
  20894. }
  20895. bool AudioIODevice::showControlPanel()
  20896. {
  20897. jassertfalse; // this should only be called for devices which return true from
  20898. // their hasControlPanel() method.
  20899. return false;
  20900. }
  20901. END_JUCE_NAMESPACE
  20902. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20903. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20904. BEGIN_JUCE_NAMESPACE
  20905. AudioIODeviceType::AudioIODeviceType (const String& name)
  20906. : typeName (name)
  20907. {
  20908. }
  20909. AudioIODeviceType::~AudioIODeviceType()
  20910. {
  20911. }
  20912. END_JUCE_NAMESPACE
  20913. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20914. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20915. BEGIN_JUCE_NAMESPACE
  20916. MidiOutput::MidiOutput()
  20917. : Thread ("midi out"),
  20918. internal (0),
  20919. firstMessage (0)
  20920. {
  20921. }
  20922. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20923. const double sampleNumber)
  20924. : message (data, len, sampleNumber)
  20925. {
  20926. }
  20927. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20928. const double millisecondCounterToStartAt,
  20929. double samplesPerSecondForBuffer)
  20930. {
  20931. // You've got to call startBackgroundThread() for this to actually work..
  20932. jassert (isThreadRunning());
  20933. // this needs to be a value in the future - RTFM for this method!
  20934. jassert (millisecondCounterToStartAt > 0);
  20935. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20936. MidiBuffer::Iterator i (buffer);
  20937. const uint8* data;
  20938. int len, time;
  20939. while (i.getNextEvent (data, len, time))
  20940. {
  20941. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20942. PendingMessage* const m
  20943. = new PendingMessage (data, len, eventTime);
  20944. const ScopedLock sl (lock);
  20945. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20946. {
  20947. m->next = firstMessage;
  20948. firstMessage = m;
  20949. }
  20950. else
  20951. {
  20952. PendingMessage* mm = firstMessage;
  20953. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20954. mm = mm->next;
  20955. m->next = mm->next;
  20956. mm->next = m;
  20957. }
  20958. }
  20959. notify();
  20960. }
  20961. void MidiOutput::clearAllPendingMessages()
  20962. {
  20963. const ScopedLock sl (lock);
  20964. while (firstMessage != 0)
  20965. {
  20966. PendingMessage* const m = firstMessage;
  20967. firstMessage = firstMessage->next;
  20968. delete m;
  20969. }
  20970. }
  20971. void MidiOutput::startBackgroundThread()
  20972. {
  20973. startThread (9);
  20974. }
  20975. void MidiOutput::stopBackgroundThread()
  20976. {
  20977. stopThread (5000);
  20978. }
  20979. void MidiOutput::run()
  20980. {
  20981. while (! threadShouldExit())
  20982. {
  20983. uint32 now = Time::getMillisecondCounter();
  20984. uint32 eventTime = 0;
  20985. uint32 timeToWait = 500;
  20986. PendingMessage* message;
  20987. {
  20988. const ScopedLock sl (lock);
  20989. message = firstMessage;
  20990. if (message != 0)
  20991. {
  20992. eventTime = roundToInt (message->message.getTimeStamp());
  20993. if (eventTime > now + 20)
  20994. {
  20995. timeToWait = eventTime - (now + 20);
  20996. message = 0;
  20997. }
  20998. else
  20999. {
  21000. firstMessage = message->next;
  21001. }
  21002. }
  21003. }
  21004. if (message != 0)
  21005. {
  21006. if (eventTime > now)
  21007. {
  21008. Time::waitForMillisecondCounter (eventTime);
  21009. if (threadShouldExit())
  21010. break;
  21011. }
  21012. if (eventTime > now - 200)
  21013. sendMessageNow (message->message);
  21014. delete message;
  21015. }
  21016. else
  21017. {
  21018. jassert (timeToWait < 1000 * 30);
  21019. wait (timeToWait);
  21020. }
  21021. }
  21022. clearAllPendingMessages();
  21023. }
  21024. END_JUCE_NAMESPACE
  21025. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21026. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21027. BEGIN_JUCE_NAMESPACE
  21028. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21029. {
  21030. const double maxVal = (double) 0x7fff;
  21031. char* intData = static_cast <char*> (dest);
  21032. if (dest != (void*) source || destBytesPerSample <= 4)
  21033. {
  21034. for (int i = 0; i < numSamples; ++i)
  21035. {
  21036. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21037. intData += destBytesPerSample;
  21038. }
  21039. }
  21040. else
  21041. {
  21042. intData += destBytesPerSample * numSamples;
  21043. for (int i = numSamples; --i >= 0;)
  21044. {
  21045. intData -= destBytesPerSample;
  21046. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21047. }
  21048. }
  21049. }
  21050. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21051. {
  21052. const double maxVal = (double) 0x7fff;
  21053. char* intData = static_cast <char*> (dest);
  21054. if (dest != (void*) source || destBytesPerSample <= 4)
  21055. {
  21056. for (int i = 0; i < numSamples; ++i)
  21057. {
  21058. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21059. intData += destBytesPerSample;
  21060. }
  21061. }
  21062. else
  21063. {
  21064. intData += destBytesPerSample * numSamples;
  21065. for (int i = numSamples; --i >= 0;)
  21066. {
  21067. intData -= destBytesPerSample;
  21068. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21069. }
  21070. }
  21071. }
  21072. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21073. {
  21074. const double maxVal = (double) 0x7fffff;
  21075. char* intData = static_cast <char*> (dest);
  21076. if (dest != (void*) source || destBytesPerSample <= 4)
  21077. {
  21078. for (int i = 0; i < numSamples; ++i)
  21079. {
  21080. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21081. intData += destBytesPerSample;
  21082. }
  21083. }
  21084. else
  21085. {
  21086. intData += destBytesPerSample * numSamples;
  21087. for (int i = numSamples; --i >= 0;)
  21088. {
  21089. intData -= destBytesPerSample;
  21090. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21091. }
  21092. }
  21093. }
  21094. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21095. {
  21096. const double maxVal = (double) 0x7fffff;
  21097. char* intData = static_cast <char*> (dest);
  21098. if (dest != (void*) source || destBytesPerSample <= 4)
  21099. {
  21100. for (int i = 0; i < numSamples; ++i)
  21101. {
  21102. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21103. intData += destBytesPerSample;
  21104. }
  21105. }
  21106. else
  21107. {
  21108. intData += destBytesPerSample * numSamples;
  21109. for (int i = numSamples; --i >= 0;)
  21110. {
  21111. intData -= destBytesPerSample;
  21112. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21113. }
  21114. }
  21115. }
  21116. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21117. {
  21118. const double maxVal = (double) 0x7fffffff;
  21119. char* intData = static_cast <char*> (dest);
  21120. if (dest != (void*) source || destBytesPerSample <= 4)
  21121. {
  21122. for (int i = 0; i < numSamples; ++i)
  21123. {
  21124. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21125. intData += destBytesPerSample;
  21126. }
  21127. }
  21128. else
  21129. {
  21130. intData += destBytesPerSample * numSamples;
  21131. for (int i = numSamples; --i >= 0;)
  21132. {
  21133. intData -= destBytesPerSample;
  21134. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21135. }
  21136. }
  21137. }
  21138. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21139. {
  21140. const double maxVal = (double) 0x7fffffff;
  21141. char* intData = static_cast <char*> (dest);
  21142. if (dest != (void*) source || destBytesPerSample <= 4)
  21143. {
  21144. for (int i = 0; i < numSamples; ++i)
  21145. {
  21146. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21147. intData += destBytesPerSample;
  21148. }
  21149. }
  21150. else
  21151. {
  21152. intData += destBytesPerSample * numSamples;
  21153. for (int i = numSamples; --i >= 0;)
  21154. {
  21155. intData -= destBytesPerSample;
  21156. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21157. }
  21158. }
  21159. }
  21160. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21161. {
  21162. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21163. char* d = static_cast <char*> (dest);
  21164. for (int i = 0; i < numSamples; ++i)
  21165. {
  21166. *(float*) d = source[i];
  21167. #if JUCE_BIG_ENDIAN
  21168. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21169. #endif
  21170. d += destBytesPerSample;
  21171. }
  21172. }
  21173. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21174. {
  21175. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21176. char* d = static_cast <char*> (dest);
  21177. for (int i = 0; i < numSamples; ++i)
  21178. {
  21179. *(float*) d = source[i];
  21180. #if JUCE_LITTLE_ENDIAN
  21181. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21182. #endif
  21183. d += destBytesPerSample;
  21184. }
  21185. }
  21186. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21187. {
  21188. const float scale = 1.0f / 0x7fff;
  21189. const char* intData = static_cast <const char*> (source);
  21190. if (source != (void*) dest || srcBytesPerSample >= 4)
  21191. {
  21192. for (int i = 0; i < numSamples; ++i)
  21193. {
  21194. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21195. intData += srcBytesPerSample;
  21196. }
  21197. }
  21198. else
  21199. {
  21200. intData += srcBytesPerSample * numSamples;
  21201. for (int i = numSamples; --i >= 0;)
  21202. {
  21203. intData -= srcBytesPerSample;
  21204. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21205. }
  21206. }
  21207. }
  21208. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21209. {
  21210. const float scale = 1.0f / 0x7fff;
  21211. const char* intData = static_cast <const char*> (source);
  21212. if (source != (void*) dest || srcBytesPerSample >= 4)
  21213. {
  21214. for (int i = 0; i < numSamples; ++i)
  21215. {
  21216. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21217. intData += srcBytesPerSample;
  21218. }
  21219. }
  21220. else
  21221. {
  21222. intData += srcBytesPerSample * numSamples;
  21223. for (int i = numSamples; --i >= 0;)
  21224. {
  21225. intData -= srcBytesPerSample;
  21226. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21227. }
  21228. }
  21229. }
  21230. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21231. {
  21232. const float scale = 1.0f / 0x7fffff;
  21233. const char* intData = static_cast <const char*> (source);
  21234. if (source != (void*) dest || srcBytesPerSample >= 4)
  21235. {
  21236. for (int i = 0; i < numSamples; ++i)
  21237. {
  21238. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21239. intData += srcBytesPerSample;
  21240. }
  21241. }
  21242. else
  21243. {
  21244. intData += srcBytesPerSample * numSamples;
  21245. for (int i = numSamples; --i >= 0;)
  21246. {
  21247. intData -= srcBytesPerSample;
  21248. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21249. }
  21250. }
  21251. }
  21252. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21253. {
  21254. const float scale = 1.0f / 0x7fffff;
  21255. const char* intData = static_cast <const char*> (source);
  21256. if (source != (void*) dest || srcBytesPerSample >= 4)
  21257. {
  21258. for (int i = 0; i < numSamples; ++i)
  21259. {
  21260. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21261. intData += srcBytesPerSample;
  21262. }
  21263. }
  21264. else
  21265. {
  21266. intData += srcBytesPerSample * numSamples;
  21267. for (int i = numSamples; --i >= 0;)
  21268. {
  21269. intData -= srcBytesPerSample;
  21270. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21271. }
  21272. }
  21273. }
  21274. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21275. {
  21276. const float scale = 1.0f / 0x7fffffff;
  21277. const char* intData = static_cast <const char*> (source);
  21278. if (source != (void*) dest || srcBytesPerSample >= 4)
  21279. {
  21280. for (int i = 0; i < numSamples; ++i)
  21281. {
  21282. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21283. intData += srcBytesPerSample;
  21284. }
  21285. }
  21286. else
  21287. {
  21288. intData += srcBytesPerSample * numSamples;
  21289. for (int i = numSamples; --i >= 0;)
  21290. {
  21291. intData -= srcBytesPerSample;
  21292. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21293. }
  21294. }
  21295. }
  21296. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21297. {
  21298. const float scale = 1.0f / 0x7fffffff;
  21299. const char* intData = static_cast <const char*> (source);
  21300. if (source != (void*) dest || srcBytesPerSample >= 4)
  21301. {
  21302. for (int i = 0; i < numSamples; ++i)
  21303. {
  21304. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21305. intData += srcBytesPerSample;
  21306. }
  21307. }
  21308. else
  21309. {
  21310. intData += srcBytesPerSample * numSamples;
  21311. for (int i = numSamples; --i >= 0;)
  21312. {
  21313. intData -= srcBytesPerSample;
  21314. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21315. }
  21316. }
  21317. }
  21318. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21319. {
  21320. const char* s = static_cast <const char*> (source);
  21321. for (int i = 0; i < numSamples; ++i)
  21322. {
  21323. dest[i] = *(float*)s;
  21324. #if JUCE_BIG_ENDIAN
  21325. uint32* const d = (uint32*) (dest + i);
  21326. *d = ByteOrder::swap (*d);
  21327. #endif
  21328. s += srcBytesPerSample;
  21329. }
  21330. }
  21331. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21332. {
  21333. const char* s = static_cast <const char*> (source);
  21334. for (int i = 0; i < numSamples; ++i)
  21335. {
  21336. dest[i] = *(float*)s;
  21337. #if JUCE_LITTLE_ENDIAN
  21338. uint32* const d = (uint32*) (dest + i);
  21339. *d = ByteOrder::swap (*d);
  21340. #endif
  21341. s += srcBytesPerSample;
  21342. }
  21343. }
  21344. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21345. const float* const source,
  21346. void* const dest,
  21347. const int numSamples)
  21348. {
  21349. switch (destFormat)
  21350. {
  21351. case int16LE:
  21352. convertFloatToInt16LE (source, dest, numSamples);
  21353. break;
  21354. case int16BE:
  21355. convertFloatToInt16BE (source, dest, numSamples);
  21356. break;
  21357. case int24LE:
  21358. convertFloatToInt24LE (source, dest, numSamples);
  21359. break;
  21360. case int24BE:
  21361. convertFloatToInt24BE (source, dest, numSamples);
  21362. break;
  21363. case int32LE:
  21364. convertFloatToInt32LE (source, dest, numSamples);
  21365. break;
  21366. case int32BE:
  21367. convertFloatToInt32BE (source, dest, numSamples);
  21368. break;
  21369. case float32LE:
  21370. convertFloatToFloat32LE (source, dest, numSamples);
  21371. break;
  21372. case float32BE:
  21373. convertFloatToFloat32BE (source, dest, numSamples);
  21374. break;
  21375. default:
  21376. jassertfalse;
  21377. break;
  21378. }
  21379. }
  21380. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21381. const void* const source,
  21382. float* const dest,
  21383. const int numSamples)
  21384. {
  21385. switch (sourceFormat)
  21386. {
  21387. case int16LE:
  21388. convertInt16LEToFloat (source, dest, numSamples);
  21389. break;
  21390. case int16BE:
  21391. convertInt16BEToFloat (source, dest, numSamples);
  21392. break;
  21393. case int24LE:
  21394. convertInt24LEToFloat (source, dest, numSamples);
  21395. break;
  21396. case int24BE:
  21397. convertInt24BEToFloat (source, dest, numSamples);
  21398. break;
  21399. case int32LE:
  21400. convertInt32LEToFloat (source, dest, numSamples);
  21401. break;
  21402. case int32BE:
  21403. convertInt32BEToFloat (source, dest, numSamples);
  21404. break;
  21405. case float32LE:
  21406. convertFloat32LEToFloat (source, dest, numSamples);
  21407. break;
  21408. case float32BE:
  21409. convertFloat32BEToFloat (source, dest, numSamples);
  21410. break;
  21411. default:
  21412. jassertfalse;
  21413. break;
  21414. }
  21415. }
  21416. void AudioDataConverters::interleaveSamples (const float** const source,
  21417. float* const dest,
  21418. const int numSamples,
  21419. const int numChannels)
  21420. {
  21421. for (int chan = 0; chan < numChannels; ++chan)
  21422. {
  21423. int i = chan;
  21424. const float* src = source [chan];
  21425. for (int j = 0; j < numSamples; ++j)
  21426. {
  21427. dest [i] = src [j];
  21428. i += numChannels;
  21429. }
  21430. }
  21431. }
  21432. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21433. float** const dest,
  21434. const int numSamples,
  21435. const int numChannels)
  21436. {
  21437. for (int chan = 0; chan < numChannels; ++chan)
  21438. {
  21439. int i = chan;
  21440. float* dst = dest [chan];
  21441. for (int j = 0; j < numSamples; ++j)
  21442. {
  21443. dst [j] = source [i];
  21444. i += numChannels;
  21445. }
  21446. }
  21447. }
  21448. #if JUCE_UNIT_TESTS
  21449. class AudioConversionTests : public UnitTest
  21450. {
  21451. public:
  21452. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21453. template <class F1, class E1, class F2, class E2>
  21454. struct Test5
  21455. {
  21456. static void test (UnitTest& unitTest)
  21457. {
  21458. test (unitTest, false);
  21459. test (unitTest, true);
  21460. }
  21461. static void test (UnitTest& unitTest, bool inPlace)
  21462. {
  21463. const int numSamples = 2048;
  21464. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21465. {
  21466. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21467. bool clippingFailed = false;
  21468. for (int i = 0; i < numSamples / 2; ++i)
  21469. {
  21470. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21471. if (! d.isFloatingPoint())
  21472. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21473. ++d;
  21474. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21475. ++d;
  21476. }
  21477. unitTest.expect (! clippingFailed);
  21478. }
  21479. // convert data from the source to dest format..
  21480. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21481. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21482. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21483. // ..and back again..
  21484. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21485. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21486. if (! inPlace)
  21487. zerostruct (reversed);
  21488. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21489. {
  21490. int biggestDiff = 0;
  21491. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21492. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21493. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21494. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21495. for (int i = 0; i < numSamples; ++i)
  21496. {
  21497. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21498. ++d1;
  21499. ++d2;
  21500. }
  21501. unitTest.expect (biggestDiff <= errorMargin);
  21502. }
  21503. }
  21504. };
  21505. template <class F1, class E1, class FormatType>
  21506. struct Test3
  21507. {
  21508. static void test (UnitTest& unitTest)
  21509. {
  21510. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21511. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21512. }
  21513. };
  21514. template <class FormatType, class Endianness>
  21515. struct Test2
  21516. {
  21517. static void test (UnitTest& unitTest)
  21518. {
  21519. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21520. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21521. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21522. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21523. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21524. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21525. }
  21526. };
  21527. template <class FormatType>
  21528. struct Test1
  21529. {
  21530. static void test (UnitTest& unitTest)
  21531. {
  21532. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21533. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21534. }
  21535. };
  21536. void runTest()
  21537. {
  21538. beginTest ("Round-trip conversion");
  21539. Test1 <AudioData::Int8>::test (*this);
  21540. Test1 <AudioData::Int16>::test (*this);
  21541. Test1 <AudioData::Int24>::test (*this);
  21542. Test1 <AudioData::Int32>::test (*this);
  21543. Test1 <AudioData::Float32>::test (*this);
  21544. }
  21545. };
  21546. static AudioConversionTests audioConversionUnitTests;
  21547. #endif
  21548. END_JUCE_NAMESPACE
  21549. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21550. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21551. BEGIN_JUCE_NAMESPACE
  21552. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21553. const int numSamples) throw()
  21554. : numChannels (numChannels_),
  21555. size (numSamples)
  21556. {
  21557. jassert (numSamples >= 0);
  21558. jassert (numChannels_ > 0);
  21559. allocateData();
  21560. }
  21561. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21562. : numChannels (other.numChannels),
  21563. size (other.size)
  21564. {
  21565. allocateData();
  21566. const size_t numBytes = size * sizeof (float);
  21567. for (int i = 0; i < numChannels; ++i)
  21568. memcpy (channels[i], other.channels[i], numBytes);
  21569. }
  21570. void AudioSampleBuffer::allocateData()
  21571. {
  21572. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21573. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21574. allocatedData.malloc (allocatedBytes);
  21575. channels = reinterpret_cast <float**> (allocatedData.getData());
  21576. float* chan = (float*) (allocatedData + channelListSize);
  21577. for (int i = 0; i < numChannels; ++i)
  21578. {
  21579. channels[i] = chan;
  21580. chan += size;
  21581. }
  21582. channels [numChannels] = 0;
  21583. }
  21584. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21585. const int numChannels_,
  21586. const int numSamples) throw()
  21587. : numChannels (numChannels_),
  21588. size (numSamples),
  21589. allocatedBytes (0)
  21590. {
  21591. jassert (numChannels_ > 0);
  21592. allocateChannels (dataToReferTo);
  21593. }
  21594. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21595. const int newNumChannels,
  21596. const int newNumSamples) throw()
  21597. {
  21598. jassert (newNumChannels > 0);
  21599. allocatedBytes = 0;
  21600. allocatedData.free();
  21601. numChannels = newNumChannels;
  21602. size = newNumSamples;
  21603. allocateChannels (dataToReferTo);
  21604. }
  21605. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21606. {
  21607. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21608. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21609. {
  21610. channels = static_cast <float**> (preallocatedChannelSpace);
  21611. }
  21612. else
  21613. {
  21614. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21615. channels = reinterpret_cast <float**> (allocatedData.getData());
  21616. }
  21617. for (int i = 0; i < numChannels; ++i)
  21618. {
  21619. // you have to pass in the same number of valid pointers as numChannels
  21620. jassert (dataToReferTo[i] != 0);
  21621. channels[i] = dataToReferTo[i];
  21622. }
  21623. channels [numChannels] = 0;
  21624. }
  21625. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21626. {
  21627. if (this != &other)
  21628. {
  21629. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21630. const size_t numBytes = size * sizeof (float);
  21631. for (int i = 0; i < numChannels; ++i)
  21632. memcpy (channels[i], other.channels[i], numBytes);
  21633. }
  21634. return *this;
  21635. }
  21636. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21637. {
  21638. }
  21639. void AudioSampleBuffer::setSize (const int newNumChannels,
  21640. const int newNumSamples,
  21641. const bool keepExistingContent,
  21642. const bool clearExtraSpace,
  21643. const bool avoidReallocating) throw()
  21644. {
  21645. jassert (newNumChannels > 0);
  21646. if (newNumSamples != size || newNumChannels != numChannels)
  21647. {
  21648. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21649. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21650. if (keepExistingContent)
  21651. {
  21652. HeapBlock <char> newData;
  21653. newData.allocate (newTotalBytes, clearExtraSpace);
  21654. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21655. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21656. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21657. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21658. for (int i = 0; i < numChansToCopy; ++i)
  21659. {
  21660. memcpy (newChan, channels[i], numBytesToCopy);
  21661. newChannels[i] = newChan;
  21662. newChan += newNumSamples;
  21663. }
  21664. allocatedData.swapWith (newData);
  21665. allocatedBytes = (int) newTotalBytes;
  21666. channels = newChannels;
  21667. }
  21668. else
  21669. {
  21670. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21671. {
  21672. if (clearExtraSpace)
  21673. zeromem (allocatedData, newTotalBytes);
  21674. }
  21675. else
  21676. {
  21677. allocatedBytes = newTotalBytes;
  21678. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21679. channels = reinterpret_cast <float**> (allocatedData.getData());
  21680. }
  21681. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21682. for (int i = 0; i < newNumChannels; ++i)
  21683. {
  21684. channels[i] = chan;
  21685. chan += newNumSamples;
  21686. }
  21687. }
  21688. channels [newNumChannels] = 0;
  21689. size = newNumSamples;
  21690. numChannels = newNumChannels;
  21691. }
  21692. }
  21693. void AudioSampleBuffer::clear() throw()
  21694. {
  21695. for (int i = 0; i < numChannels; ++i)
  21696. zeromem (channels[i], size * sizeof (float));
  21697. }
  21698. void AudioSampleBuffer::clear (const int startSample,
  21699. const int numSamples) throw()
  21700. {
  21701. jassert (startSample >= 0 && startSample + numSamples <= size);
  21702. for (int i = 0; i < numChannels; ++i)
  21703. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21704. }
  21705. void AudioSampleBuffer::clear (const int channel,
  21706. const int startSample,
  21707. const int numSamples) throw()
  21708. {
  21709. jassert (isPositiveAndBelow (channel, numChannels));
  21710. jassert (startSample >= 0 && startSample + numSamples <= size);
  21711. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21712. }
  21713. void AudioSampleBuffer::applyGain (const int channel,
  21714. const int startSample,
  21715. int numSamples,
  21716. const float gain) throw()
  21717. {
  21718. jassert (isPositiveAndBelow (channel, numChannels));
  21719. jassert (startSample >= 0 && startSample + numSamples <= size);
  21720. if (gain != 1.0f)
  21721. {
  21722. float* d = channels [channel] + startSample;
  21723. if (gain == 0.0f)
  21724. {
  21725. zeromem (d, sizeof (float) * numSamples);
  21726. }
  21727. else
  21728. {
  21729. while (--numSamples >= 0)
  21730. *d++ *= gain;
  21731. }
  21732. }
  21733. }
  21734. void AudioSampleBuffer::applyGainRamp (const int channel,
  21735. const int startSample,
  21736. int numSamples,
  21737. float startGain,
  21738. float endGain) throw()
  21739. {
  21740. if (startGain == endGain)
  21741. {
  21742. applyGain (channel, startSample, numSamples, startGain);
  21743. }
  21744. else
  21745. {
  21746. jassert (isPositiveAndBelow (channel, numChannels));
  21747. jassert (startSample >= 0 && startSample + numSamples <= size);
  21748. const float increment = (endGain - startGain) / numSamples;
  21749. float* d = channels [channel] + startSample;
  21750. while (--numSamples >= 0)
  21751. {
  21752. *d++ *= startGain;
  21753. startGain += increment;
  21754. }
  21755. }
  21756. }
  21757. void AudioSampleBuffer::applyGain (const int startSample,
  21758. const int numSamples,
  21759. const float gain) throw()
  21760. {
  21761. for (int i = 0; i < numChannels; ++i)
  21762. applyGain (i, startSample, numSamples, gain);
  21763. }
  21764. void AudioSampleBuffer::addFrom (const int destChannel,
  21765. const int destStartSample,
  21766. const AudioSampleBuffer& source,
  21767. const int sourceChannel,
  21768. const int sourceStartSample,
  21769. int numSamples,
  21770. const float gain) throw()
  21771. {
  21772. jassert (&source != this || sourceChannel != destChannel);
  21773. jassert (isPositiveAndBelow (destChannel, numChannels));
  21774. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21775. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21776. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21777. if (gain != 0.0f && numSamples > 0)
  21778. {
  21779. float* d = channels [destChannel] + destStartSample;
  21780. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21781. if (gain != 1.0f)
  21782. {
  21783. while (--numSamples >= 0)
  21784. *d++ += gain * *s++;
  21785. }
  21786. else
  21787. {
  21788. while (--numSamples >= 0)
  21789. *d++ += *s++;
  21790. }
  21791. }
  21792. }
  21793. void AudioSampleBuffer::addFrom (const int destChannel,
  21794. const int destStartSample,
  21795. const float* source,
  21796. int numSamples,
  21797. const float gain) throw()
  21798. {
  21799. jassert (isPositiveAndBelow (destChannel, numChannels));
  21800. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21801. jassert (source != 0);
  21802. if (gain != 0.0f && numSamples > 0)
  21803. {
  21804. float* d = channels [destChannel] + destStartSample;
  21805. if (gain != 1.0f)
  21806. {
  21807. while (--numSamples >= 0)
  21808. *d++ += gain * *source++;
  21809. }
  21810. else
  21811. {
  21812. while (--numSamples >= 0)
  21813. *d++ += *source++;
  21814. }
  21815. }
  21816. }
  21817. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21818. const int destStartSample,
  21819. const float* source,
  21820. int numSamples,
  21821. float startGain,
  21822. const float endGain) throw()
  21823. {
  21824. jassert (isPositiveAndBelow (destChannel, numChannels));
  21825. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21826. jassert (source != 0);
  21827. if (startGain == endGain)
  21828. {
  21829. addFrom (destChannel,
  21830. destStartSample,
  21831. source,
  21832. numSamples,
  21833. startGain);
  21834. }
  21835. else
  21836. {
  21837. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21838. {
  21839. const float increment = (endGain - startGain) / numSamples;
  21840. float* d = channels [destChannel] + destStartSample;
  21841. while (--numSamples >= 0)
  21842. {
  21843. *d++ += startGain * *source++;
  21844. startGain += increment;
  21845. }
  21846. }
  21847. }
  21848. }
  21849. void AudioSampleBuffer::copyFrom (const int destChannel,
  21850. const int destStartSample,
  21851. const AudioSampleBuffer& source,
  21852. const int sourceChannel,
  21853. const int sourceStartSample,
  21854. int numSamples) throw()
  21855. {
  21856. jassert (&source != this || sourceChannel != destChannel);
  21857. jassert (isPositiveAndBelow (destChannel, numChannels));
  21858. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21859. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21860. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21861. if (numSamples > 0)
  21862. {
  21863. memcpy (channels [destChannel] + destStartSample,
  21864. source.channels [sourceChannel] + sourceStartSample,
  21865. sizeof (float) * numSamples);
  21866. }
  21867. }
  21868. void AudioSampleBuffer::copyFrom (const int destChannel,
  21869. const int destStartSample,
  21870. const float* source,
  21871. int numSamples) throw()
  21872. {
  21873. jassert (isPositiveAndBelow (destChannel, numChannels));
  21874. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21875. jassert (source != 0);
  21876. if (numSamples > 0)
  21877. {
  21878. memcpy (channels [destChannel] + destStartSample,
  21879. source,
  21880. sizeof (float) * numSamples);
  21881. }
  21882. }
  21883. void AudioSampleBuffer::copyFrom (const int destChannel,
  21884. const int destStartSample,
  21885. const float* source,
  21886. int numSamples,
  21887. const float gain) throw()
  21888. {
  21889. jassert (isPositiveAndBelow (destChannel, numChannels));
  21890. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21891. jassert (source != 0);
  21892. if (numSamples > 0)
  21893. {
  21894. float* d = channels [destChannel] + destStartSample;
  21895. if (gain != 1.0f)
  21896. {
  21897. if (gain == 0)
  21898. {
  21899. zeromem (d, sizeof (float) * numSamples);
  21900. }
  21901. else
  21902. {
  21903. while (--numSamples >= 0)
  21904. *d++ = gain * *source++;
  21905. }
  21906. }
  21907. else
  21908. {
  21909. memcpy (d, source, sizeof (float) * numSamples);
  21910. }
  21911. }
  21912. }
  21913. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21914. const int destStartSample,
  21915. const float* source,
  21916. int numSamples,
  21917. float startGain,
  21918. float endGain) throw()
  21919. {
  21920. jassert (isPositiveAndBelow (destChannel, numChannels));
  21921. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21922. jassert (source != 0);
  21923. if (startGain == endGain)
  21924. {
  21925. copyFrom (destChannel,
  21926. destStartSample,
  21927. source,
  21928. numSamples,
  21929. startGain);
  21930. }
  21931. else
  21932. {
  21933. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21934. {
  21935. const float increment = (endGain - startGain) / numSamples;
  21936. float* d = channels [destChannel] + destStartSample;
  21937. while (--numSamples >= 0)
  21938. {
  21939. *d++ = startGain * *source++;
  21940. startGain += increment;
  21941. }
  21942. }
  21943. }
  21944. }
  21945. void AudioSampleBuffer::findMinMax (const int channel,
  21946. const int startSample,
  21947. int numSamples,
  21948. float& minVal,
  21949. float& maxVal) const throw()
  21950. {
  21951. jassert (isPositiveAndBelow (channel, numChannels));
  21952. jassert (startSample >= 0 && startSample + numSamples <= size);
  21953. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21954. }
  21955. float AudioSampleBuffer::getMagnitude (const int channel,
  21956. const int startSample,
  21957. const int numSamples) const throw()
  21958. {
  21959. jassert (isPositiveAndBelow (channel, numChannels));
  21960. jassert (startSample >= 0 && startSample + numSamples <= size);
  21961. float mn, mx;
  21962. findMinMax (channel, startSample, numSamples, mn, mx);
  21963. return jmax (mn, -mn, mx, -mx);
  21964. }
  21965. float AudioSampleBuffer::getMagnitude (const int startSample,
  21966. const int numSamples) const throw()
  21967. {
  21968. float mag = 0.0f;
  21969. for (int i = 0; i < numChannels; ++i)
  21970. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21971. return mag;
  21972. }
  21973. float AudioSampleBuffer::getRMSLevel (const int channel,
  21974. const int startSample,
  21975. const int numSamples) const throw()
  21976. {
  21977. jassert (isPositiveAndBelow (channel, numChannels));
  21978. jassert (startSample >= 0 && startSample + numSamples <= size);
  21979. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21980. return 0.0f;
  21981. const float* const data = channels [channel] + startSample;
  21982. double sum = 0.0;
  21983. for (int i = 0; i < numSamples; ++i)
  21984. {
  21985. const float sample = data [i];
  21986. sum += sample * sample;
  21987. }
  21988. return (float) std::sqrt (sum / numSamples);
  21989. }
  21990. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21991. const int startSample,
  21992. const int numSamples,
  21993. const int readerStartSample,
  21994. const bool useLeftChan,
  21995. const bool useRightChan)
  21996. {
  21997. jassert (reader != 0);
  21998. jassert (startSample >= 0 && startSample + numSamples <= size);
  21999. if (numSamples > 0)
  22000. {
  22001. int* chans[3];
  22002. if (useLeftChan == useRightChan)
  22003. {
  22004. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22005. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22006. }
  22007. else if (useLeftChan || (reader->numChannels == 1))
  22008. {
  22009. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22010. chans[1] = 0;
  22011. }
  22012. else if (useRightChan)
  22013. {
  22014. chans[0] = 0;
  22015. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22016. }
  22017. chans[2] = 0;
  22018. reader->read (chans, 2, readerStartSample, numSamples, true);
  22019. if (! reader->usesFloatingPointData)
  22020. {
  22021. for (int j = 0; j < 2; ++j)
  22022. {
  22023. float* const d = reinterpret_cast <float*> (chans[j]);
  22024. if (d != 0)
  22025. {
  22026. const float multiplier = 1.0f / 0x7fffffff;
  22027. for (int i = 0; i < numSamples; ++i)
  22028. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22029. }
  22030. }
  22031. }
  22032. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22033. {
  22034. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22035. memcpy (getSampleData (1, startSample),
  22036. getSampleData (0, startSample),
  22037. sizeof (float) * numSamples);
  22038. }
  22039. }
  22040. }
  22041. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22042. const int startSample,
  22043. const int numSamples) const
  22044. {
  22045. jassert (writer != 0);
  22046. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22047. }
  22048. END_JUCE_NAMESPACE
  22049. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22050. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22051. BEGIN_JUCE_NAMESPACE
  22052. IIRFilter::IIRFilter()
  22053. : active (false)
  22054. {
  22055. reset();
  22056. }
  22057. IIRFilter::IIRFilter (const IIRFilter& other)
  22058. : active (other.active)
  22059. {
  22060. const ScopedLock sl (other.processLock);
  22061. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22062. reset();
  22063. }
  22064. IIRFilter::~IIRFilter()
  22065. {
  22066. }
  22067. void IIRFilter::reset() throw()
  22068. {
  22069. const ScopedLock sl (processLock);
  22070. x1 = 0;
  22071. x2 = 0;
  22072. y1 = 0;
  22073. y2 = 0;
  22074. }
  22075. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22076. {
  22077. float out = coefficients[0] * in
  22078. + coefficients[1] * x1
  22079. + coefficients[2] * x2
  22080. - coefficients[4] * y1
  22081. - coefficients[5] * y2;
  22082. #if JUCE_INTEL
  22083. if (! (out < -1.0e-8 || out > 1.0e-8))
  22084. out = 0;
  22085. #endif
  22086. x2 = x1;
  22087. x1 = in;
  22088. y2 = y1;
  22089. y1 = out;
  22090. return out;
  22091. }
  22092. void IIRFilter::processSamples (float* const samples,
  22093. const int numSamples) throw()
  22094. {
  22095. const ScopedLock sl (processLock);
  22096. if (active)
  22097. {
  22098. for (int i = 0; i < numSamples; ++i)
  22099. {
  22100. const float in = samples[i];
  22101. float out = coefficients[0] * in
  22102. + coefficients[1] * x1
  22103. + coefficients[2] * x2
  22104. - coefficients[4] * y1
  22105. - coefficients[5] * y2;
  22106. #if JUCE_INTEL
  22107. if (! (out < -1.0e-8 || out > 1.0e-8))
  22108. out = 0;
  22109. #endif
  22110. x2 = x1;
  22111. x1 = in;
  22112. y2 = y1;
  22113. y1 = out;
  22114. samples[i] = out;
  22115. }
  22116. }
  22117. }
  22118. void IIRFilter::makeLowPass (const double sampleRate,
  22119. const double frequency) throw()
  22120. {
  22121. jassert (sampleRate > 0);
  22122. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22123. const double nSquared = n * n;
  22124. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22125. setCoefficients (c1,
  22126. c1 * 2.0f,
  22127. c1,
  22128. 1.0,
  22129. c1 * 2.0 * (1.0 - nSquared),
  22130. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22131. }
  22132. void IIRFilter::makeHighPass (const double sampleRate,
  22133. const double frequency) throw()
  22134. {
  22135. const double n = tan (double_Pi * frequency / sampleRate);
  22136. const double nSquared = n * n;
  22137. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22138. setCoefficients (c1,
  22139. c1 * -2.0f,
  22140. c1,
  22141. 1.0,
  22142. c1 * 2.0 * (nSquared - 1.0),
  22143. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22144. }
  22145. void IIRFilter::makeLowShelf (const double sampleRate,
  22146. const double cutOffFrequency,
  22147. const double Q,
  22148. const float gainFactor) throw()
  22149. {
  22150. jassert (sampleRate > 0);
  22151. jassert (Q > 0);
  22152. const double A = jmax (0.0f, gainFactor);
  22153. const double aminus1 = A - 1.0;
  22154. const double aplus1 = A + 1.0;
  22155. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22156. const double coso = std::cos (omega);
  22157. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22158. const double aminus1TimesCoso = aminus1 * coso;
  22159. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22160. A * 2.0 * (aminus1 - aplus1 * coso),
  22161. A * (aplus1 - aminus1TimesCoso - beta),
  22162. aplus1 + aminus1TimesCoso + beta,
  22163. -2.0 * (aminus1 + aplus1 * coso),
  22164. aplus1 + aminus1TimesCoso - beta);
  22165. }
  22166. void IIRFilter::makeHighShelf (const double sampleRate,
  22167. const double cutOffFrequency,
  22168. const double Q,
  22169. const float gainFactor) throw()
  22170. {
  22171. jassert (sampleRate > 0);
  22172. jassert (Q > 0);
  22173. const double A = jmax (0.0f, gainFactor);
  22174. const double aminus1 = A - 1.0;
  22175. const double aplus1 = A + 1.0;
  22176. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22177. const double coso = std::cos (omega);
  22178. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22179. const double aminus1TimesCoso = aminus1 * coso;
  22180. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22181. A * -2.0 * (aminus1 + aplus1 * coso),
  22182. A * (aplus1 + aminus1TimesCoso - beta),
  22183. aplus1 - aminus1TimesCoso + beta,
  22184. 2.0 * (aminus1 - aplus1 * coso),
  22185. aplus1 - aminus1TimesCoso - beta);
  22186. }
  22187. void IIRFilter::makeBandPass (const double sampleRate,
  22188. const double centreFrequency,
  22189. const double Q,
  22190. const float gainFactor) throw()
  22191. {
  22192. jassert (sampleRate > 0);
  22193. jassert (Q > 0);
  22194. const double A = jmax (0.0f, gainFactor);
  22195. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22196. const double alpha = 0.5 * std::sin (omega) / Q;
  22197. const double c2 = -2.0 * std::cos (omega);
  22198. const double alphaTimesA = alpha * A;
  22199. const double alphaOverA = alpha / A;
  22200. setCoefficients (1.0 + alphaTimesA,
  22201. c2,
  22202. 1.0 - alphaTimesA,
  22203. 1.0 + alphaOverA,
  22204. c2,
  22205. 1.0 - alphaOverA);
  22206. }
  22207. void IIRFilter::makeInactive() throw()
  22208. {
  22209. const ScopedLock sl (processLock);
  22210. active = false;
  22211. }
  22212. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22213. {
  22214. const ScopedLock sl (processLock);
  22215. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22216. active = other.active;
  22217. }
  22218. void IIRFilter::setCoefficients (double c1,
  22219. double c2,
  22220. double c3,
  22221. double c4,
  22222. double c5,
  22223. double c6) throw()
  22224. {
  22225. const double a = 1.0 / c4;
  22226. c1 *= a;
  22227. c2 *= a;
  22228. c3 *= a;
  22229. c5 *= a;
  22230. c6 *= a;
  22231. const ScopedLock sl (processLock);
  22232. coefficients[0] = (float) c1;
  22233. coefficients[1] = (float) c2;
  22234. coefficients[2] = (float) c3;
  22235. coefficients[3] = (float) c4;
  22236. coefficients[4] = (float) c5;
  22237. coefficients[5] = (float) c6;
  22238. active = true;
  22239. }
  22240. END_JUCE_NAMESPACE
  22241. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22242. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22243. BEGIN_JUCE_NAMESPACE
  22244. MidiBuffer::MidiBuffer() throw()
  22245. : bytesUsed (0)
  22246. {
  22247. }
  22248. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22249. : bytesUsed (0)
  22250. {
  22251. addEvent (message, 0);
  22252. }
  22253. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22254. : data (other.data),
  22255. bytesUsed (other.bytesUsed)
  22256. {
  22257. }
  22258. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22259. {
  22260. bytesUsed = other.bytesUsed;
  22261. data = other.data;
  22262. return *this;
  22263. }
  22264. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22265. {
  22266. data.swapWith (other.data);
  22267. swapVariables <int> (bytesUsed, other.bytesUsed);
  22268. }
  22269. MidiBuffer::~MidiBuffer()
  22270. {
  22271. }
  22272. inline uint8* MidiBuffer::getData() const throw()
  22273. {
  22274. return static_cast <uint8*> (data.getData());
  22275. }
  22276. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22277. {
  22278. return *static_cast <const int*> (d);
  22279. }
  22280. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22281. {
  22282. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22283. }
  22284. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22285. {
  22286. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22287. }
  22288. void MidiBuffer::clear() throw()
  22289. {
  22290. bytesUsed = 0;
  22291. }
  22292. void MidiBuffer::clear (const int startSample, const int numSamples)
  22293. {
  22294. uint8* const start = findEventAfter (getData(), startSample - 1);
  22295. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22296. if (end > start)
  22297. {
  22298. const int bytesToMove = bytesUsed - (int) (end - getData());
  22299. if (bytesToMove > 0)
  22300. memmove (start, end, bytesToMove);
  22301. bytesUsed -= (int) (end - start);
  22302. }
  22303. }
  22304. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22305. {
  22306. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22307. }
  22308. namespace MidiBufferHelpers
  22309. {
  22310. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22311. {
  22312. unsigned int byte = (unsigned int) *data;
  22313. int size = 0;
  22314. if (byte == 0xf0 || byte == 0xf7)
  22315. {
  22316. const uint8* d = data + 1;
  22317. while (d < data + maxBytes)
  22318. if (*d++ == 0xf7)
  22319. break;
  22320. size = (int) (d - data);
  22321. }
  22322. else if (byte == 0xff)
  22323. {
  22324. int n;
  22325. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22326. size = jmin (maxBytes, n + 2 + bytesLeft);
  22327. }
  22328. else if (byte >= 0x80)
  22329. {
  22330. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22331. }
  22332. return size;
  22333. }
  22334. }
  22335. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22336. {
  22337. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22338. if (numBytes > 0)
  22339. {
  22340. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22341. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22342. uint8* d = findEventAfter (getData(), sampleNumber);
  22343. const int bytesToMove = bytesUsed - (int) (d - getData());
  22344. if (bytesToMove > 0)
  22345. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22346. *reinterpret_cast <int*> (d) = sampleNumber;
  22347. d += sizeof (int);
  22348. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22349. d += sizeof (uint16);
  22350. memcpy (d, newData, numBytes);
  22351. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22352. }
  22353. }
  22354. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22355. const int startSample,
  22356. const int numSamples,
  22357. const int sampleDeltaToAdd)
  22358. {
  22359. Iterator i (otherBuffer);
  22360. i.setNextSamplePosition (startSample);
  22361. const uint8* eventData;
  22362. int eventSize, position;
  22363. while (i.getNextEvent (eventData, eventSize, position)
  22364. && (position < startSample + numSamples || numSamples < 0))
  22365. {
  22366. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22367. }
  22368. }
  22369. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22370. {
  22371. data.ensureSize (minimumNumBytes);
  22372. }
  22373. bool MidiBuffer::isEmpty() const throw()
  22374. {
  22375. return bytesUsed == 0;
  22376. }
  22377. int MidiBuffer::getNumEvents() const throw()
  22378. {
  22379. int n = 0;
  22380. const uint8* d = getData();
  22381. const uint8* const end = d + bytesUsed;
  22382. while (d < end)
  22383. {
  22384. d += getEventTotalSize (d);
  22385. ++n;
  22386. }
  22387. return n;
  22388. }
  22389. int MidiBuffer::getFirstEventTime() const throw()
  22390. {
  22391. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22392. }
  22393. int MidiBuffer::getLastEventTime() const throw()
  22394. {
  22395. if (bytesUsed == 0)
  22396. return 0;
  22397. const uint8* d = getData();
  22398. const uint8* const endData = d + bytesUsed;
  22399. for (;;)
  22400. {
  22401. const uint8* const nextOne = d + getEventTotalSize (d);
  22402. if (nextOne >= endData)
  22403. return getEventTime (d);
  22404. d = nextOne;
  22405. }
  22406. }
  22407. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22408. {
  22409. const uint8* const endData = getData() + bytesUsed;
  22410. while (d < endData && getEventTime (d) <= samplePosition)
  22411. d += getEventTotalSize (d);
  22412. return d;
  22413. }
  22414. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22415. : buffer (buffer_),
  22416. data (buffer_.getData())
  22417. {
  22418. }
  22419. MidiBuffer::Iterator::~Iterator() throw()
  22420. {
  22421. }
  22422. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22423. {
  22424. data = buffer.getData();
  22425. const uint8* dataEnd = data + buffer.bytesUsed;
  22426. while (data < dataEnd && getEventTime (data) < samplePosition)
  22427. data += getEventTotalSize (data);
  22428. }
  22429. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22430. {
  22431. if (data >= buffer.getData() + buffer.bytesUsed)
  22432. return false;
  22433. samplePosition = getEventTime (data);
  22434. numBytes = getEventDataSize (data);
  22435. data += sizeof (int) + sizeof (uint16);
  22436. midiData = data;
  22437. data += numBytes;
  22438. return true;
  22439. }
  22440. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22441. {
  22442. if (data >= buffer.getData() + buffer.bytesUsed)
  22443. return false;
  22444. samplePosition = getEventTime (data);
  22445. const int numBytes = getEventDataSize (data);
  22446. data += sizeof (int) + sizeof (uint16);
  22447. result = MidiMessage (data, numBytes, samplePosition);
  22448. data += numBytes;
  22449. return true;
  22450. }
  22451. END_JUCE_NAMESPACE
  22452. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22453. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22454. BEGIN_JUCE_NAMESPACE
  22455. namespace MidiFileHelpers
  22456. {
  22457. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22458. {
  22459. unsigned int buffer = v & 0x7F;
  22460. while ((v >>= 7) != 0)
  22461. {
  22462. buffer <<= 8;
  22463. buffer |= ((v & 0x7F) | 0x80);
  22464. }
  22465. for (;;)
  22466. {
  22467. out.writeByte ((char) buffer);
  22468. if (buffer & 0x80)
  22469. buffer >>= 8;
  22470. else
  22471. break;
  22472. }
  22473. }
  22474. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22475. {
  22476. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22477. data += 4;
  22478. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22479. {
  22480. bool ok = false;
  22481. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22482. {
  22483. for (int i = 0; i < 8; ++i)
  22484. {
  22485. ch = ByteOrder::bigEndianInt (data);
  22486. data += 4;
  22487. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22488. {
  22489. ok = true;
  22490. break;
  22491. }
  22492. }
  22493. }
  22494. if (! ok)
  22495. return false;
  22496. }
  22497. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22498. data += 4;
  22499. fileType = (short) ByteOrder::bigEndianShort (data);
  22500. data += 2;
  22501. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22502. data += 2;
  22503. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22504. data += 2;
  22505. bytesRemaining -= 6;
  22506. data += bytesRemaining;
  22507. return true;
  22508. }
  22509. double convertTicksToSeconds (const double time,
  22510. const MidiMessageSequence& tempoEvents,
  22511. const int timeFormat)
  22512. {
  22513. if (timeFormat > 0)
  22514. {
  22515. int numer = 4, denom = 4;
  22516. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22517. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22518. double secsPerTick = 0.5 * tickLen;
  22519. const int numEvents = tempoEvents.getNumEvents();
  22520. for (int i = 0; i < numEvents; ++i)
  22521. {
  22522. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22523. if (time <= m.getTimeStamp())
  22524. break;
  22525. if (timeFormat > 0)
  22526. {
  22527. correctedTempoTime = correctedTempoTime
  22528. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22529. }
  22530. else
  22531. {
  22532. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22533. }
  22534. tempoTime = m.getTimeStamp();
  22535. if (m.isTempoMetaEvent())
  22536. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22537. else if (m.isTimeSignatureMetaEvent())
  22538. m.getTimeSignatureInfo (numer, denom);
  22539. while (i + 1 < numEvents)
  22540. {
  22541. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22542. if (m2.getTimeStamp() == tempoTime)
  22543. {
  22544. ++i;
  22545. if (m2.isTempoMetaEvent())
  22546. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22547. else if (m2.isTimeSignatureMetaEvent())
  22548. m2.getTimeSignatureInfo (numer, denom);
  22549. }
  22550. else
  22551. {
  22552. break;
  22553. }
  22554. }
  22555. }
  22556. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22557. }
  22558. else
  22559. {
  22560. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22561. }
  22562. }
  22563. // a comparator that puts all the note-offs before note-ons that have the same time
  22564. struct Sorter
  22565. {
  22566. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22567. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22568. {
  22569. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22570. if (diff == 0)
  22571. {
  22572. if (first->message.isNoteOff() && second->message.isNoteOn())
  22573. return -1;
  22574. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22575. return 1;
  22576. else
  22577. return 0;
  22578. }
  22579. else
  22580. {
  22581. return (diff > 0) ? 1 : -1;
  22582. }
  22583. }
  22584. };
  22585. }
  22586. MidiFile::MidiFile()
  22587. : timeFormat ((short) (unsigned short) 0xe728)
  22588. {
  22589. }
  22590. MidiFile::~MidiFile()
  22591. {
  22592. clear();
  22593. }
  22594. void MidiFile::clear()
  22595. {
  22596. tracks.clear();
  22597. }
  22598. int MidiFile::getNumTracks() const throw()
  22599. {
  22600. return tracks.size();
  22601. }
  22602. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22603. {
  22604. return tracks [index];
  22605. }
  22606. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22607. {
  22608. tracks.add (new MidiMessageSequence (trackSequence));
  22609. }
  22610. short MidiFile::getTimeFormat() const throw()
  22611. {
  22612. return timeFormat;
  22613. }
  22614. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22615. {
  22616. timeFormat = (short) ticks;
  22617. }
  22618. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22619. const int subframeResolution) throw()
  22620. {
  22621. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22622. }
  22623. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22624. {
  22625. for (int i = tracks.size(); --i >= 0;)
  22626. {
  22627. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22628. for (int j = 0; j < numEvents; ++j)
  22629. {
  22630. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22631. if (m.isTempoMetaEvent())
  22632. tempoChangeEvents.addEvent (m);
  22633. }
  22634. }
  22635. }
  22636. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22637. {
  22638. for (int i = tracks.size(); --i >= 0;)
  22639. {
  22640. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22641. for (int j = 0; j < numEvents; ++j)
  22642. {
  22643. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22644. if (m.isTimeSignatureMetaEvent())
  22645. timeSigEvents.addEvent (m);
  22646. }
  22647. }
  22648. }
  22649. double MidiFile::getLastTimestamp() const
  22650. {
  22651. double t = 0.0;
  22652. for (int i = tracks.size(); --i >= 0;)
  22653. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22654. return t;
  22655. }
  22656. bool MidiFile::readFrom (InputStream& sourceStream)
  22657. {
  22658. clear();
  22659. MemoryBlock data;
  22660. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22661. // (put a sanity-check on the file size, as midi files are generally small)
  22662. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22663. {
  22664. size_t size = data.getSize();
  22665. const uint8* d = static_cast <const uint8*> (data.getData());
  22666. short fileType, expectedTracks;
  22667. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22668. {
  22669. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22670. int track = 0;
  22671. while (size > 0 && track < expectedTracks)
  22672. {
  22673. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22674. d += 4;
  22675. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22676. d += 4;
  22677. if (chunkSize <= 0)
  22678. break;
  22679. if (size < 0)
  22680. return false;
  22681. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22682. {
  22683. readNextTrack (d, chunkSize);
  22684. }
  22685. size -= chunkSize + 8;
  22686. d += chunkSize;
  22687. ++track;
  22688. }
  22689. return true;
  22690. }
  22691. }
  22692. return false;
  22693. }
  22694. void MidiFile::readNextTrack (const uint8* data, int size)
  22695. {
  22696. double time = 0;
  22697. char lastStatusByte = 0;
  22698. MidiMessageSequence result;
  22699. while (size > 0)
  22700. {
  22701. int bytesUsed;
  22702. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22703. data += bytesUsed;
  22704. size -= bytesUsed;
  22705. time += delay;
  22706. int messSize = 0;
  22707. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22708. if (messSize <= 0)
  22709. break;
  22710. size -= messSize;
  22711. data += messSize;
  22712. result.addEvent (mm);
  22713. const char firstByte = *(mm.getRawData());
  22714. if ((firstByte & 0xf0) != 0xf0)
  22715. lastStatusByte = firstByte;
  22716. }
  22717. // use a sort that puts all the note-offs before note-ons that have the same time
  22718. MidiFileHelpers::Sorter sorter;
  22719. result.list.sort (sorter, true);
  22720. result.updateMatchedPairs();
  22721. addTrack (result);
  22722. }
  22723. void MidiFile::convertTimestampTicksToSeconds()
  22724. {
  22725. MidiMessageSequence tempoEvents;
  22726. findAllTempoEvents (tempoEvents);
  22727. findAllTimeSigEvents (tempoEvents);
  22728. for (int i = 0; i < tracks.size(); ++i)
  22729. {
  22730. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22731. for (int j = ms.getNumEvents(); --j >= 0;)
  22732. {
  22733. MidiMessage& m = ms.getEventPointer(j)->message;
  22734. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22735. tempoEvents,
  22736. timeFormat));
  22737. }
  22738. }
  22739. }
  22740. bool MidiFile::writeTo (OutputStream& out)
  22741. {
  22742. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22743. out.writeIntBigEndian (6);
  22744. out.writeShortBigEndian (1); // type
  22745. out.writeShortBigEndian ((short) tracks.size());
  22746. out.writeShortBigEndian (timeFormat);
  22747. for (int i = 0; i < tracks.size(); ++i)
  22748. writeTrack (out, i);
  22749. out.flush();
  22750. return true;
  22751. }
  22752. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22753. {
  22754. MemoryOutputStream out;
  22755. const MidiMessageSequence& ms = *tracks[trackNum];
  22756. int lastTick = 0;
  22757. char lastStatusByte = 0;
  22758. for (int i = 0; i < ms.getNumEvents(); ++i)
  22759. {
  22760. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22761. const int tick = roundToInt (mm.getTimeStamp());
  22762. const int delta = jmax (0, tick - lastTick);
  22763. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22764. lastTick = tick;
  22765. const char statusByte = *(mm.getRawData());
  22766. if ((statusByte == lastStatusByte)
  22767. && ((statusByte & 0xf0) != 0xf0)
  22768. && i > 0
  22769. && mm.getRawDataSize() > 1)
  22770. {
  22771. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22772. }
  22773. else
  22774. {
  22775. out.write (mm.getRawData(), mm.getRawDataSize());
  22776. }
  22777. lastStatusByte = statusByte;
  22778. }
  22779. out.writeByte (0);
  22780. const MidiMessage m (MidiMessage::endOfTrack());
  22781. out.write (m.getRawData(),
  22782. m.getRawDataSize());
  22783. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22784. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22785. mainOut.write (out.getData(), (int) out.getDataSize());
  22786. }
  22787. END_JUCE_NAMESPACE
  22788. /*** End of inlined file: juce_MidiFile.cpp ***/
  22789. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22790. BEGIN_JUCE_NAMESPACE
  22791. MidiKeyboardState::MidiKeyboardState()
  22792. {
  22793. zerostruct (noteStates);
  22794. }
  22795. MidiKeyboardState::~MidiKeyboardState()
  22796. {
  22797. }
  22798. void MidiKeyboardState::reset()
  22799. {
  22800. const ScopedLock sl (lock);
  22801. zerostruct (noteStates);
  22802. eventsToAdd.clear();
  22803. }
  22804. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22805. {
  22806. jassert (midiChannel >= 0 && midiChannel <= 16);
  22807. return isPositiveAndBelow (n, (int) 128)
  22808. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22809. }
  22810. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22811. {
  22812. return isPositiveAndBelow (n, (int) 128)
  22813. && (noteStates[n] & midiChannelMask) != 0;
  22814. }
  22815. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22816. {
  22817. jassert (midiChannel >= 0 && midiChannel <= 16);
  22818. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22819. const ScopedLock sl (lock);
  22820. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22821. {
  22822. const int timeNow = (int) Time::getMillisecondCounter();
  22823. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22824. eventsToAdd.clear (0, timeNow - 500);
  22825. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22826. }
  22827. }
  22828. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22829. {
  22830. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22831. {
  22832. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22833. for (int i = listeners.size(); --i >= 0;)
  22834. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22835. }
  22836. }
  22837. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22838. {
  22839. const ScopedLock sl (lock);
  22840. if (isNoteOn (midiChannel, midiNoteNumber))
  22841. {
  22842. const int timeNow = (int) Time::getMillisecondCounter();
  22843. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22844. eventsToAdd.clear (0, timeNow - 500);
  22845. noteOffInternal (midiChannel, midiNoteNumber);
  22846. }
  22847. }
  22848. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22849. {
  22850. if (isNoteOn (midiChannel, midiNoteNumber))
  22851. {
  22852. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22853. for (int i = listeners.size(); --i >= 0;)
  22854. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22855. }
  22856. }
  22857. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22858. {
  22859. const ScopedLock sl (lock);
  22860. if (midiChannel <= 0)
  22861. {
  22862. for (int i = 1; i <= 16; ++i)
  22863. allNotesOff (i);
  22864. }
  22865. else
  22866. {
  22867. for (int i = 0; i < 128; ++i)
  22868. noteOff (midiChannel, i);
  22869. }
  22870. }
  22871. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22872. {
  22873. if (message.isNoteOn())
  22874. {
  22875. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22876. }
  22877. else if (message.isNoteOff())
  22878. {
  22879. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22880. }
  22881. else if (message.isAllNotesOff())
  22882. {
  22883. for (int i = 0; i < 128; ++i)
  22884. noteOffInternal (message.getChannel(), i);
  22885. }
  22886. }
  22887. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22888. const int startSample,
  22889. const int numSamples,
  22890. const bool injectIndirectEvents)
  22891. {
  22892. MidiBuffer::Iterator i (buffer);
  22893. MidiMessage message (0xf4, 0.0);
  22894. int time;
  22895. const ScopedLock sl (lock);
  22896. while (i.getNextEvent (message, time))
  22897. processNextMidiEvent (message);
  22898. if (injectIndirectEvents)
  22899. {
  22900. MidiBuffer::Iterator i2 (eventsToAdd);
  22901. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22902. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22903. while (i2.getNextEvent (message, time))
  22904. {
  22905. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22906. buffer.addEvent (message, startSample + pos);
  22907. }
  22908. }
  22909. eventsToAdd.clear();
  22910. }
  22911. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22912. {
  22913. const ScopedLock sl (lock);
  22914. listeners.addIfNotAlreadyThere (listener);
  22915. }
  22916. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22917. {
  22918. const ScopedLock sl (lock);
  22919. listeners.removeValue (listener);
  22920. }
  22921. END_JUCE_NAMESPACE
  22922. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22923. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22924. BEGIN_JUCE_NAMESPACE
  22925. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22926. {
  22927. numBytesUsed = 0;
  22928. int v = 0;
  22929. int i;
  22930. do
  22931. {
  22932. i = (int) *data++;
  22933. if (++numBytesUsed > 6)
  22934. break;
  22935. v = (v << 7) + (i & 0x7f);
  22936. } while (i & 0x80);
  22937. return v;
  22938. }
  22939. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22940. {
  22941. // this method only works for valid starting bytes of a short midi message
  22942. jassert (firstByte >= 0x80
  22943. && firstByte != 0xf0
  22944. && firstByte != 0xf7);
  22945. static const char messageLengths[] =
  22946. {
  22947. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22948. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22949. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22950. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22951. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22952. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22953. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22954. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22955. };
  22956. return messageLengths [firstByte & 0x7f];
  22957. }
  22958. MidiMessage::MidiMessage() throw()
  22959. : timeStamp (0),
  22960. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22961. size (1)
  22962. {
  22963. data[0] = 0xfe;
  22964. }
  22965. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22966. : timeStamp (t),
  22967. size (dataSize)
  22968. {
  22969. jassert (dataSize > 0);
  22970. if (dataSize <= 4)
  22971. data = static_cast<uint8*> (preallocatedData.asBytes);
  22972. else
  22973. data = new uint8 [dataSize];
  22974. memcpy (data, d, dataSize);
  22975. // check that the length matches the data..
  22976. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22977. }
  22978. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22979. : timeStamp (t),
  22980. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22981. size (1)
  22982. {
  22983. data[0] = (uint8) byte1;
  22984. // check that the length matches the data..
  22985. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22986. }
  22987. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22988. : timeStamp (t),
  22989. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22990. size (2)
  22991. {
  22992. data[0] = (uint8) byte1;
  22993. data[1] = (uint8) byte2;
  22994. // check that the length matches the data..
  22995. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22996. }
  22997. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22998. : timeStamp (t),
  22999. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23000. size (3)
  23001. {
  23002. data[0] = (uint8) byte1;
  23003. data[1] = (uint8) byte2;
  23004. data[2] = (uint8) byte3;
  23005. // check that the length matches the data..
  23006. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23007. }
  23008. MidiMessage::MidiMessage (const MidiMessage& other)
  23009. : timeStamp (other.timeStamp),
  23010. size (other.size)
  23011. {
  23012. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23013. {
  23014. data = new uint8 [size];
  23015. memcpy (data, other.data, size);
  23016. }
  23017. else
  23018. {
  23019. data = static_cast<uint8*> (preallocatedData.asBytes);
  23020. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23021. }
  23022. }
  23023. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23024. : timeStamp (newTimeStamp),
  23025. size (other.size)
  23026. {
  23027. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23028. {
  23029. data = new uint8 [size];
  23030. memcpy (data, other.data, size);
  23031. }
  23032. else
  23033. {
  23034. data = static_cast<uint8*> (preallocatedData.asBytes);
  23035. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23036. }
  23037. }
  23038. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23039. : timeStamp (t),
  23040. data (static_cast<uint8*> (preallocatedData.asBytes))
  23041. {
  23042. const uint8* src = static_cast <const uint8*> (src_);
  23043. unsigned int byte = (unsigned int) *src;
  23044. if (byte < 0x80)
  23045. {
  23046. byte = (unsigned int) (uint8) lastStatusByte;
  23047. numBytesUsed = -1;
  23048. }
  23049. else
  23050. {
  23051. numBytesUsed = 0;
  23052. --sz;
  23053. ++src;
  23054. }
  23055. if (byte >= 0x80)
  23056. {
  23057. if (byte == 0xf0)
  23058. {
  23059. const uint8* d = src;
  23060. bool haveReadAllLengthBytes = false;
  23061. while (d < src + sz)
  23062. {
  23063. if (*d >= 0x80)
  23064. {
  23065. if (*d == 0xf7)
  23066. {
  23067. ++d; // include the trailing 0xf7 when we hit it
  23068. break;
  23069. }
  23070. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  23071. break; // bytes, assume it's the end of the sysex
  23072. ++d;
  23073. continue;
  23074. }
  23075. haveReadAllLengthBytes = true;
  23076. ++d;
  23077. }
  23078. size = 1 + (int) (d - src);
  23079. data = new uint8 [size];
  23080. *data = (uint8) byte;
  23081. memcpy (data + 1, src, size - 1);
  23082. }
  23083. else if (byte == 0xff)
  23084. {
  23085. int n;
  23086. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23087. size = jmin (sz + 1, n + 2 + bytesLeft);
  23088. data = new uint8 [size];
  23089. *data = (uint8) byte;
  23090. memcpy (data + 1, src, size - 1);
  23091. }
  23092. else
  23093. {
  23094. preallocatedData.asInt32 = 0;
  23095. size = getMessageLengthFromFirstByte ((uint8) byte);
  23096. data[0] = (uint8) byte;
  23097. if (size > 1)
  23098. {
  23099. data[1] = src[0];
  23100. if (size > 2)
  23101. data[2] = src[1];
  23102. }
  23103. }
  23104. numBytesUsed += size;
  23105. }
  23106. else
  23107. {
  23108. preallocatedData.asInt32 = 0;
  23109. size = 0;
  23110. }
  23111. }
  23112. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23113. {
  23114. if (this != &other)
  23115. {
  23116. timeStamp = other.timeStamp;
  23117. size = other.size;
  23118. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23119. delete[] data;
  23120. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23121. {
  23122. data = new uint8 [size];
  23123. memcpy (data, other.data, size);
  23124. }
  23125. else
  23126. {
  23127. data = static_cast<uint8*> (preallocatedData.asBytes);
  23128. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23129. }
  23130. }
  23131. return *this;
  23132. }
  23133. MidiMessage::~MidiMessage()
  23134. {
  23135. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23136. delete[] data;
  23137. }
  23138. int MidiMessage::getChannel() const throw()
  23139. {
  23140. if ((data[0] & 0xf0) != 0xf0)
  23141. return (data[0] & 0xf) + 1;
  23142. else
  23143. return 0;
  23144. }
  23145. bool MidiMessage::isForChannel (const int channel) const throw()
  23146. {
  23147. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23148. return ((data[0] & 0xf) == channel - 1)
  23149. && ((data[0] & 0xf0) != 0xf0);
  23150. }
  23151. void MidiMessage::setChannel (const int channel) throw()
  23152. {
  23153. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23154. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23155. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23156. | (uint8)(channel - 1));
  23157. }
  23158. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23159. {
  23160. return ((data[0] & 0xf0) == 0x90)
  23161. && (returnTrueForVelocity0 || data[2] != 0);
  23162. }
  23163. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23164. {
  23165. return ((data[0] & 0xf0) == 0x80)
  23166. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23167. }
  23168. bool MidiMessage::isNoteOnOrOff() const throw()
  23169. {
  23170. const int d = data[0] & 0xf0;
  23171. return (d == 0x90) || (d == 0x80);
  23172. }
  23173. int MidiMessage::getNoteNumber() const throw()
  23174. {
  23175. return data[1];
  23176. }
  23177. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23178. {
  23179. if (isNoteOnOrOff())
  23180. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23181. }
  23182. uint8 MidiMessage::getVelocity() const throw()
  23183. {
  23184. if (isNoteOnOrOff())
  23185. return data[2];
  23186. else
  23187. return 0;
  23188. }
  23189. float MidiMessage::getFloatVelocity() const throw()
  23190. {
  23191. return getVelocity() * (1.0f / 127.0f);
  23192. }
  23193. void MidiMessage::setVelocity (const float newVelocity) throw()
  23194. {
  23195. if (isNoteOnOrOff())
  23196. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23197. }
  23198. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23199. {
  23200. if (isNoteOnOrOff())
  23201. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23202. }
  23203. bool MidiMessage::isAftertouch() const throw()
  23204. {
  23205. return (data[0] & 0xf0) == 0xa0;
  23206. }
  23207. int MidiMessage::getAfterTouchValue() const throw()
  23208. {
  23209. return data[2];
  23210. }
  23211. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23212. const int noteNum,
  23213. const int aftertouchValue) throw()
  23214. {
  23215. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23216. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23217. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23218. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23219. noteNum & 0x7f,
  23220. aftertouchValue & 0x7f);
  23221. }
  23222. bool MidiMessage::isChannelPressure() const throw()
  23223. {
  23224. return (data[0] & 0xf0) == 0xd0;
  23225. }
  23226. int MidiMessage::getChannelPressureValue() const throw()
  23227. {
  23228. jassert (isChannelPressure());
  23229. return data[1];
  23230. }
  23231. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23232. const int pressure) throw()
  23233. {
  23234. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23235. jassert (isPositiveAndBelow (pressure, (int) 128));
  23236. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23237. pressure & 0x7f);
  23238. }
  23239. bool MidiMessage::isProgramChange() const throw()
  23240. {
  23241. return (data[0] & 0xf0) == 0xc0;
  23242. }
  23243. int MidiMessage::getProgramChangeNumber() const throw()
  23244. {
  23245. return data[1];
  23246. }
  23247. const MidiMessage MidiMessage::programChange (const int channel,
  23248. const int programNumber) throw()
  23249. {
  23250. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23251. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23252. programNumber & 0x7f);
  23253. }
  23254. bool MidiMessage::isPitchWheel() const throw()
  23255. {
  23256. return (data[0] & 0xf0) == 0xe0;
  23257. }
  23258. int MidiMessage::getPitchWheelValue() const throw()
  23259. {
  23260. return data[1] | (data[2] << 7);
  23261. }
  23262. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23263. const int position) throw()
  23264. {
  23265. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23266. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23267. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23268. position & 127,
  23269. (position >> 7) & 127);
  23270. }
  23271. bool MidiMessage::isController() const throw()
  23272. {
  23273. return (data[0] & 0xf0) == 0xb0;
  23274. }
  23275. int MidiMessage::getControllerNumber() const throw()
  23276. {
  23277. jassert (isController());
  23278. return data[1];
  23279. }
  23280. int MidiMessage::getControllerValue() const throw()
  23281. {
  23282. jassert (isController());
  23283. return data[2];
  23284. }
  23285. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23286. const int controllerType,
  23287. const int value) throw()
  23288. {
  23289. // the channel must be between 1 and 16 inclusive
  23290. jassert (channel > 0 && channel <= 16);
  23291. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23292. controllerType & 127,
  23293. value & 127);
  23294. }
  23295. const MidiMessage MidiMessage::noteOn (const int channel,
  23296. const int noteNumber,
  23297. const float velocity) throw()
  23298. {
  23299. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23300. }
  23301. const MidiMessage MidiMessage::noteOn (const int channel,
  23302. const int noteNumber,
  23303. const uint8 velocity) throw()
  23304. {
  23305. jassert (channel > 0 && channel <= 16);
  23306. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23307. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23308. noteNumber & 127,
  23309. jlimit (0, 127, roundToInt (velocity)));
  23310. }
  23311. const MidiMessage MidiMessage::noteOff (const int channel,
  23312. const int noteNumber) throw()
  23313. {
  23314. jassert (channel > 0 && channel <= 16);
  23315. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23316. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23317. }
  23318. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23319. {
  23320. return controllerEvent (channel, 123, 0);
  23321. }
  23322. bool MidiMessage::isAllNotesOff() const throw()
  23323. {
  23324. return (data[0] & 0xf0) == 0xb0
  23325. && data[1] == 123;
  23326. }
  23327. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23328. {
  23329. return controllerEvent (channel, 120, 0);
  23330. }
  23331. bool MidiMessage::isAllSoundOff() const throw()
  23332. {
  23333. return (data[0] & 0xf0) == 0xb0
  23334. && data[1] == 120;
  23335. }
  23336. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23337. {
  23338. return controllerEvent (channel, 121, 0);
  23339. }
  23340. const MidiMessage MidiMessage::masterVolume (const float volume)
  23341. {
  23342. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23343. uint8 buf[8];
  23344. buf[0] = 0xf0;
  23345. buf[1] = 0x7f;
  23346. buf[2] = 0x7f;
  23347. buf[3] = 0x04;
  23348. buf[4] = 0x01;
  23349. buf[5] = (uint8) (vol & 0x7f);
  23350. buf[6] = (uint8) (vol >> 7);
  23351. buf[7] = 0xf7;
  23352. return MidiMessage (buf, 8);
  23353. }
  23354. bool MidiMessage::isSysEx() const throw()
  23355. {
  23356. return *data == 0xf0;
  23357. }
  23358. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23359. {
  23360. MemoryBlock mm (dataSize + 2);
  23361. uint8* const m = static_cast <uint8*> (mm.getData());
  23362. m[0] = 0xf0;
  23363. memcpy (m + 1, sysexData, dataSize);
  23364. m[dataSize + 1] = 0xf7;
  23365. return MidiMessage (m, dataSize + 2);
  23366. }
  23367. const uint8* MidiMessage::getSysExData() const throw()
  23368. {
  23369. return (isSysEx()) ? getRawData() + 1 : 0;
  23370. }
  23371. int MidiMessage::getSysExDataSize() const throw()
  23372. {
  23373. return (isSysEx()) ? size - 2 : 0;
  23374. }
  23375. bool MidiMessage::isMetaEvent() const throw()
  23376. {
  23377. return *data == 0xff;
  23378. }
  23379. bool MidiMessage::isActiveSense() const throw()
  23380. {
  23381. return *data == 0xfe;
  23382. }
  23383. int MidiMessage::getMetaEventType() const throw()
  23384. {
  23385. if (*data != 0xff)
  23386. return -1;
  23387. else
  23388. return data[1];
  23389. }
  23390. int MidiMessage::getMetaEventLength() const throw()
  23391. {
  23392. if (*data == 0xff)
  23393. {
  23394. int n;
  23395. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23396. }
  23397. return 0;
  23398. }
  23399. const uint8* MidiMessage::getMetaEventData() const throw()
  23400. {
  23401. int n;
  23402. const uint8* d = data + 2;
  23403. readVariableLengthVal (d, n);
  23404. return d + n;
  23405. }
  23406. bool MidiMessage::isTrackMetaEvent() const throw()
  23407. {
  23408. return getMetaEventType() == 0;
  23409. }
  23410. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23411. {
  23412. return getMetaEventType() == 47;
  23413. }
  23414. bool MidiMessage::isTextMetaEvent() const throw()
  23415. {
  23416. const int t = getMetaEventType();
  23417. return t > 0 && t < 16;
  23418. }
  23419. const String MidiMessage::getTextFromTextMetaEvent() const
  23420. {
  23421. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23422. }
  23423. bool MidiMessage::isTrackNameEvent() const throw()
  23424. {
  23425. return (data[1] == 3)
  23426. && (*data == 0xff);
  23427. }
  23428. bool MidiMessage::isTempoMetaEvent() const throw()
  23429. {
  23430. return (data[1] == 81)
  23431. && (*data == 0xff);
  23432. }
  23433. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23434. {
  23435. return (data[1] == 0x20)
  23436. && (*data == 0xff)
  23437. && (data[2] == 1);
  23438. }
  23439. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23440. {
  23441. return data[3] + 1;
  23442. }
  23443. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23444. {
  23445. if (! isTempoMetaEvent())
  23446. return 0.0;
  23447. const uint8* const d = getMetaEventData();
  23448. return (((unsigned int) d[0] << 16)
  23449. | ((unsigned int) d[1] << 8)
  23450. | d[2])
  23451. / 1000000.0;
  23452. }
  23453. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23454. {
  23455. if (timeFormat > 0)
  23456. {
  23457. if (! isTempoMetaEvent())
  23458. return 0.5 / timeFormat;
  23459. return getTempoSecondsPerQuarterNote() / timeFormat;
  23460. }
  23461. else
  23462. {
  23463. const int frameCode = (-timeFormat) >> 8;
  23464. double framesPerSecond;
  23465. switch (frameCode)
  23466. {
  23467. case 24: framesPerSecond = 24.0; break;
  23468. case 25: framesPerSecond = 25.0; break;
  23469. case 29: framesPerSecond = 29.97; break;
  23470. case 30: framesPerSecond = 30.0; break;
  23471. default: framesPerSecond = 30.0; break;
  23472. }
  23473. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23474. }
  23475. }
  23476. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23477. {
  23478. uint8 d[8];
  23479. d[0] = 0xff;
  23480. d[1] = 81;
  23481. d[2] = 3;
  23482. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23483. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23484. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23485. return MidiMessage (d, 6, 0.0);
  23486. }
  23487. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23488. {
  23489. return (data[1] == 0x58)
  23490. && (*data == (uint8) 0xff);
  23491. }
  23492. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23493. {
  23494. if (isTimeSignatureMetaEvent())
  23495. {
  23496. const uint8* const d = getMetaEventData();
  23497. numerator = d[0];
  23498. denominator = 1 << d[1];
  23499. }
  23500. else
  23501. {
  23502. numerator = 4;
  23503. denominator = 4;
  23504. }
  23505. }
  23506. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23507. {
  23508. uint8 d[8];
  23509. d[0] = 0xff;
  23510. d[1] = 0x58;
  23511. d[2] = 0x04;
  23512. d[3] = (uint8) numerator;
  23513. int n = 1;
  23514. int powerOfTwo = 0;
  23515. while (n < denominator)
  23516. {
  23517. n <<= 1;
  23518. ++powerOfTwo;
  23519. }
  23520. d[4] = (uint8) powerOfTwo;
  23521. d[5] = 0x01;
  23522. d[6] = 96;
  23523. return MidiMessage (d, 7, 0.0);
  23524. }
  23525. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23526. {
  23527. uint8 d[8];
  23528. d[0] = 0xff;
  23529. d[1] = 0x20;
  23530. d[2] = 0x01;
  23531. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23532. return MidiMessage (d, 4, 0.0);
  23533. }
  23534. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23535. {
  23536. return getMetaEventType() == 89;
  23537. }
  23538. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23539. {
  23540. return (int) *getMetaEventData();
  23541. }
  23542. const MidiMessage MidiMessage::endOfTrack() throw()
  23543. {
  23544. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23545. }
  23546. bool MidiMessage::isSongPositionPointer() const throw()
  23547. {
  23548. return *data == 0xf2;
  23549. }
  23550. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23551. {
  23552. return data[1] | (data[2] << 7);
  23553. }
  23554. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23555. {
  23556. return MidiMessage (0xf2,
  23557. positionInMidiBeats & 127,
  23558. (positionInMidiBeats >> 7) & 127);
  23559. }
  23560. bool MidiMessage::isMidiStart() const throw()
  23561. {
  23562. return *data == 0xfa;
  23563. }
  23564. const MidiMessage MidiMessage::midiStart() throw()
  23565. {
  23566. return MidiMessage (0xfa);
  23567. }
  23568. bool MidiMessage::isMidiContinue() const throw()
  23569. {
  23570. return *data == 0xfb;
  23571. }
  23572. const MidiMessage MidiMessage::midiContinue() throw()
  23573. {
  23574. return MidiMessage (0xfb);
  23575. }
  23576. bool MidiMessage::isMidiStop() const throw()
  23577. {
  23578. return *data == 0xfc;
  23579. }
  23580. const MidiMessage MidiMessage::midiStop() throw()
  23581. {
  23582. return MidiMessage (0xfc);
  23583. }
  23584. bool MidiMessage::isMidiClock() const throw()
  23585. {
  23586. return *data == 0xf8;
  23587. }
  23588. const MidiMessage MidiMessage::midiClock() throw()
  23589. {
  23590. return MidiMessage (0xf8);
  23591. }
  23592. bool MidiMessage::isQuarterFrame() const throw()
  23593. {
  23594. return *data == 0xf1;
  23595. }
  23596. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23597. {
  23598. return ((int) data[1]) >> 4;
  23599. }
  23600. int MidiMessage::getQuarterFrameValue() const throw()
  23601. {
  23602. return ((int) data[1]) & 0x0f;
  23603. }
  23604. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23605. const int value) throw()
  23606. {
  23607. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23608. }
  23609. bool MidiMessage::isFullFrame() const throw()
  23610. {
  23611. return data[0] == 0xf0
  23612. && data[1] == 0x7f
  23613. && size >= 10
  23614. && data[3] == 0x01
  23615. && data[4] == 0x01;
  23616. }
  23617. void MidiMessage::getFullFrameParameters (int& hours,
  23618. int& minutes,
  23619. int& seconds,
  23620. int& frames,
  23621. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23622. {
  23623. jassert (isFullFrame());
  23624. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23625. hours = data[5] & 0x1f;
  23626. minutes = data[6];
  23627. seconds = data[7];
  23628. frames = data[8];
  23629. }
  23630. const MidiMessage MidiMessage::fullFrame (const int hours,
  23631. const int minutes,
  23632. const int seconds,
  23633. const int frames,
  23634. MidiMessage::SmpteTimecodeType timecodeType)
  23635. {
  23636. uint8 d[10];
  23637. d[0] = 0xf0;
  23638. d[1] = 0x7f;
  23639. d[2] = 0x7f;
  23640. d[3] = 0x01;
  23641. d[4] = 0x01;
  23642. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23643. d[6] = (uint8) minutes;
  23644. d[7] = (uint8) seconds;
  23645. d[8] = (uint8) frames;
  23646. d[9] = 0xf7;
  23647. return MidiMessage (d, 10, 0.0);
  23648. }
  23649. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23650. {
  23651. return data[0] == 0xf0
  23652. && data[1] == 0x7f
  23653. && data[3] == 0x06
  23654. && size > 5;
  23655. }
  23656. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23657. {
  23658. jassert (isMidiMachineControlMessage());
  23659. return (MidiMachineControlCommand) data[4];
  23660. }
  23661. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23662. {
  23663. uint8 d[6];
  23664. d[0] = 0xf0;
  23665. d[1] = 0x7f;
  23666. d[2] = 0x00;
  23667. d[3] = 0x06;
  23668. d[4] = (uint8) command;
  23669. d[5] = 0xf7;
  23670. return MidiMessage (d, 6, 0.0);
  23671. }
  23672. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23673. int& minutes,
  23674. int& seconds,
  23675. int& frames) const throw()
  23676. {
  23677. if (size >= 12
  23678. && data[0] == 0xf0
  23679. && data[1] == 0x7f
  23680. && data[3] == 0x06
  23681. && data[4] == 0x44
  23682. && data[5] == 0x06
  23683. && data[6] == 0x01)
  23684. {
  23685. hours = data[7] % 24; // (that some machines send out hours > 24)
  23686. minutes = data[8];
  23687. seconds = data[9];
  23688. frames = data[10];
  23689. return true;
  23690. }
  23691. return false;
  23692. }
  23693. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23694. int minutes,
  23695. int seconds,
  23696. int frames)
  23697. {
  23698. uint8 d[12];
  23699. d[0] = 0xf0;
  23700. d[1] = 0x7f;
  23701. d[2] = 0x00;
  23702. d[3] = 0x06;
  23703. d[4] = 0x44;
  23704. d[5] = 0x06;
  23705. d[6] = 0x01;
  23706. d[7] = (uint8) hours;
  23707. d[8] = (uint8) minutes;
  23708. d[9] = (uint8) seconds;
  23709. d[10] = (uint8) frames;
  23710. d[11] = 0xf7;
  23711. return MidiMessage (d, 12, 0.0);
  23712. }
  23713. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23714. {
  23715. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23716. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23717. if (isPositiveAndBelow (note, (int) 128))
  23718. {
  23719. String s (useSharps ? sharpNoteNames [note % 12]
  23720. : flatNoteNames [note % 12]);
  23721. if (includeOctaveNumber)
  23722. s << (note / 12 + (octaveNumForMiddleC - 5));
  23723. return s;
  23724. }
  23725. return String::empty;
  23726. }
  23727. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23728. {
  23729. noteNumber -= 12 * 6 + 9; // now 0 = A
  23730. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23731. }
  23732. const String MidiMessage::getGMInstrumentName (const int n)
  23733. {
  23734. const char* names[] =
  23735. {
  23736. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23737. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23738. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23739. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23740. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23741. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23742. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23743. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23744. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23745. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23746. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23747. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23748. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23749. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23750. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23751. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23752. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23753. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23754. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23755. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23756. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23757. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23758. "Applause", "Gunshot"
  23759. };
  23760. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23761. }
  23762. const String MidiMessage::getGMInstrumentBankName (const int n)
  23763. {
  23764. const char* names[] =
  23765. {
  23766. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23767. "Bass", "Strings", "Ensemble", "Brass",
  23768. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23769. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23770. };
  23771. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23772. }
  23773. const String MidiMessage::getRhythmInstrumentName (const int n)
  23774. {
  23775. const char* names[] =
  23776. {
  23777. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23778. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23779. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23780. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23781. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23782. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23783. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23784. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23785. "Mute Triangle", "Open Triangle"
  23786. };
  23787. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23788. }
  23789. const String MidiMessage::getControllerName (const int n)
  23790. {
  23791. const char* names[] =
  23792. {
  23793. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23794. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23795. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23796. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23797. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23798. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23799. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23800. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23801. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23802. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23803. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23804. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23805. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23806. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23807. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23808. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23809. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23810. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23811. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23813. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23814. "Poly Operation"
  23815. };
  23816. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23817. }
  23818. END_JUCE_NAMESPACE
  23819. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23820. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23821. BEGIN_JUCE_NAMESPACE
  23822. MidiMessageCollector::MidiMessageCollector()
  23823. : lastCallbackTime (0),
  23824. sampleRate (44100.0001)
  23825. {
  23826. }
  23827. MidiMessageCollector::~MidiMessageCollector()
  23828. {
  23829. }
  23830. void MidiMessageCollector::reset (const double sampleRate_)
  23831. {
  23832. jassert (sampleRate_ > 0);
  23833. const ScopedLock sl (midiCallbackLock);
  23834. sampleRate = sampleRate_;
  23835. incomingMessages.clear();
  23836. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23837. }
  23838. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23839. {
  23840. // you need to call reset() to set the correct sample rate before using this object
  23841. jassert (sampleRate != 44100.0001);
  23842. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23843. // for details of what the number should be.
  23844. jassert (message.getTimeStamp() != 0);
  23845. const ScopedLock sl (midiCallbackLock);
  23846. const int sampleNumber
  23847. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23848. incomingMessages.addEvent (message, sampleNumber);
  23849. // if the messages don't get used for over a second, we'd better
  23850. // get rid of any old ones to avoid the queue getting too big
  23851. if (sampleNumber > sampleRate)
  23852. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23853. }
  23854. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23855. const int numSamples)
  23856. {
  23857. // you need to call reset() to set the correct sample rate before using this object
  23858. jassert (sampleRate != 44100.0001);
  23859. const double timeNow = Time::getMillisecondCounterHiRes();
  23860. const double msElapsed = timeNow - lastCallbackTime;
  23861. const ScopedLock sl (midiCallbackLock);
  23862. lastCallbackTime = timeNow;
  23863. if (! incomingMessages.isEmpty())
  23864. {
  23865. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23866. int startSample = 0;
  23867. int scale = 1 << 16;
  23868. const uint8* midiData;
  23869. int numBytes, samplePosition;
  23870. MidiBuffer::Iterator iter (incomingMessages);
  23871. if (numSourceSamples > numSamples)
  23872. {
  23873. // if our list of events is longer than the buffer we're being
  23874. // asked for, scale them down to squeeze them all in..
  23875. const int maxBlockLengthToUse = numSamples << 5;
  23876. if (numSourceSamples > maxBlockLengthToUse)
  23877. {
  23878. startSample = numSourceSamples - maxBlockLengthToUse;
  23879. numSourceSamples = maxBlockLengthToUse;
  23880. iter.setNextSamplePosition (startSample);
  23881. }
  23882. scale = (numSamples << 10) / numSourceSamples;
  23883. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23884. {
  23885. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23886. destBuffer.addEvent (midiData, numBytes,
  23887. jlimit (0, numSamples - 1, samplePosition));
  23888. }
  23889. }
  23890. else
  23891. {
  23892. // if our event list is shorter than the number we need, put them
  23893. // towards the end of the buffer
  23894. startSample = numSamples - numSourceSamples;
  23895. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23896. {
  23897. destBuffer.addEvent (midiData, numBytes,
  23898. jlimit (0, numSamples - 1, samplePosition + startSample));
  23899. }
  23900. }
  23901. incomingMessages.clear();
  23902. }
  23903. }
  23904. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23905. {
  23906. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23907. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23908. addMessageToQueue (m);
  23909. }
  23910. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23911. {
  23912. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23913. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23914. addMessageToQueue (m);
  23915. }
  23916. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23917. {
  23918. addMessageToQueue (message);
  23919. }
  23920. END_JUCE_NAMESPACE
  23921. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23922. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23923. BEGIN_JUCE_NAMESPACE
  23924. MidiMessageSequence::MidiMessageSequence()
  23925. {
  23926. }
  23927. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23928. {
  23929. list.ensureStorageAllocated (other.list.size());
  23930. for (int i = 0; i < other.list.size(); ++i)
  23931. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23932. }
  23933. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23934. {
  23935. MidiMessageSequence otherCopy (other);
  23936. swapWith (otherCopy);
  23937. return *this;
  23938. }
  23939. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23940. {
  23941. list.swapWithArray (other.list);
  23942. }
  23943. MidiMessageSequence::~MidiMessageSequence()
  23944. {
  23945. }
  23946. void MidiMessageSequence::clear()
  23947. {
  23948. list.clear();
  23949. }
  23950. int MidiMessageSequence::getNumEvents() const
  23951. {
  23952. return list.size();
  23953. }
  23954. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23955. {
  23956. return list [index];
  23957. }
  23958. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23959. {
  23960. const MidiEventHolder* const meh = list [index];
  23961. if (meh != 0 && meh->noteOffObject != 0)
  23962. return meh->noteOffObject->message.getTimeStamp();
  23963. else
  23964. return 0.0;
  23965. }
  23966. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23967. {
  23968. const MidiEventHolder* const meh = list [index];
  23969. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23970. }
  23971. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23972. {
  23973. return list.indexOf (event);
  23974. }
  23975. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23976. {
  23977. const int numEvents = list.size();
  23978. int i;
  23979. for (i = 0; i < numEvents; ++i)
  23980. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23981. break;
  23982. return i;
  23983. }
  23984. double MidiMessageSequence::getStartTime() const
  23985. {
  23986. if (list.size() > 0)
  23987. return list.getUnchecked(0)->message.getTimeStamp();
  23988. else
  23989. return 0;
  23990. }
  23991. double MidiMessageSequence::getEndTime() const
  23992. {
  23993. if (list.size() > 0)
  23994. return list.getLast()->message.getTimeStamp();
  23995. else
  23996. return 0;
  23997. }
  23998. double MidiMessageSequence::getEventTime (const int index) const
  23999. {
  24000. if (isPositiveAndBelow (index, list.size()))
  24001. return list.getUnchecked (index)->message.getTimeStamp();
  24002. return 0.0;
  24003. }
  24004. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24005. double timeAdjustment)
  24006. {
  24007. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24008. timeAdjustment += newMessage.getTimeStamp();
  24009. newOne->message.setTimeStamp (timeAdjustment);
  24010. int i;
  24011. for (i = list.size(); --i >= 0;)
  24012. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24013. break;
  24014. list.insert (i + 1, newOne);
  24015. }
  24016. void MidiMessageSequence::deleteEvent (const int index,
  24017. const bool deleteMatchingNoteUp)
  24018. {
  24019. if (isPositiveAndBelow (index, list.size()))
  24020. {
  24021. if (deleteMatchingNoteUp)
  24022. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24023. list.remove (index);
  24024. }
  24025. }
  24026. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24027. double timeAdjustment,
  24028. double firstAllowableTime,
  24029. double endOfAllowableDestTimes)
  24030. {
  24031. firstAllowableTime -= timeAdjustment;
  24032. endOfAllowableDestTimes -= timeAdjustment;
  24033. for (int i = 0; i < other.list.size(); ++i)
  24034. {
  24035. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24036. const double t = m.getTimeStamp();
  24037. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24038. {
  24039. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24040. newOne->message.setTimeStamp (timeAdjustment + t);
  24041. list.add (newOne);
  24042. }
  24043. }
  24044. sort();
  24045. }
  24046. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24047. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24048. {
  24049. const double diff = first->message.getTimeStamp()
  24050. - second->message.getTimeStamp();
  24051. return (diff > 0) - (diff < 0);
  24052. }
  24053. void MidiMessageSequence::sort()
  24054. {
  24055. list.sort (*this, true);
  24056. }
  24057. void MidiMessageSequence::updateMatchedPairs()
  24058. {
  24059. for (int i = 0; i < list.size(); ++i)
  24060. {
  24061. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24062. if (m1.isNoteOn())
  24063. {
  24064. list.getUnchecked(i)->noteOffObject = 0;
  24065. const int note = m1.getNoteNumber();
  24066. const int chan = m1.getChannel();
  24067. const int len = list.size();
  24068. for (int j = i + 1; j < len; ++j)
  24069. {
  24070. const MidiMessage& m = list.getUnchecked(j)->message;
  24071. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24072. {
  24073. if (m.isNoteOff())
  24074. {
  24075. list.getUnchecked(i)->noteOffObject = list[j];
  24076. break;
  24077. }
  24078. else if (m.isNoteOn())
  24079. {
  24080. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24081. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24082. list.getUnchecked(i)->noteOffObject = list[j];
  24083. break;
  24084. }
  24085. }
  24086. }
  24087. }
  24088. }
  24089. }
  24090. void MidiMessageSequence::addTimeToMessages (const double delta)
  24091. {
  24092. for (int i = list.size(); --i >= 0;)
  24093. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24094. + delta);
  24095. }
  24096. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24097. MidiMessageSequence& destSequence,
  24098. const bool alsoIncludeMetaEvents) const
  24099. {
  24100. for (int i = 0; i < list.size(); ++i)
  24101. {
  24102. const MidiMessage& mm = list.getUnchecked(i)->message;
  24103. if (mm.isForChannel (channelNumberToExtract)
  24104. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24105. {
  24106. destSequence.addEvent (mm);
  24107. }
  24108. }
  24109. }
  24110. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24111. {
  24112. for (int i = 0; i < list.size(); ++i)
  24113. {
  24114. const MidiMessage& mm = list.getUnchecked(i)->message;
  24115. if (mm.isSysEx())
  24116. destSequence.addEvent (mm);
  24117. }
  24118. }
  24119. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24120. {
  24121. for (int i = list.size(); --i >= 0;)
  24122. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24123. list.remove(i);
  24124. }
  24125. void MidiMessageSequence::deleteSysExMessages()
  24126. {
  24127. for (int i = list.size(); --i >= 0;)
  24128. if (list.getUnchecked(i)->message.isSysEx())
  24129. list.remove(i);
  24130. }
  24131. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24132. const double time,
  24133. OwnedArray<MidiMessage>& dest)
  24134. {
  24135. bool doneProg = false;
  24136. bool donePitchWheel = false;
  24137. Array <int> doneControllers;
  24138. doneControllers.ensureStorageAllocated (32);
  24139. for (int i = list.size(); --i >= 0;)
  24140. {
  24141. const MidiMessage& mm = list.getUnchecked(i)->message;
  24142. if (mm.isForChannel (channelNumber)
  24143. && mm.getTimeStamp() <= time)
  24144. {
  24145. if (mm.isProgramChange())
  24146. {
  24147. if (! doneProg)
  24148. {
  24149. dest.add (new MidiMessage (mm, 0.0));
  24150. doneProg = true;
  24151. }
  24152. }
  24153. else if (mm.isController())
  24154. {
  24155. if (! doneControllers.contains (mm.getControllerNumber()))
  24156. {
  24157. dest.add (new MidiMessage (mm, 0.0));
  24158. doneControllers.add (mm.getControllerNumber());
  24159. }
  24160. }
  24161. else if (mm.isPitchWheel())
  24162. {
  24163. if (! donePitchWheel)
  24164. {
  24165. dest.add (new MidiMessage (mm, 0.0));
  24166. donePitchWheel = true;
  24167. }
  24168. }
  24169. }
  24170. }
  24171. }
  24172. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24173. : message (message_),
  24174. noteOffObject (0)
  24175. {
  24176. }
  24177. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24178. {
  24179. }
  24180. END_JUCE_NAMESPACE
  24181. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24182. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24183. BEGIN_JUCE_NAMESPACE
  24184. AudioPluginFormat::AudioPluginFormat() throw()
  24185. {
  24186. }
  24187. AudioPluginFormat::~AudioPluginFormat()
  24188. {
  24189. }
  24190. END_JUCE_NAMESPACE
  24191. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24192. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24193. BEGIN_JUCE_NAMESPACE
  24194. AudioPluginFormatManager::AudioPluginFormatManager()
  24195. {
  24196. }
  24197. AudioPluginFormatManager::~AudioPluginFormatManager()
  24198. {
  24199. clearSingletonInstance();
  24200. }
  24201. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24202. void AudioPluginFormatManager::addDefaultFormats()
  24203. {
  24204. #if JUCE_DEBUG
  24205. // you should only call this method once!
  24206. for (int i = formats.size(); --i >= 0;)
  24207. {
  24208. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24209. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24210. #endif
  24211. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24212. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24213. #endif
  24214. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24215. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24216. #endif
  24217. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24218. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24219. #endif
  24220. }
  24221. #endif
  24222. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24223. formats.add (new AudioUnitPluginFormat());
  24224. #endif
  24225. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24226. formats.add (new VSTPluginFormat());
  24227. #endif
  24228. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24229. formats.add (new DirectXPluginFormat());
  24230. #endif
  24231. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24232. formats.add (new LADSPAPluginFormat());
  24233. #endif
  24234. }
  24235. int AudioPluginFormatManager::getNumFormats()
  24236. {
  24237. return formats.size();
  24238. }
  24239. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24240. {
  24241. return formats [index];
  24242. }
  24243. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24244. {
  24245. formats.add (format);
  24246. }
  24247. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24248. String& errorMessage) const
  24249. {
  24250. AudioPluginInstance* result = 0;
  24251. for (int i = 0; i < formats.size(); ++i)
  24252. {
  24253. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24254. if (result != 0)
  24255. break;
  24256. }
  24257. if (result == 0)
  24258. {
  24259. if (! doesPluginStillExist (description))
  24260. errorMessage = TRANS ("This plug-in file no longer exists");
  24261. else
  24262. errorMessage = TRANS ("This plug-in failed to load correctly");
  24263. }
  24264. return result;
  24265. }
  24266. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24267. {
  24268. for (int i = 0; i < formats.size(); ++i)
  24269. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24270. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24271. return false;
  24272. }
  24273. END_JUCE_NAMESPACE
  24274. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24275. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24276. #define JUCE_PLUGIN_HOST 1
  24277. BEGIN_JUCE_NAMESPACE
  24278. AudioPluginInstance::AudioPluginInstance()
  24279. {
  24280. }
  24281. AudioPluginInstance::~AudioPluginInstance()
  24282. {
  24283. }
  24284. void* AudioPluginInstance::getPlatformSpecificData()
  24285. {
  24286. return 0;
  24287. }
  24288. END_JUCE_NAMESPACE
  24289. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24290. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24291. BEGIN_JUCE_NAMESPACE
  24292. KnownPluginList::KnownPluginList()
  24293. {
  24294. }
  24295. KnownPluginList::~KnownPluginList()
  24296. {
  24297. }
  24298. void KnownPluginList::clear()
  24299. {
  24300. if (types.size() > 0)
  24301. {
  24302. types.clear();
  24303. sendChangeMessage();
  24304. }
  24305. }
  24306. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24307. {
  24308. for (int i = 0; i < types.size(); ++i)
  24309. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24310. return types.getUnchecked(i);
  24311. return 0;
  24312. }
  24313. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24314. {
  24315. for (int i = 0; i < types.size(); ++i)
  24316. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24317. return types.getUnchecked(i);
  24318. return 0;
  24319. }
  24320. bool KnownPluginList::addType (const PluginDescription& type)
  24321. {
  24322. for (int i = types.size(); --i >= 0;)
  24323. {
  24324. if (types.getUnchecked(i)->isDuplicateOf (type))
  24325. {
  24326. // strange - found a duplicate plugin with different info..
  24327. jassert (types.getUnchecked(i)->name == type.name);
  24328. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24329. *types.getUnchecked(i) = type;
  24330. return false;
  24331. }
  24332. }
  24333. types.add (new PluginDescription (type));
  24334. sendChangeMessage();
  24335. return true;
  24336. }
  24337. void KnownPluginList::removeType (const int index)
  24338. {
  24339. types.remove (index);
  24340. sendChangeMessage();
  24341. }
  24342. namespace
  24343. {
  24344. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24345. {
  24346. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24347. return File (fileOrIdentifier).getLastModificationTime();
  24348. return Time();
  24349. }
  24350. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24351. {
  24352. return t1 != t2 || t1 == Time();
  24353. }
  24354. }
  24355. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24356. {
  24357. if (getTypeForFile (fileOrIdentifier) == 0)
  24358. return false;
  24359. for (int i = types.size(); --i >= 0;)
  24360. {
  24361. const PluginDescription* const d = types.getUnchecked(i);
  24362. if (d->fileOrIdentifier == fileOrIdentifier
  24363. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24364. {
  24365. return false;
  24366. }
  24367. }
  24368. return true;
  24369. }
  24370. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24371. const bool dontRescanIfAlreadyInList,
  24372. OwnedArray <PluginDescription>& typesFound,
  24373. AudioPluginFormat& format)
  24374. {
  24375. bool addedOne = false;
  24376. if (dontRescanIfAlreadyInList
  24377. && getTypeForFile (fileOrIdentifier) != 0)
  24378. {
  24379. bool needsRescanning = false;
  24380. for (int i = types.size(); --i >= 0;)
  24381. {
  24382. const PluginDescription* const d = types.getUnchecked(i);
  24383. if (d->fileOrIdentifier == fileOrIdentifier)
  24384. {
  24385. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24386. needsRescanning = true;
  24387. else
  24388. typesFound.add (new PluginDescription (*d));
  24389. }
  24390. }
  24391. if (! needsRescanning)
  24392. return false;
  24393. }
  24394. OwnedArray <PluginDescription> found;
  24395. format.findAllTypesForFile (found, fileOrIdentifier);
  24396. for (int i = 0; i < found.size(); ++i)
  24397. {
  24398. PluginDescription* const desc = found.getUnchecked(i);
  24399. jassert (desc != 0);
  24400. if (addType (*desc))
  24401. addedOne = true;
  24402. typesFound.add (new PluginDescription (*desc));
  24403. }
  24404. return addedOne;
  24405. }
  24406. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24407. OwnedArray <PluginDescription>& typesFound)
  24408. {
  24409. for (int i = 0; i < files.size(); ++i)
  24410. {
  24411. bool loaded = false;
  24412. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24413. {
  24414. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24415. if (scanAndAddFile (files[i], true, typesFound, *format))
  24416. loaded = true;
  24417. }
  24418. if (! loaded)
  24419. {
  24420. const File f (files[i]);
  24421. if (f.isDirectory())
  24422. {
  24423. StringArray s;
  24424. {
  24425. Array<File> subFiles;
  24426. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24427. for (int j = 0; j < subFiles.size(); ++j)
  24428. s.add (subFiles.getReference(j).getFullPathName());
  24429. }
  24430. scanAndAddDragAndDroppedFiles (s, typesFound);
  24431. }
  24432. }
  24433. }
  24434. }
  24435. class PluginSorter
  24436. {
  24437. public:
  24438. KnownPluginList::SortMethod method;
  24439. PluginSorter() throw() {}
  24440. int compareElements (const PluginDescription* const first,
  24441. const PluginDescription* const second) const
  24442. {
  24443. int diff = 0;
  24444. if (method == KnownPluginList::sortByCategory)
  24445. diff = first->category.compareLexicographically (second->category);
  24446. else if (method == KnownPluginList::sortByManufacturer)
  24447. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24448. else if (method == KnownPluginList::sortByFileSystemLocation)
  24449. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24450. .upToLastOccurrenceOf ("/", false, false)
  24451. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24452. .upToLastOccurrenceOf ("/", false, false));
  24453. if (diff == 0)
  24454. diff = first->name.compareLexicographically (second->name);
  24455. return diff;
  24456. }
  24457. };
  24458. void KnownPluginList::sort (const SortMethod method)
  24459. {
  24460. if (method != defaultOrder)
  24461. {
  24462. PluginSorter sorter;
  24463. sorter.method = method;
  24464. types.sort (sorter, true);
  24465. sendChangeMessage();
  24466. }
  24467. }
  24468. XmlElement* KnownPluginList::createXml() const
  24469. {
  24470. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24471. for (int i = 0; i < types.size(); ++i)
  24472. e->addChildElement (types.getUnchecked(i)->createXml());
  24473. return e;
  24474. }
  24475. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24476. {
  24477. clear();
  24478. if (xml.hasTagName ("KNOWNPLUGINS"))
  24479. {
  24480. forEachXmlChildElement (xml, e)
  24481. {
  24482. PluginDescription info;
  24483. if (info.loadFromXml (*e))
  24484. addType (info);
  24485. }
  24486. }
  24487. }
  24488. const int menuIdBase = 0x324503f4;
  24489. // This is used to turn a bunch of paths into a nested menu structure.
  24490. struct PluginFilesystemTree
  24491. {
  24492. private:
  24493. String folder;
  24494. OwnedArray <PluginFilesystemTree> subFolders;
  24495. Array <PluginDescription*> plugins;
  24496. void addPlugin (PluginDescription* const pd, const String& path)
  24497. {
  24498. if (path.isEmpty())
  24499. {
  24500. plugins.add (pd);
  24501. }
  24502. else
  24503. {
  24504. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24505. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24506. for (int i = subFolders.size(); --i >= 0;)
  24507. {
  24508. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24509. {
  24510. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24511. return;
  24512. }
  24513. }
  24514. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24515. newFolder->folder = firstSubFolder;
  24516. subFolders.add (newFolder);
  24517. newFolder->addPlugin (pd, remainingPath);
  24518. }
  24519. }
  24520. // removes any deeply nested folders that don't contain any actual plugins
  24521. void optimise()
  24522. {
  24523. for (int i = subFolders.size(); --i >= 0;)
  24524. {
  24525. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24526. sub->optimise();
  24527. if (sub->plugins.size() == 0)
  24528. {
  24529. for (int j = 0; j < sub->subFolders.size(); ++j)
  24530. subFolders.add (sub->subFolders.getUnchecked(j));
  24531. sub->subFolders.clear (false);
  24532. subFolders.remove (i);
  24533. }
  24534. }
  24535. }
  24536. public:
  24537. void buildTree (const Array <PluginDescription*>& allPlugins)
  24538. {
  24539. for (int i = 0; i < allPlugins.size(); ++i)
  24540. {
  24541. String path (allPlugins.getUnchecked(i)
  24542. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24543. .upToLastOccurrenceOf ("/", false, false));
  24544. if (path.substring (1, 2) == ":")
  24545. path = path.substring (2);
  24546. addPlugin (allPlugins.getUnchecked(i), path);
  24547. }
  24548. optimise();
  24549. }
  24550. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24551. {
  24552. int i;
  24553. for (i = 0; i < subFolders.size(); ++i)
  24554. {
  24555. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24556. PopupMenu subMenu;
  24557. sub->addToMenu (subMenu, allPlugins);
  24558. #if JUCE_MAC
  24559. // avoid the special AU formatting nonsense on Mac..
  24560. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24561. #else
  24562. m.addSubMenu (sub->folder, subMenu);
  24563. #endif
  24564. }
  24565. for (i = 0; i < plugins.size(); ++i)
  24566. {
  24567. PluginDescription* const plugin = plugins.getUnchecked(i);
  24568. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24569. plugin->name, true, false);
  24570. }
  24571. }
  24572. };
  24573. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24574. {
  24575. Array <PluginDescription*> sorted;
  24576. {
  24577. PluginSorter sorter;
  24578. sorter.method = sortMethod;
  24579. for (int i = 0; i < types.size(); ++i)
  24580. sorted.addSorted (sorter, types.getUnchecked(i));
  24581. }
  24582. if (sortMethod == sortByCategory
  24583. || sortMethod == sortByManufacturer)
  24584. {
  24585. String lastSubMenuName;
  24586. PopupMenu sub;
  24587. for (int i = 0; i < sorted.size(); ++i)
  24588. {
  24589. const PluginDescription* const pd = sorted.getUnchecked(i);
  24590. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24591. : pd->manufacturerName);
  24592. if (! thisSubMenuName.containsNonWhitespaceChars())
  24593. thisSubMenuName = "Other";
  24594. if (thisSubMenuName != lastSubMenuName)
  24595. {
  24596. if (sub.getNumItems() > 0)
  24597. {
  24598. menu.addSubMenu (lastSubMenuName, sub);
  24599. sub.clear();
  24600. }
  24601. lastSubMenuName = thisSubMenuName;
  24602. }
  24603. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24604. }
  24605. if (sub.getNumItems() > 0)
  24606. menu.addSubMenu (lastSubMenuName, sub);
  24607. }
  24608. else if (sortMethod == sortByFileSystemLocation)
  24609. {
  24610. PluginFilesystemTree root;
  24611. root.buildTree (sorted);
  24612. root.addToMenu (menu, types);
  24613. }
  24614. else
  24615. {
  24616. for (int i = 0; i < sorted.size(); ++i)
  24617. {
  24618. const PluginDescription* const pd = sorted.getUnchecked(i);
  24619. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24620. }
  24621. }
  24622. }
  24623. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24624. {
  24625. const int i = menuResultCode - menuIdBase;
  24626. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24627. }
  24628. END_JUCE_NAMESPACE
  24629. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24630. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24631. BEGIN_JUCE_NAMESPACE
  24632. PluginDescription::PluginDescription()
  24633. : uid (0),
  24634. isInstrument (false),
  24635. numInputChannels (0),
  24636. numOutputChannels (0)
  24637. {
  24638. }
  24639. PluginDescription::~PluginDescription()
  24640. {
  24641. }
  24642. PluginDescription::PluginDescription (const PluginDescription& other)
  24643. : name (other.name),
  24644. descriptiveName (other.descriptiveName),
  24645. pluginFormatName (other.pluginFormatName),
  24646. category (other.category),
  24647. manufacturerName (other.manufacturerName),
  24648. version (other.version),
  24649. fileOrIdentifier (other.fileOrIdentifier),
  24650. lastFileModTime (other.lastFileModTime),
  24651. uid (other.uid),
  24652. isInstrument (other.isInstrument),
  24653. numInputChannels (other.numInputChannels),
  24654. numOutputChannels (other.numOutputChannels)
  24655. {
  24656. }
  24657. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24658. {
  24659. name = other.name;
  24660. descriptiveName = other.descriptiveName;
  24661. pluginFormatName = other.pluginFormatName;
  24662. category = other.category;
  24663. manufacturerName = other.manufacturerName;
  24664. version = other.version;
  24665. fileOrIdentifier = other.fileOrIdentifier;
  24666. uid = other.uid;
  24667. isInstrument = other.isInstrument;
  24668. lastFileModTime = other.lastFileModTime;
  24669. numInputChannels = other.numInputChannels;
  24670. numOutputChannels = other.numOutputChannels;
  24671. return *this;
  24672. }
  24673. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24674. {
  24675. return fileOrIdentifier == other.fileOrIdentifier
  24676. && uid == other.uid;
  24677. }
  24678. const String PluginDescription::createIdentifierString() const
  24679. {
  24680. return pluginFormatName
  24681. + "-" + name
  24682. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24683. + "-" + String::toHexString (uid);
  24684. }
  24685. XmlElement* PluginDescription::createXml() const
  24686. {
  24687. XmlElement* const e = new XmlElement ("PLUGIN");
  24688. e->setAttribute ("name", name);
  24689. if (descriptiveName != name)
  24690. e->setAttribute ("descriptiveName", descriptiveName);
  24691. e->setAttribute ("format", pluginFormatName);
  24692. e->setAttribute ("category", category);
  24693. e->setAttribute ("manufacturer", manufacturerName);
  24694. e->setAttribute ("version", version);
  24695. e->setAttribute ("file", fileOrIdentifier);
  24696. e->setAttribute ("uid", String::toHexString (uid));
  24697. e->setAttribute ("isInstrument", isInstrument);
  24698. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24699. e->setAttribute ("numInputs", numInputChannels);
  24700. e->setAttribute ("numOutputs", numOutputChannels);
  24701. return e;
  24702. }
  24703. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24704. {
  24705. if (xml.hasTagName ("PLUGIN"))
  24706. {
  24707. name = xml.getStringAttribute ("name");
  24708. descriptiveName = xml.getStringAttribute ("name", name);
  24709. pluginFormatName = xml.getStringAttribute ("format");
  24710. category = xml.getStringAttribute ("category");
  24711. manufacturerName = xml.getStringAttribute ("manufacturer");
  24712. version = xml.getStringAttribute ("version");
  24713. fileOrIdentifier = xml.getStringAttribute ("file");
  24714. uid = xml.getStringAttribute ("uid").getHexValue32();
  24715. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24716. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24717. numInputChannels = xml.getIntAttribute ("numInputs");
  24718. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24719. return true;
  24720. }
  24721. return false;
  24722. }
  24723. END_JUCE_NAMESPACE
  24724. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24725. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24726. BEGIN_JUCE_NAMESPACE
  24727. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24728. AudioPluginFormat& formatToLookFor,
  24729. FileSearchPath directoriesToSearch,
  24730. const bool recursive,
  24731. const File& deadMansPedalFile_)
  24732. : list (listToAddTo),
  24733. format (formatToLookFor),
  24734. deadMansPedalFile (deadMansPedalFile_),
  24735. nextIndex (0),
  24736. progress (0)
  24737. {
  24738. directoriesToSearch.removeRedundantPaths();
  24739. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24740. // If any plugins have crashed recently when being loaded, move them to the
  24741. // end of the list to give the others a chance to load correctly..
  24742. const StringArray crashedPlugins (getDeadMansPedalFile());
  24743. for (int i = 0; i < crashedPlugins.size(); ++i)
  24744. {
  24745. const String f = crashedPlugins[i];
  24746. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24747. if (f == filesOrIdentifiersToScan[j])
  24748. filesOrIdentifiersToScan.move (j, -1);
  24749. }
  24750. }
  24751. PluginDirectoryScanner::~PluginDirectoryScanner()
  24752. {
  24753. }
  24754. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24755. {
  24756. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24757. }
  24758. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24759. {
  24760. String file (filesOrIdentifiersToScan [nextIndex]);
  24761. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24762. {
  24763. OwnedArray <PluginDescription> typesFound;
  24764. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24765. StringArray crashedPlugins (getDeadMansPedalFile());
  24766. crashedPlugins.removeString (file);
  24767. crashedPlugins.add (file);
  24768. setDeadMansPedalFile (crashedPlugins);
  24769. list.scanAndAddFile (file,
  24770. dontRescanIfAlreadyInList,
  24771. typesFound,
  24772. format);
  24773. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24774. crashedPlugins.removeString (file);
  24775. setDeadMansPedalFile (crashedPlugins);
  24776. if (typesFound.size() == 0)
  24777. failedFiles.add (file);
  24778. }
  24779. return skipNextFile();
  24780. }
  24781. bool PluginDirectoryScanner::skipNextFile()
  24782. {
  24783. if (nextIndex >= filesOrIdentifiersToScan.size())
  24784. return false;
  24785. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24786. return nextIndex < filesOrIdentifiersToScan.size();
  24787. }
  24788. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24789. {
  24790. StringArray lines;
  24791. if (deadMansPedalFile != File::nonexistent)
  24792. {
  24793. lines.addLines (deadMansPedalFile.loadFileAsString());
  24794. lines.removeEmptyStrings();
  24795. }
  24796. return lines;
  24797. }
  24798. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24799. {
  24800. if (deadMansPedalFile != File::nonexistent)
  24801. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24802. }
  24803. END_JUCE_NAMESPACE
  24804. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24805. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24806. BEGIN_JUCE_NAMESPACE
  24807. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24808. const File& deadMansPedalFile_,
  24809. PropertiesFile* const propertiesToUse_)
  24810. : list (listToEdit),
  24811. deadMansPedalFile (deadMansPedalFile_),
  24812. optionsButton ("Options..."),
  24813. propertiesToUse (propertiesToUse_)
  24814. {
  24815. listBox.setModel (this);
  24816. addAndMakeVisible (&listBox);
  24817. addAndMakeVisible (&optionsButton);
  24818. optionsButton.addListener (this);
  24819. optionsButton.setTriggeredOnMouseDown (true);
  24820. setSize (400, 600);
  24821. list.addChangeListener (this);
  24822. changeListenerCallback (0);
  24823. }
  24824. PluginListComponent::~PluginListComponent()
  24825. {
  24826. list.removeChangeListener (this);
  24827. }
  24828. void PluginListComponent::resized()
  24829. {
  24830. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24831. optionsButton.changeWidthToFitText (24);
  24832. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24833. }
  24834. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24835. {
  24836. listBox.updateContent();
  24837. listBox.repaint();
  24838. }
  24839. int PluginListComponent::getNumRows()
  24840. {
  24841. return list.getNumTypes();
  24842. }
  24843. void PluginListComponent::paintListBoxItem (int row,
  24844. Graphics& g,
  24845. int width, int height,
  24846. bool rowIsSelected)
  24847. {
  24848. if (rowIsSelected)
  24849. g.fillAll (findColour (TextEditor::highlightColourId));
  24850. const PluginDescription* const pd = list.getType (row);
  24851. if (pd != 0)
  24852. {
  24853. GlyphArrangement ga;
  24854. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24855. g.setColour (Colours::black);
  24856. ga.draw (g);
  24857. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24858. String desc;
  24859. desc << pd->pluginFormatName
  24860. << (pd->isInstrument ? " instrument" : " effect")
  24861. << " - "
  24862. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24863. << " / "
  24864. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24865. if (pd->manufacturerName.isNotEmpty())
  24866. desc << " - " << pd->manufacturerName;
  24867. if (pd->version.isNotEmpty())
  24868. desc << " - " << pd->version;
  24869. if (pd->category.isNotEmpty())
  24870. desc << " - category: '" << pd->category << '\'';
  24871. g.setColour (Colours::grey);
  24872. ga.clear();
  24873. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24874. ga.draw (g);
  24875. }
  24876. }
  24877. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24878. {
  24879. list.removeType (lastRowSelected);
  24880. }
  24881. void PluginListComponent::buttonClicked (Button* button)
  24882. {
  24883. if (button == &optionsButton)
  24884. {
  24885. PopupMenu menu;
  24886. menu.addItem (1, TRANS("Clear list"));
  24887. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24888. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24889. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24890. menu.addSeparator();
  24891. menu.addItem (2, TRANS("Sort alphabetically"));
  24892. menu.addItem (3, TRANS("Sort by category"));
  24893. menu.addItem (4, TRANS("Sort by manufacturer"));
  24894. menu.addSeparator();
  24895. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24896. {
  24897. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24898. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24899. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24900. }
  24901. const int r = menu.showAt (&optionsButton);
  24902. if (r == 1)
  24903. {
  24904. list.clear();
  24905. }
  24906. else if (r == 2)
  24907. {
  24908. list.sort (KnownPluginList::sortAlphabetically);
  24909. }
  24910. else if (r == 3)
  24911. {
  24912. list.sort (KnownPluginList::sortByCategory);
  24913. }
  24914. else if (r == 4)
  24915. {
  24916. list.sort (KnownPluginList::sortByManufacturer);
  24917. }
  24918. else if (r == 5)
  24919. {
  24920. const SparseSet <int> selected (listBox.getSelectedRows());
  24921. for (int i = list.getNumTypes(); --i >= 0;)
  24922. if (selected.contains (i))
  24923. list.removeType (i);
  24924. }
  24925. else if (r == 6)
  24926. {
  24927. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24928. if (desc != 0)
  24929. {
  24930. if (File (desc->fileOrIdentifier).existsAsFile())
  24931. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24932. }
  24933. }
  24934. else if (r == 7)
  24935. {
  24936. for (int i = list.getNumTypes(); --i >= 0;)
  24937. {
  24938. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24939. {
  24940. list.removeType (i);
  24941. }
  24942. }
  24943. }
  24944. else if (r != 0)
  24945. {
  24946. typeToScan = r - 10;
  24947. startTimer (1);
  24948. }
  24949. }
  24950. }
  24951. void PluginListComponent::timerCallback()
  24952. {
  24953. stopTimer();
  24954. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24955. }
  24956. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24957. {
  24958. return true;
  24959. }
  24960. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24961. {
  24962. OwnedArray <PluginDescription> typesFound;
  24963. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24964. }
  24965. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24966. {
  24967. if (format == 0)
  24968. return;
  24969. FileSearchPath path (format->getDefaultLocationsToSearch());
  24970. if (propertiesToUse != 0)
  24971. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24972. {
  24973. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24974. FileSearchPathListComponent pathList;
  24975. pathList.setSize (500, 300);
  24976. pathList.setPath (path);
  24977. aw.addCustomComponent (&pathList);
  24978. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24979. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24980. if (aw.runModalLoop() == 0)
  24981. return;
  24982. path = pathList.getPath();
  24983. }
  24984. if (propertiesToUse != 0)
  24985. {
  24986. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24987. propertiesToUse->saveIfNeeded();
  24988. }
  24989. double progress = 0.0;
  24990. AlertWindow aw (TRANS("Scanning for plugins..."),
  24991. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24992. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24993. aw.addProgressBarComponent (progress);
  24994. aw.enterModalState();
  24995. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24996. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24997. for (;;)
  24998. {
  24999. aw.setMessage (TRANS("Testing:\n\n")
  25000. + scanner.getNextPluginFileThatWillBeScanned());
  25001. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25002. if (! scanner.scanNextFile (true))
  25003. break;
  25004. if (! aw.isCurrentlyModal())
  25005. break;
  25006. progress = scanner.getProgress();
  25007. }
  25008. if (scanner.getFailedFiles().size() > 0)
  25009. {
  25010. StringArray shortNames;
  25011. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25012. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25013. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25014. TRANS("Scan complete"),
  25015. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25016. + shortNames.joinIntoString (", "));
  25017. }
  25018. }
  25019. END_JUCE_NAMESPACE
  25020. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25021. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25022. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25023. #include <AudioUnit/AudioUnit.h>
  25024. #include <AudioUnit/AUCocoaUIView.h>
  25025. #include <CoreAudioKit/AUGenericView.h>
  25026. #if JUCE_SUPPORT_CARBON
  25027. #include <AudioToolbox/AudioUnitUtilities.h>
  25028. #include <AudioUnit/AudioUnitCarbonView.h>
  25029. #endif
  25030. BEGIN_JUCE_NAMESPACE
  25031. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25032. #endif
  25033. #if JUCE_MAC
  25034. // Change this to disable logging of various activities
  25035. #ifndef AU_LOGGING
  25036. #define AU_LOGGING 1
  25037. #endif
  25038. #if AU_LOGGING
  25039. #define log(a) Logger::writeToLog(a);
  25040. #else
  25041. #define log(a)
  25042. #endif
  25043. namespace AudioUnitFormatHelpers
  25044. {
  25045. static int insideCallback = 0;
  25046. const String osTypeToString (OSType type)
  25047. {
  25048. char s[4];
  25049. s[0] = (char) (((uint32) type) >> 24);
  25050. s[1] = (char) (((uint32) type) >> 16);
  25051. s[2] = (char) (((uint32) type) >> 8);
  25052. s[3] = (char) ((uint32) type);
  25053. return String (s, 4);
  25054. }
  25055. OSType stringToOSType (const String& s1)
  25056. {
  25057. const String s (s1 + " ");
  25058. return (((OSType) (unsigned char) s[0]) << 24)
  25059. | (((OSType) (unsigned char) s[1]) << 16)
  25060. | (((OSType) (unsigned char) s[2]) << 8)
  25061. | ((OSType) (unsigned char) s[3]);
  25062. }
  25063. static const char* auIdentifierPrefix = "AudioUnit:";
  25064. const String createAUPluginIdentifier (const ComponentDescription& desc)
  25065. {
  25066. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25067. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25068. String s (auIdentifierPrefix);
  25069. if (desc.componentType == kAudioUnitType_MusicDevice)
  25070. s << "Synths/";
  25071. else if (desc.componentType == kAudioUnitType_MusicEffect
  25072. || desc.componentType == kAudioUnitType_Effect)
  25073. s << "Effects/";
  25074. else if (desc.componentType == kAudioUnitType_Generator)
  25075. s << "Generators/";
  25076. else if (desc.componentType == kAudioUnitType_Panner)
  25077. s << "Panners/";
  25078. s << osTypeToString (desc.componentType) << ","
  25079. << osTypeToString (desc.componentSubType) << ","
  25080. << osTypeToString (desc.componentManufacturer);
  25081. return s;
  25082. }
  25083. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25084. {
  25085. Handle componentNameHandle = NewHandle (sizeof (void*));
  25086. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25087. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25088. {
  25089. ComponentDescription desc;
  25090. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25091. {
  25092. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25093. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25094. if (nameString != 0 && nameString[0] != 0)
  25095. {
  25096. const String all ((const char*) nameString + 1, nameString[0]);
  25097. DBG ("name: "+ all);
  25098. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25099. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25100. }
  25101. if (infoString != 0 && infoString[0] != 0)
  25102. {
  25103. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25104. }
  25105. if (name.isEmpty())
  25106. name = "<Unknown>";
  25107. }
  25108. DisposeHandle (componentNameHandle);
  25109. DisposeHandle (componentInfoHandle);
  25110. }
  25111. }
  25112. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25113. String& name, String& version, String& manufacturer)
  25114. {
  25115. zerostruct (desc);
  25116. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25117. {
  25118. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25119. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25120. StringArray tokens;
  25121. tokens.addTokens (s, ",", String::empty);
  25122. tokens.trim();
  25123. tokens.removeEmptyStrings();
  25124. if (tokens.size() == 3)
  25125. {
  25126. desc.componentType = stringToOSType (tokens[0]);
  25127. desc.componentSubType = stringToOSType (tokens[1]);
  25128. desc.componentManufacturer = stringToOSType (tokens[2]);
  25129. ComponentRecord* comp = FindNextComponent (0, &desc);
  25130. if (comp != 0)
  25131. {
  25132. getAUDetails (comp, name, manufacturer);
  25133. return true;
  25134. }
  25135. }
  25136. }
  25137. return false;
  25138. }
  25139. }
  25140. class AudioUnitPluginWindowCarbon;
  25141. class AudioUnitPluginWindowCocoa;
  25142. class AudioUnitPluginInstance : public AudioPluginInstance
  25143. {
  25144. public:
  25145. ~AudioUnitPluginInstance();
  25146. void initialise();
  25147. // AudioPluginInstance methods:
  25148. void fillInPluginDescription (PluginDescription& desc) const
  25149. {
  25150. desc.name = pluginName;
  25151. desc.descriptiveName = pluginName;
  25152. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25153. desc.uid = ((int) componentDesc.componentType)
  25154. ^ ((int) componentDesc.componentSubType)
  25155. ^ ((int) componentDesc.componentManufacturer);
  25156. desc.lastFileModTime = Time();
  25157. desc.pluginFormatName = "AudioUnit";
  25158. desc.category = getCategory();
  25159. desc.manufacturerName = manufacturer;
  25160. desc.version = version;
  25161. desc.numInputChannels = getNumInputChannels();
  25162. desc.numOutputChannels = getNumOutputChannels();
  25163. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25164. }
  25165. void* getPlatformSpecificData() { return audioUnit; }
  25166. const String getName() const { return pluginName; }
  25167. bool acceptsMidi() const { return wantsMidiMessages; }
  25168. bool producesMidi() const { return false; }
  25169. // AudioProcessor methods:
  25170. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25171. void releaseResources();
  25172. void processBlock (AudioSampleBuffer& buffer,
  25173. MidiBuffer& midiMessages);
  25174. bool hasEditor() const;
  25175. AudioProcessorEditor* createEditor();
  25176. const String getInputChannelName (int index) const;
  25177. bool isInputChannelStereoPair (int index) const;
  25178. const String getOutputChannelName (int index) const;
  25179. bool isOutputChannelStereoPair (int index) const;
  25180. int getNumParameters();
  25181. float getParameter (int index);
  25182. void setParameter (int index, float newValue);
  25183. const String getParameterName (int index);
  25184. const String getParameterText (int index);
  25185. bool isParameterAutomatable (int index) const;
  25186. int getNumPrograms();
  25187. int getCurrentProgram();
  25188. void setCurrentProgram (int index);
  25189. const String getProgramName (int index);
  25190. void changeProgramName (int index, const String& newName);
  25191. void getStateInformation (MemoryBlock& destData);
  25192. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25193. void setStateInformation (const void* data, int sizeInBytes);
  25194. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25195. private:
  25196. friend class AudioUnitPluginWindowCarbon;
  25197. friend class AudioUnitPluginWindowCocoa;
  25198. friend class AudioUnitPluginFormat;
  25199. ComponentDescription componentDesc;
  25200. String pluginName, manufacturer, version;
  25201. String fileOrIdentifier;
  25202. CriticalSection lock;
  25203. bool wantsMidiMessages, wasPlaying, prepared;
  25204. HeapBlock <AudioBufferList> outputBufferList;
  25205. AudioTimeStamp timeStamp;
  25206. AudioSampleBuffer* currentBuffer;
  25207. AudioUnit audioUnit;
  25208. Array <int> parameterIds;
  25209. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25210. void setPluginCallbacks();
  25211. void getParameterListFromPlugin();
  25212. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25213. const AudioTimeStamp* inTimeStamp,
  25214. UInt32 inBusNumber,
  25215. UInt32 inNumberFrames,
  25216. AudioBufferList* ioData) const;
  25217. static OSStatus renderGetInputCallback (void* inRefCon,
  25218. AudioUnitRenderActionFlags* ioActionFlags,
  25219. const AudioTimeStamp* inTimeStamp,
  25220. UInt32 inBusNumber,
  25221. UInt32 inNumberFrames,
  25222. AudioBufferList* ioData)
  25223. {
  25224. return ((AudioUnitPluginInstance*) inRefCon)
  25225. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25226. }
  25227. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25228. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25229. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25230. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25231. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25232. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25233. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25234. {
  25235. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25236. }
  25237. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25238. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25239. Float64* outCurrentMeasureDownBeat)
  25240. {
  25241. return ((AudioUnitPluginInstance*) inHostUserData)
  25242. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25243. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25244. }
  25245. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25246. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25247. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25248. {
  25249. return ((AudioUnitPluginInstance*) inHostUserData)
  25250. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25251. outCurrentSampleInTimeLine, outIsCycling,
  25252. outCycleStartBeat, outCycleEndBeat);
  25253. }
  25254. void getNumChannels (int& numIns, int& numOuts)
  25255. {
  25256. numIns = 0;
  25257. numOuts = 0;
  25258. AUChannelInfo supportedChannels [128];
  25259. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25260. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25261. 0, supportedChannels, &supportedChannelsSize) == noErr
  25262. && supportedChannelsSize > 0)
  25263. {
  25264. int explicitNumIns = 0;
  25265. int explicitNumOuts = 0;
  25266. int maximumNumIns = 0;
  25267. int maximumNumOuts = 0;
  25268. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25269. {
  25270. const int inChannels = (int) supportedChannels[i].inChannels;
  25271. const int outChannels = (int) supportedChannels[i].outChannels;
  25272. if (inChannels < 0)
  25273. maximumNumIns = jmin (maximumNumIns, inChannels);
  25274. else
  25275. explicitNumIns = jmax (explicitNumIns, inChannels);
  25276. if (outChannels < 0)
  25277. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25278. else
  25279. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25280. }
  25281. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25282. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25283. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25284. {
  25285. numIns = numOuts = 2;
  25286. }
  25287. else
  25288. {
  25289. numIns = explicitNumIns;
  25290. numOuts = explicitNumOuts;
  25291. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25292. numIns = 2;
  25293. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25294. numOuts = 2;
  25295. }
  25296. }
  25297. else
  25298. {
  25299. // (this really means the plugin will take any number of ins/outs as long
  25300. // as they are the same)
  25301. numIns = numOuts = 2;
  25302. }
  25303. }
  25304. const String getCategory() const;
  25305. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25306. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25307. };
  25308. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25309. : fileOrIdentifier (fileOrIdentifier),
  25310. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25311. currentBuffer (0),
  25312. audioUnit (0)
  25313. {
  25314. using namespace AudioUnitFormatHelpers;
  25315. try
  25316. {
  25317. ++insideCallback;
  25318. log ("Opening AU: " + fileOrIdentifier);
  25319. if (getComponentDescFromFile (fileOrIdentifier))
  25320. {
  25321. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25322. if (comp != 0)
  25323. {
  25324. audioUnit = (AudioUnit) OpenComponent (comp);
  25325. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25326. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25327. }
  25328. }
  25329. --insideCallback;
  25330. }
  25331. catch (...)
  25332. {
  25333. --insideCallback;
  25334. }
  25335. }
  25336. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25337. {
  25338. const ScopedLock sl (lock);
  25339. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25340. if (audioUnit != 0)
  25341. {
  25342. AudioUnitUninitialize (audioUnit);
  25343. CloseComponent (audioUnit);
  25344. audioUnit = 0;
  25345. }
  25346. }
  25347. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25348. {
  25349. zerostruct (componentDesc);
  25350. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25351. return true;
  25352. const File file (fileOrIdentifier);
  25353. if (! file.hasFileExtension (".component"))
  25354. return false;
  25355. const char* const utf8 = fileOrIdentifier.toUTF8();
  25356. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25357. strlen (utf8), file.isDirectory());
  25358. if (url != 0)
  25359. {
  25360. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25361. CFRelease (url);
  25362. if (bundleRef != 0)
  25363. {
  25364. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25365. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25366. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25367. if (pluginName.isEmpty())
  25368. pluginName = file.getFileNameWithoutExtension();
  25369. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25370. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25371. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25372. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25373. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25374. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25375. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25376. UseResFile (resFileId);
  25377. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25378. {
  25379. Handle h = Get1IndResource ('thng', i);
  25380. if (h != 0)
  25381. {
  25382. HLock (h);
  25383. const uint32* const types = (const uint32*) *h;
  25384. if (types[0] == kAudioUnitType_MusicDevice
  25385. || types[0] == kAudioUnitType_MusicEffect
  25386. || types[0] == kAudioUnitType_Effect
  25387. || types[0] == kAudioUnitType_Generator
  25388. || types[0] == kAudioUnitType_Panner)
  25389. {
  25390. componentDesc.componentType = types[0];
  25391. componentDesc.componentSubType = types[1];
  25392. componentDesc.componentManufacturer = types[2];
  25393. break;
  25394. }
  25395. HUnlock (h);
  25396. ReleaseResource (h);
  25397. }
  25398. }
  25399. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25400. CFRelease (bundleRef);
  25401. }
  25402. }
  25403. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25404. }
  25405. void AudioUnitPluginInstance::initialise()
  25406. {
  25407. getParameterListFromPlugin();
  25408. setPluginCallbacks();
  25409. int numIns, numOuts;
  25410. getNumChannels (numIns, numOuts);
  25411. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25412. setLatencySamples (0);
  25413. }
  25414. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25415. {
  25416. parameterIds.clear();
  25417. if (audioUnit != 0)
  25418. {
  25419. UInt32 paramListSize = 0;
  25420. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25421. 0, 0, &paramListSize);
  25422. if (paramListSize > 0)
  25423. {
  25424. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25425. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25426. 0, &parameterIds.getReference(0), &paramListSize);
  25427. }
  25428. }
  25429. }
  25430. void AudioUnitPluginInstance::setPluginCallbacks()
  25431. {
  25432. if (audioUnit != 0)
  25433. {
  25434. {
  25435. AURenderCallbackStruct info;
  25436. zerostruct (info);
  25437. info.inputProcRefCon = this;
  25438. info.inputProc = renderGetInputCallback;
  25439. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25440. 0, &info, sizeof (info));
  25441. }
  25442. {
  25443. HostCallbackInfo info;
  25444. zerostruct (info);
  25445. info.hostUserData = this;
  25446. info.beatAndTempoProc = getBeatAndTempoCallback;
  25447. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25448. info.transportStateProc = getTransportStateCallback;
  25449. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25450. 0, &info, sizeof (info));
  25451. }
  25452. }
  25453. }
  25454. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25455. int samplesPerBlockExpected)
  25456. {
  25457. if (audioUnit != 0)
  25458. {
  25459. releaseResources();
  25460. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25461. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25462. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25463. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25464. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25465. {
  25466. Float64 sr = sampleRate_;
  25467. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25468. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25469. }
  25470. int numIns, numOuts;
  25471. getNumChannels (numIns, numOuts);
  25472. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25473. Float64 latencySecs = 0.0;
  25474. UInt32 latencySize = sizeof (latencySecs);
  25475. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25476. 0, &latencySecs, &latencySize);
  25477. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25478. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25479. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25480. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25481. {
  25482. AudioStreamBasicDescription stream;
  25483. zerostruct (stream);
  25484. stream.mSampleRate = sampleRate_;
  25485. stream.mFormatID = kAudioFormatLinearPCM;
  25486. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25487. stream.mFramesPerPacket = 1;
  25488. stream.mBytesPerPacket = 4;
  25489. stream.mBytesPerFrame = 4;
  25490. stream.mBitsPerChannel = 32;
  25491. stream.mChannelsPerFrame = numIns;
  25492. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25493. 0, &stream, sizeof (stream));
  25494. stream.mChannelsPerFrame = numOuts;
  25495. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25496. 0, &stream, sizeof (stream));
  25497. }
  25498. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25499. outputBufferList->mNumberBuffers = numOuts;
  25500. for (int i = numOuts; --i >= 0;)
  25501. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25502. zerostruct (timeStamp);
  25503. timeStamp.mSampleTime = 0;
  25504. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25505. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25506. currentBuffer = 0;
  25507. wasPlaying = false;
  25508. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25509. }
  25510. }
  25511. void AudioUnitPluginInstance::releaseResources()
  25512. {
  25513. if (prepared)
  25514. {
  25515. AudioUnitUninitialize (audioUnit);
  25516. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25517. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25518. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25519. outputBufferList.free();
  25520. currentBuffer = 0;
  25521. prepared = false;
  25522. }
  25523. }
  25524. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25525. const AudioTimeStamp* inTimeStamp,
  25526. UInt32 inBusNumber,
  25527. UInt32 inNumberFrames,
  25528. AudioBufferList* ioData) const
  25529. {
  25530. if (inBusNumber == 0
  25531. && currentBuffer != 0)
  25532. {
  25533. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25534. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25535. {
  25536. if (i < currentBuffer->getNumChannels())
  25537. {
  25538. memcpy (ioData->mBuffers[i].mData,
  25539. currentBuffer->getSampleData (i, 0),
  25540. sizeof (float) * inNumberFrames);
  25541. }
  25542. else
  25543. {
  25544. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25545. }
  25546. }
  25547. }
  25548. return noErr;
  25549. }
  25550. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25551. MidiBuffer& midiMessages)
  25552. {
  25553. const int numSamples = buffer.getNumSamples();
  25554. if (prepared)
  25555. {
  25556. AudioUnitRenderActionFlags flags = 0;
  25557. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25558. for (int i = getNumOutputChannels(); --i >= 0;)
  25559. {
  25560. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25561. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25562. }
  25563. currentBuffer = &buffer;
  25564. if (wantsMidiMessages)
  25565. {
  25566. const uint8* midiEventData;
  25567. int midiEventSize, midiEventPosition;
  25568. MidiBuffer::Iterator i (midiMessages);
  25569. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25570. {
  25571. if (midiEventSize <= 3)
  25572. MusicDeviceMIDIEvent (audioUnit,
  25573. midiEventData[0], midiEventData[1], midiEventData[2],
  25574. midiEventPosition);
  25575. else
  25576. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25577. }
  25578. midiMessages.clear();
  25579. }
  25580. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25581. 0, numSamples, outputBufferList);
  25582. timeStamp.mSampleTime += numSamples;
  25583. }
  25584. else
  25585. {
  25586. // Plugin not working correctly, so just bypass..
  25587. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25588. buffer.clear (i, 0, buffer.getNumSamples());
  25589. }
  25590. }
  25591. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25592. {
  25593. AudioPlayHead* const ph = getPlayHead();
  25594. AudioPlayHead::CurrentPositionInfo result;
  25595. if (ph != 0 && ph->getCurrentPosition (result))
  25596. {
  25597. if (outCurrentBeat != 0)
  25598. *outCurrentBeat = result.ppqPosition;
  25599. if (outCurrentTempo != 0)
  25600. *outCurrentTempo = result.bpm;
  25601. }
  25602. else
  25603. {
  25604. if (outCurrentBeat != 0)
  25605. *outCurrentBeat = 0;
  25606. if (outCurrentTempo != 0)
  25607. *outCurrentTempo = 120.0;
  25608. }
  25609. return noErr;
  25610. }
  25611. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25612. Float32* outTimeSig_Numerator,
  25613. UInt32* outTimeSig_Denominator,
  25614. Float64* outCurrentMeasureDownBeat) const
  25615. {
  25616. AudioPlayHead* const ph = getPlayHead();
  25617. AudioPlayHead::CurrentPositionInfo result;
  25618. if (ph != 0 && ph->getCurrentPosition (result))
  25619. {
  25620. if (outTimeSig_Numerator != 0)
  25621. *outTimeSig_Numerator = result.timeSigNumerator;
  25622. if (outTimeSig_Denominator != 0)
  25623. *outTimeSig_Denominator = result.timeSigDenominator;
  25624. if (outDeltaSampleOffsetToNextBeat != 0)
  25625. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25626. if (outCurrentMeasureDownBeat != 0)
  25627. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25628. }
  25629. else
  25630. {
  25631. if (outDeltaSampleOffsetToNextBeat != 0)
  25632. *outDeltaSampleOffsetToNextBeat = 0;
  25633. if (outTimeSig_Numerator != 0)
  25634. *outTimeSig_Numerator = 4;
  25635. if (outTimeSig_Denominator != 0)
  25636. *outTimeSig_Denominator = 4;
  25637. if (outCurrentMeasureDownBeat != 0)
  25638. *outCurrentMeasureDownBeat = 0;
  25639. }
  25640. return noErr;
  25641. }
  25642. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25643. Boolean* outTransportStateChanged,
  25644. Float64* outCurrentSampleInTimeLine,
  25645. Boolean* outIsCycling,
  25646. Float64* outCycleStartBeat,
  25647. Float64* outCycleEndBeat)
  25648. {
  25649. AudioPlayHead* const ph = getPlayHead();
  25650. AudioPlayHead::CurrentPositionInfo result;
  25651. if (ph != 0 && ph->getCurrentPosition (result))
  25652. {
  25653. if (outIsPlaying != 0)
  25654. *outIsPlaying = result.isPlaying;
  25655. if (outTransportStateChanged != 0)
  25656. {
  25657. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25658. wasPlaying = result.isPlaying;
  25659. }
  25660. if (outCurrentSampleInTimeLine != 0)
  25661. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25662. if (outIsCycling != 0)
  25663. *outIsCycling = false;
  25664. if (outCycleStartBeat != 0)
  25665. *outCycleStartBeat = 0;
  25666. if (outCycleEndBeat != 0)
  25667. *outCycleEndBeat = 0;
  25668. }
  25669. else
  25670. {
  25671. if (outIsPlaying != 0)
  25672. *outIsPlaying = false;
  25673. if (outTransportStateChanged != 0)
  25674. *outTransportStateChanged = false;
  25675. if (outCurrentSampleInTimeLine != 0)
  25676. *outCurrentSampleInTimeLine = 0;
  25677. if (outIsCycling != 0)
  25678. *outIsCycling = false;
  25679. if (outCycleStartBeat != 0)
  25680. *outCycleStartBeat = 0;
  25681. if (outCycleEndBeat != 0)
  25682. *outCycleEndBeat = 0;
  25683. }
  25684. return noErr;
  25685. }
  25686. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25687. public Timer
  25688. {
  25689. public:
  25690. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25691. : AudioProcessorEditor (&plugin_),
  25692. plugin (plugin_)
  25693. {
  25694. addAndMakeVisible (&wrapper);
  25695. setOpaque (true);
  25696. setVisible (true);
  25697. setSize (100, 100);
  25698. createView (createGenericViewIfNeeded);
  25699. }
  25700. ~AudioUnitPluginWindowCocoa()
  25701. {
  25702. const bool wasValid = isValid();
  25703. wrapper.setView (0);
  25704. if (wasValid)
  25705. plugin.editorBeingDeleted (this);
  25706. }
  25707. bool isValid() const { return wrapper.getView() != 0; }
  25708. void paint (Graphics& g)
  25709. {
  25710. g.fillAll (Colours::white);
  25711. }
  25712. void resized()
  25713. {
  25714. wrapper.setSize (getWidth(), getHeight());
  25715. }
  25716. void timerCallback()
  25717. {
  25718. wrapper.resizeToFitView();
  25719. startTimer (jmin (713, getTimerInterval() + 51));
  25720. }
  25721. void childBoundsChanged (Component* child)
  25722. {
  25723. setSize (wrapper.getWidth(), wrapper.getHeight());
  25724. startTimer (70);
  25725. }
  25726. private:
  25727. AudioUnitPluginInstance& plugin;
  25728. NSViewComponent wrapper;
  25729. bool createView (const bool createGenericViewIfNeeded)
  25730. {
  25731. NSView* pluginView = 0;
  25732. UInt32 dataSize = 0;
  25733. Boolean isWritable = false;
  25734. AudioUnitInitialize (plugin.audioUnit);
  25735. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25736. 0, &dataSize, &isWritable) == noErr
  25737. && dataSize != 0
  25738. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25739. 0, &dataSize, &isWritable) == noErr)
  25740. {
  25741. HeapBlock <AudioUnitCocoaViewInfo> info;
  25742. info.calloc (dataSize, 1);
  25743. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25744. 0, info, &dataSize) == noErr)
  25745. {
  25746. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25747. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25748. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25749. Class viewClass = [viewBundle classNamed: viewClassName];
  25750. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25751. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25752. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25753. {
  25754. id factory = [[[viewClass alloc] init] autorelease];
  25755. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25756. withSize: NSMakeSize (getWidth(), getHeight())];
  25757. }
  25758. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25759. CFRelease (info->mCocoaAUViewClass[i]);
  25760. CFRelease (info->mCocoaAUViewBundleLocation);
  25761. }
  25762. }
  25763. if (createGenericViewIfNeeded && (pluginView == 0))
  25764. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25765. wrapper.setView (pluginView);
  25766. if (pluginView != 0)
  25767. {
  25768. timerCallback();
  25769. startTimer (70);
  25770. }
  25771. return pluginView != 0;
  25772. }
  25773. };
  25774. #if JUCE_SUPPORT_CARBON
  25775. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25776. {
  25777. public:
  25778. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25779. : AudioProcessorEditor (&plugin_),
  25780. plugin (plugin_),
  25781. viewComponent (0)
  25782. {
  25783. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25784. setOpaque (true);
  25785. setVisible (true);
  25786. setSize (400, 300);
  25787. ComponentDescription viewList [16];
  25788. UInt32 viewListSize = sizeof (viewList);
  25789. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25790. 0, &viewList, &viewListSize);
  25791. componentRecord = FindNextComponent (0, &viewList[0]);
  25792. }
  25793. ~AudioUnitPluginWindowCarbon()
  25794. {
  25795. innerWrapper = 0;
  25796. if (isValid())
  25797. plugin.editorBeingDeleted (this);
  25798. }
  25799. bool isValid() const throw() { return componentRecord != 0; }
  25800. void paint (Graphics& g)
  25801. {
  25802. g.fillAll (Colours::black);
  25803. }
  25804. void resized()
  25805. {
  25806. innerWrapper->setSize (getWidth(), getHeight());
  25807. }
  25808. bool keyStateChanged (bool)
  25809. {
  25810. return false;
  25811. }
  25812. bool keyPressed (const KeyPress&)
  25813. {
  25814. return false;
  25815. }
  25816. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25817. AudioUnitCarbonView getViewComponent()
  25818. {
  25819. if (viewComponent == 0 && componentRecord != 0)
  25820. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25821. return viewComponent;
  25822. }
  25823. void closeViewComponent()
  25824. {
  25825. if (viewComponent != 0)
  25826. {
  25827. log ("Closing AU GUI: " + plugin.getName());
  25828. CloseComponent (viewComponent);
  25829. viewComponent = 0;
  25830. }
  25831. }
  25832. private:
  25833. AudioUnitPluginInstance& plugin;
  25834. ComponentRecord* componentRecord;
  25835. AudioUnitCarbonView viewComponent;
  25836. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25837. {
  25838. public:
  25839. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25840. : owner (owner_)
  25841. {
  25842. }
  25843. ~InnerWrapperComponent()
  25844. {
  25845. deleteWindow();
  25846. }
  25847. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25848. {
  25849. log ("Opening AU GUI: " + owner->plugin.getName());
  25850. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25851. if (viewComponent == 0)
  25852. return 0;
  25853. Float32Point pos = { 0, 0 };
  25854. Float32Point size = { 250, 200 };
  25855. HIViewRef pluginView = 0;
  25856. AudioUnitCarbonViewCreate (viewComponent,
  25857. owner->getAudioUnit(),
  25858. windowRef,
  25859. rootView,
  25860. &pos,
  25861. &size,
  25862. (ControlRef*) &pluginView);
  25863. return pluginView;
  25864. }
  25865. void removeView (HIViewRef)
  25866. {
  25867. owner->closeViewComponent();
  25868. }
  25869. private:
  25870. AudioUnitPluginWindowCarbon* const owner;
  25871. };
  25872. friend class InnerWrapperComponent;
  25873. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25874. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25875. };
  25876. #endif
  25877. bool AudioUnitPluginInstance::hasEditor() const
  25878. {
  25879. return true;
  25880. }
  25881. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25882. {
  25883. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25884. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25885. w = 0;
  25886. #if JUCE_SUPPORT_CARBON
  25887. if (w == 0)
  25888. {
  25889. w = new AudioUnitPluginWindowCarbon (*this);
  25890. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25891. w = 0;
  25892. }
  25893. #endif
  25894. if (w == 0)
  25895. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25896. return w.release();
  25897. }
  25898. const String AudioUnitPluginInstance::getCategory() const
  25899. {
  25900. const char* result = 0;
  25901. switch (componentDesc.componentType)
  25902. {
  25903. case kAudioUnitType_Effect:
  25904. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25905. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25906. case kAudioUnitType_Generator: result = "Generator"; break;
  25907. case kAudioUnitType_Panner: result = "Panner"; break;
  25908. default: break;
  25909. }
  25910. return result;
  25911. }
  25912. int AudioUnitPluginInstance::getNumParameters()
  25913. {
  25914. return parameterIds.size();
  25915. }
  25916. float AudioUnitPluginInstance::getParameter (int index)
  25917. {
  25918. const ScopedLock sl (lock);
  25919. Float32 value = 0.0f;
  25920. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25921. {
  25922. AudioUnitGetParameter (audioUnit,
  25923. (UInt32) parameterIds.getUnchecked (index),
  25924. kAudioUnitScope_Global, 0,
  25925. &value);
  25926. }
  25927. return value;
  25928. }
  25929. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25930. {
  25931. const ScopedLock sl (lock);
  25932. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25933. {
  25934. AudioUnitSetParameter (audioUnit,
  25935. (UInt32) parameterIds.getUnchecked (index),
  25936. kAudioUnitScope_Global, 0,
  25937. newValue, 0);
  25938. }
  25939. }
  25940. const String AudioUnitPluginInstance::getParameterName (int index)
  25941. {
  25942. AudioUnitParameterInfo info;
  25943. zerostruct (info);
  25944. UInt32 sz = sizeof (info);
  25945. String name;
  25946. if (AudioUnitGetProperty (audioUnit,
  25947. kAudioUnitProperty_ParameterInfo,
  25948. kAudioUnitScope_Global,
  25949. parameterIds [index], &info, &sz) == noErr)
  25950. {
  25951. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25952. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25953. else
  25954. name = String (info.name, sizeof (info.name));
  25955. }
  25956. return name;
  25957. }
  25958. const String AudioUnitPluginInstance::getParameterText (int index)
  25959. {
  25960. return String (getParameter (index));
  25961. }
  25962. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25963. {
  25964. AudioUnitParameterInfo info;
  25965. UInt32 sz = sizeof (info);
  25966. if (AudioUnitGetProperty (audioUnit,
  25967. kAudioUnitProperty_ParameterInfo,
  25968. kAudioUnitScope_Global,
  25969. parameterIds [index], &info, &sz) == noErr)
  25970. {
  25971. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25972. }
  25973. return true;
  25974. }
  25975. int AudioUnitPluginInstance::getNumPrograms()
  25976. {
  25977. CFArrayRef presets;
  25978. UInt32 sz = sizeof (CFArrayRef);
  25979. int num = 0;
  25980. if (AudioUnitGetProperty (audioUnit,
  25981. kAudioUnitProperty_FactoryPresets,
  25982. kAudioUnitScope_Global,
  25983. 0, &presets, &sz) == noErr)
  25984. {
  25985. num = (int) CFArrayGetCount (presets);
  25986. CFRelease (presets);
  25987. }
  25988. return num;
  25989. }
  25990. int AudioUnitPluginInstance::getCurrentProgram()
  25991. {
  25992. AUPreset current;
  25993. current.presetNumber = 0;
  25994. UInt32 sz = sizeof (AUPreset);
  25995. AudioUnitGetProperty (audioUnit,
  25996. kAudioUnitProperty_FactoryPresets,
  25997. kAudioUnitScope_Global,
  25998. 0, &current, &sz);
  25999. return current.presetNumber;
  26000. }
  26001. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26002. {
  26003. AUPreset current;
  26004. current.presetNumber = newIndex;
  26005. current.presetName = 0;
  26006. AudioUnitSetProperty (audioUnit,
  26007. kAudioUnitProperty_FactoryPresets,
  26008. kAudioUnitScope_Global,
  26009. 0, &current, sizeof (AUPreset));
  26010. }
  26011. const String AudioUnitPluginInstance::getProgramName (int index)
  26012. {
  26013. String s;
  26014. CFArrayRef presets;
  26015. UInt32 sz = sizeof (CFArrayRef);
  26016. if (AudioUnitGetProperty (audioUnit,
  26017. kAudioUnitProperty_FactoryPresets,
  26018. kAudioUnitScope_Global,
  26019. 0, &presets, &sz) == noErr)
  26020. {
  26021. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26022. {
  26023. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26024. if (p != 0 && p->presetNumber == index)
  26025. {
  26026. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26027. break;
  26028. }
  26029. }
  26030. CFRelease (presets);
  26031. }
  26032. return s;
  26033. }
  26034. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26035. {
  26036. jassertfalse; // xxx not implemented!
  26037. }
  26038. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26039. {
  26040. if (isPositiveAndBelow (index, getNumInputChannels()))
  26041. return "Input " + String (index + 1);
  26042. return String::empty;
  26043. }
  26044. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26045. {
  26046. if (! isPositiveAndBelow (index, getNumInputChannels()))
  26047. return false;
  26048. return true;
  26049. }
  26050. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26051. {
  26052. if (isPositiveAndBelow (index, getNumOutputChannels()))
  26053. return "Output " + String (index + 1);
  26054. return String::empty;
  26055. }
  26056. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26057. {
  26058. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  26059. return false;
  26060. return true;
  26061. }
  26062. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26063. {
  26064. getCurrentProgramStateInformation (destData);
  26065. }
  26066. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26067. {
  26068. CFPropertyListRef propertyList = 0;
  26069. UInt32 sz = sizeof (CFPropertyListRef);
  26070. if (AudioUnitGetProperty (audioUnit,
  26071. kAudioUnitProperty_ClassInfo,
  26072. kAudioUnitScope_Global,
  26073. 0, &propertyList, &sz) == noErr)
  26074. {
  26075. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26076. CFWriteStreamOpen (stream);
  26077. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26078. CFWriteStreamClose (stream);
  26079. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26080. destData.setSize (bytesWritten);
  26081. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26082. CFRelease (data);
  26083. CFRelease (stream);
  26084. CFRelease (propertyList);
  26085. }
  26086. }
  26087. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26088. {
  26089. setCurrentProgramStateInformation (data, sizeInBytes);
  26090. }
  26091. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26092. {
  26093. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26094. (const UInt8*) data,
  26095. sizeInBytes,
  26096. kCFAllocatorNull);
  26097. CFReadStreamOpen (stream);
  26098. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26099. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26100. stream,
  26101. 0,
  26102. kCFPropertyListImmutable,
  26103. &format,
  26104. 0);
  26105. CFRelease (stream);
  26106. if (propertyList != 0)
  26107. AudioUnitSetProperty (audioUnit,
  26108. kAudioUnitProperty_ClassInfo,
  26109. kAudioUnitScope_Global,
  26110. 0, &propertyList, sizeof (propertyList));
  26111. }
  26112. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26113. {
  26114. }
  26115. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26116. {
  26117. }
  26118. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26119. const String& fileOrIdentifier)
  26120. {
  26121. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26122. return;
  26123. PluginDescription desc;
  26124. desc.fileOrIdentifier = fileOrIdentifier;
  26125. desc.uid = 0;
  26126. try
  26127. {
  26128. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26129. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26130. if (auInstance != 0)
  26131. {
  26132. auInstance->fillInPluginDescription (desc);
  26133. results.add (new PluginDescription (desc));
  26134. }
  26135. }
  26136. catch (...)
  26137. {
  26138. // crashed while loading...
  26139. }
  26140. }
  26141. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26142. {
  26143. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26144. {
  26145. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26146. if (result->audioUnit != 0)
  26147. {
  26148. result->initialise();
  26149. return result.release();
  26150. }
  26151. }
  26152. return 0;
  26153. }
  26154. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26155. const bool /*recursive*/)
  26156. {
  26157. StringArray result;
  26158. ComponentRecord* comp = 0;
  26159. ComponentDescription desc;
  26160. zerostruct (desc);
  26161. for (;;)
  26162. {
  26163. zerostruct (desc);
  26164. comp = FindNextComponent (comp, &desc);
  26165. if (comp == 0)
  26166. break;
  26167. GetComponentInfo (comp, &desc, 0, 0, 0);
  26168. if (desc.componentType == kAudioUnitType_MusicDevice
  26169. || desc.componentType == kAudioUnitType_MusicEffect
  26170. || desc.componentType == kAudioUnitType_Effect
  26171. || desc.componentType == kAudioUnitType_Generator
  26172. || desc.componentType == kAudioUnitType_Panner)
  26173. {
  26174. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26175. DBG (s);
  26176. result.add (s);
  26177. }
  26178. }
  26179. return result;
  26180. }
  26181. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26182. {
  26183. ComponentDescription desc;
  26184. String name, version, manufacturer;
  26185. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26186. return FindNextComponent (0, &desc) != 0;
  26187. const File f (fileOrIdentifier);
  26188. return f.hasFileExtension (".component")
  26189. && f.isDirectory();
  26190. }
  26191. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26192. {
  26193. ComponentDescription desc;
  26194. String name, version, manufacturer;
  26195. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26196. if (name.isEmpty())
  26197. name = fileOrIdentifier;
  26198. return name;
  26199. }
  26200. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26201. {
  26202. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26203. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26204. else
  26205. return File (desc.fileOrIdentifier).exists();
  26206. }
  26207. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26208. {
  26209. return FileSearchPath ("/(Default AudioUnit locations)");
  26210. }
  26211. #endif
  26212. END_JUCE_NAMESPACE
  26213. #undef log
  26214. #endif
  26215. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26216. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26217. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26218. #define JUCE_MAC_VST_INCLUDED 1
  26219. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26220. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26221. #if JUCE_WINDOWS
  26222. #undef _WIN32_WINNT
  26223. #define _WIN32_WINNT 0x500
  26224. #undef STRICT
  26225. #define STRICT
  26226. #include <windows.h>
  26227. #include <float.h>
  26228. #pragma warning (disable : 4312 4355)
  26229. #elif JUCE_LINUX
  26230. #include <float.h>
  26231. #include <sys/time.h>
  26232. #include <X11/Xlib.h>
  26233. #include <X11/Xutil.h>
  26234. #include <X11/Xatom.h>
  26235. #undef Font
  26236. #undef KeyPress
  26237. #undef Drawable
  26238. #undef Time
  26239. #else
  26240. #include <Cocoa/Cocoa.h>
  26241. #include <Carbon/Carbon.h>
  26242. #endif
  26243. #if ! (JUCE_MAC && JUCE_64BIT)
  26244. BEGIN_JUCE_NAMESPACE
  26245. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26246. #endif
  26247. #undef PRAGMA_ALIGN_SUPPORTED
  26248. #define VST_FORCE_DEPRECATED 0
  26249. #if JUCE_MSVC
  26250. #pragma warning (push)
  26251. #pragma warning (disable: 4996)
  26252. #endif
  26253. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26254. your include path if you want to add VST support.
  26255. If you're not interested in VSTs, you can disable them by changing the
  26256. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26257. */
  26258. #include <pluginterfaces/vst2.x/aeffectx.h>
  26259. #if JUCE_MSVC
  26260. #pragma warning (pop)
  26261. #endif
  26262. #if JUCE_LINUX
  26263. #define Font JUCE_NAMESPACE::Font
  26264. #define KeyPress JUCE_NAMESPACE::KeyPress
  26265. #define Drawable JUCE_NAMESPACE::Drawable
  26266. #define Time JUCE_NAMESPACE::Time
  26267. #endif
  26268. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26269. #ifdef __aeffect__
  26270. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26271. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26272. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26273. events to the list.
  26274. This is used by both the VST hosting code and the plugin wrapper.
  26275. */
  26276. class VSTMidiEventList
  26277. {
  26278. public:
  26279. VSTMidiEventList()
  26280. : numEventsUsed (0), numEventsAllocated (0)
  26281. {
  26282. }
  26283. ~VSTMidiEventList()
  26284. {
  26285. freeEvents();
  26286. }
  26287. void clear()
  26288. {
  26289. numEventsUsed = 0;
  26290. if (events != 0)
  26291. events->numEvents = 0;
  26292. }
  26293. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26294. {
  26295. ensureSize (numEventsUsed + 1);
  26296. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26297. events->numEvents = ++numEventsUsed;
  26298. if (numBytes <= 4)
  26299. {
  26300. if (e->type == kVstSysExType)
  26301. {
  26302. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26303. e->type = kVstMidiType;
  26304. e->byteSize = sizeof (VstMidiEvent);
  26305. e->noteLength = 0;
  26306. e->noteOffset = 0;
  26307. e->detune = 0;
  26308. e->noteOffVelocity = 0;
  26309. }
  26310. e->deltaFrames = frameOffset;
  26311. memcpy (e->midiData, midiData, numBytes);
  26312. }
  26313. else
  26314. {
  26315. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26316. if (se->type == kVstSysExType)
  26317. delete[] se->sysexDump;
  26318. se->sysexDump = new char [numBytes];
  26319. memcpy (se->sysexDump, midiData, numBytes);
  26320. se->type = kVstSysExType;
  26321. se->byteSize = sizeof (VstMidiSysexEvent);
  26322. se->deltaFrames = frameOffset;
  26323. se->flags = 0;
  26324. se->dumpBytes = numBytes;
  26325. se->resvd1 = 0;
  26326. se->resvd2 = 0;
  26327. }
  26328. }
  26329. // Handy method to pull the events out of an event buffer supplied by the host
  26330. // or plugin.
  26331. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26332. {
  26333. for (int i = 0; i < events->numEvents; ++i)
  26334. {
  26335. const VstEvent* const e = events->events[i];
  26336. if (e != 0)
  26337. {
  26338. if (e->type == kVstMidiType)
  26339. {
  26340. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26341. 4, e->deltaFrames);
  26342. }
  26343. else if (e->type == kVstSysExType)
  26344. {
  26345. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26346. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26347. e->deltaFrames);
  26348. }
  26349. }
  26350. }
  26351. }
  26352. void ensureSize (int numEventsNeeded)
  26353. {
  26354. if (numEventsNeeded > numEventsAllocated)
  26355. {
  26356. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26357. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26358. if (events == 0)
  26359. events.calloc (size, 1);
  26360. else
  26361. events.realloc (size, 1);
  26362. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26363. {
  26364. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26365. (int) sizeof (VstMidiSysexEvent)));
  26366. e->type = kVstMidiType;
  26367. e->byteSize = sizeof (VstMidiEvent);
  26368. events->events[i] = (VstEvent*) e;
  26369. }
  26370. numEventsAllocated = numEventsNeeded;
  26371. }
  26372. }
  26373. void freeEvents()
  26374. {
  26375. if (events != 0)
  26376. {
  26377. for (int i = numEventsAllocated; --i >= 0;)
  26378. {
  26379. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26380. if (e->type == kVstSysExType)
  26381. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26382. juce_free (e);
  26383. }
  26384. events.free();
  26385. numEventsUsed = 0;
  26386. numEventsAllocated = 0;
  26387. }
  26388. }
  26389. HeapBlock <VstEvents> events;
  26390. private:
  26391. int numEventsUsed, numEventsAllocated;
  26392. };
  26393. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26394. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26395. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26396. #if ! JUCE_WINDOWS
  26397. static void _fpreset() {}
  26398. static void _clearfp() {}
  26399. #endif
  26400. extern void juce_callAnyTimersSynchronously();
  26401. const int fxbVersionNum = 1;
  26402. struct fxProgram
  26403. {
  26404. long chunkMagic; // 'CcnK'
  26405. long byteSize; // of this chunk, excl. magic + byteSize
  26406. long fxMagic; // 'FxCk'
  26407. long version;
  26408. long fxID; // fx unique id
  26409. long fxVersion;
  26410. long numParams;
  26411. char prgName[28];
  26412. float params[1]; // variable no. of parameters
  26413. };
  26414. struct fxSet
  26415. {
  26416. long chunkMagic; // 'CcnK'
  26417. long byteSize; // of this chunk, excl. magic + byteSize
  26418. long fxMagic; // 'FxBk'
  26419. long version;
  26420. long fxID; // fx unique id
  26421. long fxVersion;
  26422. long numPrograms;
  26423. char future[128];
  26424. fxProgram programs[1]; // variable no. of programs
  26425. };
  26426. struct fxChunkSet
  26427. {
  26428. long chunkMagic; // 'CcnK'
  26429. long byteSize; // of this chunk, excl. magic + byteSize
  26430. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26431. long version;
  26432. long fxID; // fx unique id
  26433. long fxVersion;
  26434. long numPrograms;
  26435. char future[128];
  26436. long chunkSize;
  26437. char chunk[8]; // variable
  26438. };
  26439. struct fxProgramSet
  26440. {
  26441. long chunkMagic; // 'CcnK'
  26442. long byteSize; // of this chunk, excl. magic + byteSize
  26443. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26444. long version;
  26445. long fxID; // fx unique id
  26446. long fxVersion;
  26447. long numPrograms;
  26448. char name[28];
  26449. long chunkSize;
  26450. char chunk[8]; // variable
  26451. };
  26452. namespace
  26453. {
  26454. long vst_swap (const long x) throw()
  26455. {
  26456. #ifdef JUCE_LITTLE_ENDIAN
  26457. return (long) ByteOrder::swap ((uint32) x);
  26458. #else
  26459. return x;
  26460. #endif
  26461. }
  26462. float vst_swapFloat (const float x) throw()
  26463. {
  26464. #ifdef JUCE_LITTLE_ENDIAN
  26465. union { uint32 asInt; float asFloat; } n;
  26466. n.asFloat = x;
  26467. n.asInt = ByteOrder::swap (n.asInt);
  26468. return n.asFloat;
  26469. #else
  26470. return x;
  26471. #endif
  26472. }
  26473. double getVSTHostTimeNanoseconds()
  26474. {
  26475. #if JUCE_WINDOWS
  26476. return timeGetTime() * 1000000.0;
  26477. #elif JUCE_LINUX
  26478. timeval micro;
  26479. gettimeofday (&micro, 0);
  26480. return micro.tv_usec * 1000.0;
  26481. #elif JUCE_MAC
  26482. UnsignedWide micro;
  26483. Microseconds (&micro);
  26484. return micro.lo * 1000.0;
  26485. #endif
  26486. }
  26487. }
  26488. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26489. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26490. static int shellUIDToCreate = 0;
  26491. static int insideVSTCallback = 0;
  26492. class VSTPluginWindow;
  26493. // Change this to disable logging of various VST activities
  26494. #ifndef VST_LOGGING
  26495. #define VST_LOGGING 1
  26496. #endif
  26497. #if VST_LOGGING
  26498. #define log(a) Logger::writeToLog(a);
  26499. #else
  26500. #define log(a)
  26501. #endif
  26502. #if JUCE_MAC && JUCE_PPC
  26503. static void* NewCFMFromMachO (void* const machofp) throw()
  26504. {
  26505. void* result = (void*) new char[8];
  26506. ((void**) result)[0] = machofp;
  26507. ((void**) result)[1] = result;
  26508. return result;
  26509. }
  26510. #endif
  26511. #if JUCE_LINUX
  26512. extern Display* display;
  26513. extern XContext windowHandleXContext;
  26514. typedef void (*EventProcPtr) (XEvent* ev);
  26515. static bool xErrorTriggered;
  26516. namespace
  26517. {
  26518. int temporaryErrorHandler (Display*, XErrorEvent*)
  26519. {
  26520. xErrorTriggered = true;
  26521. return 0;
  26522. }
  26523. int getPropertyFromXWindow (Window handle, Atom atom)
  26524. {
  26525. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26526. xErrorTriggered = false;
  26527. int userSize;
  26528. unsigned long bytes, userCount;
  26529. unsigned char* data;
  26530. Atom userType;
  26531. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26532. &userType, &userSize, &userCount, &bytes, &data);
  26533. XSetErrorHandler (oldErrorHandler);
  26534. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26535. : 0;
  26536. }
  26537. Window getChildWindow (Window windowToCheck)
  26538. {
  26539. Window rootWindow, parentWindow;
  26540. Window* childWindows;
  26541. unsigned int numChildren;
  26542. XQueryTree (display,
  26543. windowToCheck,
  26544. &rootWindow,
  26545. &parentWindow,
  26546. &childWindows,
  26547. &numChildren);
  26548. if (numChildren > 0)
  26549. return childWindows [0];
  26550. return 0;
  26551. }
  26552. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26553. {
  26554. if (e.mods.isLeftButtonDown())
  26555. {
  26556. ev.xbutton.button = Button1;
  26557. ev.xbutton.state |= Button1Mask;
  26558. }
  26559. else if (e.mods.isRightButtonDown())
  26560. {
  26561. ev.xbutton.button = Button3;
  26562. ev.xbutton.state |= Button3Mask;
  26563. }
  26564. else if (e.mods.isMiddleButtonDown())
  26565. {
  26566. ev.xbutton.button = Button2;
  26567. ev.xbutton.state |= Button2Mask;
  26568. }
  26569. }
  26570. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26571. {
  26572. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26573. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26574. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26575. }
  26576. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26577. {
  26578. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26579. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26580. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26581. }
  26582. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26583. {
  26584. if (increment < 0)
  26585. {
  26586. ev.xbutton.button = Button5;
  26587. ev.xbutton.state |= Button5Mask;
  26588. }
  26589. else if (increment > 0)
  26590. {
  26591. ev.xbutton.button = Button4;
  26592. ev.xbutton.state |= Button4Mask;
  26593. }
  26594. }
  26595. }
  26596. #endif
  26597. class ModuleHandle : public ReferenceCountedObject
  26598. {
  26599. public:
  26600. File file;
  26601. MainCall moduleMain;
  26602. String pluginName;
  26603. static Array <ModuleHandle*>& getActiveModules()
  26604. {
  26605. static Array <ModuleHandle*> activeModules;
  26606. return activeModules;
  26607. }
  26608. static ModuleHandle* findOrCreateModule (const File& file)
  26609. {
  26610. for (int i = getActiveModules().size(); --i >= 0;)
  26611. {
  26612. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26613. if (module->file == file)
  26614. return module;
  26615. }
  26616. _fpreset(); // (doesn't do any harm)
  26617. ++insideVSTCallback;
  26618. shellUIDToCreate = 0;
  26619. log ("Attempting to load VST: " + file.getFullPathName());
  26620. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26621. if (! m->open())
  26622. m = 0;
  26623. --insideVSTCallback;
  26624. _fpreset(); // (doesn't do any harm)
  26625. return m.release();
  26626. }
  26627. ModuleHandle (const File& file_)
  26628. : file (file_),
  26629. moduleMain (0),
  26630. #if JUCE_WINDOWS || JUCE_LINUX
  26631. hModule (0)
  26632. #elif JUCE_MAC
  26633. fragId (0),
  26634. resHandle (0),
  26635. bundleRef (0),
  26636. resFileId (0)
  26637. #endif
  26638. {
  26639. getActiveModules().add (this);
  26640. #if JUCE_WINDOWS || JUCE_LINUX
  26641. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26642. #elif JUCE_MAC
  26643. FSRef ref;
  26644. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26645. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26646. #endif
  26647. }
  26648. ~ModuleHandle()
  26649. {
  26650. getActiveModules().removeValue (this);
  26651. close();
  26652. }
  26653. #if JUCE_WINDOWS || JUCE_LINUX
  26654. void* hModule;
  26655. String fullParentDirectoryPathName;
  26656. bool open()
  26657. {
  26658. #if JUCE_WINDOWS
  26659. static bool timePeriodSet = false;
  26660. if (! timePeriodSet)
  26661. {
  26662. timePeriodSet = true;
  26663. timeBeginPeriod (2);
  26664. }
  26665. #endif
  26666. pluginName = file.getFileNameWithoutExtension();
  26667. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26668. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26669. if (moduleMain == 0)
  26670. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26671. return moduleMain != 0;
  26672. }
  26673. void close()
  26674. {
  26675. _fpreset(); // (doesn't do any harm)
  26676. PlatformUtilities::freeDynamicLibrary (hModule);
  26677. }
  26678. void closeEffect (AEffect* eff)
  26679. {
  26680. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26681. }
  26682. #else
  26683. CFragConnectionID fragId;
  26684. Handle resHandle;
  26685. CFBundleRef bundleRef;
  26686. FSSpec parentDirFSSpec;
  26687. short resFileId;
  26688. bool open()
  26689. {
  26690. bool ok = false;
  26691. const String filename (file.getFullPathName());
  26692. if (file.hasFileExtension (".vst"))
  26693. {
  26694. const char* const utf8 = filename.toUTF8();
  26695. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26696. strlen (utf8), file.isDirectory());
  26697. if (url != 0)
  26698. {
  26699. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26700. CFRelease (url);
  26701. if (bundleRef != 0)
  26702. {
  26703. if (CFBundleLoadExecutable (bundleRef))
  26704. {
  26705. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26706. if (moduleMain == 0)
  26707. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26708. if (moduleMain != 0)
  26709. {
  26710. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26711. if (name != 0)
  26712. {
  26713. if (CFGetTypeID (name) == CFStringGetTypeID())
  26714. {
  26715. char buffer[1024];
  26716. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26717. pluginName = buffer;
  26718. }
  26719. }
  26720. if (pluginName.isEmpty())
  26721. pluginName = file.getFileNameWithoutExtension();
  26722. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26723. ok = true;
  26724. }
  26725. }
  26726. if (! ok)
  26727. {
  26728. CFBundleUnloadExecutable (bundleRef);
  26729. CFRelease (bundleRef);
  26730. bundleRef = 0;
  26731. }
  26732. }
  26733. }
  26734. }
  26735. #if JUCE_PPC
  26736. else
  26737. {
  26738. FSRef fn;
  26739. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26740. {
  26741. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26742. if (resFileId != -1)
  26743. {
  26744. const int numEffs = Count1Resources ('aEff');
  26745. for (int i = 0; i < numEffs; ++i)
  26746. {
  26747. resHandle = Get1IndResource ('aEff', i + 1);
  26748. if (resHandle != 0)
  26749. {
  26750. OSType type;
  26751. Str255 name;
  26752. SInt16 id;
  26753. GetResInfo (resHandle, &id, &type, name);
  26754. pluginName = String ((const char*) name + 1, name[0]);
  26755. DetachResource (resHandle);
  26756. HLock (resHandle);
  26757. Ptr ptr;
  26758. Str255 errorText;
  26759. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26760. name, kPrivateCFragCopy,
  26761. &fragId, &ptr, errorText);
  26762. if (err == noErr)
  26763. {
  26764. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26765. ok = true;
  26766. }
  26767. else
  26768. {
  26769. HUnlock (resHandle);
  26770. }
  26771. break;
  26772. }
  26773. }
  26774. if (! ok)
  26775. CloseResFile (resFileId);
  26776. }
  26777. }
  26778. }
  26779. #endif
  26780. return ok;
  26781. }
  26782. void close()
  26783. {
  26784. #if JUCE_PPC
  26785. if (fragId != 0)
  26786. {
  26787. if (moduleMain != 0)
  26788. disposeMachOFromCFM ((void*) moduleMain);
  26789. CloseConnection (&fragId);
  26790. HUnlock (resHandle);
  26791. if (resFileId != 0)
  26792. CloseResFile (resFileId);
  26793. }
  26794. else
  26795. #endif
  26796. if (bundleRef != 0)
  26797. {
  26798. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26799. if (CFGetRetainCount (bundleRef) == 1)
  26800. CFBundleUnloadExecutable (bundleRef);
  26801. if (CFGetRetainCount (bundleRef) > 0)
  26802. CFRelease (bundleRef);
  26803. }
  26804. }
  26805. void closeEffect (AEffect* eff)
  26806. {
  26807. #if JUCE_PPC
  26808. if (fragId != 0)
  26809. {
  26810. Array<void*> thingsToDelete;
  26811. thingsToDelete.add ((void*) eff->dispatcher);
  26812. thingsToDelete.add ((void*) eff->process);
  26813. thingsToDelete.add ((void*) eff->setParameter);
  26814. thingsToDelete.add ((void*) eff->getParameter);
  26815. thingsToDelete.add ((void*) eff->processReplacing);
  26816. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26817. for (int i = thingsToDelete.size(); --i >= 0;)
  26818. disposeMachOFromCFM (thingsToDelete[i]);
  26819. }
  26820. else
  26821. #endif
  26822. {
  26823. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26824. }
  26825. }
  26826. #if JUCE_PPC
  26827. static void* newMachOFromCFM (void* cfmfp)
  26828. {
  26829. if (cfmfp == 0)
  26830. return 0;
  26831. UInt32* const mfp = new UInt32[6];
  26832. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26833. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26834. mfp[2] = 0x800c0000;
  26835. mfp[3] = 0x804c0004;
  26836. mfp[4] = 0x7c0903a6;
  26837. mfp[5] = 0x4e800420;
  26838. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26839. return mfp;
  26840. }
  26841. static void disposeMachOFromCFM (void* ptr)
  26842. {
  26843. delete[] static_cast <UInt32*> (ptr);
  26844. }
  26845. void coerceAEffectFunctionCalls (AEffect* eff)
  26846. {
  26847. if (fragId != 0)
  26848. {
  26849. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26850. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26851. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26852. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26853. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26854. }
  26855. }
  26856. #endif
  26857. #endif
  26858. private:
  26859. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26860. };
  26861. /**
  26862. An instance of a plugin, created by a VSTPluginFormat.
  26863. */
  26864. class VSTPluginInstance : public AudioPluginInstance,
  26865. private Timer,
  26866. private AsyncUpdater
  26867. {
  26868. public:
  26869. ~VSTPluginInstance();
  26870. // AudioPluginInstance methods:
  26871. void fillInPluginDescription (PluginDescription& desc) const
  26872. {
  26873. desc.name = name;
  26874. {
  26875. char buffer [512];
  26876. zerostruct (buffer);
  26877. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26878. desc.descriptiveName = String (buffer).trim();
  26879. if (desc.descriptiveName.isEmpty())
  26880. desc.descriptiveName = name;
  26881. }
  26882. desc.fileOrIdentifier = module->file.getFullPathName();
  26883. desc.uid = getUID();
  26884. desc.lastFileModTime = module->file.getLastModificationTime();
  26885. desc.pluginFormatName = "VST";
  26886. desc.category = getCategory();
  26887. {
  26888. char buffer [kVstMaxVendorStrLen + 8];
  26889. zerostruct (buffer);
  26890. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26891. desc.manufacturerName = buffer;
  26892. }
  26893. desc.version = getVersion();
  26894. desc.numInputChannels = getNumInputChannels();
  26895. desc.numOutputChannels = getNumOutputChannels();
  26896. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26897. }
  26898. void* getPlatformSpecificData() { return effect; }
  26899. const String getName() const { return name; }
  26900. int getUID() const;
  26901. bool acceptsMidi() const { return wantsMidiMessages; }
  26902. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26903. // AudioProcessor methods:
  26904. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26905. void releaseResources();
  26906. void processBlock (AudioSampleBuffer& buffer,
  26907. MidiBuffer& midiMessages);
  26908. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26909. AudioProcessorEditor* createEditor();
  26910. const String getInputChannelName (int index) const;
  26911. bool isInputChannelStereoPair (int index) const;
  26912. const String getOutputChannelName (int index) const;
  26913. bool isOutputChannelStereoPair (int index) const;
  26914. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26915. float getParameter (int index);
  26916. void setParameter (int index, float newValue);
  26917. const String getParameterName (int index);
  26918. const String getParameterText (int index);
  26919. bool isParameterAutomatable (int index) const;
  26920. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26921. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26922. void setCurrentProgram (int index);
  26923. const String getProgramName (int index);
  26924. void changeProgramName (int index, const String& newName);
  26925. void getStateInformation (MemoryBlock& destData);
  26926. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26927. void setStateInformation (const void* data, int sizeInBytes);
  26928. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26929. void timerCallback();
  26930. void handleAsyncUpdate();
  26931. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26932. private:
  26933. friend class VSTPluginWindow;
  26934. friend class VSTPluginFormat;
  26935. AEffect* effect;
  26936. String name;
  26937. CriticalSection lock;
  26938. bool wantsMidiMessages, initialised, isPowerOn;
  26939. mutable StringArray programNames;
  26940. AudioSampleBuffer tempBuffer;
  26941. CriticalSection midiInLock;
  26942. MidiBuffer incomingMidi;
  26943. VSTMidiEventList midiEventsToSend;
  26944. VstTimeInfo vstHostTime;
  26945. ReferenceCountedObjectPtr <ModuleHandle> module;
  26946. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26947. bool restoreProgramSettings (const fxProgram* const prog);
  26948. const String getCurrentProgramName();
  26949. void setParamsInProgramBlock (fxProgram* const prog);
  26950. void updateStoredProgramNames();
  26951. void initialise();
  26952. void handleMidiFromPlugin (const VstEvents* const events);
  26953. void createTempParameterStore (MemoryBlock& dest);
  26954. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26955. const String getParameterLabel (int index) const;
  26956. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26957. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26958. void setChunkData (const char* data, int size, bool isPreset);
  26959. bool loadFromFXBFile (const void* data, int numBytes);
  26960. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26961. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26962. const String getVersion() const;
  26963. const String getCategory() const;
  26964. void setPower (const bool on);
  26965. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26966. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26967. };
  26968. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26969. : effect (0),
  26970. wantsMidiMessages (false),
  26971. initialised (false),
  26972. isPowerOn (false),
  26973. tempBuffer (1, 1),
  26974. module (module_)
  26975. {
  26976. try
  26977. {
  26978. _fpreset();
  26979. ++insideVSTCallback;
  26980. name = module->pluginName;
  26981. log ("Creating VST instance: " + name);
  26982. #if JUCE_MAC
  26983. if (module->resFileId != 0)
  26984. UseResFile (module->resFileId);
  26985. #if JUCE_PPC
  26986. if (module->fragId != 0)
  26987. {
  26988. static void* audioMasterCoerced = 0;
  26989. if (audioMasterCoerced == 0)
  26990. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26991. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26992. }
  26993. else
  26994. #endif
  26995. #endif
  26996. {
  26997. effect = module->moduleMain (&audioMaster);
  26998. }
  26999. --insideVSTCallback;
  27000. if (effect != 0 && effect->magic == kEffectMagic)
  27001. {
  27002. #if JUCE_PPC
  27003. module->coerceAEffectFunctionCalls (effect);
  27004. #endif
  27005. jassert (effect->resvd2 == 0);
  27006. jassert (effect->object != 0);
  27007. _fpreset(); // some dodgy plugs fuck around with this
  27008. }
  27009. else
  27010. {
  27011. effect = 0;
  27012. }
  27013. }
  27014. catch (...)
  27015. {
  27016. --insideVSTCallback;
  27017. }
  27018. }
  27019. VSTPluginInstance::~VSTPluginInstance()
  27020. {
  27021. const ScopedLock sl (lock);
  27022. jassert (insideVSTCallback == 0);
  27023. if (effect != 0 && effect->magic == kEffectMagic)
  27024. {
  27025. try
  27026. {
  27027. #if JUCE_MAC
  27028. if (module->resFileId != 0)
  27029. UseResFile (module->resFileId);
  27030. #endif
  27031. // Must delete any editors before deleting the plugin instance!
  27032. jassert (getActiveEditor() == 0);
  27033. _fpreset(); // some dodgy plugs fuck around with this
  27034. module->closeEffect (effect);
  27035. }
  27036. catch (...)
  27037. {}
  27038. }
  27039. module = 0;
  27040. effect = 0;
  27041. }
  27042. void VSTPluginInstance::initialise()
  27043. {
  27044. if (initialised || effect == 0)
  27045. return;
  27046. log ("Initialising VST: " + module->pluginName);
  27047. initialised = true;
  27048. dispatch (effIdentify, 0, 0, 0, 0);
  27049. if (getSampleRate() > 0)
  27050. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27051. if (getBlockSize() > 0)
  27052. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27053. dispatch (effOpen, 0, 0, 0, 0);
  27054. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27055. getSampleRate(), getBlockSize());
  27056. if (getNumPrograms() > 1)
  27057. setCurrentProgram (0);
  27058. else
  27059. dispatch (effSetProgram, 0, 0, 0, 0);
  27060. int i;
  27061. for (i = effect->numInputs; --i >= 0;)
  27062. dispatch (effConnectInput, i, 1, 0, 0);
  27063. for (i = effect->numOutputs; --i >= 0;)
  27064. dispatch (effConnectOutput, i, 1, 0, 0);
  27065. updateStoredProgramNames();
  27066. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27067. setLatencySamples (effect->initialDelay);
  27068. }
  27069. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27070. int samplesPerBlockExpected)
  27071. {
  27072. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27073. sampleRate_, samplesPerBlockExpected);
  27074. setLatencySamples (effect->initialDelay);
  27075. vstHostTime.tempo = 120.0;
  27076. vstHostTime.timeSigNumerator = 4;
  27077. vstHostTime.timeSigDenominator = 4;
  27078. vstHostTime.sampleRate = sampleRate_;
  27079. vstHostTime.samplePos = 0;
  27080. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27081. initialise();
  27082. if (initialised)
  27083. {
  27084. wantsMidiMessages = wantsMidiMessages
  27085. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27086. if (wantsMidiMessages)
  27087. midiEventsToSend.ensureSize (256);
  27088. else
  27089. midiEventsToSend.freeEvents();
  27090. incomingMidi.clear();
  27091. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27092. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27093. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27094. if (! isPowerOn)
  27095. setPower (true);
  27096. // dodgy hack to force some plugins to initialise the sample rate..
  27097. if ((! hasEditor()) && getNumParameters() > 0)
  27098. {
  27099. const float old = getParameter (0);
  27100. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27101. setParameter (0, old);
  27102. }
  27103. dispatch (effStartProcess, 0, 0, 0, 0);
  27104. }
  27105. }
  27106. void VSTPluginInstance::releaseResources()
  27107. {
  27108. if (initialised)
  27109. {
  27110. dispatch (effStopProcess, 0, 0, 0, 0);
  27111. setPower (false);
  27112. }
  27113. tempBuffer.setSize (1, 1);
  27114. incomingMidi.clear();
  27115. midiEventsToSend.freeEvents();
  27116. }
  27117. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27118. MidiBuffer& midiMessages)
  27119. {
  27120. const int numSamples = buffer.getNumSamples();
  27121. if (initialised)
  27122. {
  27123. AudioPlayHead* playHead = getPlayHead();
  27124. if (playHead != 0)
  27125. {
  27126. AudioPlayHead::CurrentPositionInfo position;
  27127. playHead->getCurrentPosition (position);
  27128. vstHostTime.tempo = position.bpm;
  27129. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27130. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27131. vstHostTime.ppqPos = position.ppqPosition;
  27132. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27133. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27134. if (position.isPlaying)
  27135. vstHostTime.flags |= kVstTransportPlaying;
  27136. else
  27137. vstHostTime.flags &= ~kVstTransportPlaying;
  27138. }
  27139. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27140. if (wantsMidiMessages)
  27141. {
  27142. midiEventsToSend.clear();
  27143. midiEventsToSend.ensureSize (1);
  27144. MidiBuffer::Iterator iter (midiMessages);
  27145. const uint8* midiData;
  27146. int numBytesOfMidiData, samplePosition;
  27147. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27148. {
  27149. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27150. jlimit (0, numSamples - 1, samplePosition));
  27151. }
  27152. try
  27153. {
  27154. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27155. }
  27156. catch (...)
  27157. {}
  27158. }
  27159. _clearfp();
  27160. if ((effect->flags & effFlagsCanReplacing) != 0)
  27161. {
  27162. try
  27163. {
  27164. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27165. }
  27166. catch (...)
  27167. {}
  27168. }
  27169. else
  27170. {
  27171. tempBuffer.setSize (effect->numOutputs, numSamples);
  27172. tempBuffer.clear();
  27173. try
  27174. {
  27175. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27176. }
  27177. catch (...)
  27178. {}
  27179. for (int i = effect->numOutputs; --i >= 0;)
  27180. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27181. }
  27182. }
  27183. else
  27184. {
  27185. // Not initialised, so just bypass..
  27186. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27187. buffer.clear (i, 0, buffer.getNumSamples());
  27188. }
  27189. {
  27190. // copy any incoming midi..
  27191. const ScopedLock sl (midiInLock);
  27192. midiMessages.swapWith (incomingMidi);
  27193. incomingMidi.clear();
  27194. }
  27195. }
  27196. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27197. {
  27198. if (events != 0)
  27199. {
  27200. const ScopedLock sl (midiInLock);
  27201. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27202. }
  27203. }
  27204. static Array <VSTPluginWindow*> activeVSTWindows;
  27205. class VSTPluginWindow : public AudioProcessorEditor,
  27206. #if ! JUCE_MAC
  27207. public ComponentMovementWatcher,
  27208. #endif
  27209. public Timer
  27210. {
  27211. public:
  27212. VSTPluginWindow (VSTPluginInstance& plugin_)
  27213. : AudioProcessorEditor (&plugin_),
  27214. #if ! JUCE_MAC
  27215. ComponentMovementWatcher (this),
  27216. #endif
  27217. plugin (plugin_),
  27218. isOpen (false),
  27219. wasShowing (false),
  27220. recursiveResize (false),
  27221. pluginWantsKeys (false),
  27222. pluginRefusesToResize (false),
  27223. alreadyInside (false)
  27224. {
  27225. #if JUCE_WINDOWS
  27226. sizeCheckCount = 0;
  27227. pluginHWND = 0;
  27228. #elif JUCE_LINUX
  27229. pluginWindow = None;
  27230. pluginProc = None;
  27231. #else
  27232. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27233. #endif
  27234. activeVSTWindows.add (this);
  27235. setSize (1, 1);
  27236. setOpaque (true);
  27237. setVisible (true);
  27238. }
  27239. ~VSTPluginWindow()
  27240. {
  27241. #if JUCE_MAC
  27242. innerWrapper = 0;
  27243. #else
  27244. closePluginWindow();
  27245. #endif
  27246. activeVSTWindows.removeValue (this);
  27247. plugin.editorBeingDeleted (this);
  27248. }
  27249. #if ! JUCE_MAC
  27250. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27251. {
  27252. if (recursiveResize)
  27253. return;
  27254. Component* const topComp = getTopLevelComponent();
  27255. if (topComp->getPeer() != 0)
  27256. {
  27257. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27258. recursiveResize = true;
  27259. #if JUCE_WINDOWS
  27260. if (pluginHWND != 0)
  27261. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27262. #elif JUCE_LINUX
  27263. if (pluginWindow != 0)
  27264. {
  27265. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27266. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27267. XMapRaised (display, pluginWindow);
  27268. }
  27269. #endif
  27270. recursiveResize = false;
  27271. }
  27272. }
  27273. void componentVisibilityChanged (Component&)
  27274. {
  27275. const bool isShowingNow = isShowing();
  27276. if (wasShowing != isShowingNow)
  27277. {
  27278. wasShowing = isShowingNow;
  27279. if (isShowingNow)
  27280. openPluginWindow();
  27281. else
  27282. closePluginWindow();
  27283. }
  27284. componentMovedOrResized (true, true);
  27285. }
  27286. void componentPeerChanged()
  27287. {
  27288. closePluginWindow();
  27289. openPluginWindow();
  27290. }
  27291. #endif
  27292. bool keyStateChanged (bool)
  27293. {
  27294. return pluginWantsKeys;
  27295. }
  27296. bool keyPressed (const KeyPress&)
  27297. {
  27298. return pluginWantsKeys;
  27299. }
  27300. #if JUCE_MAC
  27301. void paint (Graphics& g)
  27302. {
  27303. g.fillAll (Colours::black);
  27304. }
  27305. #else
  27306. void paint (Graphics& g)
  27307. {
  27308. if (isOpen)
  27309. {
  27310. ComponentPeer* const peer = getPeer();
  27311. if (peer != 0)
  27312. {
  27313. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27314. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27315. #if JUCE_LINUX
  27316. if (pluginWindow != 0)
  27317. {
  27318. const Rectangle<int> clip (g.getClipBounds());
  27319. XEvent ev;
  27320. zerostruct (ev);
  27321. ev.xexpose.type = Expose;
  27322. ev.xexpose.display = display;
  27323. ev.xexpose.window = pluginWindow;
  27324. ev.xexpose.x = clip.getX();
  27325. ev.xexpose.y = clip.getY();
  27326. ev.xexpose.width = clip.getWidth();
  27327. ev.xexpose.height = clip.getHeight();
  27328. sendEventToChild (&ev);
  27329. }
  27330. #endif
  27331. }
  27332. }
  27333. else
  27334. {
  27335. g.fillAll (Colours::black);
  27336. }
  27337. }
  27338. #endif
  27339. void timerCallback()
  27340. {
  27341. #if JUCE_WINDOWS
  27342. if (--sizeCheckCount <= 0)
  27343. {
  27344. sizeCheckCount = 10;
  27345. checkPluginWindowSize();
  27346. }
  27347. #endif
  27348. try
  27349. {
  27350. static bool reentrant = false;
  27351. if (! reentrant)
  27352. {
  27353. reentrant = true;
  27354. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27355. reentrant = false;
  27356. }
  27357. }
  27358. catch (...)
  27359. {}
  27360. }
  27361. void mouseDown (const MouseEvent& e)
  27362. {
  27363. #if JUCE_LINUX
  27364. if (pluginWindow == 0)
  27365. return;
  27366. toFront (true);
  27367. XEvent ev;
  27368. zerostruct (ev);
  27369. ev.xbutton.display = display;
  27370. ev.xbutton.type = ButtonPress;
  27371. ev.xbutton.window = pluginWindow;
  27372. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27373. ev.xbutton.time = CurrentTime;
  27374. ev.xbutton.x = e.x;
  27375. ev.xbutton.y = e.y;
  27376. ev.xbutton.x_root = e.getScreenX();
  27377. ev.xbutton.y_root = e.getScreenY();
  27378. translateJuceToXButtonModifiers (e, ev);
  27379. sendEventToChild (&ev);
  27380. #elif JUCE_WINDOWS
  27381. (void) e;
  27382. toFront (true);
  27383. #endif
  27384. }
  27385. void broughtToFront()
  27386. {
  27387. activeVSTWindows.removeValue (this);
  27388. activeVSTWindows.add (this);
  27389. #if JUCE_MAC
  27390. dispatch (effEditTop, 0, 0, 0, 0);
  27391. #endif
  27392. }
  27393. private:
  27394. VSTPluginInstance& plugin;
  27395. bool isOpen, wasShowing, recursiveResize;
  27396. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27397. #if JUCE_WINDOWS
  27398. HWND pluginHWND;
  27399. void* originalWndProc;
  27400. int sizeCheckCount;
  27401. #elif JUCE_LINUX
  27402. Window pluginWindow;
  27403. EventProcPtr pluginProc;
  27404. #endif
  27405. #if JUCE_MAC
  27406. void openPluginWindow (WindowRef parentWindow)
  27407. {
  27408. if (isOpen || parentWindow == 0)
  27409. return;
  27410. isOpen = true;
  27411. ERect* rect = 0;
  27412. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27413. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27414. // do this before and after like in the steinberg example
  27415. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27416. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27417. // Install keyboard hooks
  27418. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27419. // double-check it's not too tiny
  27420. int w = 250, h = 150;
  27421. if (rect != 0)
  27422. {
  27423. w = rect->right - rect->left;
  27424. h = rect->bottom - rect->top;
  27425. if (w == 0 || h == 0)
  27426. {
  27427. w = 250;
  27428. h = 150;
  27429. }
  27430. }
  27431. w = jmax (w, 32);
  27432. h = jmax (h, 32);
  27433. setSize (w, h);
  27434. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27435. repaint();
  27436. }
  27437. #else
  27438. void openPluginWindow()
  27439. {
  27440. if (isOpen || getWindowHandle() == 0)
  27441. return;
  27442. log ("Opening VST UI: " + plugin.name);
  27443. isOpen = true;
  27444. ERect* rect = 0;
  27445. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27446. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27447. // do this before and after like in the steinberg example
  27448. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27449. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27450. // Install keyboard hooks
  27451. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27452. #if JUCE_WINDOWS
  27453. originalWndProc = 0;
  27454. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27455. if (pluginHWND == 0)
  27456. {
  27457. isOpen = false;
  27458. setSize (300, 150);
  27459. return;
  27460. }
  27461. #pragma warning (push)
  27462. #pragma warning (disable: 4244)
  27463. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27464. if (! pluginWantsKeys)
  27465. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27466. #pragma warning (pop)
  27467. int w, h;
  27468. RECT r;
  27469. GetWindowRect (pluginHWND, &r);
  27470. w = r.right - r.left;
  27471. h = r.bottom - r.top;
  27472. if (rect != 0)
  27473. {
  27474. const int rw = rect->right - rect->left;
  27475. const int rh = rect->bottom - rect->top;
  27476. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27477. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27478. {
  27479. // very dodgy logic to decide which size is right.
  27480. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27481. {
  27482. SetWindowPos (pluginHWND, 0,
  27483. 0, 0, rw, rh,
  27484. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27485. GetWindowRect (pluginHWND, &r);
  27486. w = r.right - r.left;
  27487. h = r.bottom - r.top;
  27488. pluginRefusesToResize = (w != rw) || (h != rh);
  27489. w = rw;
  27490. h = rh;
  27491. }
  27492. }
  27493. }
  27494. #elif JUCE_LINUX
  27495. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27496. if (pluginWindow != 0)
  27497. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27498. XInternAtom (display, "_XEventProc", False));
  27499. int w = 250, h = 150;
  27500. if (rect != 0)
  27501. {
  27502. w = rect->right - rect->left;
  27503. h = rect->bottom - rect->top;
  27504. if (w == 0 || h == 0)
  27505. {
  27506. w = 250;
  27507. h = 150;
  27508. }
  27509. }
  27510. if (pluginWindow != 0)
  27511. XMapRaised (display, pluginWindow);
  27512. #endif
  27513. // double-check it's not too tiny
  27514. w = jmax (w, 32);
  27515. h = jmax (h, 32);
  27516. setSize (w, h);
  27517. #if JUCE_WINDOWS
  27518. checkPluginWindowSize();
  27519. #endif
  27520. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27521. repaint();
  27522. }
  27523. #endif
  27524. #if ! JUCE_MAC
  27525. void closePluginWindow()
  27526. {
  27527. if (isOpen)
  27528. {
  27529. log ("Closing VST UI: " + plugin.getName());
  27530. isOpen = false;
  27531. dispatch (effEditClose, 0, 0, 0, 0);
  27532. #if JUCE_WINDOWS
  27533. #pragma warning (push)
  27534. #pragma warning (disable: 4244)
  27535. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27536. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27537. #pragma warning (pop)
  27538. stopTimer();
  27539. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27540. DestroyWindow (pluginHWND);
  27541. pluginHWND = 0;
  27542. #elif JUCE_LINUX
  27543. stopTimer();
  27544. pluginWindow = 0;
  27545. pluginProc = 0;
  27546. #endif
  27547. }
  27548. }
  27549. #endif
  27550. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27551. {
  27552. return plugin.dispatch (opcode, index, value, ptr, opt);
  27553. }
  27554. #if JUCE_WINDOWS
  27555. void checkPluginWindowSize()
  27556. {
  27557. RECT r;
  27558. GetWindowRect (pluginHWND, &r);
  27559. const int w = r.right - r.left;
  27560. const int h = r.bottom - r.top;
  27561. if (isShowing() && w > 0 && h > 0
  27562. && (w != getWidth() || h != getHeight())
  27563. && ! pluginRefusesToResize)
  27564. {
  27565. setSize (w, h);
  27566. sizeCheckCount = 0;
  27567. }
  27568. }
  27569. // hooks to get keyboard events from VST windows..
  27570. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27571. {
  27572. for (int i = activeVSTWindows.size(); --i >= 0;)
  27573. {
  27574. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27575. if (w->pluginHWND == hW)
  27576. {
  27577. if (message == WM_CHAR
  27578. || message == WM_KEYDOWN
  27579. || message == WM_SYSKEYDOWN
  27580. || message == WM_KEYUP
  27581. || message == WM_SYSKEYUP
  27582. || message == WM_APPCOMMAND)
  27583. {
  27584. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27585. message, wParam, lParam);
  27586. }
  27587. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27588. (HWND) w->pluginHWND,
  27589. message,
  27590. wParam,
  27591. lParam);
  27592. }
  27593. }
  27594. return DefWindowProc (hW, message, wParam, lParam);
  27595. }
  27596. #endif
  27597. #if JUCE_LINUX
  27598. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27599. void sendEventToChild (XEvent* event)
  27600. {
  27601. if (pluginProc != 0)
  27602. {
  27603. // if the plugin publishes an event procedure, pass the event directly..
  27604. pluginProc (event);
  27605. }
  27606. else if (pluginWindow != 0)
  27607. {
  27608. // if the plugin has a window, then send the event to the window so that
  27609. // its message thread will pick it up..
  27610. XSendEvent (display, pluginWindow, False, 0L, event);
  27611. XFlush (display);
  27612. }
  27613. }
  27614. void mouseEnter (const MouseEvent& e)
  27615. {
  27616. if (pluginWindow != 0)
  27617. {
  27618. XEvent ev;
  27619. zerostruct (ev);
  27620. ev.xcrossing.display = display;
  27621. ev.xcrossing.type = EnterNotify;
  27622. ev.xcrossing.window = pluginWindow;
  27623. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27624. ev.xcrossing.time = CurrentTime;
  27625. ev.xcrossing.x = e.x;
  27626. ev.xcrossing.y = e.y;
  27627. ev.xcrossing.x_root = e.getScreenX();
  27628. ev.xcrossing.y_root = e.getScreenY();
  27629. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27630. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27631. translateJuceToXCrossingModifiers (e, ev);
  27632. sendEventToChild (&ev);
  27633. }
  27634. }
  27635. void mouseExit (const MouseEvent& e)
  27636. {
  27637. if (pluginWindow != 0)
  27638. {
  27639. XEvent ev;
  27640. zerostruct (ev);
  27641. ev.xcrossing.display = display;
  27642. ev.xcrossing.type = LeaveNotify;
  27643. ev.xcrossing.window = pluginWindow;
  27644. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27645. ev.xcrossing.time = CurrentTime;
  27646. ev.xcrossing.x = e.x;
  27647. ev.xcrossing.y = e.y;
  27648. ev.xcrossing.x_root = e.getScreenX();
  27649. ev.xcrossing.y_root = e.getScreenY();
  27650. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27651. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27652. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27653. translateJuceToXCrossingModifiers (e, ev);
  27654. sendEventToChild (&ev);
  27655. }
  27656. }
  27657. void mouseMove (const MouseEvent& e)
  27658. {
  27659. if (pluginWindow != 0)
  27660. {
  27661. XEvent ev;
  27662. zerostruct (ev);
  27663. ev.xmotion.display = display;
  27664. ev.xmotion.type = MotionNotify;
  27665. ev.xmotion.window = pluginWindow;
  27666. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27667. ev.xmotion.time = CurrentTime;
  27668. ev.xmotion.is_hint = NotifyNormal;
  27669. ev.xmotion.x = e.x;
  27670. ev.xmotion.y = e.y;
  27671. ev.xmotion.x_root = e.getScreenX();
  27672. ev.xmotion.y_root = e.getScreenY();
  27673. sendEventToChild (&ev);
  27674. }
  27675. }
  27676. void mouseDrag (const MouseEvent& e)
  27677. {
  27678. if (pluginWindow != 0)
  27679. {
  27680. XEvent ev;
  27681. zerostruct (ev);
  27682. ev.xmotion.display = display;
  27683. ev.xmotion.type = MotionNotify;
  27684. ev.xmotion.window = pluginWindow;
  27685. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27686. ev.xmotion.time = CurrentTime;
  27687. ev.xmotion.x = e.x ;
  27688. ev.xmotion.y = e.y;
  27689. ev.xmotion.x_root = e.getScreenX();
  27690. ev.xmotion.y_root = e.getScreenY();
  27691. ev.xmotion.is_hint = NotifyNormal;
  27692. translateJuceToXMotionModifiers (e, ev);
  27693. sendEventToChild (&ev);
  27694. }
  27695. }
  27696. void mouseUp (const MouseEvent& e)
  27697. {
  27698. if (pluginWindow != 0)
  27699. {
  27700. XEvent ev;
  27701. zerostruct (ev);
  27702. ev.xbutton.display = display;
  27703. ev.xbutton.type = ButtonRelease;
  27704. ev.xbutton.window = pluginWindow;
  27705. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27706. ev.xbutton.time = CurrentTime;
  27707. ev.xbutton.x = e.x;
  27708. ev.xbutton.y = e.y;
  27709. ev.xbutton.x_root = e.getScreenX();
  27710. ev.xbutton.y_root = e.getScreenY();
  27711. translateJuceToXButtonModifiers (e, ev);
  27712. sendEventToChild (&ev);
  27713. }
  27714. }
  27715. void mouseWheelMove (const MouseEvent& e,
  27716. float incrementX,
  27717. float incrementY)
  27718. {
  27719. if (pluginWindow != 0)
  27720. {
  27721. XEvent ev;
  27722. zerostruct (ev);
  27723. ev.xbutton.display = display;
  27724. ev.xbutton.type = ButtonPress;
  27725. ev.xbutton.window = pluginWindow;
  27726. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27727. ev.xbutton.time = CurrentTime;
  27728. ev.xbutton.x = e.x;
  27729. ev.xbutton.y = e.y;
  27730. ev.xbutton.x_root = e.getScreenX();
  27731. ev.xbutton.y_root = e.getScreenY();
  27732. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27733. sendEventToChild (&ev);
  27734. // TODO - put a usleep here ?
  27735. ev.xbutton.type = ButtonRelease;
  27736. sendEventToChild (&ev);
  27737. }
  27738. }
  27739. #endif
  27740. #if JUCE_MAC
  27741. #if ! JUCE_SUPPORT_CARBON
  27742. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27743. #endif
  27744. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27745. {
  27746. public:
  27747. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27748. : owner (owner_),
  27749. alreadyInside (false)
  27750. {
  27751. }
  27752. ~InnerWrapperComponent()
  27753. {
  27754. deleteWindow();
  27755. }
  27756. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27757. {
  27758. owner->openPluginWindow (windowRef);
  27759. return 0;
  27760. }
  27761. void removeView (HIViewRef)
  27762. {
  27763. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27764. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27765. }
  27766. bool getEmbeddedViewSize (int& w, int& h)
  27767. {
  27768. ERect* rect = 0;
  27769. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27770. w = rect->right - rect->left;
  27771. h = rect->bottom - rect->top;
  27772. return true;
  27773. }
  27774. void mouseDown (int x, int y)
  27775. {
  27776. if (! alreadyInside)
  27777. {
  27778. alreadyInside = true;
  27779. getTopLevelComponent()->toFront (true);
  27780. owner->dispatch (effEditMouse, x, y, 0, 0);
  27781. alreadyInside = false;
  27782. }
  27783. else
  27784. {
  27785. PostEvent (::mouseDown, 0);
  27786. }
  27787. }
  27788. void paint()
  27789. {
  27790. ComponentPeer* const peer = getPeer();
  27791. if (peer != 0)
  27792. {
  27793. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27794. ERect r;
  27795. r.left = pos.getX();
  27796. r.right = r.left + getWidth();
  27797. r.top = pos.getY();
  27798. r.bottom = r.top + getHeight();
  27799. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27800. }
  27801. }
  27802. private:
  27803. VSTPluginWindow* const owner;
  27804. bool alreadyInside;
  27805. };
  27806. friend class InnerWrapperComponent;
  27807. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27808. void resized()
  27809. {
  27810. innerWrapper->setSize (getWidth(), getHeight());
  27811. }
  27812. #endif
  27813. private:
  27814. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27815. };
  27816. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27817. {
  27818. if (hasEditor())
  27819. return new VSTPluginWindow (*this);
  27820. return 0;
  27821. }
  27822. void VSTPluginInstance::handleAsyncUpdate()
  27823. {
  27824. // indicates that something about the plugin has changed..
  27825. updateHostDisplay();
  27826. }
  27827. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27828. {
  27829. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27830. {
  27831. changeProgramName (getCurrentProgram(), prog->prgName);
  27832. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27833. setParameter (i, vst_swapFloat (prog->params[i]));
  27834. return true;
  27835. }
  27836. return false;
  27837. }
  27838. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27839. const int dataSize)
  27840. {
  27841. if (dataSize < 28)
  27842. return false;
  27843. const fxSet* const set = (const fxSet*) data;
  27844. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27845. || vst_swap (set->version) > fxbVersionNum)
  27846. return false;
  27847. if (vst_swap (set->fxMagic) == 'FxBk')
  27848. {
  27849. // bank of programs
  27850. if (vst_swap (set->numPrograms) >= 0)
  27851. {
  27852. const int oldProg = getCurrentProgram();
  27853. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27854. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27855. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27856. {
  27857. if (i != oldProg)
  27858. {
  27859. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27860. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27861. return false;
  27862. if (vst_swap (set->numPrograms) > 0)
  27863. setCurrentProgram (i);
  27864. if (! restoreProgramSettings (prog))
  27865. return false;
  27866. }
  27867. }
  27868. if (vst_swap (set->numPrograms) > 0)
  27869. setCurrentProgram (oldProg);
  27870. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27871. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27872. return false;
  27873. if (! restoreProgramSettings (prog))
  27874. return false;
  27875. }
  27876. }
  27877. else if (vst_swap (set->fxMagic) == 'FxCk')
  27878. {
  27879. // single program
  27880. const fxProgram* const prog = (const fxProgram*) data;
  27881. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27882. return false;
  27883. changeProgramName (getCurrentProgram(), prog->prgName);
  27884. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27885. setParameter (i, vst_swapFloat (prog->params[i]));
  27886. }
  27887. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27888. {
  27889. // non-preset chunk
  27890. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27891. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27892. return false;
  27893. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27894. }
  27895. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27896. {
  27897. // preset chunk
  27898. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27899. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27900. return false;
  27901. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27902. changeProgramName (getCurrentProgram(), cset->name);
  27903. }
  27904. else
  27905. {
  27906. return false;
  27907. }
  27908. return true;
  27909. }
  27910. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27911. {
  27912. const int numParams = getNumParameters();
  27913. prog->chunkMagic = vst_swap ('CcnK');
  27914. prog->byteSize = 0;
  27915. prog->fxMagic = vst_swap ('FxCk');
  27916. prog->version = vst_swap (fxbVersionNum);
  27917. prog->fxID = vst_swap (getUID());
  27918. prog->fxVersion = vst_swap (getVersionNumber());
  27919. prog->numParams = vst_swap (numParams);
  27920. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27921. for (int i = 0; i < numParams; ++i)
  27922. prog->params[i] = vst_swapFloat (getParameter (i));
  27923. }
  27924. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27925. {
  27926. const int numPrograms = getNumPrograms();
  27927. const int numParams = getNumParameters();
  27928. if (usesChunks())
  27929. {
  27930. if (isFXB)
  27931. {
  27932. MemoryBlock chunk;
  27933. getChunkData (chunk, false, maxSizeMB);
  27934. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27935. dest.setSize (totalLen, true);
  27936. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27937. set->chunkMagic = vst_swap ('CcnK');
  27938. set->byteSize = 0;
  27939. set->fxMagic = vst_swap ('FBCh');
  27940. set->version = vst_swap (fxbVersionNum);
  27941. set->fxID = vst_swap (getUID());
  27942. set->fxVersion = vst_swap (getVersionNumber());
  27943. set->numPrograms = vst_swap (numPrograms);
  27944. set->chunkSize = vst_swap ((long) chunk.getSize());
  27945. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27946. }
  27947. else
  27948. {
  27949. MemoryBlock chunk;
  27950. getChunkData (chunk, true, maxSizeMB);
  27951. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27952. dest.setSize (totalLen, true);
  27953. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27954. set->chunkMagic = vst_swap ('CcnK');
  27955. set->byteSize = 0;
  27956. set->fxMagic = vst_swap ('FPCh');
  27957. set->version = vst_swap (fxbVersionNum);
  27958. set->fxID = vst_swap (getUID());
  27959. set->fxVersion = vst_swap (getVersionNumber());
  27960. set->numPrograms = vst_swap (numPrograms);
  27961. set->chunkSize = vst_swap ((long) chunk.getSize());
  27962. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27963. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27964. }
  27965. }
  27966. else
  27967. {
  27968. if (isFXB)
  27969. {
  27970. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27971. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27972. dest.setSize (len, true);
  27973. fxSet* const set = (fxSet*) dest.getData();
  27974. set->chunkMagic = vst_swap ('CcnK');
  27975. set->byteSize = 0;
  27976. set->fxMagic = vst_swap ('FxBk');
  27977. set->version = vst_swap (fxbVersionNum);
  27978. set->fxID = vst_swap (getUID());
  27979. set->fxVersion = vst_swap (getVersionNumber());
  27980. set->numPrograms = vst_swap (numPrograms);
  27981. const int oldProgram = getCurrentProgram();
  27982. MemoryBlock oldSettings;
  27983. createTempParameterStore (oldSettings);
  27984. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27985. for (int i = 0; i < numPrograms; ++i)
  27986. {
  27987. if (i != oldProgram)
  27988. {
  27989. setCurrentProgram (i);
  27990. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27991. }
  27992. }
  27993. setCurrentProgram (oldProgram);
  27994. restoreFromTempParameterStore (oldSettings);
  27995. }
  27996. else
  27997. {
  27998. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27999. dest.setSize (totalLen, true);
  28000. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28001. }
  28002. }
  28003. return true;
  28004. }
  28005. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28006. {
  28007. if (usesChunks())
  28008. {
  28009. void* data = 0;
  28010. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28011. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28012. {
  28013. mb.setSize (bytes);
  28014. mb.copyFrom (data, 0, bytes);
  28015. }
  28016. }
  28017. }
  28018. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28019. {
  28020. if (size > 0 && usesChunks())
  28021. {
  28022. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28023. if (! isPreset)
  28024. updateStoredProgramNames();
  28025. }
  28026. }
  28027. void VSTPluginInstance::timerCallback()
  28028. {
  28029. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28030. stopTimer();
  28031. }
  28032. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28033. {
  28034. const ScopedLock sl (lock);
  28035. ++insideVSTCallback;
  28036. int result = 0;
  28037. try
  28038. {
  28039. if (effect != 0)
  28040. {
  28041. #if JUCE_MAC
  28042. if (module->resFileId != 0)
  28043. UseResFile (module->resFileId);
  28044. #endif
  28045. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28046. #if JUCE_MAC
  28047. module->resFileId = CurResFile();
  28048. #endif
  28049. --insideVSTCallback;
  28050. return result;
  28051. }
  28052. }
  28053. catch (...)
  28054. {
  28055. }
  28056. --insideVSTCallback;
  28057. return result;
  28058. }
  28059. namespace
  28060. {
  28061. static const int defaultVSTSampleRateValue = 16384;
  28062. static const int defaultVSTBlockSizeValue = 512;
  28063. // handles non plugin-specific callbacks..
  28064. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28065. {
  28066. (void) index;
  28067. (void) value;
  28068. (void) opt;
  28069. switch (opcode)
  28070. {
  28071. case audioMasterCanDo:
  28072. {
  28073. static const char* canDos[] = { "supplyIdle",
  28074. "sendVstEvents",
  28075. "sendVstMidiEvent",
  28076. "sendVstTimeInfo",
  28077. "receiveVstEvents",
  28078. "receiveVstMidiEvent",
  28079. "supportShell",
  28080. "shellCategory" };
  28081. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28082. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28083. return 1;
  28084. return 0;
  28085. }
  28086. case audioMasterVersion: return 0x2400;
  28087. case audioMasterCurrentId: return shellUIDToCreate;
  28088. case audioMasterGetNumAutomatableParameters: return 0;
  28089. case audioMasterGetAutomationState: return 1;
  28090. case audioMasterGetVendorVersion: return 0x0101;
  28091. case audioMasterGetVendorString:
  28092. case audioMasterGetProductString:
  28093. {
  28094. String hostName ("Juce VST Host");
  28095. if (JUCEApplication::getInstance() != 0)
  28096. hostName = JUCEApplication::getInstance()->getApplicationName();
  28097. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28098. break;
  28099. }
  28100. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28101. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28102. case audioMasterSetOutputSampleRate: return 0;
  28103. default:
  28104. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28105. break;
  28106. }
  28107. return 0;
  28108. }
  28109. }
  28110. // handles callbacks for a specific plugin
  28111. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28112. {
  28113. switch (opcode)
  28114. {
  28115. case audioMasterAutomate:
  28116. sendParamChangeMessageToListeners (index, opt);
  28117. break;
  28118. case audioMasterProcessEvents:
  28119. handleMidiFromPlugin ((const VstEvents*) ptr);
  28120. break;
  28121. case audioMasterGetTime:
  28122. #if JUCE_MSVC
  28123. #pragma warning (push)
  28124. #pragma warning (disable: 4311)
  28125. #endif
  28126. return (VstIntPtr) &vstHostTime;
  28127. #if JUCE_MSVC
  28128. #pragma warning (pop)
  28129. #endif
  28130. break;
  28131. case audioMasterIdle:
  28132. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28133. {
  28134. ++insideVSTCallback;
  28135. #if JUCE_MAC
  28136. if (getActiveEditor() != 0)
  28137. dispatch (effEditIdle, 0, 0, 0, 0);
  28138. #endif
  28139. juce_callAnyTimersSynchronously();
  28140. handleUpdateNowIfNeeded();
  28141. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28142. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28143. --insideVSTCallback;
  28144. }
  28145. break;
  28146. case audioMasterUpdateDisplay:
  28147. triggerAsyncUpdate();
  28148. break;
  28149. case audioMasterTempoAt:
  28150. // returns (10000 * bpm)
  28151. break;
  28152. case audioMasterNeedIdle:
  28153. startTimer (50);
  28154. break;
  28155. case audioMasterSizeWindow:
  28156. if (getActiveEditor() != 0)
  28157. getActiveEditor()->setSize (index, value);
  28158. return 1;
  28159. case audioMasterGetSampleRate:
  28160. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28161. case audioMasterGetBlockSize:
  28162. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28163. case audioMasterWantMidi:
  28164. wantsMidiMessages = true;
  28165. break;
  28166. case audioMasterGetDirectory:
  28167. #if JUCE_MAC
  28168. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28169. #else
  28170. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28171. #endif
  28172. case audioMasterGetAutomationState:
  28173. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28174. break;
  28175. // none of these are handled (yet)..
  28176. case audioMasterBeginEdit:
  28177. case audioMasterEndEdit:
  28178. case audioMasterSetTime:
  28179. case audioMasterPinConnected:
  28180. case audioMasterGetParameterQuantization:
  28181. case audioMasterIOChanged:
  28182. case audioMasterGetInputLatency:
  28183. case audioMasterGetOutputLatency:
  28184. case audioMasterGetPreviousPlug:
  28185. case audioMasterGetNextPlug:
  28186. case audioMasterWillReplaceOrAccumulate:
  28187. case audioMasterGetCurrentProcessLevel:
  28188. case audioMasterOfflineStart:
  28189. case audioMasterOfflineRead:
  28190. case audioMasterOfflineWrite:
  28191. case audioMasterOfflineGetCurrentPass:
  28192. case audioMasterOfflineGetCurrentMetaPass:
  28193. case audioMasterVendorSpecific:
  28194. case audioMasterSetIcon:
  28195. case audioMasterGetLanguage:
  28196. case audioMasterOpenWindow:
  28197. case audioMasterCloseWindow:
  28198. break;
  28199. default:
  28200. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28201. }
  28202. return 0;
  28203. }
  28204. // entry point for all callbacks from the plugin
  28205. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28206. {
  28207. try
  28208. {
  28209. if (effect != 0 && effect->resvd2 != 0)
  28210. {
  28211. return ((VSTPluginInstance*)(effect->resvd2))
  28212. ->handleCallback (opcode, index, value, ptr, opt);
  28213. }
  28214. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28215. }
  28216. catch (...)
  28217. {
  28218. return 0;
  28219. }
  28220. }
  28221. const String VSTPluginInstance::getVersion() const
  28222. {
  28223. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28224. String s;
  28225. if (v == 0 || v == -1)
  28226. v = getVersionNumber();
  28227. if (v != 0)
  28228. {
  28229. int versionBits[4];
  28230. int n = 0;
  28231. while (v != 0)
  28232. {
  28233. versionBits [n++] = (v & 0xff);
  28234. v >>= 8;
  28235. }
  28236. s << 'V';
  28237. while (n > 0)
  28238. {
  28239. s << versionBits [--n];
  28240. if (n > 0)
  28241. s << '.';
  28242. }
  28243. }
  28244. return s;
  28245. }
  28246. int VSTPluginInstance::getUID() const
  28247. {
  28248. int uid = effect != 0 ? effect->uniqueID : 0;
  28249. if (uid == 0)
  28250. uid = module->file.hashCode();
  28251. return uid;
  28252. }
  28253. const String VSTPluginInstance::getCategory() const
  28254. {
  28255. const char* result = 0;
  28256. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28257. {
  28258. case kPlugCategEffect: result = "Effect"; break;
  28259. case kPlugCategSynth: result = "Synth"; break;
  28260. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28261. case kPlugCategMastering: result = "Mastering"; break;
  28262. case kPlugCategSpacializer: result = "Spacial"; break;
  28263. case kPlugCategRoomFx: result = "Reverb"; break;
  28264. case kPlugSurroundFx: result = "Surround"; break;
  28265. case kPlugCategRestoration: result = "Restoration"; break;
  28266. case kPlugCategGenerator: result = "Tone generation"; break;
  28267. default: break;
  28268. }
  28269. return result;
  28270. }
  28271. float VSTPluginInstance::getParameter (int index)
  28272. {
  28273. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28274. {
  28275. try
  28276. {
  28277. const ScopedLock sl (lock);
  28278. return effect->getParameter (effect, index);
  28279. }
  28280. catch (...)
  28281. {
  28282. }
  28283. }
  28284. return 0.0f;
  28285. }
  28286. void VSTPluginInstance::setParameter (int index, float newValue)
  28287. {
  28288. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28289. {
  28290. try
  28291. {
  28292. const ScopedLock sl (lock);
  28293. if (effect->getParameter (effect, index) != newValue)
  28294. effect->setParameter (effect, index, newValue);
  28295. }
  28296. catch (...)
  28297. {
  28298. }
  28299. }
  28300. }
  28301. const String VSTPluginInstance::getParameterName (int index)
  28302. {
  28303. if (effect != 0)
  28304. {
  28305. jassert (index >= 0 && index < effect->numParams);
  28306. char nm [256];
  28307. zerostruct (nm);
  28308. dispatch (effGetParamName, index, 0, nm, 0);
  28309. return String (nm).trim();
  28310. }
  28311. return String::empty;
  28312. }
  28313. const String VSTPluginInstance::getParameterLabel (int index) const
  28314. {
  28315. if (effect != 0)
  28316. {
  28317. jassert (index >= 0 && index < effect->numParams);
  28318. char nm [256];
  28319. zerostruct (nm);
  28320. dispatch (effGetParamLabel, index, 0, nm, 0);
  28321. return String (nm).trim();
  28322. }
  28323. return String::empty;
  28324. }
  28325. const String VSTPluginInstance::getParameterText (int index)
  28326. {
  28327. if (effect != 0)
  28328. {
  28329. jassert (index >= 0 && index < effect->numParams);
  28330. char nm [256];
  28331. zerostruct (nm);
  28332. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28333. return String (nm).trim();
  28334. }
  28335. return String::empty;
  28336. }
  28337. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28338. {
  28339. if (effect != 0)
  28340. {
  28341. jassert (index >= 0 && index < effect->numParams);
  28342. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28343. }
  28344. return false;
  28345. }
  28346. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28347. {
  28348. dest.setSize (64 + 4 * getNumParameters());
  28349. dest.fillWith (0);
  28350. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28351. float* const p = (float*) (((char*) dest.getData()) + 64);
  28352. for (int i = 0; i < getNumParameters(); ++i)
  28353. p[i] = getParameter(i);
  28354. }
  28355. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28356. {
  28357. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28358. float* p = (float*) (((char*) m.getData()) + 64);
  28359. for (int i = 0; i < getNumParameters(); ++i)
  28360. setParameter (i, p[i]);
  28361. }
  28362. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28363. {
  28364. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28365. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28366. }
  28367. const String VSTPluginInstance::getProgramName (int index)
  28368. {
  28369. if (index == getCurrentProgram())
  28370. {
  28371. return getCurrentProgramName();
  28372. }
  28373. else if (effect != 0)
  28374. {
  28375. char nm [256];
  28376. zerostruct (nm);
  28377. if (dispatch (effGetProgramNameIndexed,
  28378. jlimit (0, getNumPrograms(), index),
  28379. -1, nm, 0) != 0)
  28380. {
  28381. return String (nm).trim();
  28382. }
  28383. }
  28384. return programNames [index];
  28385. }
  28386. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28387. {
  28388. if (index == getCurrentProgram())
  28389. {
  28390. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28391. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28392. }
  28393. else
  28394. {
  28395. jassertfalse; // xxx not implemented!
  28396. }
  28397. }
  28398. void VSTPluginInstance::updateStoredProgramNames()
  28399. {
  28400. if (effect != 0 && getNumPrograms() > 0)
  28401. {
  28402. char nm [256];
  28403. zerostruct (nm);
  28404. // only do this if the plugin can't use indexed names..
  28405. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28406. {
  28407. const int oldProgram = getCurrentProgram();
  28408. MemoryBlock oldSettings;
  28409. createTempParameterStore (oldSettings);
  28410. for (int i = 0; i < getNumPrograms(); ++i)
  28411. {
  28412. setCurrentProgram (i);
  28413. getCurrentProgramName(); // (this updates the list)
  28414. }
  28415. setCurrentProgram (oldProgram);
  28416. restoreFromTempParameterStore (oldSettings);
  28417. }
  28418. }
  28419. }
  28420. const String VSTPluginInstance::getCurrentProgramName()
  28421. {
  28422. if (effect != 0)
  28423. {
  28424. char nm [256];
  28425. zerostruct (nm);
  28426. dispatch (effGetProgramName, 0, 0, nm, 0);
  28427. const int index = getCurrentProgram();
  28428. if (programNames[index].isEmpty())
  28429. {
  28430. while (programNames.size() < index)
  28431. programNames.add (String::empty);
  28432. programNames.set (index, String (nm).trim());
  28433. }
  28434. return String (nm).trim();
  28435. }
  28436. return String::empty;
  28437. }
  28438. const String VSTPluginInstance::getInputChannelName (int index) const
  28439. {
  28440. if (index >= 0 && index < getNumInputChannels())
  28441. {
  28442. VstPinProperties pinProps;
  28443. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28444. return String (pinProps.label, sizeof (pinProps.label));
  28445. }
  28446. return String::empty;
  28447. }
  28448. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28449. {
  28450. if (index < 0 || index >= getNumInputChannels())
  28451. return false;
  28452. VstPinProperties pinProps;
  28453. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28454. return (pinProps.flags & kVstPinIsStereo) != 0;
  28455. return true;
  28456. }
  28457. const String VSTPluginInstance::getOutputChannelName (int index) const
  28458. {
  28459. if (index >= 0 && index < getNumOutputChannels())
  28460. {
  28461. VstPinProperties pinProps;
  28462. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28463. return String (pinProps.label, sizeof (pinProps.label));
  28464. }
  28465. return String::empty;
  28466. }
  28467. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28468. {
  28469. if (index < 0 || index >= getNumOutputChannels())
  28470. return false;
  28471. VstPinProperties pinProps;
  28472. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28473. return (pinProps.flags & kVstPinIsStereo) != 0;
  28474. return true;
  28475. }
  28476. void VSTPluginInstance::setPower (const bool on)
  28477. {
  28478. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28479. isPowerOn = on;
  28480. }
  28481. const int defaultMaxSizeMB = 64;
  28482. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28483. {
  28484. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28485. }
  28486. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28487. {
  28488. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28489. }
  28490. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28491. {
  28492. loadFromFXBFile (data, sizeInBytes);
  28493. }
  28494. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28495. {
  28496. loadFromFXBFile (data, sizeInBytes);
  28497. }
  28498. VSTPluginFormat::VSTPluginFormat()
  28499. {
  28500. }
  28501. VSTPluginFormat::~VSTPluginFormat()
  28502. {
  28503. }
  28504. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28505. const String& fileOrIdentifier)
  28506. {
  28507. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28508. return;
  28509. PluginDescription desc;
  28510. desc.fileOrIdentifier = fileOrIdentifier;
  28511. desc.uid = 0;
  28512. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28513. if (instance == 0)
  28514. return;
  28515. try
  28516. {
  28517. #if JUCE_MAC
  28518. if (instance->module->resFileId != 0)
  28519. UseResFile (instance->module->resFileId);
  28520. #endif
  28521. instance->fillInPluginDescription (desc);
  28522. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28523. if (category != kPlugCategShell)
  28524. {
  28525. // Normal plugin...
  28526. results.add (new PluginDescription (desc));
  28527. ++insideVSTCallback;
  28528. instance->dispatch (effOpen, 0, 0, 0, 0);
  28529. --insideVSTCallback;
  28530. }
  28531. else
  28532. {
  28533. // It's a shell plugin, so iterate all the subtypes...
  28534. char shellEffectName [64];
  28535. for (;;)
  28536. {
  28537. zerostruct (shellEffectName);
  28538. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28539. if (uid == 0)
  28540. {
  28541. break;
  28542. }
  28543. else
  28544. {
  28545. desc.uid = uid;
  28546. desc.name = shellEffectName;
  28547. desc.descriptiveName = shellEffectName;
  28548. bool alreadyThere = false;
  28549. for (int i = results.size(); --i >= 0;)
  28550. {
  28551. PluginDescription* const d = results.getUnchecked(i);
  28552. if (d->isDuplicateOf (desc))
  28553. {
  28554. alreadyThere = true;
  28555. break;
  28556. }
  28557. }
  28558. if (! alreadyThere)
  28559. results.add (new PluginDescription (desc));
  28560. }
  28561. }
  28562. }
  28563. }
  28564. catch (...)
  28565. {
  28566. // crashed while loading...
  28567. }
  28568. }
  28569. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28570. {
  28571. ScopedPointer <VSTPluginInstance> result;
  28572. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28573. {
  28574. File file (desc.fileOrIdentifier);
  28575. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28576. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28577. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28578. if (module != 0)
  28579. {
  28580. shellUIDToCreate = desc.uid;
  28581. result = new VSTPluginInstance (module);
  28582. if (result->effect != 0)
  28583. {
  28584. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28585. result->initialise();
  28586. }
  28587. else
  28588. {
  28589. result = 0;
  28590. }
  28591. }
  28592. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28593. }
  28594. return result.release();
  28595. }
  28596. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28597. {
  28598. const File f (fileOrIdentifier);
  28599. #if JUCE_MAC
  28600. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28601. return true;
  28602. #if JUCE_PPC
  28603. FSRef fileRef;
  28604. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28605. {
  28606. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28607. if (resFileId != -1)
  28608. {
  28609. const int numEffects = Count1Resources ('aEff');
  28610. CloseResFile (resFileId);
  28611. if (numEffects > 0)
  28612. return true;
  28613. }
  28614. }
  28615. #endif
  28616. return false;
  28617. #elif JUCE_WINDOWS
  28618. return f.existsAsFile() && f.hasFileExtension (".dll");
  28619. #elif JUCE_LINUX
  28620. return f.existsAsFile() && f.hasFileExtension (".so");
  28621. #endif
  28622. }
  28623. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28624. {
  28625. return fileOrIdentifier;
  28626. }
  28627. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28628. {
  28629. return File (desc.fileOrIdentifier).exists();
  28630. }
  28631. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28632. {
  28633. StringArray results;
  28634. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28635. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28636. return results;
  28637. }
  28638. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28639. {
  28640. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28641. // .component or .vst directories.
  28642. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28643. while (iter.next())
  28644. {
  28645. const File f (iter.getFile());
  28646. bool isPlugin = false;
  28647. if (fileMightContainThisPluginType (f.getFullPathName()))
  28648. {
  28649. isPlugin = true;
  28650. results.add (f.getFullPathName());
  28651. }
  28652. if (recursive && (! isPlugin) && f.isDirectory())
  28653. recursiveFileSearch (results, f, true);
  28654. }
  28655. }
  28656. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28657. {
  28658. #if JUCE_MAC
  28659. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28660. #elif JUCE_WINDOWS
  28661. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28662. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28663. #elif JUCE_LINUX
  28664. return FileSearchPath ("/usr/lib/vst");
  28665. #endif
  28666. }
  28667. END_JUCE_NAMESPACE
  28668. #endif
  28669. #undef log
  28670. #endif
  28671. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28672. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28673. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28674. BEGIN_JUCE_NAMESPACE
  28675. AudioProcessor::AudioProcessor()
  28676. : playHead (0),
  28677. sampleRate (0),
  28678. blockSize (0),
  28679. numInputChannels (0),
  28680. numOutputChannels (0),
  28681. latencySamples (0),
  28682. suspended (false),
  28683. nonRealtime (false)
  28684. {
  28685. }
  28686. AudioProcessor::~AudioProcessor()
  28687. {
  28688. // ooh, nasty - the editor should have been deleted before the filter
  28689. // that it refers to is deleted..
  28690. jassert (activeEditor == 0);
  28691. #if JUCE_DEBUG
  28692. // This will fail if you've called beginParameterChangeGesture() for one
  28693. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28694. jassert (changingParams.countNumberOfSetBits() == 0);
  28695. #endif
  28696. }
  28697. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28698. {
  28699. playHead = newPlayHead;
  28700. }
  28701. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28702. {
  28703. const ScopedLock sl (listenerLock);
  28704. listeners.addIfNotAlreadyThere (newListener);
  28705. }
  28706. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28707. {
  28708. const ScopedLock sl (listenerLock);
  28709. listeners.removeValue (listenerToRemove);
  28710. }
  28711. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28712. const int numOuts,
  28713. const double sampleRate_,
  28714. const int blockSize_) throw()
  28715. {
  28716. numInputChannels = numIns;
  28717. numOutputChannels = numOuts;
  28718. sampleRate = sampleRate_;
  28719. blockSize = blockSize_;
  28720. }
  28721. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28722. {
  28723. nonRealtime = nonRealtime_;
  28724. }
  28725. void AudioProcessor::setLatencySamples (const int newLatency)
  28726. {
  28727. if (latencySamples != newLatency)
  28728. {
  28729. latencySamples = newLatency;
  28730. updateHostDisplay();
  28731. }
  28732. }
  28733. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28734. const float newValue)
  28735. {
  28736. setParameter (parameterIndex, newValue);
  28737. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28738. }
  28739. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28740. {
  28741. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28742. for (int i = listeners.size(); --i >= 0;)
  28743. {
  28744. AudioProcessorListener* l;
  28745. {
  28746. const ScopedLock sl (listenerLock);
  28747. l = listeners [i];
  28748. }
  28749. if (l != 0)
  28750. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28751. }
  28752. }
  28753. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28754. {
  28755. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28756. #if JUCE_DEBUG
  28757. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28758. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28759. jassert (! changingParams [parameterIndex]);
  28760. changingParams.setBit (parameterIndex);
  28761. #endif
  28762. for (int i = listeners.size(); --i >= 0;)
  28763. {
  28764. AudioProcessorListener* l;
  28765. {
  28766. const ScopedLock sl (listenerLock);
  28767. l = listeners [i];
  28768. }
  28769. if (l != 0)
  28770. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28771. }
  28772. }
  28773. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28774. {
  28775. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28776. #if JUCE_DEBUG
  28777. // This means you've called endParameterChangeGesture without having previously called
  28778. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28779. // calls matched correctly.
  28780. jassert (changingParams [parameterIndex]);
  28781. changingParams.clearBit (parameterIndex);
  28782. #endif
  28783. for (int i = listeners.size(); --i >= 0;)
  28784. {
  28785. AudioProcessorListener* l;
  28786. {
  28787. const ScopedLock sl (listenerLock);
  28788. l = listeners [i];
  28789. }
  28790. if (l != 0)
  28791. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28792. }
  28793. }
  28794. void AudioProcessor::updateHostDisplay()
  28795. {
  28796. for (int i = listeners.size(); --i >= 0;)
  28797. {
  28798. AudioProcessorListener* l;
  28799. {
  28800. const ScopedLock sl (listenerLock);
  28801. l = listeners [i];
  28802. }
  28803. if (l != 0)
  28804. l->audioProcessorChanged (this);
  28805. }
  28806. }
  28807. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28808. {
  28809. return true;
  28810. }
  28811. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28812. {
  28813. return false;
  28814. }
  28815. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28816. {
  28817. const ScopedLock sl (callbackLock);
  28818. suspended = shouldBeSuspended;
  28819. }
  28820. void AudioProcessor::reset()
  28821. {
  28822. }
  28823. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28824. {
  28825. const ScopedLock sl (callbackLock);
  28826. if (activeEditor == editor)
  28827. activeEditor = 0;
  28828. }
  28829. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28830. {
  28831. if (activeEditor != 0)
  28832. return activeEditor;
  28833. AudioProcessorEditor* const ed = createEditor();
  28834. // You must make your hasEditor() method return a consistent result!
  28835. jassert (hasEditor() == (ed != 0));
  28836. if (ed != 0)
  28837. {
  28838. // you must give your editor comp a size before returning it..
  28839. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28840. const ScopedLock sl (callbackLock);
  28841. activeEditor = ed;
  28842. }
  28843. return ed;
  28844. }
  28845. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28846. {
  28847. getStateInformation (destData);
  28848. }
  28849. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28850. {
  28851. setStateInformation (data, sizeInBytes);
  28852. }
  28853. // magic number to identify memory blocks that we've stored as XML
  28854. const uint32 magicXmlNumber = 0x21324356;
  28855. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28856. JUCE_NAMESPACE::MemoryBlock& destData)
  28857. {
  28858. const String xmlString (xml.createDocument (String::empty, true, false));
  28859. const int stringLength = xmlString.getNumBytesAsUTF8();
  28860. destData.setSize (stringLength + 10);
  28861. char* const d = static_cast<char*> (destData.getData());
  28862. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28863. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28864. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28865. }
  28866. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28867. const int sizeInBytes)
  28868. {
  28869. if (sizeInBytes > 8
  28870. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28871. {
  28872. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28873. if (stringLength > 0)
  28874. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28875. jmin ((sizeInBytes - 8), stringLength)));
  28876. }
  28877. return 0;
  28878. }
  28879. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28880. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28881. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28882. {
  28883. return timeInSeconds == other.timeInSeconds
  28884. && ppqPosition == other.ppqPosition
  28885. && editOriginTime == other.editOriginTime
  28886. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28887. && frameRate == other.frameRate
  28888. && isPlaying == other.isPlaying
  28889. && isRecording == other.isRecording
  28890. && bpm == other.bpm
  28891. && timeSigNumerator == other.timeSigNumerator
  28892. && timeSigDenominator == other.timeSigDenominator;
  28893. }
  28894. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28895. {
  28896. return ! operator== (other);
  28897. }
  28898. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28899. {
  28900. zerostruct (*this);
  28901. timeSigNumerator = 4;
  28902. timeSigDenominator = 4;
  28903. bpm = 120;
  28904. }
  28905. END_JUCE_NAMESPACE
  28906. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28907. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28908. BEGIN_JUCE_NAMESPACE
  28909. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28910. : owner (owner_)
  28911. {
  28912. // the filter must be valid..
  28913. jassert (owner != 0);
  28914. }
  28915. AudioProcessorEditor::~AudioProcessorEditor()
  28916. {
  28917. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28918. // filter for some reason..
  28919. jassert (owner->getActiveEditor() != this);
  28920. }
  28921. END_JUCE_NAMESPACE
  28922. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28923. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28924. BEGIN_JUCE_NAMESPACE
  28925. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28926. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28927. : id (id_),
  28928. processor (processor_),
  28929. isPrepared (false)
  28930. {
  28931. jassert (processor_ != 0);
  28932. }
  28933. AudioProcessorGraph::Node::~Node()
  28934. {
  28935. }
  28936. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28937. AudioProcessorGraph* const graph)
  28938. {
  28939. if (! isPrepared)
  28940. {
  28941. isPrepared = true;
  28942. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28943. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28944. if (ioProc != 0)
  28945. ioProc->setParentGraph (graph);
  28946. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28947. processor->getNumOutputChannels(),
  28948. sampleRate, blockSize);
  28949. processor->prepareToPlay (sampleRate, blockSize);
  28950. }
  28951. }
  28952. void AudioProcessorGraph::Node::unprepare()
  28953. {
  28954. if (isPrepared)
  28955. {
  28956. isPrepared = false;
  28957. processor->releaseResources();
  28958. }
  28959. }
  28960. AudioProcessorGraph::AudioProcessorGraph()
  28961. : lastNodeId (0),
  28962. renderingBuffers (1, 1),
  28963. currentAudioOutputBuffer (1, 1)
  28964. {
  28965. }
  28966. AudioProcessorGraph::~AudioProcessorGraph()
  28967. {
  28968. clearRenderingSequence();
  28969. clear();
  28970. }
  28971. const String AudioProcessorGraph::getName() const
  28972. {
  28973. return "Audio Graph";
  28974. }
  28975. void AudioProcessorGraph::clear()
  28976. {
  28977. nodes.clear();
  28978. connections.clear();
  28979. triggerAsyncUpdate();
  28980. }
  28981. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28982. {
  28983. for (int i = nodes.size(); --i >= 0;)
  28984. if (nodes.getUnchecked(i)->id == nodeId)
  28985. return nodes.getUnchecked(i);
  28986. return 0;
  28987. }
  28988. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28989. uint32 nodeId)
  28990. {
  28991. if (newProcessor == 0)
  28992. {
  28993. jassertfalse;
  28994. return 0;
  28995. }
  28996. if (nodeId == 0)
  28997. {
  28998. nodeId = ++lastNodeId;
  28999. }
  29000. else
  29001. {
  29002. // you can't add a node with an id that already exists in the graph..
  29003. jassert (getNodeForId (nodeId) == 0);
  29004. removeNode (nodeId);
  29005. }
  29006. lastNodeId = nodeId;
  29007. Node* const n = new Node (nodeId, newProcessor);
  29008. nodes.add (n);
  29009. triggerAsyncUpdate();
  29010. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29011. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29012. if (ioProc != 0)
  29013. ioProc->setParentGraph (this);
  29014. return n;
  29015. }
  29016. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29017. {
  29018. disconnectNode (nodeId);
  29019. for (int i = nodes.size(); --i >= 0;)
  29020. {
  29021. if (nodes.getUnchecked(i)->id == nodeId)
  29022. {
  29023. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29024. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29025. if (ioProc != 0)
  29026. ioProc->setParentGraph (0);
  29027. nodes.remove (i);
  29028. triggerAsyncUpdate();
  29029. return true;
  29030. }
  29031. }
  29032. return false;
  29033. }
  29034. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29035. const int sourceChannelIndex,
  29036. const uint32 destNodeId,
  29037. const int destChannelIndex) const
  29038. {
  29039. for (int i = connections.size(); --i >= 0;)
  29040. {
  29041. const Connection* const c = connections.getUnchecked(i);
  29042. if (c->sourceNodeId == sourceNodeId
  29043. && c->destNodeId == destNodeId
  29044. && c->sourceChannelIndex == sourceChannelIndex
  29045. && c->destChannelIndex == destChannelIndex)
  29046. {
  29047. return c;
  29048. }
  29049. }
  29050. return 0;
  29051. }
  29052. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29053. const uint32 possibleDestNodeId) const
  29054. {
  29055. for (int i = connections.size(); --i >= 0;)
  29056. {
  29057. const Connection* const c = connections.getUnchecked(i);
  29058. if (c->sourceNodeId == possibleSourceNodeId
  29059. && c->destNodeId == possibleDestNodeId)
  29060. {
  29061. return true;
  29062. }
  29063. }
  29064. return false;
  29065. }
  29066. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29067. const int sourceChannelIndex,
  29068. const uint32 destNodeId,
  29069. const int destChannelIndex) const
  29070. {
  29071. if (sourceChannelIndex < 0
  29072. || destChannelIndex < 0
  29073. || sourceNodeId == destNodeId
  29074. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29075. return false;
  29076. const Node* const source = getNodeForId (sourceNodeId);
  29077. if (source == 0
  29078. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29079. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29080. return false;
  29081. const Node* const dest = getNodeForId (destNodeId);
  29082. if (dest == 0
  29083. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29084. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29085. return false;
  29086. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29087. destNodeId, destChannelIndex) == 0;
  29088. }
  29089. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29090. const int sourceChannelIndex,
  29091. const uint32 destNodeId,
  29092. const int destChannelIndex)
  29093. {
  29094. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29095. return false;
  29096. Connection* const c = new Connection();
  29097. c->sourceNodeId = sourceNodeId;
  29098. c->sourceChannelIndex = sourceChannelIndex;
  29099. c->destNodeId = destNodeId;
  29100. c->destChannelIndex = destChannelIndex;
  29101. connections.add (c);
  29102. triggerAsyncUpdate();
  29103. return true;
  29104. }
  29105. void AudioProcessorGraph::removeConnection (const int index)
  29106. {
  29107. connections.remove (index);
  29108. triggerAsyncUpdate();
  29109. }
  29110. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29111. const uint32 destNodeId, const int destChannelIndex)
  29112. {
  29113. bool doneAnything = false;
  29114. for (int i = connections.size(); --i >= 0;)
  29115. {
  29116. const Connection* const c = connections.getUnchecked(i);
  29117. if (c->sourceNodeId == sourceNodeId
  29118. && c->destNodeId == destNodeId
  29119. && c->sourceChannelIndex == sourceChannelIndex
  29120. && c->destChannelIndex == destChannelIndex)
  29121. {
  29122. removeConnection (i);
  29123. doneAnything = true;
  29124. triggerAsyncUpdate();
  29125. }
  29126. }
  29127. return doneAnything;
  29128. }
  29129. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29130. {
  29131. bool doneAnything = false;
  29132. for (int i = connections.size(); --i >= 0;)
  29133. {
  29134. const Connection* const c = connections.getUnchecked(i);
  29135. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29136. {
  29137. removeConnection (i);
  29138. doneAnything = true;
  29139. triggerAsyncUpdate();
  29140. }
  29141. }
  29142. return doneAnything;
  29143. }
  29144. bool AudioProcessorGraph::removeIllegalConnections()
  29145. {
  29146. bool doneAnything = false;
  29147. for (int i = connections.size(); --i >= 0;)
  29148. {
  29149. const Connection* const c = connections.getUnchecked(i);
  29150. const Node* const source = getNodeForId (c->sourceNodeId);
  29151. const Node* const dest = getNodeForId (c->destNodeId);
  29152. if (source == 0 || dest == 0
  29153. || (c->sourceChannelIndex != midiChannelIndex
  29154. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  29155. || (c->sourceChannelIndex == midiChannelIndex
  29156. && ! source->processor->producesMidi())
  29157. || (c->destChannelIndex != midiChannelIndex
  29158. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  29159. || (c->destChannelIndex == midiChannelIndex
  29160. && ! dest->processor->acceptsMidi()))
  29161. {
  29162. removeConnection (i);
  29163. doneAnything = true;
  29164. triggerAsyncUpdate();
  29165. }
  29166. }
  29167. return doneAnything;
  29168. }
  29169. namespace GraphRenderingOps
  29170. {
  29171. class AudioGraphRenderingOp
  29172. {
  29173. public:
  29174. AudioGraphRenderingOp() {}
  29175. virtual ~AudioGraphRenderingOp() {}
  29176. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29177. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29178. const int numSamples) = 0;
  29179. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29180. };
  29181. class ClearChannelOp : public AudioGraphRenderingOp
  29182. {
  29183. public:
  29184. ClearChannelOp (const int channelNum_)
  29185. : channelNum (channelNum_)
  29186. {}
  29187. ~ClearChannelOp() {}
  29188. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29189. {
  29190. sharedBufferChans.clear (channelNum, 0, numSamples);
  29191. }
  29192. private:
  29193. const int channelNum;
  29194. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29195. };
  29196. class CopyChannelOp : public AudioGraphRenderingOp
  29197. {
  29198. public:
  29199. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29200. : srcChannelNum (srcChannelNum_),
  29201. dstChannelNum (dstChannelNum_)
  29202. {}
  29203. ~CopyChannelOp() {}
  29204. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29205. {
  29206. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29207. }
  29208. private:
  29209. const int srcChannelNum, dstChannelNum;
  29210. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29211. };
  29212. class AddChannelOp : public AudioGraphRenderingOp
  29213. {
  29214. public:
  29215. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29216. : srcChannelNum (srcChannelNum_),
  29217. dstChannelNum (dstChannelNum_)
  29218. {}
  29219. ~AddChannelOp() {}
  29220. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29221. {
  29222. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29223. }
  29224. private:
  29225. const int srcChannelNum, dstChannelNum;
  29226. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29227. };
  29228. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29229. {
  29230. public:
  29231. ClearMidiBufferOp (const int bufferNum_)
  29232. : bufferNum (bufferNum_)
  29233. {}
  29234. ~ClearMidiBufferOp() {}
  29235. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29236. {
  29237. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29238. }
  29239. private:
  29240. const int bufferNum;
  29241. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29242. };
  29243. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29244. {
  29245. public:
  29246. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29247. : srcBufferNum (srcBufferNum_),
  29248. dstBufferNum (dstBufferNum_)
  29249. {}
  29250. ~CopyMidiBufferOp() {}
  29251. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29252. {
  29253. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29254. }
  29255. private:
  29256. const int srcBufferNum, dstBufferNum;
  29257. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29258. };
  29259. class AddMidiBufferOp : public AudioGraphRenderingOp
  29260. {
  29261. public:
  29262. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29263. : srcBufferNum (srcBufferNum_),
  29264. dstBufferNum (dstBufferNum_)
  29265. {}
  29266. ~AddMidiBufferOp() {}
  29267. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29268. {
  29269. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29270. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29271. }
  29272. private:
  29273. const int srcBufferNum, dstBufferNum;
  29274. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29275. };
  29276. class ProcessBufferOp : public AudioGraphRenderingOp
  29277. {
  29278. public:
  29279. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29280. const Array <int>& audioChannelsToUse_,
  29281. const int totalChans_,
  29282. const int midiBufferToUse_)
  29283. : node (node_),
  29284. processor (node_->getProcessor()),
  29285. audioChannelsToUse (audioChannelsToUse_),
  29286. totalChans (jmax (1, totalChans_)),
  29287. midiBufferToUse (midiBufferToUse_)
  29288. {
  29289. channels.calloc (totalChans);
  29290. while (audioChannelsToUse.size() < totalChans)
  29291. audioChannelsToUse.add (0);
  29292. }
  29293. ~ProcessBufferOp()
  29294. {
  29295. }
  29296. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29297. {
  29298. for (int i = totalChans; --i >= 0;)
  29299. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29300. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29301. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29302. }
  29303. const AudioProcessorGraph::Node::Ptr node;
  29304. AudioProcessor* const processor;
  29305. private:
  29306. Array <int> audioChannelsToUse;
  29307. HeapBlock <float*> channels;
  29308. int totalChans;
  29309. int midiBufferToUse;
  29310. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29311. };
  29312. /** Used to calculate the correct sequence of rendering ops needed, based on
  29313. the best re-use of shared buffers at each stage.
  29314. */
  29315. class RenderingOpSequenceCalculator
  29316. {
  29317. public:
  29318. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29319. const Array<void*>& orderedNodes_,
  29320. Array<void*>& renderingOps)
  29321. : graph (graph_),
  29322. orderedNodes (orderedNodes_)
  29323. {
  29324. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29325. channels.add (0);
  29326. midiNodeIds.add ((uint32) zeroNodeID);
  29327. for (int i = 0; i < orderedNodes.size(); ++i)
  29328. {
  29329. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29330. renderingOps, i);
  29331. markAnyUnusedBuffersAsFree (i);
  29332. }
  29333. }
  29334. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29335. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29336. private:
  29337. AudioProcessorGraph& graph;
  29338. const Array<void*>& orderedNodes;
  29339. Array <int> channels;
  29340. Array <uint32> nodeIds, midiNodeIds;
  29341. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29342. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29343. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29344. Array<void*>& renderingOps,
  29345. const int ourRenderingIndex)
  29346. {
  29347. const int numIns = node->getProcessor()->getNumInputChannels();
  29348. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29349. const int totalChans = jmax (numIns, numOuts);
  29350. Array <int> audioChannelsToUse;
  29351. int midiBufferToUse = -1;
  29352. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29353. {
  29354. // get a list of all the inputs to this node
  29355. Array <int> sourceNodes, sourceOutputChans;
  29356. for (int i = graph.getNumConnections(); --i >= 0;)
  29357. {
  29358. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29359. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29360. {
  29361. sourceNodes.add (c->sourceNodeId);
  29362. sourceOutputChans.add (c->sourceChannelIndex);
  29363. }
  29364. }
  29365. int bufIndex = -1;
  29366. if (sourceNodes.size() == 0)
  29367. {
  29368. // unconnected input channel
  29369. if (inputChan >= numOuts)
  29370. {
  29371. bufIndex = getReadOnlyEmptyBuffer();
  29372. jassert (bufIndex >= 0);
  29373. }
  29374. else
  29375. {
  29376. bufIndex = getFreeBuffer (false);
  29377. renderingOps.add (new ClearChannelOp (bufIndex));
  29378. }
  29379. }
  29380. else if (sourceNodes.size() == 1)
  29381. {
  29382. // channel with a straightforward single input..
  29383. const int srcNode = sourceNodes.getUnchecked(0);
  29384. const int srcChan = sourceOutputChans.getUnchecked(0);
  29385. bufIndex = getBufferContaining (srcNode, srcChan);
  29386. if (bufIndex < 0)
  29387. {
  29388. // if not found, this is probably a feedback loop
  29389. bufIndex = getReadOnlyEmptyBuffer();
  29390. jassert (bufIndex >= 0);
  29391. }
  29392. if (inputChan < numOuts
  29393. && isBufferNeededLater (ourRenderingIndex,
  29394. inputChan,
  29395. srcNode, srcChan))
  29396. {
  29397. // can't mess up this channel because it's needed later by another node, so we
  29398. // need to use a copy of it..
  29399. const int newFreeBuffer = getFreeBuffer (false);
  29400. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29401. bufIndex = newFreeBuffer;
  29402. }
  29403. }
  29404. else
  29405. {
  29406. // channel with a mix of several inputs..
  29407. // try to find a re-usable channel from our inputs..
  29408. int reusableInputIndex = -1;
  29409. for (int i = 0; i < sourceNodes.size(); ++i)
  29410. {
  29411. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29412. sourceOutputChans.getUnchecked(i));
  29413. if (sourceBufIndex >= 0
  29414. && ! isBufferNeededLater (ourRenderingIndex,
  29415. inputChan,
  29416. sourceNodes.getUnchecked(i),
  29417. sourceOutputChans.getUnchecked(i)))
  29418. {
  29419. // we've found one of our input chans that can be re-used..
  29420. reusableInputIndex = i;
  29421. bufIndex = sourceBufIndex;
  29422. break;
  29423. }
  29424. }
  29425. if (reusableInputIndex < 0)
  29426. {
  29427. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29428. bufIndex = getFreeBuffer (false);
  29429. jassert (bufIndex != 0);
  29430. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29431. sourceOutputChans.getUnchecked (0));
  29432. if (srcIndex < 0)
  29433. {
  29434. // if not found, this is probably a feedback loop
  29435. renderingOps.add (new ClearChannelOp (bufIndex));
  29436. }
  29437. else
  29438. {
  29439. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29440. }
  29441. reusableInputIndex = 0;
  29442. }
  29443. for (int j = 0; j < sourceNodes.size(); ++j)
  29444. {
  29445. if (j != reusableInputIndex)
  29446. {
  29447. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29448. sourceOutputChans.getUnchecked(j));
  29449. if (srcIndex >= 0)
  29450. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29451. }
  29452. }
  29453. }
  29454. jassert (bufIndex >= 0);
  29455. audioChannelsToUse.add (bufIndex);
  29456. if (inputChan < numOuts)
  29457. markBufferAsContaining (bufIndex, node->id, inputChan);
  29458. }
  29459. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29460. {
  29461. const int bufIndex = getFreeBuffer (false);
  29462. jassert (bufIndex != 0);
  29463. audioChannelsToUse.add (bufIndex);
  29464. markBufferAsContaining (bufIndex, node->id, outputChan);
  29465. }
  29466. // Now the same thing for midi..
  29467. Array <int> midiSourceNodes;
  29468. for (int i = graph.getNumConnections(); --i >= 0;)
  29469. {
  29470. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29471. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29472. midiSourceNodes.add (c->sourceNodeId);
  29473. }
  29474. if (midiSourceNodes.size() == 0)
  29475. {
  29476. // No midi inputs..
  29477. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29478. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29479. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29480. }
  29481. else if (midiSourceNodes.size() == 1)
  29482. {
  29483. // One midi input..
  29484. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29485. AudioProcessorGraph::midiChannelIndex);
  29486. if (midiBufferToUse >= 0)
  29487. {
  29488. if (isBufferNeededLater (ourRenderingIndex,
  29489. AudioProcessorGraph::midiChannelIndex,
  29490. midiSourceNodes.getUnchecked(0),
  29491. AudioProcessorGraph::midiChannelIndex))
  29492. {
  29493. // can't mess up this channel because it's needed later by another node, so we
  29494. // need to use a copy of it..
  29495. const int newFreeBuffer = getFreeBuffer (true);
  29496. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29497. midiBufferToUse = newFreeBuffer;
  29498. }
  29499. }
  29500. else
  29501. {
  29502. // probably a feedback loop, so just use an empty one..
  29503. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29504. }
  29505. }
  29506. else
  29507. {
  29508. // More than one midi input being mixed..
  29509. int reusableInputIndex = -1;
  29510. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29511. {
  29512. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29513. AudioProcessorGraph::midiChannelIndex);
  29514. if (sourceBufIndex >= 0
  29515. && ! isBufferNeededLater (ourRenderingIndex,
  29516. AudioProcessorGraph::midiChannelIndex,
  29517. midiSourceNodes.getUnchecked(i),
  29518. AudioProcessorGraph::midiChannelIndex))
  29519. {
  29520. // we've found one of our input buffers that can be re-used..
  29521. reusableInputIndex = i;
  29522. midiBufferToUse = sourceBufIndex;
  29523. break;
  29524. }
  29525. }
  29526. if (reusableInputIndex < 0)
  29527. {
  29528. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29529. midiBufferToUse = getFreeBuffer (true);
  29530. jassert (midiBufferToUse >= 0);
  29531. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29532. AudioProcessorGraph::midiChannelIndex);
  29533. if (srcIndex >= 0)
  29534. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29535. else
  29536. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29537. reusableInputIndex = 0;
  29538. }
  29539. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29540. {
  29541. if (j != reusableInputIndex)
  29542. {
  29543. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29544. AudioProcessorGraph::midiChannelIndex);
  29545. if (srcIndex >= 0)
  29546. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29547. }
  29548. }
  29549. }
  29550. if (node->getProcessor()->producesMidi())
  29551. markBufferAsContaining (midiBufferToUse, node->id,
  29552. AudioProcessorGraph::midiChannelIndex);
  29553. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29554. totalChans, midiBufferToUse));
  29555. }
  29556. int getFreeBuffer (const bool forMidi)
  29557. {
  29558. if (forMidi)
  29559. {
  29560. for (int i = 1; i < midiNodeIds.size(); ++i)
  29561. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29562. return i;
  29563. midiNodeIds.add ((uint32) freeNodeID);
  29564. return midiNodeIds.size() - 1;
  29565. }
  29566. else
  29567. {
  29568. for (int i = 1; i < nodeIds.size(); ++i)
  29569. if (nodeIds.getUnchecked(i) == freeNodeID)
  29570. return i;
  29571. nodeIds.add ((uint32) freeNodeID);
  29572. channels.add (0);
  29573. return nodeIds.size() - 1;
  29574. }
  29575. }
  29576. int getReadOnlyEmptyBuffer() const
  29577. {
  29578. return 0;
  29579. }
  29580. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29581. {
  29582. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29583. {
  29584. for (int i = midiNodeIds.size(); --i >= 0;)
  29585. if (midiNodeIds.getUnchecked(i) == nodeId)
  29586. return i;
  29587. }
  29588. else
  29589. {
  29590. for (int i = nodeIds.size(); --i >= 0;)
  29591. if (nodeIds.getUnchecked(i) == nodeId
  29592. && channels.getUnchecked(i) == outputChannel)
  29593. return i;
  29594. }
  29595. return -1;
  29596. }
  29597. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29598. {
  29599. int i;
  29600. for (i = 0; i < nodeIds.size(); ++i)
  29601. {
  29602. if (isNodeBusy (nodeIds.getUnchecked(i))
  29603. && ! isBufferNeededLater (stepIndex, -1,
  29604. nodeIds.getUnchecked(i),
  29605. channels.getUnchecked(i)))
  29606. {
  29607. nodeIds.set (i, (uint32) freeNodeID);
  29608. }
  29609. }
  29610. for (i = 0; i < midiNodeIds.size(); ++i)
  29611. {
  29612. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29613. && ! isBufferNeededLater (stepIndex, -1,
  29614. midiNodeIds.getUnchecked(i),
  29615. AudioProcessorGraph::midiChannelIndex))
  29616. {
  29617. midiNodeIds.set (i, (uint32) freeNodeID);
  29618. }
  29619. }
  29620. }
  29621. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29622. int inputChannelOfIndexToIgnore,
  29623. const uint32 nodeId,
  29624. const int outputChanIndex) const
  29625. {
  29626. while (stepIndexToSearchFrom < orderedNodes.size())
  29627. {
  29628. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29629. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29630. {
  29631. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29632. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29633. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29634. return true;
  29635. }
  29636. else
  29637. {
  29638. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29639. if (i != inputChannelOfIndexToIgnore
  29640. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29641. node->id, i) != 0)
  29642. return true;
  29643. }
  29644. inputChannelOfIndexToIgnore = -1;
  29645. ++stepIndexToSearchFrom;
  29646. }
  29647. return false;
  29648. }
  29649. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29650. {
  29651. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29652. {
  29653. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29654. midiNodeIds.set (bufferNum, nodeId);
  29655. }
  29656. else
  29657. {
  29658. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29659. nodeIds.set (bufferNum, nodeId);
  29660. channels.set (bufferNum, outputIndex);
  29661. }
  29662. }
  29663. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29664. };
  29665. }
  29666. void AudioProcessorGraph::clearRenderingSequence()
  29667. {
  29668. const ScopedLock sl (renderLock);
  29669. for (int i = renderingOps.size(); --i >= 0;)
  29670. {
  29671. GraphRenderingOps::AudioGraphRenderingOp* const r
  29672. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29673. renderingOps.remove (i);
  29674. delete r;
  29675. }
  29676. }
  29677. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29678. const uint32 possibleDestinationId,
  29679. const int recursionCheck) const
  29680. {
  29681. if (recursionCheck > 0)
  29682. {
  29683. for (int i = connections.size(); --i >= 0;)
  29684. {
  29685. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29686. if (c->destNodeId == possibleDestinationId
  29687. && (c->sourceNodeId == possibleInputId
  29688. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29689. return true;
  29690. }
  29691. }
  29692. return false;
  29693. }
  29694. void AudioProcessorGraph::buildRenderingSequence()
  29695. {
  29696. Array<void*> newRenderingOps;
  29697. int numRenderingBuffersNeeded = 2;
  29698. int numMidiBuffersNeeded = 1;
  29699. {
  29700. MessageManagerLock mml;
  29701. Array<void*> orderedNodes;
  29702. int i;
  29703. for (i = 0; i < nodes.size(); ++i)
  29704. {
  29705. Node* const node = nodes.getUnchecked(i);
  29706. node->prepare (getSampleRate(), getBlockSize(), this);
  29707. int j = 0;
  29708. for (; j < orderedNodes.size(); ++j)
  29709. if (isAnInputTo (node->id,
  29710. ((Node*) orderedNodes.getUnchecked (j))->id,
  29711. nodes.size() + 1))
  29712. break;
  29713. orderedNodes.insert (j, node);
  29714. }
  29715. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29716. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29717. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29718. }
  29719. Array<void*> oldRenderingOps (renderingOps);
  29720. {
  29721. // swap over to the new rendering sequence..
  29722. const ScopedLock sl (renderLock);
  29723. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29724. renderingBuffers.clear();
  29725. for (int i = midiBuffers.size(); --i >= 0;)
  29726. midiBuffers.getUnchecked(i)->clear();
  29727. while (midiBuffers.size() < numMidiBuffersNeeded)
  29728. midiBuffers.add (new MidiBuffer());
  29729. renderingOps = newRenderingOps;
  29730. }
  29731. for (int i = oldRenderingOps.size(); --i >= 0;)
  29732. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29733. }
  29734. void AudioProcessorGraph::handleAsyncUpdate()
  29735. {
  29736. buildRenderingSequence();
  29737. }
  29738. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29739. {
  29740. currentAudioInputBuffer = 0;
  29741. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29742. currentMidiInputBuffer = 0;
  29743. currentMidiOutputBuffer.clear();
  29744. clearRenderingSequence();
  29745. buildRenderingSequence();
  29746. }
  29747. void AudioProcessorGraph::releaseResources()
  29748. {
  29749. for (int i = 0; i < nodes.size(); ++i)
  29750. nodes.getUnchecked(i)->unprepare();
  29751. renderingBuffers.setSize (1, 1);
  29752. midiBuffers.clear();
  29753. currentAudioInputBuffer = 0;
  29754. currentAudioOutputBuffer.setSize (1, 1);
  29755. currentMidiInputBuffer = 0;
  29756. currentMidiOutputBuffer.clear();
  29757. }
  29758. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29759. {
  29760. const int numSamples = buffer.getNumSamples();
  29761. const ScopedLock sl (renderLock);
  29762. currentAudioInputBuffer = &buffer;
  29763. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29764. currentAudioOutputBuffer.clear();
  29765. currentMidiInputBuffer = &midiMessages;
  29766. currentMidiOutputBuffer.clear();
  29767. int i;
  29768. for (i = 0; i < renderingOps.size(); ++i)
  29769. {
  29770. GraphRenderingOps::AudioGraphRenderingOp* const op
  29771. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29772. op->perform (renderingBuffers, midiBuffers, numSamples);
  29773. }
  29774. for (i = 0; i < buffer.getNumChannels(); ++i)
  29775. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29776. midiMessages.clear();
  29777. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29778. }
  29779. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29780. {
  29781. return "Input " + String (channelIndex + 1);
  29782. }
  29783. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29784. {
  29785. return "Output " + String (channelIndex + 1);
  29786. }
  29787. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29788. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29789. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29790. bool AudioProcessorGraph::producesMidi() const { return true; }
  29791. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29792. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29793. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29794. : type (type_),
  29795. graph (0)
  29796. {
  29797. }
  29798. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29799. {
  29800. }
  29801. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29802. {
  29803. switch (type)
  29804. {
  29805. case audioOutputNode: return "Audio Output";
  29806. case audioInputNode: return "Audio Input";
  29807. case midiOutputNode: return "Midi Output";
  29808. case midiInputNode: return "Midi Input";
  29809. default: break;
  29810. }
  29811. return String::empty;
  29812. }
  29813. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29814. {
  29815. d.name = getName();
  29816. d.uid = d.name.hashCode();
  29817. d.category = "I/O devices";
  29818. d.pluginFormatName = "Internal";
  29819. d.manufacturerName = "Raw Material Software";
  29820. d.version = "1.0";
  29821. d.isInstrument = false;
  29822. d.numInputChannels = getNumInputChannels();
  29823. if (type == audioOutputNode && graph != 0)
  29824. d.numInputChannels = graph->getNumInputChannels();
  29825. d.numOutputChannels = getNumOutputChannels();
  29826. if (type == audioInputNode && graph != 0)
  29827. d.numOutputChannels = graph->getNumOutputChannels();
  29828. }
  29829. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29830. {
  29831. jassert (graph != 0);
  29832. }
  29833. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29834. {
  29835. }
  29836. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29837. MidiBuffer& midiMessages)
  29838. {
  29839. jassert (graph != 0);
  29840. switch (type)
  29841. {
  29842. case audioOutputNode:
  29843. {
  29844. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29845. buffer.getNumChannels()); --i >= 0;)
  29846. {
  29847. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29848. }
  29849. break;
  29850. }
  29851. case audioInputNode:
  29852. {
  29853. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29854. buffer.getNumChannels()); --i >= 0;)
  29855. {
  29856. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29857. }
  29858. break;
  29859. }
  29860. case midiOutputNode:
  29861. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29862. break;
  29863. case midiInputNode:
  29864. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29865. break;
  29866. default:
  29867. break;
  29868. }
  29869. }
  29870. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29871. {
  29872. return type == midiOutputNode;
  29873. }
  29874. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29875. {
  29876. return type == midiInputNode;
  29877. }
  29878. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29879. {
  29880. switch (type)
  29881. {
  29882. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29883. case midiOutputNode: return "Midi Output";
  29884. default: break;
  29885. }
  29886. return String::empty;
  29887. }
  29888. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29889. {
  29890. switch (type)
  29891. {
  29892. case audioInputNode: return "Input " + String (channelIndex + 1);
  29893. case midiInputNode: return "Midi Input";
  29894. default: break;
  29895. }
  29896. return String::empty;
  29897. }
  29898. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29899. {
  29900. return type == audioInputNode || type == audioOutputNode;
  29901. }
  29902. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29903. {
  29904. return isInputChannelStereoPair (index);
  29905. }
  29906. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29907. {
  29908. return type == audioInputNode || type == midiInputNode;
  29909. }
  29910. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29911. {
  29912. return type == audioOutputNode || type == midiOutputNode;
  29913. }
  29914. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29915. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29916. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29917. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29918. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29919. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29920. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29921. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29922. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29923. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29924. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29925. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29926. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29927. {
  29928. }
  29929. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29930. {
  29931. }
  29932. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29933. {
  29934. graph = newGraph;
  29935. if (graph != 0)
  29936. {
  29937. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29938. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29939. getSampleRate(),
  29940. getBlockSize());
  29941. updateHostDisplay();
  29942. }
  29943. }
  29944. END_JUCE_NAMESPACE
  29945. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29946. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29947. BEGIN_JUCE_NAMESPACE
  29948. AudioProcessorPlayer::AudioProcessorPlayer()
  29949. : processor (0),
  29950. sampleRate (0),
  29951. blockSize (0),
  29952. isPrepared (false),
  29953. numInputChans (0),
  29954. numOutputChans (0),
  29955. tempBuffer (1, 1)
  29956. {
  29957. }
  29958. AudioProcessorPlayer::~AudioProcessorPlayer()
  29959. {
  29960. setProcessor (0);
  29961. }
  29962. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29963. {
  29964. if (processor != processorToPlay)
  29965. {
  29966. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29967. {
  29968. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29969. sampleRate, blockSize);
  29970. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29971. }
  29972. AudioProcessor* oldOne;
  29973. {
  29974. const ScopedLock sl (lock);
  29975. oldOne = isPrepared ? processor : 0;
  29976. processor = processorToPlay;
  29977. isPrepared = true;
  29978. }
  29979. if (oldOne != 0)
  29980. oldOne->releaseResources();
  29981. }
  29982. }
  29983. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29984. const int numInputChannels,
  29985. float** const outputChannelData,
  29986. const int numOutputChannels,
  29987. const int numSamples)
  29988. {
  29989. // these should have been prepared by audioDeviceAboutToStart()...
  29990. jassert (sampleRate > 0 && blockSize > 0);
  29991. incomingMidi.clear();
  29992. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29993. int i, totalNumChans = 0;
  29994. if (numInputChannels > numOutputChannels)
  29995. {
  29996. // if there aren't enough output channels for the number of
  29997. // inputs, we need to create some temporary extra ones (can't
  29998. // use the input data in case it gets written to)
  29999. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30000. false, false, true);
  30001. for (i = 0; i < numOutputChannels; ++i)
  30002. {
  30003. channels[totalNumChans] = outputChannelData[i];
  30004. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30005. ++totalNumChans;
  30006. }
  30007. for (i = numOutputChannels; i < numInputChannels; ++i)
  30008. {
  30009. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30010. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30011. ++totalNumChans;
  30012. }
  30013. }
  30014. else
  30015. {
  30016. for (i = 0; i < numInputChannels; ++i)
  30017. {
  30018. channels[totalNumChans] = outputChannelData[i];
  30019. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30020. ++totalNumChans;
  30021. }
  30022. for (i = numInputChannels; i < numOutputChannels; ++i)
  30023. {
  30024. channels[totalNumChans] = outputChannelData[i];
  30025. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30026. ++totalNumChans;
  30027. }
  30028. }
  30029. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30030. const ScopedLock sl (lock);
  30031. if (processor != 0)
  30032. {
  30033. const ScopedLock sl2 (processor->getCallbackLock());
  30034. if (processor->isSuspended())
  30035. {
  30036. for (i = 0; i < numOutputChannels; ++i)
  30037. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30038. }
  30039. else
  30040. {
  30041. processor->processBlock (buffer, incomingMidi);
  30042. }
  30043. }
  30044. }
  30045. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30046. {
  30047. const ScopedLock sl (lock);
  30048. sampleRate = device->getCurrentSampleRate();
  30049. blockSize = device->getCurrentBufferSizeSamples();
  30050. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30051. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30052. messageCollector.reset (sampleRate);
  30053. zeromem (channels, sizeof (channels));
  30054. if (processor != 0)
  30055. {
  30056. if (isPrepared)
  30057. processor->releaseResources();
  30058. AudioProcessor* const oldProcessor = processor;
  30059. setProcessor (0);
  30060. setProcessor (oldProcessor);
  30061. }
  30062. }
  30063. void AudioProcessorPlayer::audioDeviceStopped()
  30064. {
  30065. const ScopedLock sl (lock);
  30066. if (processor != 0 && isPrepared)
  30067. processor->releaseResources();
  30068. sampleRate = 0.0;
  30069. blockSize = 0;
  30070. isPrepared = false;
  30071. tempBuffer.setSize (1, 1);
  30072. }
  30073. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30074. {
  30075. messageCollector.addMessageToQueue (message);
  30076. }
  30077. END_JUCE_NAMESPACE
  30078. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30079. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30080. BEGIN_JUCE_NAMESPACE
  30081. class ProcessorParameterPropertyComp : public PropertyComponent,
  30082. public AudioProcessorListener,
  30083. public Timer
  30084. {
  30085. public:
  30086. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30087. : PropertyComponent (name),
  30088. owner (owner_),
  30089. index (index_),
  30090. paramHasChanged (false),
  30091. slider (owner_, index_)
  30092. {
  30093. startTimer (100);
  30094. addAndMakeVisible (&slider);
  30095. owner_.addListener (this);
  30096. }
  30097. ~ProcessorParameterPropertyComp()
  30098. {
  30099. owner.removeListener (this);
  30100. }
  30101. void refresh()
  30102. {
  30103. paramHasChanged = false;
  30104. slider.setValue (owner.getParameter (index), false);
  30105. }
  30106. void audioProcessorChanged (AudioProcessor*) {}
  30107. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30108. {
  30109. if (parameterIndex == index)
  30110. paramHasChanged = true;
  30111. }
  30112. void timerCallback()
  30113. {
  30114. if (paramHasChanged)
  30115. {
  30116. refresh();
  30117. startTimer (1000 / 50);
  30118. }
  30119. else
  30120. {
  30121. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30122. }
  30123. }
  30124. private:
  30125. class ParamSlider : public Slider
  30126. {
  30127. public:
  30128. ParamSlider (AudioProcessor& owner_, const int index_)
  30129. : owner (owner_),
  30130. index (index_)
  30131. {
  30132. setRange (0.0, 1.0, 0.0);
  30133. setSliderStyle (Slider::LinearBar);
  30134. setTextBoxIsEditable (false);
  30135. setScrollWheelEnabled (false);
  30136. }
  30137. void valueChanged()
  30138. {
  30139. const float newVal = (float) getValue();
  30140. if (owner.getParameter (index) != newVal)
  30141. owner.setParameter (index, newVal);
  30142. }
  30143. const String getTextFromValue (double /*value*/)
  30144. {
  30145. return owner.getParameterText (index);
  30146. }
  30147. private:
  30148. AudioProcessor& owner;
  30149. const int index;
  30150. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  30151. };
  30152. AudioProcessor& owner;
  30153. const int index;
  30154. bool volatile paramHasChanged;
  30155. ParamSlider slider;
  30156. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  30157. };
  30158. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30159. : AudioProcessorEditor (owner_)
  30160. {
  30161. jassert (owner_ != 0);
  30162. setOpaque (true);
  30163. addAndMakeVisible (&panel);
  30164. Array <PropertyComponent*> params;
  30165. const int numParams = owner_->getNumParameters();
  30166. int totalHeight = 0;
  30167. for (int i = 0; i < numParams; ++i)
  30168. {
  30169. String name (owner_->getParameterName (i));
  30170. if (name.trim().isEmpty())
  30171. name = "Unnamed";
  30172. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30173. params.add (pc);
  30174. totalHeight += pc->getPreferredHeight();
  30175. }
  30176. panel.addProperties (params);
  30177. setSize (400, jlimit (25, 400, totalHeight));
  30178. }
  30179. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30180. {
  30181. }
  30182. void GenericAudioProcessorEditor::paint (Graphics& g)
  30183. {
  30184. g.fillAll (Colours::white);
  30185. }
  30186. void GenericAudioProcessorEditor::resized()
  30187. {
  30188. panel.setBounds (getLocalBounds());
  30189. }
  30190. END_JUCE_NAMESPACE
  30191. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30192. /*** Start of inlined file: juce_Sampler.cpp ***/
  30193. BEGIN_JUCE_NAMESPACE
  30194. SamplerSound::SamplerSound (const String& name_,
  30195. AudioFormatReader& source,
  30196. const BigInteger& midiNotes_,
  30197. const int midiNoteForNormalPitch,
  30198. const double attackTimeSecs,
  30199. const double releaseTimeSecs,
  30200. const double maxSampleLengthSeconds)
  30201. : name (name_),
  30202. midiNotes (midiNotes_),
  30203. midiRootNote (midiNoteForNormalPitch)
  30204. {
  30205. sourceSampleRate = source.sampleRate;
  30206. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30207. {
  30208. length = 0;
  30209. attackSamples = 0;
  30210. releaseSamples = 0;
  30211. }
  30212. else
  30213. {
  30214. length = jmin ((int) source.lengthInSamples,
  30215. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30216. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30217. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30218. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30219. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30220. }
  30221. }
  30222. SamplerSound::~SamplerSound()
  30223. {
  30224. }
  30225. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30226. {
  30227. return midiNotes [midiNoteNumber];
  30228. }
  30229. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30230. {
  30231. return true;
  30232. }
  30233. SamplerVoice::SamplerVoice()
  30234. : pitchRatio (0.0),
  30235. sourceSamplePosition (0.0),
  30236. lgain (0.0f),
  30237. rgain (0.0f),
  30238. isInAttack (false),
  30239. isInRelease (false)
  30240. {
  30241. }
  30242. SamplerVoice::~SamplerVoice()
  30243. {
  30244. }
  30245. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30246. {
  30247. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30248. }
  30249. void SamplerVoice::startNote (const int midiNoteNumber,
  30250. const float velocity,
  30251. SynthesiserSound* s,
  30252. const int /*currentPitchWheelPosition*/)
  30253. {
  30254. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30255. jassert (sound != 0); // this object can only play SamplerSounds!
  30256. if (sound != 0)
  30257. {
  30258. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30259. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30260. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30261. sourceSamplePosition = 0.0;
  30262. lgain = velocity;
  30263. rgain = velocity;
  30264. isInAttack = (sound->attackSamples > 0);
  30265. isInRelease = false;
  30266. if (isInAttack)
  30267. {
  30268. attackReleaseLevel = 0.0f;
  30269. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30270. }
  30271. else
  30272. {
  30273. attackReleaseLevel = 1.0f;
  30274. attackDelta = 0.0f;
  30275. }
  30276. if (sound->releaseSamples > 0)
  30277. {
  30278. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30279. }
  30280. else
  30281. {
  30282. releaseDelta = 0.0f;
  30283. }
  30284. }
  30285. }
  30286. void SamplerVoice::stopNote (const bool allowTailOff)
  30287. {
  30288. if (allowTailOff)
  30289. {
  30290. isInAttack = false;
  30291. isInRelease = true;
  30292. }
  30293. else
  30294. {
  30295. clearCurrentNote();
  30296. }
  30297. }
  30298. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30299. {
  30300. }
  30301. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30302. const int /*newValue*/)
  30303. {
  30304. }
  30305. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30306. {
  30307. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30308. if (playingSound != 0)
  30309. {
  30310. const float* const inL = playingSound->data->getSampleData (0, 0);
  30311. const float* const inR = playingSound->data->getNumChannels() > 1
  30312. ? playingSound->data->getSampleData (1, 0) : 0;
  30313. float* outL = outputBuffer.getSampleData (0, startSample);
  30314. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30315. while (--numSamples >= 0)
  30316. {
  30317. const int pos = (int) sourceSamplePosition;
  30318. const float alpha = (float) (sourceSamplePosition - pos);
  30319. const float invAlpha = 1.0f - alpha;
  30320. // just using a very simple linear interpolation here..
  30321. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30322. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30323. : l;
  30324. l *= lgain;
  30325. r *= rgain;
  30326. if (isInAttack)
  30327. {
  30328. l *= attackReleaseLevel;
  30329. r *= attackReleaseLevel;
  30330. attackReleaseLevel += attackDelta;
  30331. if (attackReleaseLevel >= 1.0f)
  30332. {
  30333. attackReleaseLevel = 1.0f;
  30334. isInAttack = false;
  30335. }
  30336. }
  30337. else if (isInRelease)
  30338. {
  30339. l *= attackReleaseLevel;
  30340. r *= attackReleaseLevel;
  30341. attackReleaseLevel += releaseDelta;
  30342. if (attackReleaseLevel <= 0.0f)
  30343. {
  30344. stopNote (false);
  30345. break;
  30346. }
  30347. }
  30348. if (outR != 0)
  30349. {
  30350. *outL++ += l;
  30351. *outR++ += r;
  30352. }
  30353. else
  30354. {
  30355. *outL++ += (l + r) * 0.5f;
  30356. }
  30357. sourceSamplePosition += pitchRatio;
  30358. if (sourceSamplePosition > playingSound->length)
  30359. {
  30360. stopNote (false);
  30361. break;
  30362. }
  30363. }
  30364. }
  30365. }
  30366. END_JUCE_NAMESPACE
  30367. /*** End of inlined file: juce_Sampler.cpp ***/
  30368. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30369. BEGIN_JUCE_NAMESPACE
  30370. SynthesiserSound::SynthesiserSound()
  30371. {
  30372. }
  30373. SynthesiserSound::~SynthesiserSound()
  30374. {
  30375. }
  30376. SynthesiserVoice::SynthesiserVoice()
  30377. : currentSampleRate (44100.0),
  30378. currentlyPlayingNote (-1),
  30379. noteOnTime (0),
  30380. currentlyPlayingSound (0)
  30381. {
  30382. }
  30383. SynthesiserVoice::~SynthesiserVoice()
  30384. {
  30385. }
  30386. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30387. {
  30388. return currentlyPlayingSound != 0
  30389. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30390. }
  30391. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30392. {
  30393. currentSampleRate = newRate;
  30394. }
  30395. void SynthesiserVoice::clearCurrentNote()
  30396. {
  30397. currentlyPlayingNote = -1;
  30398. currentlyPlayingSound = 0;
  30399. }
  30400. Synthesiser::Synthesiser()
  30401. : sampleRate (0),
  30402. lastNoteOnCounter (0),
  30403. shouldStealNotes (true)
  30404. {
  30405. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30406. lastPitchWheelValues[i] = 0x2000;
  30407. }
  30408. Synthesiser::~Synthesiser()
  30409. {
  30410. }
  30411. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30412. {
  30413. const ScopedLock sl (lock);
  30414. return voices [index];
  30415. }
  30416. void Synthesiser::clearVoices()
  30417. {
  30418. const ScopedLock sl (lock);
  30419. voices.clear();
  30420. }
  30421. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30422. {
  30423. const ScopedLock sl (lock);
  30424. voices.add (newVoice);
  30425. }
  30426. void Synthesiser::removeVoice (const int index)
  30427. {
  30428. const ScopedLock sl (lock);
  30429. voices.remove (index);
  30430. }
  30431. void Synthesiser::clearSounds()
  30432. {
  30433. const ScopedLock sl (lock);
  30434. sounds.clear();
  30435. }
  30436. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30437. {
  30438. const ScopedLock sl (lock);
  30439. sounds.add (newSound);
  30440. }
  30441. void Synthesiser::removeSound (const int index)
  30442. {
  30443. const ScopedLock sl (lock);
  30444. sounds.remove (index);
  30445. }
  30446. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30447. {
  30448. shouldStealNotes = shouldStealNotes_;
  30449. }
  30450. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30451. {
  30452. if (sampleRate != newRate)
  30453. {
  30454. const ScopedLock sl (lock);
  30455. allNotesOff (0, false);
  30456. sampleRate = newRate;
  30457. for (int i = voices.size(); --i >= 0;)
  30458. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30459. }
  30460. }
  30461. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30462. const MidiBuffer& midiData,
  30463. int startSample,
  30464. int numSamples)
  30465. {
  30466. // must set the sample rate before using this!
  30467. jassert (sampleRate != 0);
  30468. const ScopedLock sl (lock);
  30469. MidiBuffer::Iterator midiIterator (midiData);
  30470. midiIterator.setNextSamplePosition (startSample);
  30471. MidiMessage m (0xf4, 0.0);
  30472. while (numSamples > 0)
  30473. {
  30474. int midiEventPos;
  30475. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30476. && midiEventPos < startSample + numSamples;
  30477. const int numThisTime = useEvent ? midiEventPos - startSample
  30478. : numSamples;
  30479. if (numThisTime > 0)
  30480. {
  30481. for (int i = voices.size(); --i >= 0;)
  30482. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30483. }
  30484. if (useEvent)
  30485. {
  30486. if (m.isNoteOn())
  30487. {
  30488. const int channel = m.getChannel();
  30489. noteOn (channel,
  30490. m.getNoteNumber(),
  30491. m.getFloatVelocity());
  30492. }
  30493. else if (m.isNoteOff())
  30494. {
  30495. noteOff (m.getChannel(),
  30496. m.getNoteNumber(),
  30497. true);
  30498. }
  30499. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30500. {
  30501. allNotesOff (m.getChannel(), true);
  30502. }
  30503. else if (m.isPitchWheel())
  30504. {
  30505. const int channel = m.getChannel();
  30506. const int wheelPos = m.getPitchWheelValue();
  30507. lastPitchWheelValues [channel - 1] = wheelPos;
  30508. handlePitchWheel (channel, wheelPos);
  30509. }
  30510. else if (m.isController())
  30511. {
  30512. handleController (m.getChannel(),
  30513. m.getControllerNumber(),
  30514. m.getControllerValue());
  30515. }
  30516. }
  30517. startSample += numThisTime;
  30518. numSamples -= numThisTime;
  30519. }
  30520. }
  30521. void Synthesiser::noteOn (const int midiChannel,
  30522. const int midiNoteNumber,
  30523. const float velocity)
  30524. {
  30525. const ScopedLock sl (lock);
  30526. for (int i = sounds.size(); --i >= 0;)
  30527. {
  30528. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30529. if (sound->appliesToNote (midiNoteNumber)
  30530. && sound->appliesToChannel (midiChannel))
  30531. {
  30532. startVoice (findFreeVoice (sound, shouldStealNotes),
  30533. sound, midiChannel, midiNoteNumber, velocity);
  30534. }
  30535. }
  30536. }
  30537. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30538. SynthesiserSound* const sound,
  30539. const int midiChannel,
  30540. const int midiNoteNumber,
  30541. const float velocity)
  30542. {
  30543. if (voice != 0 && sound != 0)
  30544. {
  30545. if (voice->currentlyPlayingSound != 0)
  30546. voice->stopNote (false);
  30547. voice->startNote (midiNoteNumber,
  30548. velocity,
  30549. sound,
  30550. lastPitchWheelValues [midiChannel - 1]);
  30551. voice->currentlyPlayingNote = midiNoteNumber;
  30552. voice->noteOnTime = ++lastNoteOnCounter;
  30553. voice->currentlyPlayingSound = sound;
  30554. }
  30555. }
  30556. void Synthesiser::noteOff (const int midiChannel,
  30557. const int midiNoteNumber,
  30558. const bool allowTailOff)
  30559. {
  30560. const ScopedLock sl (lock);
  30561. for (int i = voices.size(); --i >= 0;)
  30562. {
  30563. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30564. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30565. {
  30566. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30567. if (sound != 0
  30568. && sound->appliesToNote (midiNoteNumber)
  30569. && sound->appliesToChannel (midiChannel))
  30570. {
  30571. voice->stopNote (allowTailOff);
  30572. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30573. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30574. }
  30575. }
  30576. }
  30577. }
  30578. void Synthesiser::allNotesOff (const int midiChannel,
  30579. const bool allowTailOff)
  30580. {
  30581. const ScopedLock sl (lock);
  30582. for (int i = voices.size(); --i >= 0;)
  30583. {
  30584. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30585. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30586. voice->stopNote (allowTailOff);
  30587. }
  30588. }
  30589. void Synthesiser::handlePitchWheel (const int midiChannel,
  30590. const int wheelValue)
  30591. {
  30592. const ScopedLock sl (lock);
  30593. for (int i = voices.size(); --i >= 0;)
  30594. {
  30595. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30596. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30597. {
  30598. voice->pitchWheelMoved (wheelValue);
  30599. }
  30600. }
  30601. }
  30602. void Synthesiser::handleController (const int midiChannel,
  30603. const int controllerNumber,
  30604. const int controllerValue)
  30605. {
  30606. const ScopedLock sl (lock);
  30607. for (int i = voices.size(); --i >= 0;)
  30608. {
  30609. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30610. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30611. voice->controllerMoved (controllerNumber, controllerValue);
  30612. }
  30613. }
  30614. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30615. const bool stealIfNoneAvailable) const
  30616. {
  30617. const ScopedLock sl (lock);
  30618. for (int i = voices.size(); --i >= 0;)
  30619. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30620. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30621. return voices.getUnchecked (i);
  30622. if (stealIfNoneAvailable)
  30623. {
  30624. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30625. SynthesiserVoice* oldest = 0;
  30626. for (int i = voices.size(); --i >= 0;)
  30627. {
  30628. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30629. if (voice->canPlaySound (soundToPlay)
  30630. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30631. oldest = voice;
  30632. }
  30633. jassert (oldest != 0);
  30634. return oldest;
  30635. }
  30636. return 0;
  30637. }
  30638. END_JUCE_NAMESPACE
  30639. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30640. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30641. BEGIN_JUCE_NAMESPACE
  30642. // special message of our own with a string in it
  30643. class ActionMessage : public Message
  30644. {
  30645. public:
  30646. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30647. : message (messageText)
  30648. {
  30649. pointerParameter = listener_;
  30650. }
  30651. const String message;
  30652. private:
  30653. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30654. };
  30655. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30656. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30657. {
  30658. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30659. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30660. if (owner->actionListeners.contains (target))
  30661. target->actionListenerCallback (am.message);
  30662. }
  30663. ActionBroadcaster::ActionBroadcaster()
  30664. {
  30665. // are you trying to create this object before or after juce has been intialised??
  30666. jassert (MessageManager::instance != 0);
  30667. callback.owner = this;
  30668. }
  30669. ActionBroadcaster::~ActionBroadcaster()
  30670. {
  30671. // all event-based objects must be deleted BEFORE juce is shut down!
  30672. jassert (MessageManager::instance != 0);
  30673. }
  30674. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30675. {
  30676. const ScopedLock sl (actionListenerLock);
  30677. if (listener != 0)
  30678. actionListeners.add (listener);
  30679. }
  30680. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30681. {
  30682. const ScopedLock sl (actionListenerLock);
  30683. actionListeners.removeValue (listener);
  30684. }
  30685. void ActionBroadcaster::removeAllActionListeners()
  30686. {
  30687. const ScopedLock sl (actionListenerLock);
  30688. actionListeners.clear();
  30689. }
  30690. void ActionBroadcaster::sendActionMessage (const String& message) const
  30691. {
  30692. const ScopedLock sl (actionListenerLock);
  30693. for (int i = actionListeners.size(); --i >= 0;)
  30694. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30695. }
  30696. END_JUCE_NAMESPACE
  30697. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30698. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30699. BEGIN_JUCE_NAMESPACE
  30700. class AsyncUpdaterMessage : public CallbackMessage
  30701. {
  30702. public:
  30703. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30704. : owner (owner_)
  30705. {
  30706. }
  30707. void messageCallback()
  30708. {
  30709. if (shouldDeliver.compareAndSetBool (0, 1))
  30710. owner.handleAsyncUpdate();
  30711. }
  30712. Atomic<int> shouldDeliver;
  30713. private:
  30714. AsyncUpdater& owner;
  30715. };
  30716. AsyncUpdater::AsyncUpdater()
  30717. {
  30718. message = new AsyncUpdaterMessage (*this);
  30719. }
  30720. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30721. {
  30722. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30723. }
  30724. AsyncUpdater::~AsyncUpdater()
  30725. {
  30726. // You're deleting this object with a background thread while there's an update
  30727. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30728. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30729. // deleting this object, or find some other way to avoid such a race condition.
  30730. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30731. getDeliveryFlag().set (0);
  30732. }
  30733. void AsyncUpdater::triggerAsyncUpdate()
  30734. {
  30735. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30736. message->post();
  30737. }
  30738. void AsyncUpdater::cancelPendingUpdate() throw()
  30739. {
  30740. getDeliveryFlag().set (0);
  30741. }
  30742. void AsyncUpdater::handleUpdateNowIfNeeded()
  30743. {
  30744. // This can only be called by the event thread.
  30745. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30746. if (getDeliveryFlag().exchange (0) != 0)
  30747. handleAsyncUpdate();
  30748. }
  30749. bool AsyncUpdater::isUpdatePending() const throw()
  30750. {
  30751. return getDeliveryFlag().value != 0;
  30752. }
  30753. END_JUCE_NAMESPACE
  30754. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30755. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30756. BEGIN_JUCE_NAMESPACE
  30757. ChangeBroadcaster::ChangeBroadcaster() throw()
  30758. {
  30759. // are you trying to create this object before or after juce has been intialised??
  30760. jassert (MessageManager::instance != 0);
  30761. callback.owner = this;
  30762. }
  30763. ChangeBroadcaster::~ChangeBroadcaster()
  30764. {
  30765. // all event-based objects must be deleted BEFORE juce is shut down!
  30766. jassert (MessageManager::instance != 0);
  30767. }
  30768. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30769. {
  30770. // Listeners can only be safely added when the event thread is locked
  30771. // You can use a MessageManagerLock if you need to call this from another thread.
  30772. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30773. changeListeners.add (listener);
  30774. }
  30775. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30776. {
  30777. // Listeners can only be safely added when the event thread is locked
  30778. // You can use a MessageManagerLock if you need to call this from another thread.
  30779. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30780. changeListeners.remove (listener);
  30781. }
  30782. void ChangeBroadcaster::removeAllChangeListeners()
  30783. {
  30784. // Listeners can only be safely added when the event thread is locked
  30785. // You can use a MessageManagerLock if you need to call this from another thread.
  30786. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30787. changeListeners.clear();
  30788. }
  30789. void ChangeBroadcaster::sendChangeMessage()
  30790. {
  30791. if (changeListeners.size() > 0)
  30792. callback.triggerAsyncUpdate();
  30793. }
  30794. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30795. {
  30796. // This can only be called by the event thread.
  30797. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30798. callback.cancelPendingUpdate();
  30799. callListeners();
  30800. }
  30801. void ChangeBroadcaster::dispatchPendingMessages()
  30802. {
  30803. callback.handleUpdateNowIfNeeded();
  30804. }
  30805. void ChangeBroadcaster::callListeners()
  30806. {
  30807. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30808. }
  30809. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30810. : owner (0)
  30811. {
  30812. }
  30813. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30814. {
  30815. jassert (owner != 0);
  30816. owner->callListeners();
  30817. }
  30818. END_JUCE_NAMESPACE
  30819. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30820. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30821. BEGIN_JUCE_NAMESPACE
  30822. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30823. const uint32 magicMessageHeaderNumber)
  30824. : Thread ("Juce IPC connection"),
  30825. callbackConnectionState (false),
  30826. useMessageThread (callbacksOnMessageThread),
  30827. magicMessageHeader (magicMessageHeaderNumber),
  30828. pipeReceiveMessageTimeout (-1)
  30829. {
  30830. }
  30831. InterprocessConnection::~InterprocessConnection()
  30832. {
  30833. callbackConnectionState = false;
  30834. disconnect();
  30835. }
  30836. bool InterprocessConnection::connectToSocket (const String& hostName,
  30837. const int portNumber,
  30838. const int timeOutMillisecs)
  30839. {
  30840. disconnect();
  30841. const ScopedLock sl (pipeAndSocketLock);
  30842. socket = new StreamingSocket();
  30843. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30844. {
  30845. connectionMadeInt();
  30846. startThread();
  30847. return true;
  30848. }
  30849. else
  30850. {
  30851. socket = 0;
  30852. return false;
  30853. }
  30854. }
  30855. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30856. const int pipeReceiveMessageTimeoutMs)
  30857. {
  30858. disconnect();
  30859. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30860. if (newPipe->openExisting (pipeName))
  30861. {
  30862. const ScopedLock sl (pipeAndSocketLock);
  30863. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30864. initialiseWithPipe (newPipe.release());
  30865. return true;
  30866. }
  30867. return false;
  30868. }
  30869. bool InterprocessConnection::createPipe (const String& pipeName,
  30870. const int pipeReceiveMessageTimeoutMs)
  30871. {
  30872. disconnect();
  30873. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30874. if (newPipe->createNewPipe (pipeName))
  30875. {
  30876. const ScopedLock sl (pipeAndSocketLock);
  30877. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30878. initialiseWithPipe (newPipe.release());
  30879. return true;
  30880. }
  30881. return false;
  30882. }
  30883. void InterprocessConnection::disconnect()
  30884. {
  30885. if (socket != 0)
  30886. socket->close();
  30887. if (pipe != 0)
  30888. {
  30889. pipe->cancelPendingReads();
  30890. pipe->close();
  30891. }
  30892. stopThread (4000);
  30893. {
  30894. const ScopedLock sl (pipeAndSocketLock);
  30895. socket = 0;
  30896. pipe = 0;
  30897. }
  30898. connectionLostInt();
  30899. }
  30900. bool InterprocessConnection::isConnected() const
  30901. {
  30902. const ScopedLock sl (pipeAndSocketLock);
  30903. return ((socket != 0 && socket->isConnected())
  30904. || (pipe != 0 && pipe->isOpen()))
  30905. && isThreadRunning();
  30906. }
  30907. const String InterprocessConnection::getConnectedHostName() const
  30908. {
  30909. if (pipe != 0)
  30910. {
  30911. return "localhost";
  30912. }
  30913. else if (socket != 0)
  30914. {
  30915. if (! socket->isLocal())
  30916. return socket->getHostName();
  30917. return "localhost";
  30918. }
  30919. return String::empty;
  30920. }
  30921. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30922. {
  30923. uint32 messageHeader[2];
  30924. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30925. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30926. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30927. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30928. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30929. size_t bytesWritten = 0;
  30930. const ScopedLock sl (pipeAndSocketLock);
  30931. if (socket != 0)
  30932. {
  30933. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30934. }
  30935. else if (pipe != 0)
  30936. {
  30937. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30938. }
  30939. if (bytesWritten < 0)
  30940. {
  30941. // error..
  30942. return false;
  30943. }
  30944. return (bytesWritten == messageData.getSize());
  30945. }
  30946. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30947. {
  30948. jassert (socket == 0);
  30949. socket = socket_;
  30950. connectionMadeInt();
  30951. startThread();
  30952. }
  30953. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30954. {
  30955. jassert (pipe == 0);
  30956. pipe = pipe_;
  30957. connectionMadeInt();
  30958. startThread();
  30959. }
  30960. const int messageMagicNumber = 0xb734128b;
  30961. void InterprocessConnection::handleMessage (const Message& message)
  30962. {
  30963. if (message.intParameter1 == messageMagicNumber)
  30964. {
  30965. switch (message.intParameter2)
  30966. {
  30967. case 0:
  30968. {
  30969. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30970. messageReceived (*data);
  30971. break;
  30972. }
  30973. case 1:
  30974. connectionMade();
  30975. break;
  30976. case 2:
  30977. connectionLost();
  30978. break;
  30979. }
  30980. }
  30981. }
  30982. void InterprocessConnection::connectionMadeInt()
  30983. {
  30984. if (! callbackConnectionState)
  30985. {
  30986. callbackConnectionState = true;
  30987. if (useMessageThread)
  30988. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30989. else
  30990. connectionMade();
  30991. }
  30992. }
  30993. void InterprocessConnection::connectionLostInt()
  30994. {
  30995. if (callbackConnectionState)
  30996. {
  30997. callbackConnectionState = false;
  30998. if (useMessageThread)
  30999. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31000. else
  31001. connectionLost();
  31002. }
  31003. }
  31004. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31005. {
  31006. jassert (callbackConnectionState);
  31007. if (useMessageThread)
  31008. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31009. else
  31010. messageReceived (data);
  31011. }
  31012. bool InterprocessConnection::readNextMessageInt()
  31013. {
  31014. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31015. uint32 messageHeader[2];
  31016. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31017. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31018. if (bytes == sizeof (messageHeader)
  31019. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31020. {
  31021. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31022. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31023. {
  31024. MemoryBlock messageData (bytesInMessage, true);
  31025. int bytesRead = 0;
  31026. while (bytesInMessage > 0)
  31027. {
  31028. if (threadShouldExit())
  31029. return false;
  31030. const int numThisTime = jmin (bytesInMessage, 65536);
  31031. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31032. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31033. if (bytesIn <= 0)
  31034. break;
  31035. bytesRead += bytesIn;
  31036. bytesInMessage -= bytesIn;
  31037. }
  31038. if (bytesRead >= 0)
  31039. deliverDataInt (messageData);
  31040. }
  31041. }
  31042. else if (bytes < 0)
  31043. {
  31044. {
  31045. const ScopedLock sl (pipeAndSocketLock);
  31046. socket = 0;
  31047. }
  31048. connectionLostInt();
  31049. return false;
  31050. }
  31051. return true;
  31052. }
  31053. void InterprocessConnection::run()
  31054. {
  31055. while (! threadShouldExit())
  31056. {
  31057. if (socket != 0)
  31058. {
  31059. const int ready = socket->waitUntilReady (true, 0);
  31060. if (ready < 0)
  31061. {
  31062. {
  31063. const ScopedLock sl (pipeAndSocketLock);
  31064. socket = 0;
  31065. }
  31066. connectionLostInt();
  31067. break;
  31068. }
  31069. else if (ready > 0)
  31070. {
  31071. if (! readNextMessageInt())
  31072. break;
  31073. }
  31074. else
  31075. {
  31076. Thread::sleep (2);
  31077. }
  31078. }
  31079. else if (pipe != 0)
  31080. {
  31081. if (! pipe->isOpen())
  31082. {
  31083. {
  31084. const ScopedLock sl (pipeAndSocketLock);
  31085. pipe = 0;
  31086. }
  31087. connectionLostInt();
  31088. break;
  31089. }
  31090. else
  31091. {
  31092. if (! readNextMessageInt())
  31093. break;
  31094. }
  31095. }
  31096. else
  31097. {
  31098. break;
  31099. }
  31100. }
  31101. }
  31102. END_JUCE_NAMESPACE
  31103. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31104. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31105. BEGIN_JUCE_NAMESPACE
  31106. InterprocessConnectionServer::InterprocessConnectionServer()
  31107. : Thread ("Juce IPC server")
  31108. {
  31109. }
  31110. InterprocessConnectionServer::~InterprocessConnectionServer()
  31111. {
  31112. stop();
  31113. }
  31114. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31115. {
  31116. stop();
  31117. socket = new StreamingSocket();
  31118. if (socket->createListener (portNumber))
  31119. {
  31120. startThread();
  31121. return true;
  31122. }
  31123. socket = 0;
  31124. return false;
  31125. }
  31126. void InterprocessConnectionServer::stop()
  31127. {
  31128. signalThreadShouldExit();
  31129. if (socket != 0)
  31130. socket->close();
  31131. stopThread (4000);
  31132. socket = 0;
  31133. }
  31134. void InterprocessConnectionServer::run()
  31135. {
  31136. while ((! threadShouldExit()) && socket != 0)
  31137. {
  31138. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31139. if (clientSocket != 0)
  31140. {
  31141. InterprocessConnection* newConnection = createConnectionObject();
  31142. if (newConnection != 0)
  31143. newConnection->initialiseWithSocket (clientSocket.release());
  31144. }
  31145. }
  31146. }
  31147. END_JUCE_NAMESPACE
  31148. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31149. /*** Start of inlined file: juce_Message.cpp ***/
  31150. BEGIN_JUCE_NAMESPACE
  31151. Message::Message() throw()
  31152. : intParameter1 (0),
  31153. intParameter2 (0),
  31154. intParameter3 (0),
  31155. pointerParameter (0),
  31156. messageRecipient (0)
  31157. {
  31158. }
  31159. Message::Message (const int intParameter1_,
  31160. const int intParameter2_,
  31161. const int intParameter3_,
  31162. void* const pointerParameter_) throw()
  31163. : intParameter1 (intParameter1_),
  31164. intParameter2 (intParameter2_),
  31165. intParameter3 (intParameter3_),
  31166. pointerParameter (pointerParameter_),
  31167. messageRecipient (0)
  31168. {
  31169. }
  31170. Message::~Message()
  31171. {
  31172. }
  31173. END_JUCE_NAMESPACE
  31174. /*** End of inlined file: juce_Message.cpp ***/
  31175. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31176. BEGIN_JUCE_NAMESPACE
  31177. MessageListener::MessageListener() throw()
  31178. {
  31179. // are you trying to create a messagelistener before or after juce has been intialised??
  31180. jassert (MessageManager::instance != 0);
  31181. if (MessageManager::instance != 0)
  31182. MessageManager::instance->messageListeners.add (this);
  31183. }
  31184. MessageListener::~MessageListener()
  31185. {
  31186. if (MessageManager::instance != 0)
  31187. MessageManager::instance->messageListeners.removeValue (this);
  31188. }
  31189. void MessageListener::postMessage (Message* const message) const throw()
  31190. {
  31191. message->messageRecipient = const_cast <MessageListener*> (this);
  31192. if (MessageManager::instance == 0)
  31193. MessageManager::getInstance();
  31194. MessageManager::instance->postMessageToQueue (message);
  31195. }
  31196. bool MessageListener::isValidMessageListener() const throw()
  31197. {
  31198. return (MessageManager::instance != 0)
  31199. && MessageManager::instance->messageListeners.contains (this);
  31200. }
  31201. END_JUCE_NAMESPACE
  31202. /*** End of inlined file: juce_MessageListener.cpp ***/
  31203. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31204. BEGIN_JUCE_NAMESPACE
  31205. // platform-specific functions..
  31206. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31207. bool juce_postMessageToSystemQueue (Message* message);
  31208. MessageManager* MessageManager::instance = 0;
  31209. static const int quitMessageId = 0xfffff321;
  31210. MessageManager::MessageManager() throw()
  31211. : quitMessagePosted (false),
  31212. quitMessageReceived (false),
  31213. threadWithLock (0)
  31214. {
  31215. messageThreadId = Thread::getCurrentThreadId();
  31216. if (JUCEApplication::isStandaloneApp())
  31217. Thread::setCurrentThreadName ("Juce Message Thread");
  31218. }
  31219. MessageManager::~MessageManager() throw()
  31220. {
  31221. broadcaster = 0;
  31222. doPlatformSpecificShutdown();
  31223. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31224. jassert (messageListeners.size() == 0);
  31225. jassert (instance == this);
  31226. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31227. }
  31228. MessageManager* MessageManager::getInstance() throw()
  31229. {
  31230. if (instance == 0)
  31231. {
  31232. instance = new MessageManager();
  31233. doPlatformSpecificInitialisation();
  31234. }
  31235. return instance;
  31236. }
  31237. void MessageManager::postMessageToQueue (Message* const message)
  31238. {
  31239. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31240. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31241. }
  31242. CallbackMessage::CallbackMessage() throw() {}
  31243. CallbackMessage::~CallbackMessage() {}
  31244. void CallbackMessage::post()
  31245. {
  31246. if (MessageManager::instance != 0)
  31247. MessageManager::instance->postMessageToQueue (this);
  31248. }
  31249. // not for public use..
  31250. void MessageManager::deliverMessage (Message* const message)
  31251. {
  31252. JUCE_TRY
  31253. {
  31254. MessageListener* const recipient = message->messageRecipient;
  31255. if (recipient == 0)
  31256. {
  31257. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31258. if (callbackMessage != 0)
  31259. {
  31260. callbackMessage->messageCallback();
  31261. }
  31262. else if (message->intParameter1 == quitMessageId)
  31263. {
  31264. quitMessageReceived = true;
  31265. }
  31266. }
  31267. else if (messageListeners.contains (recipient))
  31268. {
  31269. recipient->handleMessage (*message);
  31270. }
  31271. }
  31272. JUCE_CATCH_EXCEPTION
  31273. }
  31274. #if ! (JUCE_MAC || JUCE_IOS)
  31275. void MessageManager::runDispatchLoop()
  31276. {
  31277. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31278. runDispatchLoopUntil (-1);
  31279. }
  31280. void MessageManager::stopDispatchLoop()
  31281. {
  31282. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31283. quitMessagePosted = true;
  31284. }
  31285. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31286. {
  31287. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31288. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31289. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31290. && ! quitMessageReceived)
  31291. {
  31292. JUCE_TRY
  31293. {
  31294. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31295. {
  31296. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31297. if (msToWait > 0)
  31298. Thread::sleep (jmin (5, msToWait));
  31299. }
  31300. }
  31301. JUCE_CATCH_EXCEPTION
  31302. }
  31303. return ! quitMessageReceived;
  31304. }
  31305. #endif
  31306. void MessageManager::deliverBroadcastMessage (const String& value)
  31307. {
  31308. if (broadcaster != 0)
  31309. broadcaster->sendActionMessage (value);
  31310. }
  31311. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31312. {
  31313. if (broadcaster == 0)
  31314. broadcaster = new ActionBroadcaster();
  31315. broadcaster->addActionListener (listener);
  31316. }
  31317. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31318. {
  31319. if (broadcaster != 0)
  31320. broadcaster->removeActionListener (listener);
  31321. }
  31322. bool MessageManager::isThisTheMessageThread() const throw()
  31323. {
  31324. return Thread::getCurrentThreadId() == messageThreadId;
  31325. }
  31326. void MessageManager::setCurrentThreadAsMessageThread()
  31327. {
  31328. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31329. if (messageThreadId != thisThread)
  31330. {
  31331. messageThreadId = thisThread;
  31332. // This is needed on windows to make sure the message window is created by this thread
  31333. doPlatformSpecificShutdown();
  31334. doPlatformSpecificInitialisation();
  31335. }
  31336. }
  31337. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31338. {
  31339. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31340. return thisThread == messageThreadId || thisThread == threadWithLock;
  31341. }
  31342. /* The only safe way to lock the message thread while another thread does
  31343. some work is by posting a special message, whose purpose is to tie up the event
  31344. loop until the other thread has finished its business.
  31345. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31346. get locked before making an event callback, because if the same OS lock gets indirectly
  31347. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31348. in Cocoa).
  31349. */
  31350. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31351. {
  31352. public:
  31353. BlockingMessage() {}
  31354. void messageCallback()
  31355. {
  31356. lockedEvent.signal();
  31357. releaseEvent.wait();
  31358. }
  31359. WaitableEvent lockedEvent, releaseEvent;
  31360. private:
  31361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31362. };
  31363. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31364. : locked (false)
  31365. {
  31366. init (threadToCheck, 0);
  31367. }
  31368. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31369. : locked (false)
  31370. {
  31371. init (0, jobToCheckForExitSignal);
  31372. }
  31373. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31374. {
  31375. if (MessageManager::instance != 0)
  31376. {
  31377. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31378. {
  31379. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31380. }
  31381. else
  31382. {
  31383. if (threadToCheck == 0 && job == 0)
  31384. {
  31385. MessageManager::instance->lockingLock.enter();
  31386. }
  31387. else
  31388. {
  31389. while (! MessageManager::instance->lockingLock.tryEnter())
  31390. {
  31391. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31392. || (job != 0 && job->shouldExit()))
  31393. return;
  31394. Thread::sleep (1);
  31395. }
  31396. }
  31397. blockingMessage = new BlockingMessage();
  31398. blockingMessage->post();
  31399. while (! blockingMessage->lockedEvent.wait (20))
  31400. {
  31401. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31402. || (job != 0 && job->shouldExit()))
  31403. {
  31404. blockingMessage->releaseEvent.signal();
  31405. blockingMessage = 0;
  31406. MessageManager::instance->lockingLock.exit();
  31407. return;
  31408. }
  31409. }
  31410. jassert (MessageManager::instance->threadWithLock == 0);
  31411. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31412. locked = true;
  31413. }
  31414. }
  31415. }
  31416. MessageManagerLock::~MessageManagerLock() throw()
  31417. {
  31418. if (blockingMessage != 0)
  31419. {
  31420. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31421. blockingMessage->releaseEvent.signal();
  31422. blockingMessage = 0;
  31423. if (MessageManager::instance != 0)
  31424. {
  31425. MessageManager::instance->threadWithLock = 0;
  31426. MessageManager::instance->lockingLock.exit();
  31427. }
  31428. }
  31429. }
  31430. END_JUCE_NAMESPACE
  31431. /*** End of inlined file: juce_MessageManager.cpp ***/
  31432. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31433. BEGIN_JUCE_NAMESPACE
  31434. class MultiTimer::MultiTimerCallback : public Timer
  31435. {
  31436. public:
  31437. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31438. : timerId (timerId_),
  31439. owner (owner_)
  31440. {
  31441. }
  31442. ~MultiTimerCallback()
  31443. {
  31444. }
  31445. void timerCallback()
  31446. {
  31447. owner.timerCallback (timerId);
  31448. }
  31449. const int timerId;
  31450. private:
  31451. MultiTimer& owner;
  31452. };
  31453. MultiTimer::MultiTimer() throw()
  31454. {
  31455. }
  31456. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31457. {
  31458. }
  31459. MultiTimer::~MultiTimer()
  31460. {
  31461. const ScopedLock sl (timerListLock);
  31462. timers.clear();
  31463. }
  31464. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31465. {
  31466. const ScopedLock sl (timerListLock);
  31467. for (int i = timers.size(); --i >= 0;)
  31468. {
  31469. MultiTimerCallback* const t = timers.getUnchecked(i);
  31470. if (t->timerId == timerId)
  31471. {
  31472. t->startTimer (intervalInMilliseconds);
  31473. return;
  31474. }
  31475. }
  31476. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31477. timers.add (newTimer);
  31478. newTimer->startTimer (intervalInMilliseconds);
  31479. }
  31480. void MultiTimer::stopTimer (const int timerId) throw()
  31481. {
  31482. const ScopedLock sl (timerListLock);
  31483. for (int i = timers.size(); --i >= 0;)
  31484. {
  31485. MultiTimerCallback* const t = timers.getUnchecked(i);
  31486. if (t->timerId == timerId)
  31487. t->stopTimer();
  31488. }
  31489. }
  31490. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31491. {
  31492. const ScopedLock sl (timerListLock);
  31493. for (int i = timers.size(); --i >= 0;)
  31494. {
  31495. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31496. if (t->timerId == timerId)
  31497. return t->isTimerRunning();
  31498. }
  31499. return false;
  31500. }
  31501. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31502. {
  31503. const ScopedLock sl (timerListLock);
  31504. for (int i = timers.size(); --i >= 0;)
  31505. {
  31506. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31507. if (t->timerId == timerId)
  31508. return t->getTimerInterval();
  31509. }
  31510. return 0;
  31511. }
  31512. END_JUCE_NAMESPACE
  31513. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31514. /*** Start of inlined file: juce_Timer.cpp ***/
  31515. BEGIN_JUCE_NAMESPACE
  31516. class InternalTimerThread : private Thread,
  31517. private MessageListener,
  31518. private DeletedAtShutdown,
  31519. private AsyncUpdater
  31520. {
  31521. public:
  31522. InternalTimerThread()
  31523. : Thread ("Juce Timer"),
  31524. firstTimer (0),
  31525. callbackNeeded (0)
  31526. {
  31527. triggerAsyncUpdate();
  31528. }
  31529. ~InternalTimerThread() throw()
  31530. {
  31531. stopThread (4000);
  31532. jassert (instance == this || instance == 0);
  31533. if (instance == this)
  31534. instance = 0;
  31535. }
  31536. void run()
  31537. {
  31538. uint32 lastTime = Time::getMillisecondCounter();
  31539. Message::Ptr message (new Message());
  31540. while (! threadShouldExit())
  31541. {
  31542. const uint32 now = Time::getMillisecondCounter();
  31543. if (now <= lastTime)
  31544. {
  31545. wait (2);
  31546. continue;
  31547. }
  31548. const int elapsed = now - lastTime;
  31549. lastTime = now;
  31550. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31551. if (timeUntilFirstTimer <= 0)
  31552. {
  31553. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31554. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31555. but if it fails it means the message-thread changed the value from under us so at least
  31556. some processing is happenening and we can just loop around and try again
  31557. */
  31558. if (callbackNeeded.compareAndSetBool (1, 0))
  31559. {
  31560. postMessage (message);
  31561. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31562. when the app has a modal loop), so this is how long to wait before assuming the
  31563. message has been lost and trying again.
  31564. */
  31565. const uint32 messageDeliveryTimeout = now + 2000;
  31566. while (callbackNeeded.get() != 0)
  31567. {
  31568. wait (4);
  31569. if (threadShouldExit())
  31570. return;
  31571. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31572. break;
  31573. }
  31574. }
  31575. }
  31576. else
  31577. {
  31578. // don't wait for too long because running this loop also helps keep the
  31579. // Time::getApproximateMillisecondTimer value stay up-to-date
  31580. wait (jlimit (1, 50, timeUntilFirstTimer));
  31581. }
  31582. }
  31583. }
  31584. void callTimers()
  31585. {
  31586. const ScopedLock sl (lock);
  31587. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31588. {
  31589. Timer* const t = firstTimer;
  31590. t->countdownMs = t->periodMs;
  31591. removeTimer (t);
  31592. addTimer (t);
  31593. const ScopedUnlock ul (lock);
  31594. JUCE_TRY
  31595. {
  31596. t->timerCallback();
  31597. }
  31598. JUCE_CATCH_EXCEPTION
  31599. }
  31600. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31601. before the boolean is set. This set should never fail since if it was false in the first place,
  31602. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31603. get a message then the value is true and the other thread can only set it to true again and
  31604. we will get another callback to set it to false.
  31605. */
  31606. callbackNeeded.set (0);
  31607. }
  31608. void handleMessage (const Message&)
  31609. {
  31610. callTimers();
  31611. }
  31612. void callTimersSynchronously()
  31613. {
  31614. if (! isThreadRunning())
  31615. {
  31616. // (This is relied on by some plugins in cases where the MM has
  31617. // had to restart and the async callback never started)
  31618. cancelPendingUpdate();
  31619. triggerAsyncUpdate();
  31620. }
  31621. callTimers();
  31622. }
  31623. static void callAnyTimersSynchronously()
  31624. {
  31625. if (InternalTimerThread::instance != 0)
  31626. InternalTimerThread::instance->callTimersSynchronously();
  31627. }
  31628. static inline void add (Timer* const tim) throw()
  31629. {
  31630. if (instance == 0)
  31631. instance = new InternalTimerThread();
  31632. const ScopedLock sl (instance->lock);
  31633. instance->addTimer (tim);
  31634. }
  31635. static inline void remove (Timer* const tim) throw()
  31636. {
  31637. if (instance != 0)
  31638. {
  31639. const ScopedLock sl (instance->lock);
  31640. instance->removeTimer (tim);
  31641. }
  31642. }
  31643. static inline void resetCounter (Timer* const tim,
  31644. const int newCounter) throw()
  31645. {
  31646. if (instance != 0)
  31647. {
  31648. tim->countdownMs = newCounter;
  31649. tim->periodMs = newCounter;
  31650. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31651. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31652. {
  31653. const ScopedLock sl (instance->lock);
  31654. instance->removeTimer (tim);
  31655. instance->addTimer (tim);
  31656. }
  31657. }
  31658. }
  31659. private:
  31660. friend class Timer;
  31661. static InternalTimerThread* instance;
  31662. static CriticalSection lock;
  31663. Timer* volatile firstTimer;
  31664. Atomic <int> callbackNeeded;
  31665. void addTimer (Timer* const t) throw()
  31666. {
  31667. #if JUCE_DEBUG
  31668. Timer* tt = firstTimer;
  31669. while (tt != 0)
  31670. {
  31671. // trying to add a timer that's already here - shouldn't get to this point,
  31672. // so if you get this assertion, let me know!
  31673. jassert (tt != t);
  31674. tt = tt->next;
  31675. }
  31676. jassert (t->previous == 0 && t->next == 0);
  31677. #endif
  31678. Timer* i = firstTimer;
  31679. if (i == 0 || i->countdownMs > t->countdownMs)
  31680. {
  31681. t->next = firstTimer;
  31682. firstTimer = t;
  31683. }
  31684. else
  31685. {
  31686. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31687. i = i->next;
  31688. jassert (i != 0);
  31689. t->next = i->next;
  31690. t->previous = i;
  31691. i->next = t;
  31692. }
  31693. if (t->next != 0)
  31694. t->next->previous = t;
  31695. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31696. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31697. notify();
  31698. }
  31699. void removeTimer (Timer* const t) throw()
  31700. {
  31701. #if JUCE_DEBUG
  31702. Timer* tt = firstTimer;
  31703. bool found = false;
  31704. while (tt != 0)
  31705. {
  31706. if (tt == t)
  31707. {
  31708. found = true;
  31709. break;
  31710. }
  31711. tt = tt->next;
  31712. }
  31713. // trying to remove a timer that's not here - shouldn't get to this point,
  31714. // so if you get this assertion, let me know!
  31715. jassert (found);
  31716. #endif
  31717. if (t->previous != 0)
  31718. {
  31719. jassert (firstTimer != t);
  31720. t->previous->next = t->next;
  31721. }
  31722. else
  31723. {
  31724. jassert (firstTimer == t);
  31725. firstTimer = t->next;
  31726. }
  31727. if (t->next != 0)
  31728. t->next->previous = t->previous;
  31729. t->next = 0;
  31730. t->previous = 0;
  31731. }
  31732. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31733. {
  31734. const ScopedLock sl (lock);
  31735. for (Timer* t = firstTimer; t != 0; t = t->next)
  31736. t->countdownMs -= numMillisecsElapsed;
  31737. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31738. }
  31739. void handleAsyncUpdate()
  31740. {
  31741. startThread (7);
  31742. }
  31743. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31744. };
  31745. InternalTimerThread* InternalTimerThread::instance = 0;
  31746. CriticalSection InternalTimerThread::lock;
  31747. void juce_callAnyTimersSynchronously()
  31748. {
  31749. InternalTimerThread::callAnyTimersSynchronously();
  31750. }
  31751. #if JUCE_DEBUG
  31752. static SortedSet <Timer*> activeTimers;
  31753. #endif
  31754. Timer::Timer() throw()
  31755. : countdownMs (0),
  31756. periodMs (0),
  31757. previous (0),
  31758. next (0)
  31759. {
  31760. #if JUCE_DEBUG
  31761. activeTimers.add (this);
  31762. #endif
  31763. }
  31764. Timer::Timer (const Timer&) throw()
  31765. : countdownMs (0),
  31766. periodMs (0),
  31767. previous (0),
  31768. next (0)
  31769. {
  31770. #if JUCE_DEBUG
  31771. activeTimers.add (this);
  31772. #endif
  31773. }
  31774. Timer::~Timer()
  31775. {
  31776. stopTimer();
  31777. #if JUCE_DEBUG
  31778. activeTimers.removeValue (this);
  31779. #endif
  31780. }
  31781. void Timer::startTimer (const int interval) throw()
  31782. {
  31783. const ScopedLock sl (InternalTimerThread::lock);
  31784. #if JUCE_DEBUG
  31785. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31786. jassert (activeTimers.contains (this));
  31787. #endif
  31788. if (periodMs == 0)
  31789. {
  31790. countdownMs = interval;
  31791. periodMs = jmax (1, interval);
  31792. InternalTimerThread::add (this);
  31793. }
  31794. else
  31795. {
  31796. InternalTimerThread::resetCounter (this, interval);
  31797. }
  31798. }
  31799. void Timer::stopTimer() throw()
  31800. {
  31801. const ScopedLock sl (InternalTimerThread::lock);
  31802. #if JUCE_DEBUG
  31803. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31804. jassert (activeTimers.contains (this));
  31805. #endif
  31806. if (periodMs > 0)
  31807. {
  31808. InternalTimerThread::remove (this);
  31809. periodMs = 0;
  31810. }
  31811. }
  31812. END_JUCE_NAMESPACE
  31813. /*** End of inlined file: juce_Timer.cpp ***/
  31814. #endif
  31815. #if JUCE_BUILD_GUI
  31816. /*** Start of inlined file: juce_Component.cpp ***/
  31817. BEGIN_JUCE_NAMESPACE
  31818. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31819. Component* Component::currentlyFocusedComponent = 0;
  31820. class Component::MouseListenerList
  31821. {
  31822. public:
  31823. MouseListenerList()
  31824. : numDeepMouseListeners (0)
  31825. {
  31826. }
  31827. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31828. {
  31829. if (! listeners.contains (newListener))
  31830. {
  31831. if (wantsEventsForAllNestedChildComponents)
  31832. {
  31833. listeners.insert (0, newListener);
  31834. ++numDeepMouseListeners;
  31835. }
  31836. else
  31837. {
  31838. listeners.add (newListener);
  31839. }
  31840. }
  31841. }
  31842. void removeListener (MouseListener* const listenerToRemove)
  31843. {
  31844. const int index = listeners.indexOf (listenerToRemove);
  31845. if (index >= 0)
  31846. {
  31847. if (index < numDeepMouseListeners)
  31848. --numDeepMouseListeners;
  31849. listeners.remove (index);
  31850. }
  31851. }
  31852. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31853. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31854. {
  31855. if (checker.shouldBailOut())
  31856. return;
  31857. {
  31858. MouseListenerList* const list = comp.mouseListeners;
  31859. if (list != 0)
  31860. {
  31861. for (int i = list->listeners.size(); --i >= 0;)
  31862. {
  31863. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31864. if (checker.shouldBailOut())
  31865. return;
  31866. i = jmin (i, list->listeners.size());
  31867. }
  31868. }
  31869. }
  31870. Component* p = comp.parentComponent;
  31871. while (p != 0)
  31872. {
  31873. MouseListenerList* const list = p->mouseListeners;
  31874. if (list != 0 && list->numDeepMouseListeners > 0)
  31875. {
  31876. BailOutChecker2 checker2 (checker, p);
  31877. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31878. {
  31879. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31880. if (checker2.shouldBailOut())
  31881. return;
  31882. i = jmin (i, list->numDeepMouseListeners);
  31883. }
  31884. }
  31885. p = p->parentComponent;
  31886. }
  31887. }
  31888. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31889. const float wheelIncrementX, const float wheelIncrementY)
  31890. {
  31891. {
  31892. MouseListenerList* const list = comp.mouseListeners;
  31893. if (list != 0)
  31894. {
  31895. for (int i = list->listeners.size(); --i >= 0;)
  31896. {
  31897. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31898. if (checker.shouldBailOut())
  31899. return;
  31900. i = jmin (i, list->listeners.size());
  31901. }
  31902. }
  31903. }
  31904. Component* p = comp.parentComponent;
  31905. while (p != 0)
  31906. {
  31907. MouseListenerList* const list = p->mouseListeners;
  31908. if (list != 0 && list->numDeepMouseListeners > 0)
  31909. {
  31910. BailOutChecker2 checker2 (checker, p);
  31911. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31912. {
  31913. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31914. if (checker2.shouldBailOut())
  31915. return;
  31916. i = jmin (i, list->numDeepMouseListeners);
  31917. }
  31918. }
  31919. p = p->parentComponent;
  31920. }
  31921. }
  31922. private:
  31923. Array <MouseListener*> listeners;
  31924. int numDeepMouseListeners;
  31925. class BailOutChecker2
  31926. {
  31927. public:
  31928. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31929. : checker (checker_), safePointer (component)
  31930. {
  31931. }
  31932. bool shouldBailOut() const throw()
  31933. {
  31934. return checker.shouldBailOut() || safePointer == 0;
  31935. }
  31936. private:
  31937. BailOutChecker& checker;
  31938. const WeakReference<Component> safePointer;
  31939. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31940. };
  31941. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31942. };
  31943. class Component::ComponentHelpers
  31944. {
  31945. public:
  31946. static void* runModalLoopCallback (void* userData)
  31947. {
  31948. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31949. }
  31950. static const Identifier getColourPropertyId (const int colourId)
  31951. {
  31952. String s;
  31953. s.preallocateStorage (18);
  31954. s << "jcclr_" << String::toHexString (colourId);
  31955. return s;
  31956. }
  31957. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31958. {
  31959. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31960. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31961. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31962. }
  31963. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31964. {
  31965. if (comp.affineTransform == 0)
  31966. return pointInParentSpace - comp.getPosition();
  31967. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31968. }
  31969. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31970. {
  31971. if (comp.affineTransform == 0)
  31972. return areaInParentSpace - comp.getPosition();
  31973. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31974. }
  31975. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31976. {
  31977. if (comp.affineTransform == 0)
  31978. return pointInLocalSpace + comp.getPosition();
  31979. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31980. }
  31981. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31982. {
  31983. if (comp.affineTransform == 0)
  31984. return areaInLocalSpace + comp.getPosition();
  31985. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31986. }
  31987. template <typename Type>
  31988. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31989. {
  31990. const Component* const directParent = target.getParentComponent();
  31991. jassert (directParent != 0);
  31992. if (directParent == parent)
  31993. return convertFromParentSpace (target, coordInParent);
  31994. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31995. }
  31996. template <typename Type>
  31997. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31998. {
  31999. while (source != 0)
  32000. {
  32001. if (source == target)
  32002. return p;
  32003. if (source->isParentOf (target))
  32004. return convertFromDistantParentSpace (source, *target, p);
  32005. if (source->isOnDesktop())
  32006. {
  32007. p = source->getPeer()->localToGlobal (p);
  32008. source = 0;
  32009. }
  32010. else
  32011. {
  32012. p = convertToParentSpace (*source, p);
  32013. source = source->getParentComponent();
  32014. }
  32015. }
  32016. jassert (source == 0);
  32017. if (target == 0)
  32018. return p;
  32019. const Component* const topLevelComp = target->getTopLevelComponent();
  32020. if (topLevelComp->isOnDesktop())
  32021. p = topLevelComp->getPeer()->globalToLocal (p);
  32022. else
  32023. p = convertFromParentSpace (*topLevelComp, p);
  32024. if (topLevelComp == target)
  32025. return p;
  32026. return convertFromDistantParentSpace (topLevelComp, *target, p);
  32027. }
  32028. static const Rectangle<int> getUnclippedArea (const Component& comp)
  32029. {
  32030. Rectangle<int> r (comp.getLocalBounds());
  32031. Component* const p = comp.getParentComponent();
  32032. if (p != 0)
  32033. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  32034. return r;
  32035. }
  32036. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  32037. {
  32038. for (int i = comp.childComponentList.size(); --i >= 0;)
  32039. {
  32040. const Component& child = *comp.childComponentList.getUnchecked(i);
  32041. if (child.isVisible() && ! child.isTransformed())
  32042. {
  32043. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  32044. if (! newClip.isEmpty())
  32045. {
  32046. if (child.isOpaque())
  32047. {
  32048. g.excludeClipRegion (newClip + delta);
  32049. }
  32050. else
  32051. {
  32052. const Point<int> childPos (child.getPosition());
  32053. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  32054. }
  32055. }
  32056. }
  32057. }
  32058. }
  32059. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  32060. const Point<int>& delta,
  32061. const Rectangle<int>& clipRect,
  32062. const Component* const compToAvoid)
  32063. {
  32064. for (int i = comp.childComponentList.size(); --i >= 0;)
  32065. {
  32066. const Component* const c = comp.childComponentList.getUnchecked(i);
  32067. if (c != compToAvoid && c->isVisible())
  32068. {
  32069. if (c->isOpaque())
  32070. {
  32071. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  32072. childBounds.translate (delta.getX(), delta.getY());
  32073. result.subtract (childBounds);
  32074. }
  32075. else
  32076. {
  32077. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  32078. newClip.translate (-c->getX(), -c->getY());
  32079. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  32080. newClip, compToAvoid);
  32081. }
  32082. }
  32083. }
  32084. }
  32085. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  32086. {
  32087. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  32088. : Desktop::getInstance().getMainMonitorArea();
  32089. }
  32090. };
  32091. Component::Component()
  32092. : parentComponent (0),
  32093. lookAndFeel (0),
  32094. effect (0),
  32095. componentFlags (0),
  32096. componentTransparency (0)
  32097. {
  32098. }
  32099. Component::Component (const String& name)
  32100. : componentName (name),
  32101. parentComponent (0),
  32102. lookAndFeel (0),
  32103. effect (0),
  32104. componentFlags (0),
  32105. componentTransparency (0)
  32106. {
  32107. }
  32108. Component::~Component()
  32109. {
  32110. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  32111. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  32112. #endif
  32113. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32114. weakReferenceMaster.clear();
  32115. while (childComponentList.size() > 0)
  32116. removeChildComponent (childComponentList.size() - 1, false, true);
  32117. if (parentComponent != 0)
  32118. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  32119. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32120. giveAwayFocus (currentlyFocusedComponent != this);
  32121. if (flags.hasHeavyweightPeerFlag)
  32122. removeFromDesktop();
  32123. // Something has added some children to this component during its destructor! Not a smart idea!
  32124. jassert (childComponentList.size() == 0);
  32125. }
  32126. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  32127. {
  32128. return weakReferenceMaster (this);
  32129. }
  32130. void Component::setName (const String& name)
  32131. {
  32132. // if component methods are being called from threads other than the message
  32133. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32134. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32135. if (componentName != name)
  32136. {
  32137. componentName = name;
  32138. if (flags.hasHeavyweightPeerFlag)
  32139. {
  32140. ComponentPeer* const peer = getPeer();
  32141. jassert (peer != 0);
  32142. if (peer != 0)
  32143. peer->setTitle (name);
  32144. }
  32145. BailOutChecker checker (this);
  32146. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32147. }
  32148. }
  32149. void Component::setComponentID (const String& newID)
  32150. {
  32151. componentID = newID;
  32152. }
  32153. void Component::setVisible (bool shouldBeVisible)
  32154. {
  32155. if (flags.visibleFlag != shouldBeVisible)
  32156. {
  32157. // if component methods are being called from threads other than the message
  32158. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32159. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32160. WeakReference<Component> safePointer (this);
  32161. flags.visibleFlag = shouldBeVisible;
  32162. internalRepaint (0, 0, getWidth(), getHeight());
  32163. sendFakeMouseMove();
  32164. if (! shouldBeVisible)
  32165. {
  32166. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  32167. {
  32168. if (parentComponent != 0)
  32169. parentComponent->grabKeyboardFocus();
  32170. else
  32171. giveAwayFocus (true);
  32172. }
  32173. }
  32174. if (safePointer != 0)
  32175. {
  32176. sendVisibilityChangeMessage();
  32177. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32178. {
  32179. ComponentPeer* const peer = getPeer();
  32180. jassert (peer != 0);
  32181. if (peer != 0)
  32182. {
  32183. peer->setVisible (shouldBeVisible);
  32184. internalHierarchyChanged();
  32185. }
  32186. }
  32187. }
  32188. }
  32189. }
  32190. void Component::visibilityChanged()
  32191. {
  32192. }
  32193. void Component::sendVisibilityChangeMessage()
  32194. {
  32195. BailOutChecker checker (this);
  32196. visibilityChanged();
  32197. if (! checker.shouldBailOut())
  32198. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32199. }
  32200. bool Component::isShowing() const
  32201. {
  32202. if (flags.visibleFlag)
  32203. {
  32204. if (parentComponent != 0)
  32205. {
  32206. return parentComponent->isShowing();
  32207. }
  32208. else
  32209. {
  32210. const ComponentPeer* const peer = getPeer();
  32211. return peer != 0 && ! peer->isMinimised();
  32212. }
  32213. }
  32214. return false;
  32215. }
  32216. void* Component::getWindowHandle() const
  32217. {
  32218. const ComponentPeer* const peer = getPeer();
  32219. if (peer != 0)
  32220. return peer->getNativeHandle();
  32221. return 0;
  32222. }
  32223. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32224. {
  32225. // if component methods are being called from threads other than the message
  32226. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32227. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32228. if (isOpaque())
  32229. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32230. else
  32231. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32232. int currentStyleFlags = 0;
  32233. // don't use getPeer(), so that we only get the peer that's specifically
  32234. // for this comp, and not for one of its parents.
  32235. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32236. if (peer != 0)
  32237. currentStyleFlags = peer->getStyleFlags();
  32238. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32239. {
  32240. WeakReference<Component> safePointer (this);
  32241. #if JUCE_LINUX
  32242. // it's wise to give the component a non-zero size before
  32243. // putting it on the desktop, as X windows get confused by this, and
  32244. // a (1, 1) minimum size is enforced here.
  32245. setSize (jmax (1, getWidth()),
  32246. jmax (1, getHeight()));
  32247. #endif
  32248. const Point<int> topLeft (getScreenPosition());
  32249. bool wasFullscreen = false;
  32250. bool wasMinimised = false;
  32251. ComponentBoundsConstrainer* currentConstainer = 0;
  32252. Rectangle<int> oldNonFullScreenBounds;
  32253. if (peer != 0)
  32254. {
  32255. wasFullscreen = peer->isFullScreen();
  32256. wasMinimised = peer->isMinimised();
  32257. currentConstainer = peer->getConstrainer();
  32258. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32259. removeFromDesktop();
  32260. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32261. }
  32262. if (parentComponent != 0)
  32263. parentComponent->removeChildComponent (this);
  32264. if (safePointer != 0)
  32265. {
  32266. flags.hasHeavyweightPeerFlag = true;
  32267. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32268. Desktop::getInstance().addDesktopComponent (this);
  32269. bounds.setPosition (topLeft);
  32270. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32271. peer->setVisible (isVisible());
  32272. if (wasFullscreen)
  32273. {
  32274. peer->setFullScreen (true);
  32275. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32276. }
  32277. if (wasMinimised)
  32278. peer->setMinimised (true);
  32279. if (isAlwaysOnTop())
  32280. peer->setAlwaysOnTop (true);
  32281. peer->setConstrainer (currentConstainer);
  32282. repaint();
  32283. }
  32284. internalHierarchyChanged();
  32285. }
  32286. }
  32287. void Component::removeFromDesktop()
  32288. {
  32289. // if component methods are being called from threads other than the message
  32290. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32291. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32292. if (flags.hasHeavyweightPeerFlag)
  32293. {
  32294. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32295. flags.hasHeavyweightPeerFlag = false;
  32296. jassert (peer != 0);
  32297. delete peer;
  32298. Desktop::getInstance().removeDesktopComponent (this);
  32299. }
  32300. }
  32301. bool Component::isOnDesktop() const throw()
  32302. {
  32303. return flags.hasHeavyweightPeerFlag;
  32304. }
  32305. void Component::userTriedToCloseWindow()
  32306. {
  32307. /* This means that the user's trying to get rid of your window with the 'close window' system
  32308. menu option (on windows) or possibly the task manager - you should really handle this
  32309. and delete or hide your component in an appropriate way.
  32310. If you want to ignore the event and don't want to trigger this assertion, just override
  32311. this method and do nothing.
  32312. */
  32313. jassertfalse;
  32314. }
  32315. void Component::minimisationStateChanged (bool)
  32316. {
  32317. }
  32318. void Component::setOpaque (const bool shouldBeOpaque)
  32319. {
  32320. if (shouldBeOpaque != flags.opaqueFlag)
  32321. {
  32322. flags.opaqueFlag = shouldBeOpaque;
  32323. if (flags.hasHeavyweightPeerFlag)
  32324. {
  32325. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32326. if (peer != 0)
  32327. {
  32328. // to make it recreate the heavyweight window
  32329. addToDesktop (peer->getStyleFlags());
  32330. }
  32331. }
  32332. repaint();
  32333. }
  32334. }
  32335. bool Component::isOpaque() const throw()
  32336. {
  32337. return flags.opaqueFlag;
  32338. }
  32339. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32340. {
  32341. if (shouldBeBuffered != flags.bufferToImageFlag)
  32342. {
  32343. bufferedImage = Image::null;
  32344. flags.bufferToImageFlag = shouldBeBuffered;
  32345. }
  32346. }
  32347. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32348. {
  32349. if (sourceIndex != destIndex)
  32350. {
  32351. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32352. jassert (c != 0);
  32353. c->repaintParent();
  32354. childComponentList.move (sourceIndex, destIndex);
  32355. sendFakeMouseMove();
  32356. internalChildrenChanged();
  32357. }
  32358. }
  32359. void Component::toFront (const bool setAsForeground)
  32360. {
  32361. // if component methods are being called from threads other than the message
  32362. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32363. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32364. if (flags.hasHeavyweightPeerFlag)
  32365. {
  32366. ComponentPeer* const peer = getPeer();
  32367. if (peer != 0)
  32368. {
  32369. peer->toFront (setAsForeground);
  32370. if (setAsForeground && ! hasKeyboardFocus (true))
  32371. grabKeyboardFocus();
  32372. }
  32373. }
  32374. else if (parentComponent != 0)
  32375. {
  32376. const Array<Component*>& childList = parentComponent->childComponentList;
  32377. if (childList.getLast() != this)
  32378. {
  32379. const int index = childList.indexOf (this);
  32380. if (index >= 0)
  32381. {
  32382. int insertIndex = -1;
  32383. if (! flags.alwaysOnTopFlag)
  32384. {
  32385. insertIndex = childList.size() - 1;
  32386. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32387. --insertIndex;
  32388. }
  32389. parentComponent->moveChildInternal (index, insertIndex);
  32390. }
  32391. }
  32392. if (setAsForeground)
  32393. {
  32394. internalBroughtToFront();
  32395. grabKeyboardFocus();
  32396. }
  32397. }
  32398. }
  32399. void Component::toBehind (Component* const other)
  32400. {
  32401. if (other != 0 && other != this)
  32402. {
  32403. // the two components must belong to the same parent..
  32404. jassert (parentComponent == other->parentComponent);
  32405. if (parentComponent != 0)
  32406. {
  32407. const Array<Component*>& childList = parentComponent->childComponentList;
  32408. const int index = childList.indexOf (this);
  32409. if (index >= 0 && childList [index + 1] != other)
  32410. {
  32411. int otherIndex = childList.indexOf (other);
  32412. if (otherIndex >= 0)
  32413. {
  32414. if (index < otherIndex)
  32415. --otherIndex;
  32416. parentComponent->moveChildInternal (index, otherIndex);
  32417. }
  32418. }
  32419. }
  32420. else if (isOnDesktop())
  32421. {
  32422. jassert (other->isOnDesktop());
  32423. if (other->isOnDesktop())
  32424. {
  32425. ComponentPeer* const us = getPeer();
  32426. ComponentPeer* const them = other->getPeer();
  32427. jassert (us != 0 && them != 0);
  32428. if (us != 0 && them != 0)
  32429. us->toBehind (them);
  32430. }
  32431. }
  32432. }
  32433. }
  32434. void Component::toBack()
  32435. {
  32436. if (isOnDesktop())
  32437. {
  32438. jassertfalse; //xxx need to add this to native window
  32439. }
  32440. else if (parentComponent != 0)
  32441. {
  32442. const Array<Component*>& childList = parentComponent->childComponentList;
  32443. if (childList.getFirst() != this)
  32444. {
  32445. const int index = childList.indexOf (this);
  32446. if (index > 0)
  32447. {
  32448. int insertIndex = 0;
  32449. if (flags.alwaysOnTopFlag)
  32450. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32451. ++insertIndex;
  32452. parentComponent->moveChildInternal (index, insertIndex);
  32453. }
  32454. }
  32455. }
  32456. }
  32457. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32458. {
  32459. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32460. {
  32461. flags.alwaysOnTopFlag = shouldStayOnTop;
  32462. if (isOnDesktop())
  32463. {
  32464. ComponentPeer* const peer = getPeer();
  32465. jassert (peer != 0);
  32466. if (peer != 0)
  32467. {
  32468. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32469. {
  32470. // some kinds of peer can't change their always-on-top status, so
  32471. // for these, we'll need to create a new window
  32472. const int oldFlags = peer->getStyleFlags();
  32473. removeFromDesktop();
  32474. addToDesktop (oldFlags);
  32475. }
  32476. }
  32477. }
  32478. if (shouldStayOnTop)
  32479. toFront (false);
  32480. internalHierarchyChanged();
  32481. }
  32482. }
  32483. bool Component::isAlwaysOnTop() const throw()
  32484. {
  32485. return flags.alwaysOnTopFlag;
  32486. }
  32487. int Component::proportionOfWidth (const float proportion) const throw()
  32488. {
  32489. return roundToInt (proportion * bounds.getWidth());
  32490. }
  32491. int Component::proportionOfHeight (const float proportion) const throw()
  32492. {
  32493. return roundToInt (proportion * bounds.getHeight());
  32494. }
  32495. int Component::getParentWidth() const throw()
  32496. {
  32497. return (parentComponent != 0) ? parentComponent->getWidth()
  32498. : getParentMonitorArea().getWidth();
  32499. }
  32500. int Component::getParentHeight() const throw()
  32501. {
  32502. return (parentComponent != 0) ? parentComponent->getHeight()
  32503. : getParentMonitorArea().getHeight();
  32504. }
  32505. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32506. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32507. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32508. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32509. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32510. {
  32511. return ComponentHelpers::convertCoordinate (this, source, point);
  32512. }
  32513. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32514. {
  32515. return ComponentHelpers::convertCoordinate (this, source, area);
  32516. }
  32517. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32518. {
  32519. return ComponentHelpers::convertCoordinate (0, this, point);
  32520. }
  32521. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32522. {
  32523. return ComponentHelpers::convertCoordinate (0, this, area);
  32524. }
  32525. /* Deprecated methods... */
  32526. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32527. {
  32528. return localPointToGlobal (relativePosition);
  32529. }
  32530. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32531. {
  32532. return getLocalPoint (0, screenPosition);
  32533. }
  32534. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32535. {
  32536. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32537. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32538. }
  32539. void Component::setBounds (const int x, const int y, int w, int h)
  32540. {
  32541. // if component methods are being called from threads other than the message
  32542. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32543. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32544. if (w < 0) w = 0;
  32545. if (h < 0) h = 0;
  32546. const bool wasResized = (getWidth() != w || getHeight() != h);
  32547. const bool wasMoved = (getX() != x || getY() != y);
  32548. #if JUCE_DEBUG
  32549. // It's a very bad idea to try to resize a window during its paint() method!
  32550. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32551. #endif
  32552. if (wasMoved || wasResized)
  32553. {
  32554. const bool showing = isShowing();
  32555. if (showing)
  32556. {
  32557. // send a fake mouse move to trigger enter/exit messages if needed..
  32558. sendFakeMouseMove();
  32559. if (! flags.hasHeavyweightPeerFlag)
  32560. repaintParent();
  32561. }
  32562. bounds.setBounds (x, y, w, h);
  32563. if (showing)
  32564. {
  32565. if (wasResized)
  32566. repaint();
  32567. else if (! flags.hasHeavyweightPeerFlag)
  32568. repaintParent();
  32569. }
  32570. if (flags.hasHeavyweightPeerFlag)
  32571. {
  32572. ComponentPeer* const peer = getPeer();
  32573. if (peer != 0)
  32574. {
  32575. if (wasMoved && wasResized)
  32576. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32577. else if (wasMoved)
  32578. peer->setPosition (getX(), getY());
  32579. else if (wasResized)
  32580. peer->setSize (getWidth(), getHeight());
  32581. }
  32582. }
  32583. sendMovedResizedMessages (wasMoved, wasResized);
  32584. }
  32585. }
  32586. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32587. {
  32588. BailOutChecker checker (this);
  32589. if (wasMoved)
  32590. {
  32591. moved();
  32592. if (checker.shouldBailOut())
  32593. return;
  32594. }
  32595. if (wasResized)
  32596. {
  32597. resized();
  32598. if (checker.shouldBailOut())
  32599. return;
  32600. for (int i = childComponentList.size(); --i >= 0;)
  32601. {
  32602. childComponentList.getUnchecked(i)->parentSizeChanged();
  32603. if (checker.shouldBailOut())
  32604. return;
  32605. i = jmin (i, childComponentList.size());
  32606. }
  32607. }
  32608. if (parentComponent != 0)
  32609. parentComponent->childBoundsChanged (this);
  32610. if (! checker.shouldBailOut())
  32611. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32612. *this, wasMoved, wasResized);
  32613. }
  32614. void Component::setSize (const int w, const int h)
  32615. {
  32616. setBounds (getX(), getY(), w, h);
  32617. }
  32618. void Component::setTopLeftPosition (const int x, const int y)
  32619. {
  32620. setBounds (x, y, getWidth(), getHeight());
  32621. }
  32622. void Component::setTopRightPosition (const int x, const int y)
  32623. {
  32624. setTopLeftPosition (x - getWidth(), y);
  32625. }
  32626. void Component::setBounds (const Rectangle<int>& r)
  32627. {
  32628. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32629. }
  32630. void Component::setBounds (const RelativeRectangle& newBounds)
  32631. {
  32632. newBounds.applyToComponent (*this);
  32633. }
  32634. void Component::setBoundsRelative (const float x, const float y,
  32635. const float w, const float h)
  32636. {
  32637. const int pw = getParentWidth();
  32638. const int ph = getParentHeight();
  32639. setBounds (roundToInt (x * pw),
  32640. roundToInt (y * ph),
  32641. roundToInt (w * pw),
  32642. roundToInt (h * ph));
  32643. }
  32644. void Component::setCentrePosition (const int x, const int y)
  32645. {
  32646. setTopLeftPosition (x - getWidth() / 2,
  32647. y - getHeight() / 2);
  32648. }
  32649. void Component::setCentreRelative (const float x, const float y)
  32650. {
  32651. setCentrePosition (roundToInt (getParentWidth() * x),
  32652. roundToInt (getParentHeight() * y));
  32653. }
  32654. void Component::centreWithSize (const int width, const int height)
  32655. {
  32656. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32657. setBounds (parentArea.getCentreX() - width / 2,
  32658. parentArea.getCentreY() - height / 2,
  32659. width, height);
  32660. }
  32661. void Component::setBoundsInset (const BorderSize& borders)
  32662. {
  32663. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32664. }
  32665. void Component::setBoundsToFit (int x, int y, int width, int height,
  32666. const Justification& justification,
  32667. const bool onlyReduceInSize)
  32668. {
  32669. // it's no good calling this method unless both the component and
  32670. // target rectangle have a finite size.
  32671. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32672. if (getWidth() > 0 && getHeight() > 0
  32673. && width > 0 && height > 0)
  32674. {
  32675. int newW, newH;
  32676. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32677. {
  32678. newW = getWidth();
  32679. newH = getHeight();
  32680. }
  32681. else
  32682. {
  32683. const double imageRatio = getHeight() / (double) getWidth();
  32684. const double targetRatio = height / (double) width;
  32685. if (imageRatio <= targetRatio)
  32686. {
  32687. newW = width;
  32688. newH = jmin (height, roundToInt (newW * imageRatio));
  32689. }
  32690. else
  32691. {
  32692. newH = height;
  32693. newW = jmin (width, roundToInt (newH / imageRatio));
  32694. }
  32695. }
  32696. if (newW > 0 && newH > 0)
  32697. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32698. Rectangle<int> (x, y, width, height)));
  32699. }
  32700. }
  32701. bool Component::isTransformed() const throw()
  32702. {
  32703. return affineTransform != 0;
  32704. }
  32705. void Component::setTransform (const AffineTransform& newTransform)
  32706. {
  32707. // If you pass in a transform with no inverse, the component will have no dimensions,
  32708. // and there will be all sorts of maths errors when converting coordinates.
  32709. jassert (! newTransform.isSingularity());
  32710. if (newTransform.isIdentity())
  32711. {
  32712. if (affineTransform != 0)
  32713. {
  32714. repaint();
  32715. affineTransform = 0;
  32716. repaint();
  32717. sendMovedResizedMessages (false, false);
  32718. }
  32719. }
  32720. else if (affineTransform == 0)
  32721. {
  32722. repaint();
  32723. affineTransform = new AffineTransform (newTransform);
  32724. repaint();
  32725. sendMovedResizedMessages (false, false);
  32726. }
  32727. else if (*affineTransform != newTransform)
  32728. {
  32729. repaint();
  32730. *affineTransform = newTransform;
  32731. repaint();
  32732. sendMovedResizedMessages (false, false);
  32733. }
  32734. }
  32735. const AffineTransform Component::getTransform() const
  32736. {
  32737. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32738. }
  32739. bool Component::hitTest (int x, int y)
  32740. {
  32741. if (! flags.ignoresMouseClicksFlag)
  32742. return true;
  32743. if (flags.allowChildMouseClicksFlag)
  32744. {
  32745. for (int i = getNumChildComponents(); --i >= 0;)
  32746. {
  32747. Component& child = *getChildComponent (i);
  32748. if (child.isVisible()
  32749. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32750. return true;
  32751. }
  32752. }
  32753. return false;
  32754. }
  32755. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32756. const bool allowClicksOnChildComponents) throw()
  32757. {
  32758. flags.ignoresMouseClicksFlag = ! allowClicks;
  32759. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32760. }
  32761. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32762. bool& allowsClicksOnChildComponents) const throw()
  32763. {
  32764. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32765. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32766. }
  32767. bool Component::contains (const Point<int>& point)
  32768. {
  32769. if (ComponentHelpers::hitTest (*this, point))
  32770. {
  32771. if (parentComponent != 0)
  32772. {
  32773. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32774. }
  32775. else if (flags.hasHeavyweightPeerFlag)
  32776. {
  32777. const ComponentPeer* const peer = getPeer();
  32778. if (peer != 0)
  32779. return peer->contains (point, true);
  32780. }
  32781. }
  32782. return false;
  32783. }
  32784. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32785. {
  32786. if (! contains (point))
  32787. return false;
  32788. Component* const top = getTopLevelComponent();
  32789. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32790. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32791. }
  32792. Component* Component::getComponentAt (const Point<int>& position)
  32793. {
  32794. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32795. {
  32796. for (int i = childComponentList.size(); --i >= 0;)
  32797. {
  32798. Component* child = childComponentList.getUnchecked(i);
  32799. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32800. if (child != 0)
  32801. return child;
  32802. }
  32803. return this;
  32804. }
  32805. return 0;
  32806. }
  32807. Component* Component::getComponentAt (const int x, const int y)
  32808. {
  32809. return getComponentAt (Point<int> (x, y));
  32810. }
  32811. void Component::addChildComponent (Component* const child, int zOrder)
  32812. {
  32813. // if component methods are being called from threads other than the message
  32814. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32815. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32816. if (child != 0 && child->parentComponent != this)
  32817. {
  32818. if (child->parentComponent != 0)
  32819. child->parentComponent->removeChildComponent (child);
  32820. else
  32821. child->removeFromDesktop();
  32822. child->parentComponent = this;
  32823. if (child->isVisible())
  32824. child->repaintParent();
  32825. if (! child->isAlwaysOnTop())
  32826. {
  32827. if (zOrder < 0 || zOrder > childComponentList.size())
  32828. zOrder = childComponentList.size();
  32829. while (zOrder > 0)
  32830. {
  32831. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32832. break;
  32833. --zOrder;
  32834. }
  32835. }
  32836. childComponentList.insert (zOrder, child);
  32837. child->internalHierarchyChanged();
  32838. internalChildrenChanged();
  32839. }
  32840. }
  32841. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32842. {
  32843. if (child != 0)
  32844. {
  32845. child->setVisible (true);
  32846. addChildComponent (child, zOrder);
  32847. }
  32848. }
  32849. void Component::removeChildComponent (Component* const child)
  32850. {
  32851. removeChildComponent (childComponentList.indexOf (child), true, true);
  32852. }
  32853. Component* Component::removeChildComponent (const int index)
  32854. {
  32855. return removeChildComponent (index, true, true);
  32856. }
  32857. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32858. {
  32859. // if component methods are being called from threads other than the message
  32860. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32861. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32862. Component* const child = childComponentList [index];
  32863. if (child != 0)
  32864. {
  32865. sendParentEvents = sendParentEvents && child->isShowing();
  32866. if (sendParentEvents)
  32867. {
  32868. sendFakeMouseMove();
  32869. child->repaintParent();
  32870. }
  32871. childComponentList.remove (index);
  32872. child->parentComponent = 0;
  32873. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32874. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32875. {
  32876. if (sendParentEvents)
  32877. {
  32878. const WeakReference<Component> thisPointer (this);
  32879. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32880. if (thisPointer == 0)
  32881. return child;
  32882. grabKeyboardFocus();
  32883. }
  32884. else
  32885. {
  32886. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32887. }
  32888. }
  32889. if (sendChildEvents)
  32890. child->internalHierarchyChanged();
  32891. if (sendParentEvents)
  32892. internalChildrenChanged();
  32893. }
  32894. return child;
  32895. }
  32896. void Component::removeAllChildren()
  32897. {
  32898. while (childComponentList.size() > 0)
  32899. removeChildComponent (childComponentList.size() - 1);
  32900. }
  32901. void Component::deleteAllChildren()
  32902. {
  32903. while (childComponentList.size() > 0)
  32904. delete (removeChildComponent (childComponentList.size() - 1));
  32905. }
  32906. int Component::getNumChildComponents() const throw()
  32907. {
  32908. return childComponentList.size();
  32909. }
  32910. Component* Component::getChildComponent (const int index) const throw()
  32911. {
  32912. return childComponentList [index];
  32913. }
  32914. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32915. {
  32916. return childComponentList.indexOf (const_cast <Component*> (child));
  32917. }
  32918. Component* Component::getTopLevelComponent() const throw()
  32919. {
  32920. const Component* comp = this;
  32921. while (comp->parentComponent != 0)
  32922. comp = comp->parentComponent;
  32923. return const_cast <Component*> (comp);
  32924. }
  32925. bool Component::isParentOf (const Component* possibleChild) const throw()
  32926. {
  32927. while (possibleChild != 0)
  32928. {
  32929. possibleChild = possibleChild->parentComponent;
  32930. if (possibleChild == this)
  32931. return true;
  32932. }
  32933. return false;
  32934. }
  32935. void Component::parentHierarchyChanged()
  32936. {
  32937. }
  32938. void Component::childrenChanged()
  32939. {
  32940. }
  32941. void Component::internalChildrenChanged()
  32942. {
  32943. if (componentListeners.isEmpty())
  32944. {
  32945. childrenChanged();
  32946. }
  32947. else
  32948. {
  32949. BailOutChecker checker (this);
  32950. childrenChanged();
  32951. if (! checker.shouldBailOut())
  32952. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32953. }
  32954. }
  32955. void Component::internalHierarchyChanged()
  32956. {
  32957. BailOutChecker checker (this);
  32958. parentHierarchyChanged();
  32959. if (checker.shouldBailOut())
  32960. return;
  32961. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32962. if (checker.shouldBailOut())
  32963. return;
  32964. for (int i = childComponentList.size(); --i >= 0;)
  32965. {
  32966. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32967. if (checker.shouldBailOut())
  32968. {
  32969. // you really shouldn't delete the parent component during a callback telling you
  32970. // that it's changed..
  32971. jassertfalse;
  32972. return;
  32973. }
  32974. i = jmin (i, childComponentList.size());
  32975. }
  32976. }
  32977. int Component::runModalLoop()
  32978. {
  32979. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32980. {
  32981. // use a callback so this can be called from non-gui threads
  32982. return (int) (pointer_sized_int) MessageManager::getInstance()
  32983. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32984. }
  32985. if (! isCurrentlyModal())
  32986. enterModalState (true);
  32987. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32988. }
  32989. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32990. {
  32991. // if component methods are being called from threads other than the message
  32992. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32993. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32994. // Check for an attempt to make a component modal when it already is!
  32995. // This can cause nasty problems..
  32996. jassert (! flags.currentlyModalFlag);
  32997. if (! isCurrentlyModal())
  32998. {
  32999. ModalComponentManager::getInstance()->startModal (this, callback);
  33000. flags.currentlyModalFlag = true;
  33001. setVisible (true);
  33002. if (shouldTakeKeyboardFocus)
  33003. grabKeyboardFocus();
  33004. }
  33005. }
  33006. void Component::exitModalState (const int returnValue)
  33007. {
  33008. if (isCurrentlyModal())
  33009. {
  33010. if (MessageManager::getInstance()->isThisTheMessageThread())
  33011. {
  33012. ModalComponentManager::getInstance()->endModal (this, returnValue);
  33013. flags.currentlyModalFlag = false;
  33014. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33015. }
  33016. else
  33017. {
  33018. class ExitModalStateMessage : public CallbackMessage
  33019. {
  33020. public:
  33021. ExitModalStateMessage (Component* const target_, const int result_)
  33022. : target (target_), result (result_) {}
  33023. void messageCallback()
  33024. {
  33025. if (target.get() != 0) // (get() required for VS2003 bug)
  33026. target->exitModalState (result);
  33027. }
  33028. private:
  33029. WeakReference<Component> target;
  33030. int result;
  33031. };
  33032. (new ExitModalStateMessage (this, returnValue))->post();
  33033. }
  33034. }
  33035. }
  33036. bool Component::isCurrentlyModal() const throw()
  33037. {
  33038. return flags.currentlyModalFlag
  33039. && getCurrentlyModalComponent() == this;
  33040. }
  33041. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  33042. {
  33043. Component* const mc = getCurrentlyModalComponent();
  33044. return mc != 0
  33045. && mc != this
  33046. && (! mc->isParentOf (this))
  33047. && ! mc->canModalEventBeSentToComponent (this);
  33048. }
  33049. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  33050. {
  33051. return ModalComponentManager::getInstance()->getNumModalComponents();
  33052. }
  33053. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  33054. {
  33055. return ModalComponentManager::getInstance()->getModalComponent (index);
  33056. }
  33057. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33058. {
  33059. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33060. }
  33061. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33062. {
  33063. return flags.bringToFrontOnClickFlag;
  33064. }
  33065. void Component::setMouseCursor (const MouseCursor& newCursor)
  33066. {
  33067. if (cursor != newCursor)
  33068. {
  33069. cursor = newCursor;
  33070. if (flags.visibleFlag)
  33071. updateMouseCursor();
  33072. }
  33073. }
  33074. const MouseCursor Component::getMouseCursor()
  33075. {
  33076. return cursor;
  33077. }
  33078. void Component::updateMouseCursor() const
  33079. {
  33080. sendFakeMouseMove();
  33081. }
  33082. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33083. {
  33084. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33085. }
  33086. void Component::setAlpha (const float newAlpha)
  33087. {
  33088. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33089. if (componentTransparency != newIntAlpha)
  33090. {
  33091. componentTransparency = newIntAlpha;
  33092. if (flags.hasHeavyweightPeerFlag)
  33093. {
  33094. ComponentPeer* const peer = getPeer();
  33095. if (peer != 0)
  33096. peer->setAlpha (newAlpha);
  33097. }
  33098. else
  33099. {
  33100. repaint();
  33101. }
  33102. }
  33103. }
  33104. float Component::getAlpha() const
  33105. {
  33106. return (255 - componentTransparency) / 255.0f;
  33107. }
  33108. void Component::repaintParent()
  33109. {
  33110. if (flags.visibleFlag)
  33111. internalRepaint (0, 0, getWidth(), getHeight());
  33112. }
  33113. void Component::repaint()
  33114. {
  33115. repaint (0, 0, getWidth(), getHeight());
  33116. }
  33117. void Component::repaint (const int x, const int y,
  33118. const int w, const int h)
  33119. {
  33120. bufferedImage = Image::null;
  33121. if (flags.visibleFlag)
  33122. internalRepaint (x, y, w, h);
  33123. }
  33124. void Component::repaint (const Rectangle<int>& area)
  33125. {
  33126. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33127. }
  33128. void Component::internalRepaint (int x, int y, int w, int h)
  33129. {
  33130. // if component methods are being called from threads other than the message
  33131. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33132. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33133. if (x < 0)
  33134. {
  33135. w += x;
  33136. x = 0;
  33137. }
  33138. if (x + w > getWidth())
  33139. w = getWidth() - x;
  33140. if (w > 0)
  33141. {
  33142. if (y < 0)
  33143. {
  33144. h += y;
  33145. y = 0;
  33146. }
  33147. if (y + h > getHeight())
  33148. h = getHeight() - y;
  33149. if (h > 0)
  33150. {
  33151. if (parentComponent != 0)
  33152. {
  33153. if (parentComponent->flags.visibleFlag)
  33154. {
  33155. if (affineTransform == 0)
  33156. {
  33157. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  33158. }
  33159. else
  33160. {
  33161. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  33162. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  33163. }
  33164. }
  33165. }
  33166. else if (flags.hasHeavyweightPeerFlag)
  33167. {
  33168. ComponentPeer* const peer = getPeer();
  33169. if (peer != 0)
  33170. peer->repaint (Rectangle<int> (x, y, w, h));
  33171. }
  33172. }
  33173. }
  33174. }
  33175. void Component::paintComponent (Graphics& g)
  33176. {
  33177. if (flags.bufferToImageFlag)
  33178. {
  33179. if (bufferedImage.isNull())
  33180. {
  33181. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33182. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33183. Graphics imG (bufferedImage);
  33184. paint (imG);
  33185. }
  33186. g.setColour (Colours::black.withAlpha (getAlpha()));
  33187. g.drawImageAt (bufferedImage, 0, 0);
  33188. }
  33189. else
  33190. {
  33191. paint (g);
  33192. }
  33193. }
  33194. void Component::paintWithinParentContext (Graphics& g)
  33195. {
  33196. g.setOrigin (getX(), getY());
  33197. paintEntireComponent (g, false);
  33198. }
  33199. void Component::paintComponentAndChildren (Graphics& g)
  33200. {
  33201. const Rectangle<int> clipBounds (g.getClipBounds());
  33202. if (flags.dontClipGraphicsFlag)
  33203. {
  33204. paintComponent (g);
  33205. }
  33206. else
  33207. {
  33208. g.saveState();
  33209. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33210. if (! g.isClipEmpty())
  33211. paintComponent (g);
  33212. g.restoreState();
  33213. }
  33214. for (int i = 0; i < childComponentList.size(); ++i)
  33215. {
  33216. Component& child = *childComponentList.getUnchecked (i);
  33217. if (child.isVisible())
  33218. {
  33219. if (child.affineTransform != 0)
  33220. {
  33221. g.saveState();
  33222. g.addTransform (*child.affineTransform);
  33223. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33224. child.paintWithinParentContext (g);
  33225. g.restoreState();
  33226. }
  33227. else if (clipBounds.intersects (child.getBounds()))
  33228. {
  33229. g.saveState();
  33230. if (child.flags.dontClipGraphicsFlag)
  33231. {
  33232. child.paintWithinParentContext (g);
  33233. }
  33234. else if (g.reduceClipRegion (child.getBounds()))
  33235. {
  33236. bool nothingClipped = true;
  33237. for (int j = i + 1; j < childComponentList.size(); ++j)
  33238. {
  33239. const Component& sibling = *childComponentList.getUnchecked (j);
  33240. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33241. {
  33242. nothingClipped = false;
  33243. g.excludeClipRegion (sibling.getBounds());
  33244. }
  33245. }
  33246. if (nothingClipped || ! g.isClipEmpty())
  33247. child.paintWithinParentContext (g);
  33248. }
  33249. g.restoreState();
  33250. }
  33251. }
  33252. }
  33253. g.saveState();
  33254. paintOverChildren (g);
  33255. g.restoreState();
  33256. }
  33257. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33258. {
  33259. jassert (! g.isClipEmpty());
  33260. #if JUCE_DEBUG
  33261. flags.isInsidePaintCall = true;
  33262. #endif
  33263. if (effect != 0)
  33264. {
  33265. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33266. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33267. {
  33268. Graphics g2 (effectImage);
  33269. paintComponentAndChildren (g2);
  33270. }
  33271. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33272. }
  33273. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33274. {
  33275. if (componentTransparency < 255)
  33276. {
  33277. g.beginTransparencyLayer (getAlpha());
  33278. paintComponentAndChildren (g);
  33279. g.endTransparencyLayer();
  33280. }
  33281. }
  33282. else
  33283. {
  33284. paintComponentAndChildren (g);
  33285. }
  33286. #if JUCE_DEBUG
  33287. flags.isInsidePaintCall = false;
  33288. #endif
  33289. }
  33290. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33291. {
  33292. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33293. }
  33294. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33295. const bool clipImageToComponentBounds)
  33296. {
  33297. Rectangle<int> r (areaToGrab);
  33298. if (clipImageToComponentBounds)
  33299. r = r.getIntersection (getLocalBounds());
  33300. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33301. jmax (1, r.getWidth()),
  33302. jmax (1, r.getHeight()),
  33303. true);
  33304. Graphics imageContext (componentImage);
  33305. imageContext.setOrigin (-r.getX(), -r.getY());
  33306. paintEntireComponent (imageContext, true);
  33307. return componentImage;
  33308. }
  33309. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33310. {
  33311. if (effect != newEffect)
  33312. {
  33313. effect = newEffect;
  33314. repaint();
  33315. }
  33316. }
  33317. LookAndFeel& Component::getLookAndFeel() const throw()
  33318. {
  33319. const Component* c = this;
  33320. do
  33321. {
  33322. if (c->lookAndFeel != 0)
  33323. return *(c->lookAndFeel);
  33324. c = c->parentComponent;
  33325. }
  33326. while (c != 0);
  33327. return LookAndFeel::getDefaultLookAndFeel();
  33328. }
  33329. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33330. {
  33331. if (lookAndFeel != newLookAndFeel)
  33332. {
  33333. lookAndFeel = newLookAndFeel;
  33334. sendLookAndFeelChange();
  33335. }
  33336. }
  33337. void Component::lookAndFeelChanged()
  33338. {
  33339. }
  33340. void Component::sendLookAndFeelChange()
  33341. {
  33342. repaint();
  33343. WeakReference<Component> safePointer (this);
  33344. lookAndFeelChanged();
  33345. if (safePointer != 0)
  33346. {
  33347. for (int i = childComponentList.size(); --i >= 0;)
  33348. {
  33349. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33350. if (safePointer == 0)
  33351. return;
  33352. i = jmin (i, childComponentList.size());
  33353. }
  33354. }
  33355. }
  33356. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33357. {
  33358. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33359. if (v != 0)
  33360. return Colour ((int) *v);
  33361. if (inheritFromParent && parentComponent != 0)
  33362. return parentComponent->findColour (colourId, true);
  33363. return getLookAndFeel().findColour (colourId);
  33364. }
  33365. bool Component::isColourSpecified (const int colourId) const
  33366. {
  33367. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33368. }
  33369. void Component::removeColour (const int colourId)
  33370. {
  33371. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33372. colourChanged();
  33373. }
  33374. void Component::setColour (const int colourId, const Colour& colour)
  33375. {
  33376. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33377. colourChanged();
  33378. }
  33379. void Component::copyAllExplicitColoursTo (Component& target) const
  33380. {
  33381. bool changed = false;
  33382. for (int i = properties.size(); --i >= 0;)
  33383. {
  33384. const Identifier name (properties.getName(i));
  33385. if (name.toString().startsWith ("jcclr_"))
  33386. if (target.properties.set (name, properties [name]))
  33387. changed = true;
  33388. }
  33389. if (changed)
  33390. target.colourChanged();
  33391. }
  33392. void Component::colourChanged()
  33393. {
  33394. }
  33395. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33396. {
  33397. return 0;
  33398. }
  33399. Component::Positioner::Positioner (Component& component_) throw()
  33400. : component (component_)
  33401. {
  33402. }
  33403. Component::Positioner* Component::getPositioner() const throw()
  33404. {
  33405. return positioner;
  33406. }
  33407. void Component::setPositioner (Positioner* newPositioner)
  33408. {
  33409. // You can only assign a positioner to the component that it was created for!
  33410. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33411. positioner = newPositioner;
  33412. }
  33413. const Rectangle<int> Component::getLocalBounds() const throw()
  33414. {
  33415. return Rectangle<int> (getWidth(), getHeight());
  33416. }
  33417. const Rectangle<int> Component::getBoundsInParent() const throw()
  33418. {
  33419. return affineTransform == 0 ? bounds
  33420. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33421. }
  33422. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33423. {
  33424. result.clear();
  33425. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33426. if (! unclipped.isEmpty())
  33427. {
  33428. result.add (unclipped);
  33429. if (includeSiblings)
  33430. {
  33431. const Component* const c = getTopLevelComponent();
  33432. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33433. c->getLocalBounds(), this);
  33434. }
  33435. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33436. result.consolidate();
  33437. }
  33438. }
  33439. void Component::mouseEnter (const MouseEvent&)
  33440. {
  33441. // base class does nothing
  33442. }
  33443. void Component::mouseExit (const MouseEvent&)
  33444. {
  33445. // base class does nothing
  33446. }
  33447. void Component::mouseDown (const MouseEvent&)
  33448. {
  33449. // base class does nothing
  33450. }
  33451. void Component::mouseUp (const MouseEvent&)
  33452. {
  33453. // base class does nothing
  33454. }
  33455. void Component::mouseDrag (const MouseEvent&)
  33456. {
  33457. // base class does nothing
  33458. }
  33459. void Component::mouseMove (const MouseEvent&)
  33460. {
  33461. // base class does nothing
  33462. }
  33463. void Component::mouseDoubleClick (const MouseEvent&)
  33464. {
  33465. // base class does nothing
  33466. }
  33467. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33468. {
  33469. // the base class just passes this event up to its parent..
  33470. if (parentComponent != 0)
  33471. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33472. wheelIncrementX, wheelIncrementY);
  33473. }
  33474. void Component::resized()
  33475. {
  33476. // base class does nothing
  33477. }
  33478. void Component::moved()
  33479. {
  33480. // base class does nothing
  33481. }
  33482. void Component::childBoundsChanged (Component*)
  33483. {
  33484. // base class does nothing
  33485. }
  33486. void Component::parentSizeChanged()
  33487. {
  33488. // base class does nothing
  33489. }
  33490. void Component::addComponentListener (ComponentListener* const newListener)
  33491. {
  33492. // if component methods are being called from threads other than the message
  33493. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33494. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33495. componentListeners.add (newListener);
  33496. }
  33497. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33498. {
  33499. componentListeners.remove (listenerToRemove);
  33500. }
  33501. void Component::inputAttemptWhenModal()
  33502. {
  33503. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33504. getLookAndFeel().playAlertSound();
  33505. }
  33506. bool Component::canModalEventBeSentToComponent (const Component*)
  33507. {
  33508. return false;
  33509. }
  33510. void Component::internalModalInputAttempt()
  33511. {
  33512. Component* const current = getCurrentlyModalComponent();
  33513. if (current != 0)
  33514. current->inputAttemptWhenModal();
  33515. }
  33516. void Component::paint (Graphics&)
  33517. {
  33518. // all painting is done in the subclasses
  33519. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33520. }
  33521. void Component::paintOverChildren (Graphics&)
  33522. {
  33523. // all painting is done in the subclasses
  33524. }
  33525. void Component::postCommandMessage (const int commandId)
  33526. {
  33527. class CustomCommandMessage : public CallbackMessage
  33528. {
  33529. public:
  33530. CustomCommandMessage (Component* const target_, const int commandId_)
  33531. : target (target_), commandId (commandId_) {}
  33532. void messageCallback()
  33533. {
  33534. if (target.get() != 0) // (get() required for VS2003 bug)
  33535. target->handleCommandMessage (commandId);
  33536. }
  33537. private:
  33538. WeakReference<Component> target;
  33539. int commandId;
  33540. };
  33541. (new CustomCommandMessage (this, commandId))->post();
  33542. }
  33543. void Component::handleCommandMessage (int)
  33544. {
  33545. // used by subclasses
  33546. }
  33547. void Component::addMouseListener (MouseListener* const newListener,
  33548. const bool wantsEventsForAllNestedChildComponents)
  33549. {
  33550. // if component methods are being called from threads other than the message
  33551. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33552. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33553. // If you register a component as a mouselistener for itself, it'll receive all the events
  33554. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33555. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33556. if (mouseListeners == 0)
  33557. mouseListeners = new MouseListenerList();
  33558. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33559. }
  33560. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33561. {
  33562. // if component methods are being called from threads other than the message
  33563. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33564. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33565. if (mouseListeners != 0)
  33566. mouseListeners->removeListener (listenerToRemove);
  33567. }
  33568. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33569. {
  33570. if (isCurrentlyBlockedByAnotherModalComponent())
  33571. {
  33572. // if something else is modal, always just show a normal mouse cursor
  33573. source.showMouseCursor (MouseCursor::NormalCursor);
  33574. return;
  33575. }
  33576. if (! flags.mouseInsideFlag)
  33577. {
  33578. flags.mouseInsideFlag = true;
  33579. flags.mouseOverFlag = true;
  33580. flags.mouseDownFlag = false;
  33581. BailOutChecker checker (this);
  33582. if (flags.repaintOnMouseActivityFlag)
  33583. repaint();
  33584. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33585. this, this, time, relativePos, time, 0, false);
  33586. mouseEnter (me);
  33587. if (checker.shouldBailOut())
  33588. return;
  33589. Desktop& desktop = Desktop::getInstance();
  33590. desktop.resetTimer();
  33591. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33592. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33593. }
  33594. }
  33595. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33596. {
  33597. BailOutChecker checker (this);
  33598. if (flags.mouseDownFlag)
  33599. {
  33600. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33601. if (checker.shouldBailOut())
  33602. return;
  33603. }
  33604. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33605. {
  33606. flags.mouseInsideFlag = false;
  33607. flags.mouseOverFlag = false;
  33608. flags.mouseDownFlag = false;
  33609. if (flags.repaintOnMouseActivityFlag)
  33610. repaint();
  33611. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33612. this, this, time, relativePos, time, 0, false);
  33613. mouseExit (me);
  33614. if (checker.shouldBailOut())
  33615. return;
  33616. Desktop& desktop = Desktop::getInstance();
  33617. desktop.resetTimer();
  33618. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33619. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33620. }
  33621. }
  33622. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33623. {
  33624. Desktop& desktop = Desktop::getInstance();
  33625. BailOutChecker checker (this);
  33626. if (isCurrentlyBlockedByAnotherModalComponent())
  33627. {
  33628. internalModalInputAttempt();
  33629. if (checker.shouldBailOut())
  33630. return;
  33631. // If processing the input attempt has exited the modal loop, we'll allow the event
  33632. // to be delivered..
  33633. if (isCurrentlyBlockedByAnotherModalComponent())
  33634. {
  33635. // allow blocked mouse-events to go to global listeners..
  33636. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33637. this, this, time, relativePos, time,
  33638. source.getNumberOfMultipleClicks(), false);
  33639. desktop.resetTimer();
  33640. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33641. return;
  33642. }
  33643. }
  33644. {
  33645. Component* c = this;
  33646. while (c != 0)
  33647. {
  33648. if (c->isBroughtToFrontOnMouseClick())
  33649. {
  33650. c->toFront (true);
  33651. if (checker.shouldBailOut())
  33652. return;
  33653. }
  33654. c = c->parentComponent;
  33655. }
  33656. }
  33657. if (! flags.dontFocusOnMouseClickFlag)
  33658. {
  33659. grabFocusInternal (focusChangedByMouseClick);
  33660. if (checker.shouldBailOut())
  33661. return;
  33662. }
  33663. flags.mouseDownFlag = true;
  33664. flags.mouseOverFlag = true;
  33665. if (flags.repaintOnMouseActivityFlag)
  33666. repaint();
  33667. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33668. this, this, time, relativePos, time,
  33669. source.getNumberOfMultipleClicks(), false);
  33670. mouseDown (me);
  33671. if (checker.shouldBailOut())
  33672. return;
  33673. desktop.resetTimer();
  33674. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33675. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33676. }
  33677. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33678. {
  33679. if (flags.mouseDownFlag)
  33680. {
  33681. flags.mouseDownFlag = false;
  33682. BailOutChecker checker (this);
  33683. if (flags.repaintOnMouseActivityFlag)
  33684. repaint();
  33685. const MouseEvent me (source, relativePos,
  33686. oldModifiers, this, this, time,
  33687. getLocalPoint (0, source.getLastMouseDownPosition()),
  33688. source.getLastMouseDownTime(),
  33689. source.getNumberOfMultipleClicks(),
  33690. source.hasMouseMovedSignificantlySincePressed());
  33691. mouseUp (me);
  33692. if (checker.shouldBailOut())
  33693. return;
  33694. Desktop& desktop = Desktop::getInstance();
  33695. desktop.resetTimer();
  33696. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33697. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33698. if (checker.shouldBailOut())
  33699. return;
  33700. // check for double-click
  33701. if (me.getNumberOfClicks() >= 2)
  33702. {
  33703. mouseDoubleClick (me);
  33704. if (checker.shouldBailOut())
  33705. return;
  33706. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33707. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33708. }
  33709. }
  33710. }
  33711. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33712. {
  33713. if (flags.mouseDownFlag)
  33714. {
  33715. flags.mouseOverFlag = reallyContains (relativePos, false);
  33716. BailOutChecker checker (this);
  33717. const MouseEvent me (source, relativePos,
  33718. source.getCurrentModifiers(), this, this, time,
  33719. getLocalPoint (0, source.getLastMouseDownPosition()),
  33720. source.getLastMouseDownTime(),
  33721. source.getNumberOfMultipleClicks(),
  33722. source.hasMouseMovedSignificantlySincePressed());
  33723. mouseDrag (me);
  33724. if (checker.shouldBailOut())
  33725. return;
  33726. Desktop& desktop = Desktop::getInstance();
  33727. desktop.resetTimer();
  33728. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33729. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33730. }
  33731. }
  33732. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33733. {
  33734. Desktop& desktop = Desktop::getInstance();
  33735. BailOutChecker checker (this);
  33736. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33737. this, this, time, relativePos, time, 0, false);
  33738. if (isCurrentlyBlockedByAnotherModalComponent())
  33739. {
  33740. // allow blocked mouse-events to go to global listeners..
  33741. desktop.sendMouseMove();
  33742. }
  33743. else
  33744. {
  33745. flags.mouseOverFlag = true;
  33746. mouseMove (me);
  33747. if (checker.shouldBailOut())
  33748. return;
  33749. desktop.resetTimer();
  33750. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33751. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33752. }
  33753. }
  33754. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33755. const Time& time, const float amountX, const float amountY)
  33756. {
  33757. Desktop& desktop = Desktop::getInstance();
  33758. BailOutChecker checker (this);
  33759. const float wheelIncrementX = amountX / 256.0f;
  33760. const float wheelIncrementY = amountY / 256.0f;
  33761. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33762. this, this, time, relativePos, time, 0, false);
  33763. if (isCurrentlyBlockedByAnotherModalComponent())
  33764. {
  33765. // allow blocked mouse-events to go to global listeners..
  33766. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33767. }
  33768. else
  33769. {
  33770. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33771. if (checker.shouldBailOut())
  33772. return;
  33773. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33774. if (! checker.shouldBailOut())
  33775. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33776. }
  33777. }
  33778. void Component::sendFakeMouseMove() const
  33779. {
  33780. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33781. if (! mainMouse.isDragging())
  33782. mainMouse.triggerFakeMove();
  33783. }
  33784. void Component::beginDragAutoRepeat (const int interval)
  33785. {
  33786. Desktop::getInstance().beginDragAutoRepeat (interval);
  33787. }
  33788. void Component::broughtToFront()
  33789. {
  33790. }
  33791. void Component::internalBroughtToFront()
  33792. {
  33793. if (flags.hasHeavyweightPeerFlag)
  33794. Desktop::getInstance().componentBroughtToFront (this);
  33795. BailOutChecker checker (this);
  33796. broughtToFront();
  33797. if (checker.shouldBailOut())
  33798. return;
  33799. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33800. if (checker.shouldBailOut())
  33801. return;
  33802. // When brought to the front and there's a modal component blocking this one,
  33803. // we need to bring the modal one to the front instead..
  33804. Component* const cm = getCurrentlyModalComponent();
  33805. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33806. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33807. }
  33808. void Component::focusGained (FocusChangeType)
  33809. {
  33810. // base class does nothing
  33811. }
  33812. void Component::internalFocusGain (const FocusChangeType cause)
  33813. {
  33814. internalFocusGain (cause, WeakReference<Component> (this));
  33815. }
  33816. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33817. {
  33818. focusGained (cause);
  33819. if (safePointer != 0)
  33820. internalChildFocusChange (cause, safePointer);
  33821. }
  33822. void Component::focusLost (FocusChangeType)
  33823. {
  33824. // base class does nothing
  33825. }
  33826. void Component::internalFocusLoss (const FocusChangeType cause)
  33827. {
  33828. WeakReference<Component> safePointer (this);
  33829. focusLost (focusChangedDirectly);
  33830. if (safePointer != 0)
  33831. internalChildFocusChange (cause, safePointer);
  33832. }
  33833. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33834. {
  33835. // base class does nothing
  33836. }
  33837. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33838. {
  33839. const bool childIsNowFocused = hasKeyboardFocus (true);
  33840. if (flags.childCompFocusedFlag != childIsNowFocused)
  33841. {
  33842. flags.childCompFocusedFlag = childIsNowFocused;
  33843. focusOfChildComponentChanged (cause);
  33844. if (safePointer == 0)
  33845. return;
  33846. }
  33847. if (parentComponent != 0)
  33848. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33849. }
  33850. bool Component::isEnabled() const throw()
  33851. {
  33852. return (! flags.isDisabledFlag)
  33853. && (parentComponent == 0 || parentComponent->isEnabled());
  33854. }
  33855. void Component::setEnabled (const bool shouldBeEnabled)
  33856. {
  33857. if (flags.isDisabledFlag == shouldBeEnabled)
  33858. {
  33859. flags.isDisabledFlag = ! shouldBeEnabled;
  33860. // if any parent components are disabled, setting our flag won't make a difference,
  33861. // so no need to send a change message
  33862. if (parentComponent == 0 || parentComponent->isEnabled())
  33863. sendEnablementChangeMessage();
  33864. }
  33865. }
  33866. void Component::sendEnablementChangeMessage()
  33867. {
  33868. WeakReference<Component> safePointer (this);
  33869. enablementChanged();
  33870. if (safePointer == 0)
  33871. return;
  33872. for (int i = getNumChildComponents(); --i >= 0;)
  33873. {
  33874. Component* const c = getChildComponent (i);
  33875. if (c != 0)
  33876. {
  33877. c->sendEnablementChangeMessage();
  33878. if (safePointer == 0)
  33879. return;
  33880. }
  33881. }
  33882. }
  33883. void Component::enablementChanged()
  33884. {
  33885. }
  33886. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33887. {
  33888. flags.wantsFocusFlag = wantsFocus;
  33889. }
  33890. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33891. {
  33892. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33893. }
  33894. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33895. {
  33896. return ! flags.dontFocusOnMouseClickFlag;
  33897. }
  33898. bool Component::getWantsKeyboardFocus() const throw()
  33899. {
  33900. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33901. }
  33902. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33903. {
  33904. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33905. }
  33906. bool Component::isFocusContainer() const throw()
  33907. {
  33908. return flags.isFocusContainerFlag;
  33909. }
  33910. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33911. int Component::getExplicitFocusOrder() const
  33912. {
  33913. return properties [juce_explicitFocusOrderId];
  33914. }
  33915. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33916. {
  33917. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33918. }
  33919. KeyboardFocusTraverser* Component::createFocusTraverser()
  33920. {
  33921. if (flags.isFocusContainerFlag || parentComponent == 0)
  33922. return new KeyboardFocusTraverser();
  33923. return parentComponent->createFocusTraverser();
  33924. }
  33925. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33926. {
  33927. // give the focus to this component
  33928. if (currentlyFocusedComponent != this)
  33929. {
  33930. // get the focus onto our desktop window
  33931. ComponentPeer* const peer = getPeer();
  33932. if (peer != 0)
  33933. {
  33934. WeakReference<Component> safePointer (this);
  33935. peer->grabFocus();
  33936. if (peer->isFocused() && currentlyFocusedComponent != this)
  33937. {
  33938. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33939. currentlyFocusedComponent = this;
  33940. Desktop::getInstance().triggerFocusCallback();
  33941. // call this after setting currentlyFocusedComponent so that the one that's
  33942. // losing it has a chance to see where focus is going
  33943. if (componentLosingFocus != 0)
  33944. componentLosingFocus->internalFocusLoss (cause);
  33945. if (currentlyFocusedComponent == this)
  33946. internalFocusGain (cause, safePointer);
  33947. }
  33948. }
  33949. }
  33950. }
  33951. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33952. {
  33953. if (isShowing())
  33954. {
  33955. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33956. {
  33957. takeKeyboardFocus (cause);
  33958. }
  33959. else
  33960. {
  33961. if (isParentOf (currentlyFocusedComponent)
  33962. && currentlyFocusedComponent->isShowing())
  33963. {
  33964. // do nothing if the focused component is actually a child of ours..
  33965. }
  33966. else
  33967. {
  33968. // find the default child component..
  33969. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33970. if (traverser != 0)
  33971. {
  33972. Component* const defaultComp = traverser->getDefaultComponent (this);
  33973. traverser = 0;
  33974. if (defaultComp != 0)
  33975. {
  33976. defaultComp->grabFocusInternal (cause, false);
  33977. return;
  33978. }
  33979. }
  33980. if (canTryParent && parentComponent != 0)
  33981. {
  33982. // if no children want it and we're allowed to try our parent comp,
  33983. // then pass up to parent, which will try our siblings.
  33984. parentComponent->grabFocusInternal (cause, true);
  33985. }
  33986. }
  33987. }
  33988. }
  33989. }
  33990. void Component::grabKeyboardFocus()
  33991. {
  33992. // if component methods are being called from threads other than the message
  33993. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33994. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33995. grabFocusInternal (focusChangedDirectly);
  33996. }
  33997. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33998. {
  33999. // if component methods are being called from threads other than the message
  34000. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34001. CHECK_MESSAGE_MANAGER_IS_LOCKED
  34002. if (parentComponent != 0)
  34003. {
  34004. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34005. if (traverser != 0)
  34006. {
  34007. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34008. : traverser->getPreviousComponent (this);
  34009. traverser = 0;
  34010. if (nextComp != 0)
  34011. {
  34012. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34013. {
  34014. WeakReference<Component> nextCompPointer (nextComp);
  34015. internalModalInputAttempt();
  34016. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34017. return;
  34018. }
  34019. nextComp->grabFocusInternal (focusChangedByTabKey);
  34020. return;
  34021. }
  34022. }
  34023. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  34024. }
  34025. }
  34026. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34027. {
  34028. return (currentlyFocusedComponent == this)
  34029. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34030. }
  34031. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34032. {
  34033. return currentlyFocusedComponent;
  34034. }
  34035. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  34036. {
  34037. Component* const componentLosingFocus = currentlyFocusedComponent;
  34038. currentlyFocusedComponent = 0;
  34039. if (sendFocusLossEvent && componentLosingFocus != 0)
  34040. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34041. Desktop::getInstance().triggerFocusCallback();
  34042. }
  34043. bool Component::isMouseOver (const bool includeChildren) const
  34044. {
  34045. if (flags.mouseOverFlag)
  34046. return true;
  34047. if (includeChildren)
  34048. {
  34049. Desktop& desktop = Desktop::getInstance();
  34050. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34051. {
  34052. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  34053. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  34054. return true;
  34055. }
  34056. }
  34057. return false;
  34058. }
  34059. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  34060. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  34061. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34062. {
  34063. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34064. }
  34065. const Point<int> Component::getMouseXYRelative() const
  34066. {
  34067. return getLocalPoint (0, Desktop::getMousePosition());
  34068. }
  34069. const Rectangle<int> Component::getParentMonitorArea() const
  34070. {
  34071. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  34072. }
  34073. void Component::addKeyListener (KeyListener* const newListener)
  34074. {
  34075. if (keyListeners == 0)
  34076. keyListeners = new Array <KeyListener*>();
  34077. keyListeners->addIfNotAlreadyThere (newListener);
  34078. }
  34079. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34080. {
  34081. if (keyListeners != 0)
  34082. keyListeners->removeValue (listenerToRemove);
  34083. }
  34084. bool Component::keyPressed (const KeyPress&)
  34085. {
  34086. return false;
  34087. }
  34088. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34089. {
  34090. return false;
  34091. }
  34092. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34093. {
  34094. if (parentComponent != 0)
  34095. parentComponent->modifierKeysChanged (modifiers);
  34096. }
  34097. void Component::internalModifierKeysChanged()
  34098. {
  34099. sendFakeMouseMove();
  34100. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34101. }
  34102. ComponentPeer* Component::getPeer() const
  34103. {
  34104. if (flags.hasHeavyweightPeerFlag)
  34105. return ComponentPeer::getPeerFor (this);
  34106. else if (parentComponent == 0)
  34107. return 0;
  34108. return parentComponent->getPeer();
  34109. }
  34110. Component::BailOutChecker::BailOutChecker (Component* const component)
  34111. : safePointer (component)
  34112. {
  34113. jassert (component != 0);
  34114. }
  34115. bool Component::BailOutChecker::shouldBailOut() const throw()
  34116. {
  34117. return safePointer == 0;
  34118. }
  34119. END_JUCE_NAMESPACE
  34120. /*** End of inlined file: juce_Component.cpp ***/
  34121. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34122. BEGIN_JUCE_NAMESPACE
  34123. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34124. void ComponentListener::componentBroughtToFront (Component&) {}
  34125. void ComponentListener::componentVisibilityChanged (Component&) {}
  34126. void ComponentListener::componentChildrenChanged (Component&) {}
  34127. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34128. void ComponentListener::componentNameChanged (Component&) {}
  34129. void ComponentListener::componentBeingDeleted (Component&) {}
  34130. END_JUCE_NAMESPACE
  34131. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34132. /*** Start of inlined file: juce_Desktop.cpp ***/
  34133. BEGIN_JUCE_NAMESPACE
  34134. Desktop::Desktop()
  34135. : mouseClickCounter (0),
  34136. kioskModeComponent (0),
  34137. allowedOrientations (allOrientations)
  34138. {
  34139. createMouseInputSources();
  34140. refreshMonitorSizes();
  34141. }
  34142. Desktop::~Desktop()
  34143. {
  34144. jassert (instance == this);
  34145. instance = 0;
  34146. // doh! If you don't delete all your windows before exiting, you're going to
  34147. // be leaking memory!
  34148. jassert (desktopComponents.size() == 0);
  34149. }
  34150. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34151. {
  34152. if (instance == 0)
  34153. instance = new Desktop();
  34154. return *instance;
  34155. }
  34156. Desktop* Desktop::instance = 0;
  34157. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34158. const bool clipToWorkArea);
  34159. void Desktop::refreshMonitorSizes()
  34160. {
  34161. Array <Rectangle<int> > oldClipped, oldUnclipped;
  34162. oldClipped.swapWithArray (monitorCoordsClipped);
  34163. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  34164. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34165. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34166. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34167. if (oldClipped != monitorCoordsClipped
  34168. || oldUnclipped != monitorCoordsUnclipped)
  34169. {
  34170. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34171. {
  34172. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34173. if (p != 0)
  34174. p->handleScreenSizeChange();
  34175. }
  34176. }
  34177. }
  34178. int Desktop::getNumDisplayMonitors() const throw()
  34179. {
  34180. return monitorCoordsClipped.size();
  34181. }
  34182. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34183. {
  34184. return clippedToWorkArea ? monitorCoordsClipped [index]
  34185. : monitorCoordsUnclipped [index];
  34186. }
  34187. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34188. {
  34189. RectangleList rl;
  34190. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34191. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34192. return rl;
  34193. }
  34194. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34195. {
  34196. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34197. }
  34198. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34199. {
  34200. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34201. double bestDistance = 1.0e10;
  34202. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34203. {
  34204. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34205. if (rect.contains (position))
  34206. return rect;
  34207. const double distance = rect.getCentre().getDistanceFrom (position);
  34208. if (distance < bestDistance)
  34209. {
  34210. bestDistance = distance;
  34211. best = rect;
  34212. }
  34213. }
  34214. return best;
  34215. }
  34216. int Desktop::getNumComponents() const throw()
  34217. {
  34218. return desktopComponents.size();
  34219. }
  34220. Component* Desktop::getComponent (const int index) const throw()
  34221. {
  34222. return desktopComponents [index];
  34223. }
  34224. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34225. {
  34226. for (int i = desktopComponents.size(); --i >= 0;)
  34227. {
  34228. Component* const c = desktopComponents.getUnchecked(i);
  34229. if (c->isVisible())
  34230. {
  34231. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34232. if (c->contains (relative))
  34233. return c->getComponentAt (relative);
  34234. }
  34235. }
  34236. return 0;
  34237. }
  34238. void Desktop::addDesktopComponent (Component* const c)
  34239. {
  34240. jassert (c != 0);
  34241. jassert (! desktopComponents.contains (c));
  34242. desktopComponents.addIfNotAlreadyThere (c);
  34243. }
  34244. void Desktop::removeDesktopComponent (Component* const c)
  34245. {
  34246. desktopComponents.removeValue (c);
  34247. }
  34248. void Desktop::componentBroughtToFront (Component* const c)
  34249. {
  34250. const int index = desktopComponents.indexOf (c);
  34251. jassert (index >= 0);
  34252. if (index >= 0)
  34253. {
  34254. int newIndex = -1;
  34255. if (! c->isAlwaysOnTop())
  34256. {
  34257. newIndex = desktopComponents.size();
  34258. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34259. --newIndex;
  34260. --newIndex;
  34261. }
  34262. desktopComponents.move (index, newIndex);
  34263. }
  34264. }
  34265. const Point<int> Desktop::getMousePosition()
  34266. {
  34267. return getInstance().getMainMouseSource().getScreenPosition();
  34268. }
  34269. const Point<int> Desktop::getLastMouseDownPosition()
  34270. {
  34271. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34272. }
  34273. int Desktop::getMouseButtonClickCounter()
  34274. {
  34275. return getInstance().mouseClickCounter;
  34276. }
  34277. void Desktop::incrementMouseClickCounter() throw()
  34278. {
  34279. ++mouseClickCounter;
  34280. }
  34281. int Desktop::getNumDraggingMouseSources() const throw()
  34282. {
  34283. int num = 0;
  34284. for (int i = mouseSources.size(); --i >= 0;)
  34285. if (mouseSources.getUnchecked(i)->isDragging())
  34286. ++num;
  34287. return num;
  34288. }
  34289. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34290. {
  34291. int num = 0;
  34292. for (int i = mouseSources.size(); --i >= 0;)
  34293. {
  34294. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34295. if (mi->isDragging())
  34296. {
  34297. if (index == num)
  34298. return mi;
  34299. ++num;
  34300. }
  34301. }
  34302. return 0;
  34303. }
  34304. class MouseDragAutoRepeater : public Timer
  34305. {
  34306. public:
  34307. MouseDragAutoRepeater() {}
  34308. void timerCallback()
  34309. {
  34310. Desktop& desktop = Desktop::getInstance();
  34311. int numMiceDown = 0;
  34312. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34313. {
  34314. MouseInputSource* const source = desktop.getMouseSource(i);
  34315. if (source->isDragging())
  34316. {
  34317. source->triggerFakeMove();
  34318. ++numMiceDown;
  34319. }
  34320. }
  34321. if (numMiceDown == 0)
  34322. desktop.beginDragAutoRepeat (0);
  34323. }
  34324. private:
  34325. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34326. };
  34327. void Desktop::beginDragAutoRepeat (const int interval)
  34328. {
  34329. if (interval > 0)
  34330. {
  34331. if (dragRepeater == 0)
  34332. dragRepeater = new MouseDragAutoRepeater();
  34333. if (dragRepeater->getTimerInterval() != interval)
  34334. dragRepeater->startTimer (interval);
  34335. }
  34336. else
  34337. {
  34338. dragRepeater = 0;
  34339. }
  34340. }
  34341. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34342. {
  34343. focusListeners.add (listener);
  34344. }
  34345. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34346. {
  34347. focusListeners.remove (listener);
  34348. }
  34349. void Desktop::triggerFocusCallback()
  34350. {
  34351. triggerAsyncUpdate();
  34352. }
  34353. void Desktop::handleAsyncUpdate()
  34354. {
  34355. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34356. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34357. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34358. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34359. }
  34360. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34361. {
  34362. mouseListeners.add (listener);
  34363. resetTimer();
  34364. }
  34365. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34366. {
  34367. mouseListeners.remove (listener);
  34368. resetTimer();
  34369. }
  34370. void Desktop::timerCallback()
  34371. {
  34372. if (lastFakeMouseMove != getMousePosition())
  34373. sendMouseMove();
  34374. }
  34375. void Desktop::sendMouseMove()
  34376. {
  34377. if (! mouseListeners.isEmpty())
  34378. {
  34379. startTimer (20);
  34380. lastFakeMouseMove = getMousePosition();
  34381. Component* const target = findComponentAt (lastFakeMouseMove);
  34382. if (target != 0)
  34383. {
  34384. Component::BailOutChecker checker (target);
  34385. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34386. const Time now (Time::getCurrentTime());
  34387. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34388. target, target, now, pos, now, 0, false);
  34389. if (me.mods.isAnyMouseButtonDown())
  34390. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34391. else
  34392. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34393. }
  34394. }
  34395. }
  34396. void Desktop::resetTimer()
  34397. {
  34398. if (mouseListeners.size() == 0)
  34399. stopTimer();
  34400. else
  34401. startTimer (100);
  34402. lastFakeMouseMove = getMousePosition();
  34403. }
  34404. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34405. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34406. {
  34407. if (kioskModeComponent != componentToUse)
  34408. {
  34409. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34410. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34411. if (kioskModeComponent != 0)
  34412. {
  34413. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34414. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34415. }
  34416. kioskModeComponent = componentToUse;
  34417. if (kioskModeComponent != 0)
  34418. {
  34419. // Only components that are already on the desktop can be put into kiosk mode!
  34420. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34421. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34422. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34423. }
  34424. }
  34425. }
  34426. void Desktop::setOrientationsEnabled (const int newOrientations)
  34427. {
  34428. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34429. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34430. allowedOrientations = newOrientations;
  34431. }
  34432. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34433. {
  34434. // Make sure you only pass one valid flag in here...
  34435. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34436. return (allowedOrientations & orientation) != 0;
  34437. }
  34438. END_JUCE_NAMESPACE
  34439. /*** End of inlined file: juce_Desktop.cpp ***/
  34440. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34441. BEGIN_JUCE_NAMESPACE
  34442. class ModalComponentManager::ModalItem : public ComponentListener
  34443. {
  34444. public:
  34445. ModalItem (Component* const comp, Callback* const callback)
  34446. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34447. {
  34448. if (callback != 0)
  34449. callbacks.add (callback);
  34450. jassert (comp != 0);
  34451. component->addComponentListener (this);
  34452. }
  34453. ~ModalItem()
  34454. {
  34455. if (! isDeleted)
  34456. component->removeComponentListener (this);
  34457. }
  34458. void componentBeingDeleted (Component&)
  34459. {
  34460. isDeleted = true;
  34461. cancel();
  34462. }
  34463. void componentVisibilityChanged (Component&)
  34464. {
  34465. if (! component->isShowing())
  34466. cancel();
  34467. }
  34468. void componentParentHierarchyChanged (Component&)
  34469. {
  34470. if (! component->isShowing())
  34471. cancel();
  34472. }
  34473. void cancel()
  34474. {
  34475. if (isActive)
  34476. {
  34477. isActive = false;
  34478. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34479. }
  34480. }
  34481. Component* component;
  34482. OwnedArray<Callback> callbacks;
  34483. int returnValue;
  34484. bool isActive, isDeleted;
  34485. private:
  34486. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34487. };
  34488. ModalComponentManager::ModalComponentManager()
  34489. {
  34490. }
  34491. ModalComponentManager::~ModalComponentManager()
  34492. {
  34493. clearSingletonInstance();
  34494. }
  34495. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34496. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34497. {
  34498. if (component != 0)
  34499. stack.add (new ModalItem (component, callback));
  34500. }
  34501. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34502. {
  34503. if (callback != 0)
  34504. {
  34505. ScopedPointer<Callback> callbackDeleter (callback);
  34506. for (int i = stack.size(); --i >= 0;)
  34507. {
  34508. ModalItem* const item = stack.getUnchecked(i);
  34509. if (item->component == component)
  34510. {
  34511. item->callbacks.add (callback);
  34512. callbackDeleter.release();
  34513. break;
  34514. }
  34515. }
  34516. }
  34517. }
  34518. void ModalComponentManager::endModal (Component* component)
  34519. {
  34520. for (int i = stack.size(); --i >= 0;)
  34521. {
  34522. ModalItem* const item = stack.getUnchecked(i);
  34523. if (item->component == component)
  34524. item->cancel();
  34525. }
  34526. }
  34527. void ModalComponentManager::endModal (Component* component, int returnValue)
  34528. {
  34529. for (int i = stack.size(); --i >= 0;)
  34530. {
  34531. ModalItem* const item = stack.getUnchecked(i);
  34532. if (item->component == component)
  34533. {
  34534. item->returnValue = returnValue;
  34535. item->cancel();
  34536. }
  34537. }
  34538. }
  34539. int ModalComponentManager::getNumModalComponents() const
  34540. {
  34541. int n = 0;
  34542. for (int i = 0; i < stack.size(); ++i)
  34543. if (stack.getUnchecked(i)->isActive)
  34544. ++n;
  34545. return n;
  34546. }
  34547. Component* ModalComponentManager::getModalComponent (const int index) const
  34548. {
  34549. int n = 0;
  34550. for (int i = stack.size(); --i >= 0;)
  34551. {
  34552. const ModalItem* const item = stack.getUnchecked(i);
  34553. if (item->isActive)
  34554. if (n++ == index)
  34555. return item->component;
  34556. }
  34557. return 0;
  34558. }
  34559. bool ModalComponentManager::isModal (Component* const comp) const
  34560. {
  34561. for (int i = stack.size(); --i >= 0;)
  34562. {
  34563. const ModalItem* const item = stack.getUnchecked(i);
  34564. if (item->isActive && item->component == comp)
  34565. return true;
  34566. }
  34567. return false;
  34568. }
  34569. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34570. {
  34571. return comp == getModalComponent (0);
  34572. }
  34573. void ModalComponentManager::handleAsyncUpdate()
  34574. {
  34575. for (int i = stack.size(); --i >= 0;)
  34576. {
  34577. const ModalItem* const item = stack.getUnchecked(i);
  34578. if (! item->isActive)
  34579. {
  34580. for (int j = item->callbacks.size(); --j >= 0;)
  34581. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34582. stack.remove (i);
  34583. }
  34584. }
  34585. }
  34586. void ModalComponentManager::bringModalComponentsToFront()
  34587. {
  34588. ComponentPeer* lastOne = 0;
  34589. for (int i = 0; i < getNumModalComponents(); ++i)
  34590. {
  34591. Component* const c = getModalComponent (i);
  34592. if (c == 0)
  34593. break;
  34594. ComponentPeer* peer = c->getPeer();
  34595. if (peer != 0 && peer != lastOne)
  34596. {
  34597. if (lastOne == 0)
  34598. {
  34599. peer->toFront (true);
  34600. peer->grabFocus();
  34601. }
  34602. else
  34603. peer->toBehind (lastOne);
  34604. lastOne = peer;
  34605. }
  34606. }
  34607. }
  34608. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34609. {
  34610. public:
  34611. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34612. ~ReturnValueRetriever() {}
  34613. void modalStateFinished (int returnValue)
  34614. {
  34615. finished = true;
  34616. value = returnValue;
  34617. }
  34618. private:
  34619. int& value;
  34620. bool& finished;
  34621. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34622. };
  34623. int ModalComponentManager::runEventLoopForCurrentComponent()
  34624. {
  34625. // This can only be run from the message thread!
  34626. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34627. Component* currentlyModal = getModalComponent (0);
  34628. if (currentlyModal == 0)
  34629. return 0;
  34630. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34631. int returnValue = 0;
  34632. bool finished = false;
  34633. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34634. JUCE_TRY
  34635. {
  34636. while (! finished)
  34637. {
  34638. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34639. break;
  34640. }
  34641. }
  34642. JUCE_CATCH_EXCEPTION
  34643. if (prevFocused != 0)
  34644. prevFocused->grabKeyboardFocus();
  34645. return returnValue;
  34646. }
  34647. END_JUCE_NAMESPACE
  34648. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34649. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34650. BEGIN_JUCE_NAMESPACE
  34651. ArrowButton::ArrowButton (const String& name,
  34652. float arrowDirectionInRadians,
  34653. const Colour& arrowColour)
  34654. : Button (name),
  34655. colour (arrowColour)
  34656. {
  34657. path.lineTo (0.0f, 1.0f);
  34658. path.lineTo (1.0f, 0.5f);
  34659. path.closeSubPath();
  34660. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34661. 0.5f, 0.5f));
  34662. setComponentEffect (&shadow);
  34663. buttonStateChanged();
  34664. }
  34665. ArrowButton::~ArrowButton()
  34666. {
  34667. }
  34668. void ArrowButton::paintButton (Graphics& g,
  34669. bool /*isMouseOverButton*/,
  34670. bool /*isButtonDown*/)
  34671. {
  34672. g.setColour (colour);
  34673. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34674. (float) offset,
  34675. (float) (getWidth() - 3),
  34676. (float) (getHeight() - 3),
  34677. false));
  34678. }
  34679. void ArrowButton::buttonStateChanged()
  34680. {
  34681. offset = (isDown()) ? 1 : 0;
  34682. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34683. 0.3f, -1, 0);
  34684. }
  34685. END_JUCE_NAMESPACE
  34686. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34687. /*** Start of inlined file: juce_Button.cpp ***/
  34688. BEGIN_JUCE_NAMESPACE
  34689. class Button::RepeatTimer : public Timer
  34690. {
  34691. public:
  34692. RepeatTimer (Button& owner_) : owner (owner_) {}
  34693. void timerCallback() { owner.repeatTimerCallback(); }
  34694. private:
  34695. Button& owner;
  34696. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34697. };
  34698. Button::Button (const String& name)
  34699. : Component (name),
  34700. text (name),
  34701. buttonPressTime (0),
  34702. lastRepeatTime (0),
  34703. commandManagerToUse (0),
  34704. autoRepeatDelay (-1),
  34705. autoRepeatSpeed (0),
  34706. autoRepeatMinimumDelay (-1),
  34707. radioGroupId (0),
  34708. commandID (0),
  34709. connectedEdgeFlags (0),
  34710. buttonState (buttonNormal),
  34711. lastToggleState (false),
  34712. clickTogglesState (false),
  34713. needsToRelease (false),
  34714. needsRepainting (false),
  34715. isKeyDown (false),
  34716. triggerOnMouseDown (false),
  34717. generateTooltip (false)
  34718. {
  34719. setWantsKeyboardFocus (true);
  34720. isOn.addListener (this);
  34721. }
  34722. Button::~Button()
  34723. {
  34724. isOn.removeListener (this);
  34725. if (commandManagerToUse != 0)
  34726. commandManagerToUse->removeListener (this);
  34727. repeatTimer = 0;
  34728. clearShortcuts();
  34729. }
  34730. void Button::setButtonText (const String& newText)
  34731. {
  34732. if (text != newText)
  34733. {
  34734. text = newText;
  34735. repaint();
  34736. }
  34737. }
  34738. void Button::setTooltip (const String& newTooltip)
  34739. {
  34740. SettableTooltipClient::setTooltip (newTooltip);
  34741. generateTooltip = false;
  34742. }
  34743. const String Button::getTooltip()
  34744. {
  34745. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34746. {
  34747. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34748. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34749. for (int i = 0; i < keyPresses.size(); ++i)
  34750. {
  34751. const String key (keyPresses.getReference(i).getTextDescription());
  34752. tt << " [";
  34753. if (key.length() == 1)
  34754. tt << TRANS("shortcut") << ": '" << key << "']";
  34755. else
  34756. tt << key << ']';
  34757. }
  34758. return tt;
  34759. }
  34760. return SettableTooltipClient::getTooltip();
  34761. }
  34762. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34763. {
  34764. if (connectedEdgeFlags != connectedEdgeFlags_)
  34765. {
  34766. connectedEdgeFlags = connectedEdgeFlags_;
  34767. repaint();
  34768. }
  34769. }
  34770. void Button::setToggleState (const bool shouldBeOn,
  34771. const bool sendChangeNotification)
  34772. {
  34773. if (shouldBeOn != lastToggleState)
  34774. {
  34775. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34776. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34777. lastToggleState = shouldBeOn;
  34778. repaint();
  34779. WeakReference<Component> deletionWatcher (this);
  34780. if (sendChangeNotification)
  34781. {
  34782. sendClickMessage (ModifierKeys());
  34783. if (deletionWatcher == 0)
  34784. return;
  34785. }
  34786. if (lastToggleState)
  34787. {
  34788. turnOffOtherButtonsInGroup (sendChangeNotification);
  34789. if (deletionWatcher == 0)
  34790. return;
  34791. }
  34792. sendStateMessage();
  34793. }
  34794. }
  34795. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34796. {
  34797. clickTogglesState = shouldToggle;
  34798. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34799. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34800. // it is that this button represents, and the button will update its state to reflect this
  34801. // in the applicationCommandListChanged() method.
  34802. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34803. }
  34804. bool Button::getClickingTogglesState() const throw()
  34805. {
  34806. return clickTogglesState;
  34807. }
  34808. void Button::valueChanged (Value& value)
  34809. {
  34810. if (value.refersToSameSourceAs (isOn))
  34811. setToggleState (isOn.getValue(), true);
  34812. }
  34813. void Button::setRadioGroupId (const int newGroupId)
  34814. {
  34815. if (radioGroupId != newGroupId)
  34816. {
  34817. radioGroupId = newGroupId;
  34818. if (lastToggleState)
  34819. turnOffOtherButtonsInGroup (true);
  34820. }
  34821. }
  34822. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34823. {
  34824. Component* const p = getParentComponent();
  34825. if (p != 0 && radioGroupId != 0)
  34826. {
  34827. WeakReference<Component> deletionWatcher (this);
  34828. for (int i = p->getNumChildComponents(); --i >= 0;)
  34829. {
  34830. Component* const c = p->getChildComponent (i);
  34831. if (c != this)
  34832. {
  34833. Button* const b = dynamic_cast <Button*> (c);
  34834. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34835. {
  34836. b->setToggleState (false, sendChangeNotification);
  34837. if (deletionWatcher == 0)
  34838. return;
  34839. }
  34840. }
  34841. }
  34842. }
  34843. }
  34844. void Button::enablementChanged()
  34845. {
  34846. updateState();
  34847. repaint();
  34848. }
  34849. Button::ButtonState Button::updateState()
  34850. {
  34851. return updateState (isMouseOver (true), isMouseButtonDown());
  34852. }
  34853. Button::ButtonState Button::updateState (const bool over, const bool down)
  34854. {
  34855. ButtonState newState = buttonNormal;
  34856. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34857. {
  34858. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34859. newState = buttonDown;
  34860. else if (over)
  34861. newState = buttonOver;
  34862. }
  34863. setState (newState);
  34864. return newState;
  34865. }
  34866. void Button::setState (const ButtonState newState)
  34867. {
  34868. if (buttonState != newState)
  34869. {
  34870. buttonState = newState;
  34871. repaint();
  34872. if (buttonState == buttonDown)
  34873. {
  34874. buttonPressTime = Time::getApproximateMillisecondCounter();
  34875. lastRepeatTime = 0;
  34876. }
  34877. sendStateMessage();
  34878. }
  34879. }
  34880. bool Button::isDown() const throw()
  34881. {
  34882. return buttonState == buttonDown;
  34883. }
  34884. bool Button::isOver() const throw()
  34885. {
  34886. return buttonState != buttonNormal;
  34887. }
  34888. void Button::buttonStateChanged()
  34889. {
  34890. }
  34891. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34892. {
  34893. const uint32 now = Time::getApproximateMillisecondCounter();
  34894. return now > buttonPressTime ? now - buttonPressTime : 0;
  34895. }
  34896. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34897. {
  34898. triggerOnMouseDown = isTriggeredOnMouseDown;
  34899. }
  34900. void Button::clicked()
  34901. {
  34902. }
  34903. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34904. {
  34905. clicked();
  34906. }
  34907. static const int clickMessageId = 0x2f3f4f99;
  34908. void Button::triggerClick()
  34909. {
  34910. postCommandMessage (clickMessageId);
  34911. }
  34912. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34913. {
  34914. if (clickTogglesState)
  34915. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34916. sendClickMessage (modifiers);
  34917. }
  34918. void Button::flashButtonState()
  34919. {
  34920. if (isEnabled())
  34921. {
  34922. needsToRelease = true;
  34923. setState (buttonDown);
  34924. getRepeatTimer().startTimer (100);
  34925. }
  34926. }
  34927. void Button::handleCommandMessage (int commandId)
  34928. {
  34929. if (commandId == clickMessageId)
  34930. {
  34931. if (isEnabled())
  34932. {
  34933. flashButtonState();
  34934. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34935. }
  34936. }
  34937. else
  34938. {
  34939. Component::handleCommandMessage (commandId);
  34940. }
  34941. }
  34942. void Button::addListener (ButtonListener* const newListener)
  34943. {
  34944. buttonListeners.add (newListener);
  34945. }
  34946. void Button::removeListener (ButtonListener* const listener)
  34947. {
  34948. buttonListeners.remove (listener);
  34949. }
  34950. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34951. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34952. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34953. {
  34954. Component::BailOutChecker checker (this);
  34955. if (commandManagerToUse != 0 && commandID != 0)
  34956. {
  34957. ApplicationCommandTarget::InvocationInfo info (commandID);
  34958. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34959. info.originatingComponent = this;
  34960. commandManagerToUse->invoke (info, true);
  34961. }
  34962. clicked (modifiers);
  34963. if (! checker.shouldBailOut())
  34964. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34965. }
  34966. void Button::sendStateMessage()
  34967. {
  34968. Component::BailOutChecker checker (this);
  34969. buttonStateChanged();
  34970. if (! checker.shouldBailOut())
  34971. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34972. }
  34973. void Button::paint (Graphics& g)
  34974. {
  34975. if (needsToRelease && isEnabled())
  34976. {
  34977. needsToRelease = false;
  34978. needsRepainting = true;
  34979. }
  34980. paintButton (g, isOver(), isDown());
  34981. }
  34982. void Button::mouseEnter (const MouseEvent&)
  34983. {
  34984. updateState (true, false);
  34985. }
  34986. void Button::mouseExit (const MouseEvent&)
  34987. {
  34988. updateState (false, false);
  34989. }
  34990. void Button::mouseDown (const MouseEvent& e)
  34991. {
  34992. updateState (true, true);
  34993. if (isDown())
  34994. {
  34995. if (autoRepeatDelay >= 0)
  34996. getRepeatTimer().startTimer (autoRepeatDelay);
  34997. if (triggerOnMouseDown)
  34998. internalClickCallback (e.mods);
  34999. }
  35000. }
  35001. void Button::mouseUp (const MouseEvent& e)
  35002. {
  35003. const bool wasDown = isDown();
  35004. updateState (isMouseOver(), false);
  35005. if (wasDown && isOver() && ! triggerOnMouseDown)
  35006. internalClickCallback (e.mods);
  35007. }
  35008. void Button::mouseDrag (const MouseEvent&)
  35009. {
  35010. const ButtonState oldState = buttonState;
  35011. updateState (isMouseOver(), true);
  35012. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35013. getRepeatTimer().startTimer (autoRepeatSpeed);
  35014. }
  35015. void Button::focusGained (FocusChangeType)
  35016. {
  35017. updateState();
  35018. repaint();
  35019. }
  35020. void Button::focusLost (FocusChangeType)
  35021. {
  35022. updateState();
  35023. repaint();
  35024. }
  35025. void Button::visibilityChanged()
  35026. {
  35027. needsToRelease = false;
  35028. updateState();
  35029. }
  35030. void Button::parentHierarchyChanged()
  35031. {
  35032. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35033. if (newKeySource != keySource.get())
  35034. {
  35035. if (keySource != 0)
  35036. keySource->removeKeyListener (this);
  35037. keySource = newKeySource;
  35038. if (keySource != 0)
  35039. keySource->addKeyListener (this);
  35040. }
  35041. }
  35042. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35043. const int commandID_,
  35044. const bool generateTooltip_)
  35045. {
  35046. commandID = commandID_;
  35047. generateTooltip = generateTooltip_;
  35048. if (commandManagerToUse != commandManagerToUse_)
  35049. {
  35050. if (commandManagerToUse != 0)
  35051. commandManagerToUse->removeListener (this);
  35052. commandManagerToUse = commandManagerToUse_;
  35053. if (commandManagerToUse != 0)
  35054. commandManagerToUse->addListener (this);
  35055. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35056. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35057. // it is that this button represents, and the button will update its state to reflect this
  35058. // in the applicationCommandListChanged() method.
  35059. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35060. }
  35061. if (commandManagerToUse != 0)
  35062. applicationCommandListChanged();
  35063. else
  35064. setEnabled (true);
  35065. }
  35066. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35067. {
  35068. if (info.commandID == commandID
  35069. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35070. {
  35071. flashButtonState();
  35072. }
  35073. }
  35074. void Button::applicationCommandListChanged()
  35075. {
  35076. if (commandManagerToUse != 0)
  35077. {
  35078. ApplicationCommandInfo info (0);
  35079. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35080. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35081. if (target != 0)
  35082. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35083. }
  35084. }
  35085. void Button::addShortcut (const KeyPress& key)
  35086. {
  35087. if (key.isValid())
  35088. {
  35089. jassert (! isRegisteredForShortcut (key)); // already registered!
  35090. shortcuts.add (key);
  35091. parentHierarchyChanged();
  35092. }
  35093. }
  35094. void Button::clearShortcuts()
  35095. {
  35096. shortcuts.clear();
  35097. parentHierarchyChanged();
  35098. }
  35099. bool Button::isShortcutPressed() const
  35100. {
  35101. if (! isCurrentlyBlockedByAnotherModalComponent())
  35102. {
  35103. for (int i = shortcuts.size(); --i >= 0;)
  35104. if (shortcuts.getReference(i).isCurrentlyDown())
  35105. return true;
  35106. }
  35107. return false;
  35108. }
  35109. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35110. {
  35111. for (int i = shortcuts.size(); --i >= 0;)
  35112. if (key == shortcuts.getReference(i))
  35113. return true;
  35114. return false;
  35115. }
  35116. bool Button::keyStateChanged (const bool, Component*)
  35117. {
  35118. if (! isEnabled())
  35119. return false;
  35120. const bool wasDown = isKeyDown;
  35121. isKeyDown = isShortcutPressed();
  35122. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35123. getRepeatTimer().startTimer (autoRepeatDelay);
  35124. updateState();
  35125. if (isEnabled() && wasDown && ! isKeyDown)
  35126. {
  35127. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35128. // (return immediately - this button may now have been deleted)
  35129. return true;
  35130. }
  35131. return wasDown || isKeyDown;
  35132. }
  35133. bool Button::keyPressed (const KeyPress&, Component*)
  35134. {
  35135. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35136. return isShortcutPressed();
  35137. }
  35138. bool Button::keyPressed (const KeyPress& key)
  35139. {
  35140. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35141. {
  35142. triggerClick();
  35143. return true;
  35144. }
  35145. return false;
  35146. }
  35147. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35148. const int repeatMillisecs,
  35149. const int minimumDelayInMillisecs) throw()
  35150. {
  35151. autoRepeatDelay = initialDelayMillisecs;
  35152. autoRepeatSpeed = repeatMillisecs;
  35153. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35154. }
  35155. void Button::repeatTimerCallback()
  35156. {
  35157. if (needsRepainting)
  35158. {
  35159. getRepeatTimer().stopTimer();
  35160. updateState();
  35161. needsRepainting = false;
  35162. }
  35163. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  35164. {
  35165. int repeatSpeed = autoRepeatSpeed;
  35166. if (autoRepeatMinimumDelay >= 0)
  35167. {
  35168. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35169. timeHeldDown *= timeHeldDown;
  35170. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35171. }
  35172. repeatSpeed = jmax (1, repeatSpeed);
  35173. const uint32 now = Time::getMillisecondCounter();
  35174. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35175. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35176. repeatSpeed = jmax (1, repeatSpeed / 2);
  35177. lastRepeatTime = now;
  35178. getRepeatTimer().startTimer (repeatSpeed);
  35179. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35180. }
  35181. else if (! needsToRelease)
  35182. {
  35183. getRepeatTimer().stopTimer();
  35184. }
  35185. }
  35186. Button::RepeatTimer& Button::getRepeatTimer()
  35187. {
  35188. if (repeatTimer == 0)
  35189. repeatTimer = new RepeatTimer (*this);
  35190. return *repeatTimer;
  35191. }
  35192. END_JUCE_NAMESPACE
  35193. /*** End of inlined file: juce_Button.cpp ***/
  35194. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35195. BEGIN_JUCE_NAMESPACE
  35196. DrawableButton::DrawableButton (const String& name,
  35197. const DrawableButton::ButtonStyle buttonStyle)
  35198. : Button (name),
  35199. style (buttonStyle),
  35200. currentImage (0),
  35201. edgeIndent (3)
  35202. {
  35203. if (buttonStyle == ImageOnButtonBackground)
  35204. {
  35205. backgroundOff = Colour (0xffbbbbff);
  35206. backgroundOn = Colour (0xff3333ff);
  35207. }
  35208. else
  35209. {
  35210. backgroundOff = Colours::transparentBlack;
  35211. backgroundOn = Colour (0xaabbbbff);
  35212. }
  35213. }
  35214. DrawableButton::~DrawableButton()
  35215. {
  35216. }
  35217. void DrawableButton::setImages (const Drawable* normal,
  35218. const Drawable* over,
  35219. const Drawable* down,
  35220. const Drawable* disabled,
  35221. const Drawable* normalOn,
  35222. const Drawable* overOn,
  35223. const Drawable* downOn,
  35224. const Drawable* disabledOn)
  35225. {
  35226. jassert (normal != 0); // you really need to give it at least a normal image..
  35227. if (normal != 0) normalImage = normal->createCopy();
  35228. if (over != 0) overImage = over->createCopy();
  35229. if (down != 0) downImage = down->createCopy();
  35230. if (disabled != 0) disabledImage = disabled->createCopy();
  35231. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35232. if (overOn != 0) overImageOn = overOn->createCopy();
  35233. if (downOn != 0) downImageOn = downOn->createCopy();
  35234. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35235. buttonStateChanged();
  35236. }
  35237. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35238. {
  35239. if (style != newStyle)
  35240. {
  35241. style = newStyle;
  35242. buttonStateChanged();
  35243. }
  35244. }
  35245. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35246. const Colour& toggledOnColour)
  35247. {
  35248. if (backgroundOff != toggledOffColour
  35249. || backgroundOn != toggledOnColour)
  35250. {
  35251. backgroundOff = toggledOffColour;
  35252. backgroundOn = toggledOnColour;
  35253. repaint();
  35254. }
  35255. }
  35256. const Colour& DrawableButton::getBackgroundColour() const throw()
  35257. {
  35258. return getToggleState() ? backgroundOn
  35259. : backgroundOff;
  35260. }
  35261. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35262. {
  35263. edgeIndent = numPixelsIndent;
  35264. repaint();
  35265. resized();
  35266. }
  35267. void DrawableButton::resized()
  35268. {
  35269. Button::resized();
  35270. if (currentImage != 0)
  35271. {
  35272. if (style == ImageRaw)
  35273. {
  35274. currentImage->setOriginWithOriginalSize (Point<float>());
  35275. }
  35276. else
  35277. {
  35278. Rectangle<int> imageSpace;
  35279. if (style == ImageOnButtonBackground)
  35280. {
  35281. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35282. }
  35283. else
  35284. {
  35285. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35286. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35287. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35288. imageSpace.setBounds (indentX, indentY,
  35289. getWidth() - indentX * 2,
  35290. getHeight() - indentY * 2 - textH);
  35291. }
  35292. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35293. }
  35294. }
  35295. }
  35296. void DrawableButton::buttonStateChanged()
  35297. {
  35298. repaint();
  35299. Drawable* imageToDraw = 0;
  35300. float opacity = 1.0f;
  35301. if (isEnabled())
  35302. {
  35303. imageToDraw = getCurrentImage();
  35304. }
  35305. else
  35306. {
  35307. imageToDraw = getToggleState() ? disabledImageOn
  35308. : disabledImage;
  35309. if (imageToDraw == 0)
  35310. {
  35311. opacity = 0.4f;
  35312. imageToDraw = getNormalImage();
  35313. }
  35314. }
  35315. if (imageToDraw != currentImage)
  35316. {
  35317. removeChildComponent (currentImage);
  35318. currentImage = imageToDraw;
  35319. if (currentImage != 0)
  35320. {
  35321. addAndMakeVisible (currentImage);
  35322. DrawableButton::resized();
  35323. }
  35324. }
  35325. if (currentImage != 0)
  35326. currentImage->setAlpha (opacity);
  35327. }
  35328. void DrawableButton::paintButton (Graphics& g,
  35329. bool isMouseOverButton,
  35330. bool isButtonDown)
  35331. {
  35332. if (style == ImageOnButtonBackground)
  35333. {
  35334. getLookAndFeel().drawButtonBackground (g, *this,
  35335. getBackgroundColour(),
  35336. isMouseOverButton,
  35337. isButtonDown);
  35338. }
  35339. else
  35340. {
  35341. g.fillAll (getBackgroundColour());
  35342. const int textH = (style == ImageAboveTextLabel)
  35343. ? jmin (16, proportionOfHeight (0.25f))
  35344. : 0;
  35345. if (textH > 0)
  35346. {
  35347. g.setFont ((float) textH);
  35348. g.setColour (findColour (DrawableButton::textColourId)
  35349. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35350. g.drawFittedText (getButtonText(),
  35351. 2, getHeight() - textH - 1,
  35352. getWidth() - 4, textH,
  35353. Justification::centred, 1);
  35354. }
  35355. }
  35356. }
  35357. Drawable* DrawableButton::getCurrentImage() const throw()
  35358. {
  35359. if (isDown())
  35360. return getDownImage();
  35361. if (isOver())
  35362. return getOverImage();
  35363. return getNormalImage();
  35364. }
  35365. Drawable* DrawableButton::getNormalImage() const throw()
  35366. {
  35367. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35368. : normalImage;
  35369. }
  35370. Drawable* DrawableButton::getOverImage() const throw()
  35371. {
  35372. Drawable* d = normalImage;
  35373. if (getToggleState())
  35374. {
  35375. if (overImageOn != 0)
  35376. d = overImageOn;
  35377. else if (normalImageOn != 0)
  35378. d = normalImageOn;
  35379. else if (overImage != 0)
  35380. d = overImage;
  35381. }
  35382. else
  35383. {
  35384. if (overImage != 0)
  35385. d = overImage;
  35386. }
  35387. return d;
  35388. }
  35389. Drawable* DrawableButton::getDownImage() const throw()
  35390. {
  35391. Drawable* d = normalImage;
  35392. if (getToggleState())
  35393. {
  35394. if (downImageOn != 0)
  35395. d = downImageOn;
  35396. else if (overImageOn != 0)
  35397. d = overImageOn;
  35398. else if (normalImageOn != 0)
  35399. d = normalImageOn;
  35400. else if (downImage != 0)
  35401. d = downImage;
  35402. else
  35403. d = getOverImage();
  35404. }
  35405. else
  35406. {
  35407. if (downImage != 0)
  35408. d = downImage;
  35409. else
  35410. d = getOverImage();
  35411. }
  35412. return d;
  35413. }
  35414. END_JUCE_NAMESPACE
  35415. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35416. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35417. BEGIN_JUCE_NAMESPACE
  35418. HyperlinkButton::HyperlinkButton (const String& linkText,
  35419. const URL& linkURL)
  35420. : Button (linkText),
  35421. url (linkURL),
  35422. font (14.0f, Font::underlined),
  35423. resizeFont (true),
  35424. justification (Justification::centred)
  35425. {
  35426. setMouseCursor (MouseCursor::PointingHandCursor);
  35427. setTooltip (linkURL.toString (false));
  35428. }
  35429. HyperlinkButton::~HyperlinkButton()
  35430. {
  35431. }
  35432. void HyperlinkButton::setFont (const Font& newFont,
  35433. const bool resizeToMatchComponentHeight,
  35434. const Justification& justificationType)
  35435. {
  35436. font = newFont;
  35437. resizeFont = resizeToMatchComponentHeight;
  35438. justification = justificationType;
  35439. repaint();
  35440. }
  35441. void HyperlinkButton::setURL (const URL& newURL) throw()
  35442. {
  35443. url = newURL;
  35444. setTooltip (newURL.toString (false));
  35445. }
  35446. const Font HyperlinkButton::getFontToUse() const
  35447. {
  35448. Font f (font);
  35449. if (resizeFont)
  35450. f.setHeight (getHeight() * 0.7f);
  35451. return f;
  35452. }
  35453. void HyperlinkButton::changeWidthToFitText()
  35454. {
  35455. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35456. }
  35457. void HyperlinkButton::colourChanged()
  35458. {
  35459. repaint();
  35460. }
  35461. void HyperlinkButton::clicked()
  35462. {
  35463. if (url.isWellFormed())
  35464. url.launchInDefaultBrowser();
  35465. }
  35466. void HyperlinkButton::paintButton (Graphics& g,
  35467. bool isMouseOverButton,
  35468. bool isButtonDown)
  35469. {
  35470. const Colour textColour (findColour (textColourId));
  35471. if (isEnabled())
  35472. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35473. : textColour);
  35474. else
  35475. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35476. g.setFont (getFontToUse());
  35477. g.drawText (getButtonText(),
  35478. 2, 0, getWidth() - 2, getHeight(),
  35479. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35480. true);
  35481. }
  35482. END_JUCE_NAMESPACE
  35483. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35484. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35485. BEGIN_JUCE_NAMESPACE
  35486. ImageButton::ImageButton (const String& text_)
  35487. : Button (text_),
  35488. scaleImageToFit (true),
  35489. preserveProportions (true),
  35490. alphaThreshold (0),
  35491. imageX (0),
  35492. imageY (0),
  35493. imageW (0),
  35494. imageH (0),
  35495. normalImage (0),
  35496. overImage (0),
  35497. downImage (0)
  35498. {
  35499. }
  35500. ImageButton::~ImageButton()
  35501. {
  35502. }
  35503. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35504. const bool rescaleImagesWhenButtonSizeChanges,
  35505. const bool preserveImageProportions,
  35506. const Image& normalImage_,
  35507. const float imageOpacityWhenNormal,
  35508. const Colour& overlayColourWhenNormal,
  35509. const Image& overImage_,
  35510. const float imageOpacityWhenOver,
  35511. const Colour& overlayColourWhenOver,
  35512. const Image& downImage_,
  35513. const float imageOpacityWhenDown,
  35514. const Colour& overlayColourWhenDown,
  35515. const float hitTestAlphaThreshold)
  35516. {
  35517. normalImage = normalImage_;
  35518. overImage = overImage_;
  35519. downImage = downImage_;
  35520. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35521. {
  35522. imageW = normalImage.getWidth();
  35523. imageH = normalImage.getHeight();
  35524. setSize (imageW, imageH);
  35525. }
  35526. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35527. preserveProportions = preserveImageProportions;
  35528. normalOpacity = imageOpacityWhenNormal;
  35529. normalOverlay = overlayColourWhenNormal;
  35530. overOpacity = imageOpacityWhenOver;
  35531. overOverlay = overlayColourWhenOver;
  35532. downOpacity = imageOpacityWhenDown;
  35533. downOverlay = overlayColourWhenDown;
  35534. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35535. repaint();
  35536. }
  35537. const Image ImageButton::getCurrentImage() const
  35538. {
  35539. if (isDown() || getToggleState())
  35540. return getDownImage();
  35541. if (isOver())
  35542. return getOverImage();
  35543. return getNormalImage();
  35544. }
  35545. const Image ImageButton::getNormalImage() const
  35546. {
  35547. return normalImage;
  35548. }
  35549. const Image ImageButton::getOverImage() const
  35550. {
  35551. return overImage.isValid() ? overImage
  35552. : normalImage;
  35553. }
  35554. const Image ImageButton::getDownImage() const
  35555. {
  35556. return downImage.isValid() ? downImage
  35557. : getOverImage();
  35558. }
  35559. void ImageButton::paintButton (Graphics& g,
  35560. bool isMouseOverButton,
  35561. bool isButtonDown)
  35562. {
  35563. if (! isEnabled())
  35564. {
  35565. isMouseOverButton = false;
  35566. isButtonDown = false;
  35567. }
  35568. Image im (getCurrentImage());
  35569. if (im.isValid())
  35570. {
  35571. const int iw = im.getWidth();
  35572. const int ih = im.getHeight();
  35573. imageW = getWidth();
  35574. imageH = getHeight();
  35575. imageX = (imageW - iw) >> 1;
  35576. imageY = (imageH - ih) >> 1;
  35577. if (scaleImageToFit)
  35578. {
  35579. if (preserveProportions)
  35580. {
  35581. int newW, newH;
  35582. const float imRatio = ih / (float)iw;
  35583. const float destRatio = imageH / (float)imageW;
  35584. if (imRatio > destRatio)
  35585. {
  35586. newW = roundToInt (imageH / imRatio);
  35587. newH = imageH;
  35588. }
  35589. else
  35590. {
  35591. newW = imageW;
  35592. newH = roundToInt (imageW * imRatio);
  35593. }
  35594. imageX = (imageW - newW) / 2;
  35595. imageY = (imageH - newH) / 2;
  35596. imageW = newW;
  35597. imageH = newH;
  35598. }
  35599. else
  35600. {
  35601. imageX = 0;
  35602. imageY = 0;
  35603. }
  35604. }
  35605. if (! scaleImageToFit)
  35606. {
  35607. imageW = iw;
  35608. imageH = ih;
  35609. }
  35610. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35611. isButtonDown ? downOverlay
  35612. : (isMouseOverButton ? overOverlay
  35613. : normalOverlay),
  35614. isButtonDown ? downOpacity
  35615. : (isMouseOverButton ? overOpacity
  35616. : normalOpacity),
  35617. *this);
  35618. }
  35619. }
  35620. bool ImageButton::hitTest (int x, int y)
  35621. {
  35622. if (alphaThreshold == 0)
  35623. return true;
  35624. Image im (getCurrentImage());
  35625. return im.isNull() || (imageW > 0 && imageH > 0
  35626. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35627. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35628. }
  35629. END_JUCE_NAMESPACE
  35630. /*** End of inlined file: juce_ImageButton.cpp ***/
  35631. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35632. BEGIN_JUCE_NAMESPACE
  35633. ShapeButton::ShapeButton (const String& text_,
  35634. const Colour& normalColour_,
  35635. const Colour& overColour_,
  35636. const Colour& downColour_)
  35637. : Button (text_),
  35638. normalColour (normalColour_),
  35639. overColour (overColour_),
  35640. downColour (downColour_),
  35641. maintainShapeProportions (false),
  35642. outlineWidth (0.0f)
  35643. {
  35644. }
  35645. ShapeButton::~ShapeButton()
  35646. {
  35647. }
  35648. void ShapeButton::setColours (const Colour& newNormalColour,
  35649. const Colour& newOverColour,
  35650. const Colour& newDownColour)
  35651. {
  35652. normalColour = newNormalColour;
  35653. overColour = newOverColour;
  35654. downColour = newDownColour;
  35655. }
  35656. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35657. const float newOutlineWidth)
  35658. {
  35659. outlineColour = newOutlineColour;
  35660. outlineWidth = newOutlineWidth;
  35661. }
  35662. void ShapeButton::setShape (const Path& newShape,
  35663. const bool resizeNowToFitThisShape,
  35664. const bool maintainShapeProportions_,
  35665. const bool hasShadow)
  35666. {
  35667. shape = newShape;
  35668. maintainShapeProportions = maintainShapeProportions_;
  35669. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35670. setComponentEffect ((hasShadow) ? &shadow : 0);
  35671. if (resizeNowToFitThisShape)
  35672. {
  35673. Rectangle<float> bounds (shape.getBounds());
  35674. if (hasShadow)
  35675. bounds.expand (4.0f, 4.0f);
  35676. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35677. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35678. 1 + (int) (bounds.getHeight() + outlineWidth));
  35679. }
  35680. }
  35681. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35682. {
  35683. if (! isEnabled())
  35684. {
  35685. isMouseOverButton = false;
  35686. isButtonDown = false;
  35687. }
  35688. g.setColour ((isButtonDown) ? downColour
  35689. : (isMouseOverButton) ? overColour
  35690. : normalColour);
  35691. int w = getWidth();
  35692. int h = getHeight();
  35693. if (getComponentEffect() != 0)
  35694. {
  35695. w -= 4;
  35696. h -= 4;
  35697. }
  35698. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35699. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35700. w - offset - outlineWidth,
  35701. h - offset - outlineWidth,
  35702. maintainShapeProportions));
  35703. g.fillPath (shape, trans);
  35704. if (outlineWidth > 0.0f)
  35705. {
  35706. g.setColour (outlineColour);
  35707. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35708. }
  35709. }
  35710. END_JUCE_NAMESPACE
  35711. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35712. /*** Start of inlined file: juce_TextButton.cpp ***/
  35713. BEGIN_JUCE_NAMESPACE
  35714. TextButton::TextButton (const String& name,
  35715. const String& toolTip)
  35716. : Button (name)
  35717. {
  35718. setTooltip (toolTip);
  35719. }
  35720. TextButton::~TextButton()
  35721. {
  35722. }
  35723. void TextButton::paintButton (Graphics& g,
  35724. bool isMouseOverButton,
  35725. bool isButtonDown)
  35726. {
  35727. getLookAndFeel().drawButtonBackground (g, *this,
  35728. findColour (getToggleState() ? buttonOnColourId
  35729. : buttonColourId),
  35730. isMouseOverButton,
  35731. isButtonDown);
  35732. getLookAndFeel().drawButtonText (g, *this,
  35733. isMouseOverButton,
  35734. isButtonDown);
  35735. }
  35736. void TextButton::colourChanged()
  35737. {
  35738. repaint();
  35739. }
  35740. const Font TextButton::getFont()
  35741. {
  35742. return Font (jmin (15.0f, getHeight() * 0.6f));
  35743. }
  35744. void TextButton::changeWidthToFitText (const int newHeight)
  35745. {
  35746. if (newHeight >= 0)
  35747. setSize (jmax (1, getWidth()), newHeight);
  35748. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35749. getHeight());
  35750. }
  35751. END_JUCE_NAMESPACE
  35752. /*** End of inlined file: juce_TextButton.cpp ***/
  35753. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35754. BEGIN_JUCE_NAMESPACE
  35755. ToggleButton::ToggleButton (const String& buttonText)
  35756. : Button (buttonText)
  35757. {
  35758. setClickingTogglesState (true);
  35759. }
  35760. ToggleButton::~ToggleButton()
  35761. {
  35762. }
  35763. void ToggleButton::paintButton (Graphics& g,
  35764. bool isMouseOverButton,
  35765. bool isButtonDown)
  35766. {
  35767. getLookAndFeel().drawToggleButton (g, *this,
  35768. isMouseOverButton,
  35769. isButtonDown);
  35770. }
  35771. void ToggleButton::changeWidthToFitText()
  35772. {
  35773. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35774. }
  35775. void ToggleButton::colourChanged()
  35776. {
  35777. repaint();
  35778. }
  35779. END_JUCE_NAMESPACE
  35780. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35781. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35782. BEGIN_JUCE_NAMESPACE
  35783. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35784. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35785. : ToolbarItemComponent (itemId_, buttonText, true),
  35786. normalImage (normalImage_),
  35787. toggledOnImage (toggledOnImage_),
  35788. currentImage (0)
  35789. {
  35790. jassert (normalImage_ != 0);
  35791. }
  35792. ToolbarButton::~ToolbarButton()
  35793. {
  35794. }
  35795. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35796. {
  35797. preferredSize = minSize = maxSize = toolbarDepth;
  35798. return true;
  35799. }
  35800. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35801. {
  35802. }
  35803. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35804. {
  35805. buttonStateChanged();
  35806. }
  35807. void ToolbarButton::updateDrawable()
  35808. {
  35809. if (currentImage != 0)
  35810. {
  35811. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35812. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35813. }
  35814. }
  35815. void ToolbarButton::resized()
  35816. {
  35817. ToolbarItemComponent::resized();
  35818. updateDrawable();
  35819. }
  35820. void ToolbarButton::enablementChanged()
  35821. {
  35822. ToolbarItemComponent::enablementChanged();
  35823. updateDrawable();
  35824. }
  35825. void ToolbarButton::buttonStateChanged()
  35826. {
  35827. Drawable* d = normalImage;
  35828. if (getToggleState() && toggledOnImage != 0)
  35829. d = toggledOnImage;
  35830. if (d != currentImage)
  35831. {
  35832. removeChildComponent (currentImage);
  35833. currentImage = d;
  35834. if (d != 0)
  35835. {
  35836. enablementChanged();
  35837. addAndMakeVisible (d);
  35838. updateDrawable();
  35839. }
  35840. }
  35841. }
  35842. END_JUCE_NAMESPACE
  35843. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35844. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35845. BEGIN_JUCE_NAMESPACE
  35846. class CodeDocumentLine
  35847. {
  35848. public:
  35849. CodeDocumentLine (const juce_wchar* const line_,
  35850. const int lineLength_,
  35851. const int numNewLineChars,
  35852. const int lineStartInFile_)
  35853. : line (line_, lineLength_),
  35854. lineStartInFile (lineStartInFile_),
  35855. lineLength (lineLength_),
  35856. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35857. {
  35858. }
  35859. ~CodeDocumentLine()
  35860. {
  35861. }
  35862. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35863. {
  35864. const juce_wchar* const t = text;
  35865. int pos = 0;
  35866. while (t [pos] != 0)
  35867. {
  35868. const int startOfLine = pos;
  35869. int numNewLineChars = 0;
  35870. while (t[pos] != 0)
  35871. {
  35872. if (t[pos] == '\r')
  35873. {
  35874. ++numNewLineChars;
  35875. ++pos;
  35876. if (t[pos] == '\n')
  35877. {
  35878. ++numNewLineChars;
  35879. ++pos;
  35880. }
  35881. break;
  35882. }
  35883. if (t[pos] == '\n')
  35884. {
  35885. ++numNewLineChars;
  35886. ++pos;
  35887. break;
  35888. }
  35889. ++pos;
  35890. }
  35891. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  35892. numNewLineChars, startOfLine));
  35893. }
  35894. jassert (pos == text.length());
  35895. }
  35896. bool endsWithLineBreak() const throw()
  35897. {
  35898. return lineLengthWithoutNewLines != lineLength;
  35899. }
  35900. void updateLength() throw()
  35901. {
  35902. lineLengthWithoutNewLines = lineLength = line.length();
  35903. while (lineLengthWithoutNewLines > 0
  35904. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35905. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35906. {
  35907. --lineLengthWithoutNewLines;
  35908. }
  35909. }
  35910. String line;
  35911. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35912. };
  35913. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35914. : document (document_),
  35915. currentLine (document_->lines[0]),
  35916. line (0),
  35917. position (0)
  35918. {
  35919. }
  35920. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35921. : document (other.document),
  35922. currentLine (other.currentLine),
  35923. line (other.line),
  35924. position (other.position)
  35925. {
  35926. }
  35927. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35928. {
  35929. document = other.document;
  35930. currentLine = other.currentLine;
  35931. line = other.line;
  35932. position = other.position;
  35933. return *this;
  35934. }
  35935. CodeDocument::Iterator::~Iterator() throw()
  35936. {
  35937. }
  35938. juce_wchar CodeDocument::Iterator::nextChar()
  35939. {
  35940. if (currentLine == 0)
  35941. return 0;
  35942. jassert (currentLine == document->lines.getUnchecked (line));
  35943. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35944. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35945. {
  35946. ++line;
  35947. currentLine = document->lines [line];
  35948. }
  35949. return result;
  35950. }
  35951. void CodeDocument::Iterator::skip()
  35952. {
  35953. if (currentLine != 0)
  35954. {
  35955. jassert (currentLine == document->lines.getUnchecked (line));
  35956. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35957. {
  35958. ++line;
  35959. currentLine = document->lines [line];
  35960. }
  35961. }
  35962. }
  35963. void CodeDocument::Iterator::skipToEndOfLine()
  35964. {
  35965. if (currentLine != 0)
  35966. {
  35967. jassert (currentLine == document->lines.getUnchecked (line));
  35968. ++line;
  35969. currentLine = document->lines [line];
  35970. if (currentLine != 0)
  35971. position = currentLine->lineStartInFile;
  35972. else
  35973. position = document->getNumCharacters();
  35974. }
  35975. }
  35976. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35977. {
  35978. if (currentLine == 0)
  35979. return 0;
  35980. jassert (currentLine == document->lines.getUnchecked (line));
  35981. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35982. }
  35983. void CodeDocument::Iterator::skipWhitespace()
  35984. {
  35985. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35986. skip();
  35987. }
  35988. bool CodeDocument::Iterator::isEOF() const throw()
  35989. {
  35990. return currentLine == 0;
  35991. }
  35992. CodeDocument::Position::Position() throw()
  35993. : owner (0), characterPos (0), line (0),
  35994. indexInLine (0), positionMaintained (false)
  35995. {
  35996. }
  35997. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35998. const int line_, const int indexInLine_) throw()
  35999. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36000. characterPos (0), line (line_),
  36001. indexInLine (indexInLine_), positionMaintained (false)
  36002. {
  36003. setLineAndIndex (line_, indexInLine_);
  36004. }
  36005. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36006. const int characterPos_) throw()
  36007. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36008. positionMaintained (false)
  36009. {
  36010. setPosition (characterPos_);
  36011. }
  36012. CodeDocument::Position::Position (const Position& other) throw()
  36013. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36014. indexInLine (other.indexInLine), positionMaintained (false)
  36015. {
  36016. jassert (*this == other);
  36017. }
  36018. CodeDocument::Position::~Position()
  36019. {
  36020. setPositionMaintained (false);
  36021. }
  36022. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36023. {
  36024. if (this != &other)
  36025. {
  36026. const bool wasPositionMaintained = positionMaintained;
  36027. if (owner != other.owner)
  36028. setPositionMaintained (false);
  36029. owner = other.owner;
  36030. line = other.line;
  36031. indexInLine = other.indexInLine;
  36032. characterPos = other.characterPos;
  36033. setPositionMaintained (wasPositionMaintained);
  36034. jassert (*this == other);
  36035. }
  36036. return *this;
  36037. }
  36038. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36039. {
  36040. jassert ((characterPos == other.characterPos)
  36041. == (line == other.line && indexInLine == other.indexInLine));
  36042. return characterPos == other.characterPos
  36043. && line == other.line
  36044. && indexInLine == other.indexInLine
  36045. && owner == other.owner;
  36046. }
  36047. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36048. {
  36049. return ! operator== (other);
  36050. }
  36051. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  36052. {
  36053. jassert (owner != 0);
  36054. if (owner->lines.size() == 0)
  36055. {
  36056. line = 0;
  36057. indexInLine = 0;
  36058. characterPos = 0;
  36059. }
  36060. else
  36061. {
  36062. if (newLineNum >= owner->lines.size())
  36063. {
  36064. line = owner->lines.size() - 1;
  36065. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36066. jassert (l != 0);
  36067. indexInLine = l->lineLengthWithoutNewLines;
  36068. characterPos = l->lineStartInFile + indexInLine;
  36069. }
  36070. else
  36071. {
  36072. line = jmax (0, newLineNum);
  36073. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36074. jassert (l != 0);
  36075. if (l->lineLengthWithoutNewLines > 0)
  36076. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36077. else
  36078. indexInLine = 0;
  36079. characterPos = l->lineStartInFile + indexInLine;
  36080. }
  36081. }
  36082. }
  36083. void CodeDocument::Position::setPosition (const int newPosition)
  36084. {
  36085. jassert (owner != 0);
  36086. line = 0;
  36087. indexInLine = 0;
  36088. characterPos = 0;
  36089. if (newPosition > 0)
  36090. {
  36091. int lineStart = 0;
  36092. int lineEnd = owner->lines.size();
  36093. for (;;)
  36094. {
  36095. if (lineEnd - lineStart < 4)
  36096. {
  36097. for (int i = lineStart; i < lineEnd; ++i)
  36098. {
  36099. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36100. int index = newPosition - l->lineStartInFile;
  36101. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36102. {
  36103. line = i;
  36104. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36105. characterPos = l->lineStartInFile + indexInLine;
  36106. }
  36107. }
  36108. break;
  36109. }
  36110. else
  36111. {
  36112. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36113. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36114. if (newPosition >= mid->lineStartInFile)
  36115. lineStart = midIndex;
  36116. else
  36117. lineEnd = midIndex;
  36118. }
  36119. }
  36120. }
  36121. }
  36122. void CodeDocument::Position::moveBy (int characterDelta)
  36123. {
  36124. jassert (owner != 0);
  36125. if (characterDelta == 1)
  36126. {
  36127. setPosition (getPosition());
  36128. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36129. if (line < owner->lines.size())
  36130. {
  36131. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36132. if (indexInLine + characterDelta < l->lineLength
  36133. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36134. ++characterDelta;
  36135. }
  36136. }
  36137. setPosition (characterPos + characterDelta);
  36138. }
  36139. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36140. {
  36141. CodeDocument::Position p (*this);
  36142. p.moveBy (characterDelta);
  36143. return p;
  36144. }
  36145. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36146. {
  36147. CodeDocument::Position p (*this);
  36148. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36149. return p;
  36150. }
  36151. const juce_wchar CodeDocument::Position::getCharacter() const
  36152. {
  36153. const CodeDocumentLine* const l = owner->lines [line];
  36154. return l == 0 ? 0 : l->line [getIndexInLine()];
  36155. }
  36156. const String CodeDocument::Position::getLineText() const
  36157. {
  36158. const CodeDocumentLine* const l = owner->lines [line];
  36159. return l == 0 ? String::empty : l->line;
  36160. }
  36161. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36162. {
  36163. if (isMaintained != positionMaintained)
  36164. {
  36165. positionMaintained = isMaintained;
  36166. if (owner != 0)
  36167. {
  36168. if (isMaintained)
  36169. {
  36170. jassert (! owner->positionsToMaintain.contains (this));
  36171. owner->positionsToMaintain.add (this);
  36172. }
  36173. else
  36174. {
  36175. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36176. jassert (owner->positionsToMaintain.contains (this));
  36177. owner->positionsToMaintain.removeValue (this);
  36178. }
  36179. }
  36180. }
  36181. }
  36182. CodeDocument::CodeDocument()
  36183. : undoManager (std::numeric_limits<int>::max(), 10000),
  36184. currentActionIndex (0),
  36185. indexOfSavedState (-1),
  36186. maximumLineLength (-1),
  36187. newLineChars ("\r\n")
  36188. {
  36189. }
  36190. CodeDocument::~CodeDocument()
  36191. {
  36192. }
  36193. const String CodeDocument::getAllContent() const
  36194. {
  36195. return getTextBetween (Position (this, 0),
  36196. Position (this, lines.size(), 0));
  36197. }
  36198. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36199. {
  36200. if (end.getPosition() <= start.getPosition())
  36201. return String::empty;
  36202. const int startLine = start.getLineNumber();
  36203. const int endLine = end.getLineNumber();
  36204. if (startLine == endLine)
  36205. {
  36206. CodeDocumentLine* const line = lines [startLine];
  36207. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36208. }
  36209. String result;
  36210. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36211. String::Concatenator concatenator (result);
  36212. const int maxLine = jmin (lines.size() - 1, endLine);
  36213. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36214. {
  36215. const CodeDocumentLine* line = lines.getUnchecked(i);
  36216. int len = line->lineLength;
  36217. if (i == startLine)
  36218. {
  36219. const int index = start.getIndexInLine();
  36220. concatenator.append (line->line.substring (index, len));
  36221. }
  36222. else if (i == endLine)
  36223. {
  36224. len = end.getIndexInLine();
  36225. concatenator.append (line->line.substring (0, len));
  36226. }
  36227. else
  36228. {
  36229. concatenator.append (line->line);
  36230. }
  36231. }
  36232. return result;
  36233. }
  36234. int CodeDocument::getNumCharacters() const throw()
  36235. {
  36236. const CodeDocumentLine* const lastLine = lines.getLast();
  36237. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36238. }
  36239. const String CodeDocument::getLine (const int lineIndex) const throw()
  36240. {
  36241. const CodeDocumentLine* const line = lines [lineIndex];
  36242. return (line == 0) ? String::empty : line->line;
  36243. }
  36244. int CodeDocument::getMaximumLineLength() throw()
  36245. {
  36246. if (maximumLineLength < 0)
  36247. {
  36248. maximumLineLength = 0;
  36249. for (int i = lines.size(); --i >= 0;)
  36250. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36251. }
  36252. return maximumLineLength;
  36253. }
  36254. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36255. {
  36256. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36257. }
  36258. void CodeDocument::insertText (const Position& position, const String& text)
  36259. {
  36260. insert (text, position.getPosition(), true);
  36261. }
  36262. void CodeDocument::replaceAllContent (const String& newContent)
  36263. {
  36264. remove (0, getNumCharacters(), true);
  36265. insert (newContent, 0, true);
  36266. }
  36267. bool CodeDocument::loadFromStream (InputStream& stream)
  36268. {
  36269. replaceAllContent (stream.readEntireStreamAsString());
  36270. setSavePoint();
  36271. clearUndoHistory();
  36272. return true;
  36273. }
  36274. bool CodeDocument::writeToStream (OutputStream& stream)
  36275. {
  36276. for (int i = 0; i < lines.size(); ++i)
  36277. {
  36278. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36279. const char* utf8 = temp.toUTF8();
  36280. if (! stream.write (utf8, (int) strlen (utf8)))
  36281. return false;
  36282. }
  36283. return true;
  36284. }
  36285. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36286. {
  36287. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36288. newLineChars = newLineChars_;
  36289. }
  36290. void CodeDocument::newTransaction()
  36291. {
  36292. undoManager.beginNewTransaction (String::empty);
  36293. }
  36294. void CodeDocument::undo()
  36295. {
  36296. newTransaction();
  36297. undoManager.undo();
  36298. }
  36299. void CodeDocument::redo()
  36300. {
  36301. undoManager.redo();
  36302. }
  36303. void CodeDocument::clearUndoHistory()
  36304. {
  36305. undoManager.clearUndoHistory();
  36306. }
  36307. void CodeDocument::setSavePoint() throw()
  36308. {
  36309. indexOfSavedState = currentActionIndex;
  36310. }
  36311. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36312. {
  36313. return currentActionIndex != indexOfSavedState;
  36314. }
  36315. namespace CodeDocumentHelpers
  36316. {
  36317. int getCharacterType (const juce_wchar character) throw()
  36318. {
  36319. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36320. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36321. }
  36322. }
  36323. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36324. {
  36325. Position p (position);
  36326. const int maxDistance = 256;
  36327. int i = 0;
  36328. while (i < maxDistance
  36329. && CharacterFunctions::isWhitespace (p.getCharacter())
  36330. && (i == 0 || (p.getCharacter() != '\n'
  36331. && p.getCharacter() != '\r')))
  36332. {
  36333. ++i;
  36334. p.moveBy (1);
  36335. }
  36336. if (i == 0)
  36337. {
  36338. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36339. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36340. {
  36341. ++i;
  36342. p.moveBy (1);
  36343. }
  36344. while (i < maxDistance
  36345. && CharacterFunctions::isWhitespace (p.getCharacter())
  36346. && (i == 0 || (p.getCharacter() != '\n'
  36347. && p.getCharacter() != '\r')))
  36348. {
  36349. ++i;
  36350. p.moveBy (1);
  36351. }
  36352. }
  36353. return p;
  36354. }
  36355. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36356. {
  36357. Position p (position);
  36358. const int maxDistance = 256;
  36359. int i = 0;
  36360. bool stoppedAtLineStart = false;
  36361. while (i < maxDistance)
  36362. {
  36363. const juce_wchar c = p.movedBy (-1).getCharacter();
  36364. if (c == '\r' || c == '\n')
  36365. {
  36366. stoppedAtLineStart = true;
  36367. if (i > 0)
  36368. break;
  36369. }
  36370. if (! CharacterFunctions::isWhitespace (c))
  36371. break;
  36372. p.moveBy (-1);
  36373. ++i;
  36374. }
  36375. if (i < maxDistance && ! stoppedAtLineStart)
  36376. {
  36377. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36378. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36379. {
  36380. p.moveBy (-1);
  36381. ++i;
  36382. }
  36383. }
  36384. return p;
  36385. }
  36386. void CodeDocument::checkLastLineStatus()
  36387. {
  36388. while (lines.size() > 0
  36389. && lines.getLast()->lineLength == 0
  36390. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36391. {
  36392. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36393. lines.removeLast();
  36394. }
  36395. const CodeDocumentLine* const lastLine = lines.getLast();
  36396. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36397. {
  36398. // check that there's an empty line at the end if the preceding one ends in a newline..
  36399. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36400. }
  36401. }
  36402. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36403. {
  36404. listeners.add (listener);
  36405. }
  36406. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36407. {
  36408. listeners.remove (listener);
  36409. }
  36410. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36411. {
  36412. Position startPos (this, startLine, 0);
  36413. Position endPos (this, endLine, 0);
  36414. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36415. }
  36416. class CodeDocumentInsertAction : public UndoableAction
  36417. {
  36418. public:
  36419. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36420. : owner (owner_),
  36421. text (text_),
  36422. insertPos (insertPos_)
  36423. {
  36424. }
  36425. bool perform()
  36426. {
  36427. owner.currentActionIndex++;
  36428. owner.insert (text, insertPos, false);
  36429. return true;
  36430. }
  36431. bool undo()
  36432. {
  36433. owner.currentActionIndex--;
  36434. owner.remove (insertPos, insertPos + text.length(), false);
  36435. return true;
  36436. }
  36437. int getSizeInUnits() { return text.length() + 32; }
  36438. private:
  36439. CodeDocument& owner;
  36440. const String text;
  36441. int insertPos;
  36442. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36443. };
  36444. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36445. {
  36446. if (text.isEmpty())
  36447. return;
  36448. if (undoable)
  36449. {
  36450. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36451. }
  36452. else
  36453. {
  36454. Position pos (this, insertPos);
  36455. const int firstAffectedLine = pos.getLineNumber();
  36456. int lastAffectedLine = firstAffectedLine + 1;
  36457. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36458. String textInsideOriginalLine (text);
  36459. if (firstLine != 0)
  36460. {
  36461. const int index = pos.getIndexInLine();
  36462. textInsideOriginalLine = firstLine->line.substring (0, index)
  36463. + textInsideOriginalLine
  36464. + firstLine->line.substring (index);
  36465. }
  36466. maximumLineLength = -1;
  36467. Array <CodeDocumentLine*> newLines;
  36468. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36469. jassert (newLines.size() > 0);
  36470. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36471. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36472. lines.set (firstAffectedLine, newFirstLine);
  36473. if (newLines.size() > 1)
  36474. {
  36475. for (int i = 1; i < newLines.size(); ++i)
  36476. {
  36477. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36478. lines.insert (firstAffectedLine + i, l);
  36479. }
  36480. lastAffectedLine = lines.size();
  36481. }
  36482. int i, lineStart = newFirstLine->lineStartInFile;
  36483. for (i = firstAffectedLine; i < lines.size(); ++i)
  36484. {
  36485. CodeDocumentLine* const l = lines.getUnchecked (i);
  36486. l->lineStartInFile = lineStart;
  36487. lineStart += l->lineLength;
  36488. }
  36489. checkLastLineStatus();
  36490. const int newTextLength = text.length();
  36491. for (i = 0; i < positionsToMaintain.size(); ++i)
  36492. {
  36493. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36494. if (p->getPosition() >= insertPos)
  36495. p->setPosition (p->getPosition() + newTextLength);
  36496. }
  36497. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36498. }
  36499. }
  36500. class CodeDocumentDeleteAction : public UndoableAction
  36501. {
  36502. public:
  36503. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36504. : owner (owner_),
  36505. startPos (startPos_),
  36506. endPos (endPos_)
  36507. {
  36508. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36509. CodeDocument::Position (&owner, endPos));
  36510. }
  36511. bool perform()
  36512. {
  36513. owner.currentActionIndex++;
  36514. owner.remove (startPos, endPos, false);
  36515. return true;
  36516. }
  36517. bool undo()
  36518. {
  36519. owner.currentActionIndex--;
  36520. owner.insert (removedText, startPos, false);
  36521. return true;
  36522. }
  36523. int getSizeInUnits() { return removedText.length() + 32; }
  36524. private:
  36525. CodeDocument& owner;
  36526. int startPos, endPos;
  36527. String removedText;
  36528. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36529. };
  36530. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36531. {
  36532. if (endPos <= startPos)
  36533. return;
  36534. if (undoable)
  36535. {
  36536. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36537. }
  36538. else
  36539. {
  36540. Position startPosition (this, startPos);
  36541. Position endPosition (this, endPos);
  36542. maximumLineLength = -1;
  36543. const int firstAffectedLine = startPosition.getLineNumber();
  36544. const int endLine = endPosition.getLineNumber();
  36545. int lastAffectedLine = firstAffectedLine + 1;
  36546. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36547. if (firstAffectedLine == endLine)
  36548. {
  36549. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36550. + firstLine->line.substring (endPosition.getIndexInLine());
  36551. firstLine->updateLength();
  36552. }
  36553. else
  36554. {
  36555. lastAffectedLine = lines.size();
  36556. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36557. jassert (lastLine != 0);
  36558. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36559. + lastLine->line.substring (endPosition.getIndexInLine());
  36560. firstLine->updateLength();
  36561. int numLinesToRemove = endLine - firstAffectedLine;
  36562. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36563. }
  36564. int i;
  36565. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36566. {
  36567. CodeDocumentLine* const l = lines.getUnchecked (i);
  36568. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36569. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36570. }
  36571. checkLastLineStatus();
  36572. const int totalChars = getNumCharacters();
  36573. for (i = 0; i < positionsToMaintain.size(); ++i)
  36574. {
  36575. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36576. if (p->getPosition() > startPosition.getPosition())
  36577. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36578. if (p->getPosition() > totalChars)
  36579. p->setPosition (totalChars);
  36580. }
  36581. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36582. }
  36583. }
  36584. END_JUCE_NAMESPACE
  36585. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36586. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36587. BEGIN_JUCE_NAMESPACE
  36588. class CodeEditorComponent::CaretComponent : public Component,
  36589. public Timer
  36590. {
  36591. public:
  36592. CaretComponent (CodeEditorComponent& owner_)
  36593. : owner (owner_)
  36594. {
  36595. setAlwaysOnTop (true);
  36596. setInterceptsMouseClicks (false, false);
  36597. }
  36598. void paint (Graphics& g)
  36599. {
  36600. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36601. }
  36602. void timerCallback()
  36603. {
  36604. setVisible (shouldBeShown() && ! isVisible());
  36605. }
  36606. void updatePosition()
  36607. {
  36608. startTimer (400);
  36609. setVisible (shouldBeShown());
  36610. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36611. }
  36612. private:
  36613. CodeEditorComponent& owner;
  36614. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36615. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36616. };
  36617. class CodeEditorComponent::CodeEditorLine
  36618. {
  36619. public:
  36620. CodeEditorLine() throw()
  36621. : highlightColumnStart (0), highlightColumnEnd (0)
  36622. {
  36623. }
  36624. bool update (CodeDocument& document, int lineNum,
  36625. CodeDocument::Iterator& source,
  36626. CodeTokeniser* analyser, const int spacesPerTab,
  36627. const CodeDocument::Position& selectionStart,
  36628. const CodeDocument::Position& selectionEnd)
  36629. {
  36630. Array <SyntaxToken> newTokens;
  36631. newTokens.ensureStorageAllocated (8);
  36632. if (analyser == 0)
  36633. {
  36634. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36635. }
  36636. else if (lineNum < document.getNumLines())
  36637. {
  36638. const CodeDocument::Position pos (&document, lineNum, 0);
  36639. createTokens (pos.getPosition(), pos.getLineText(),
  36640. source, analyser, newTokens);
  36641. }
  36642. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36643. int newHighlightStart = 0;
  36644. int newHighlightEnd = 0;
  36645. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36646. {
  36647. const String line (document.getLine (lineNum));
  36648. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36649. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36650. line, spacesPerTab);
  36651. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36652. line, spacesPerTab);
  36653. }
  36654. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36655. {
  36656. highlightColumnStart = newHighlightStart;
  36657. highlightColumnEnd = newHighlightEnd;
  36658. }
  36659. else
  36660. {
  36661. if (tokens.size() == newTokens.size())
  36662. {
  36663. bool allTheSame = true;
  36664. for (int i = newTokens.size(); --i >= 0;)
  36665. {
  36666. if (tokens.getReference(i) != newTokens.getReference(i))
  36667. {
  36668. allTheSame = false;
  36669. break;
  36670. }
  36671. }
  36672. if (allTheSame)
  36673. return false;
  36674. }
  36675. }
  36676. tokens.swapWithArray (newTokens);
  36677. return true;
  36678. }
  36679. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36680. float x, const int y, const int baselineOffset, const int lineHeight,
  36681. const Colour& highlightColour) const
  36682. {
  36683. if (highlightColumnStart < highlightColumnEnd)
  36684. {
  36685. g.setColour (highlightColour);
  36686. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36687. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36688. }
  36689. int lastType = std::numeric_limits<int>::min();
  36690. for (int i = 0; i < tokens.size(); ++i)
  36691. {
  36692. SyntaxToken& token = tokens.getReference(i);
  36693. if (lastType != token.tokenType)
  36694. {
  36695. lastType = token.tokenType;
  36696. g.setColour (owner.getColourForTokenType (lastType));
  36697. }
  36698. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36699. if (i < tokens.size() - 1)
  36700. {
  36701. if (token.width < 0)
  36702. token.width = font.getStringWidthFloat (token.text);
  36703. x += token.width;
  36704. }
  36705. }
  36706. }
  36707. private:
  36708. struct SyntaxToken
  36709. {
  36710. SyntaxToken (const String& text_, const int type) throw()
  36711. : text (text_), tokenType (type), width (-1.0f)
  36712. {
  36713. }
  36714. bool operator!= (const SyntaxToken& other) const throw()
  36715. {
  36716. return text != other.text || tokenType != other.tokenType;
  36717. }
  36718. String text;
  36719. int tokenType;
  36720. float width;
  36721. };
  36722. Array <SyntaxToken> tokens;
  36723. int highlightColumnStart, highlightColumnEnd;
  36724. static void createTokens (int startPosition, const String& lineText,
  36725. CodeDocument::Iterator& source,
  36726. CodeTokeniser* analyser,
  36727. Array <SyntaxToken>& newTokens)
  36728. {
  36729. CodeDocument::Iterator lastIterator (source);
  36730. const int lineLength = lineText.length();
  36731. for (;;)
  36732. {
  36733. int tokenType = analyser->readNextToken (source);
  36734. int tokenStart = lastIterator.getPosition();
  36735. int tokenEnd = source.getPosition();
  36736. if (tokenEnd <= tokenStart)
  36737. break;
  36738. tokenEnd -= startPosition;
  36739. if (tokenEnd > 0)
  36740. {
  36741. tokenStart -= startPosition;
  36742. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36743. tokenType));
  36744. if (tokenEnd >= lineLength)
  36745. break;
  36746. }
  36747. lastIterator = source;
  36748. }
  36749. source = lastIterator;
  36750. }
  36751. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36752. {
  36753. int x = 0;
  36754. for (int i = 0; i < tokens.size(); ++i)
  36755. {
  36756. SyntaxToken& t = tokens.getReference(i);
  36757. for (;;)
  36758. {
  36759. int tabPos = t.text.indexOfChar ('\t');
  36760. if (tabPos < 0)
  36761. break;
  36762. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36763. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36764. }
  36765. x += t.text.length();
  36766. }
  36767. }
  36768. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36769. {
  36770. jassert (index <= line.length());
  36771. int col = 0;
  36772. for (int i = 0; i < index; ++i)
  36773. {
  36774. if (line[i] != '\t')
  36775. ++col;
  36776. else
  36777. col += spacesPerTab - (col % spacesPerTab);
  36778. }
  36779. return col;
  36780. }
  36781. };
  36782. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36783. CodeTokeniser* const codeTokeniser_)
  36784. : document (document_),
  36785. firstLineOnScreen (0),
  36786. gutter (5),
  36787. spacesPerTab (4),
  36788. lineHeight (0),
  36789. linesOnScreen (0),
  36790. columnsOnScreen (0),
  36791. scrollbarThickness (16),
  36792. columnToTryToMaintain (-1),
  36793. useSpacesForTabs (false),
  36794. xOffset (0),
  36795. verticalScrollBar (true),
  36796. horizontalScrollBar (false),
  36797. codeTokeniser (codeTokeniser_)
  36798. {
  36799. caretPos = CodeDocument::Position (&document_, 0, 0);
  36800. caretPos.setPositionMaintained (true);
  36801. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36802. selectionStart.setPositionMaintained (true);
  36803. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36804. selectionEnd.setPositionMaintained (true);
  36805. setOpaque (true);
  36806. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36807. setWantsKeyboardFocus (true);
  36808. addAndMakeVisible (&verticalScrollBar);
  36809. verticalScrollBar.setSingleStepSize (1.0);
  36810. addAndMakeVisible (&horizontalScrollBar);
  36811. horizontalScrollBar.setSingleStepSize (1.0);
  36812. addAndMakeVisible (caret = new CaretComponent (*this));
  36813. Font f (12.0f);
  36814. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36815. setFont (f);
  36816. resetToDefaultColours();
  36817. verticalScrollBar.addListener (this);
  36818. horizontalScrollBar.addListener (this);
  36819. document.addListener (this);
  36820. }
  36821. CodeEditorComponent::~CodeEditorComponent()
  36822. {
  36823. document.removeListener (this);
  36824. }
  36825. void CodeEditorComponent::loadContent (const String& newContent)
  36826. {
  36827. clearCachedIterators (0);
  36828. document.replaceAllContent (newContent);
  36829. document.clearUndoHistory();
  36830. document.setSavePoint();
  36831. caretPos.setPosition (0);
  36832. selectionStart.setPosition (0);
  36833. selectionEnd.setPosition (0);
  36834. scrollToLine (0);
  36835. }
  36836. bool CodeEditorComponent::isTextInputActive() const
  36837. {
  36838. return true;
  36839. }
  36840. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36841. const CodeDocument::Position& affectedTextEnd)
  36842. {
  36843. clearCachedIterators (affectedTextStart.getLineNumber());
  36844. triggerAsyncUpdate();
  36845. caret->updatePosition();
  36846. columnToTryToMaintain = -1;
  36847. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36848. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36849. deselectAll();
  36850. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36851. || caretPos.getPosition() < affectedTextStart.getPosition())
  36852. moveCaretTo (affectedTextStart, false);
  36853. updateScrollBars();
  36854. }
  36855. void CodeEditorComponent::resized()
  36856. {
  36857. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36858. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36859. lines.clear();
  36860. rebuildLineTokens();
  36861. caret->updatePosition();
  36862. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36863. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36864. updateScrollBars();
  36865. }
  36866. void CodeEditorComponent::paint (Graphics& g)
  36867. {
  36868. handleUpdateNowIfNeeded();
  36869. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36870. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36871. g.setFont (font);
  36872. const int baselineOffset = (int) font.getAscent();
  36873. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36874. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36875. const Rectangle<int> clip (g.getClipBounds());
  36876. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36877. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36878. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36879. {
  36880. lines.getUnchecked(j)->draw (*this, g, font,
  36881. (float) (gutter - xOffset * charWidth),
  36882. lineHeight * j, baselineOffset, lineHeight,
  36883. highlightColour);
  36884. }
  36885. }
  36886. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36887. {
  36888. if (scrollbarThickness != thickness)
  36889. {
  36890. scrollbarThickness = thickness;
  36891. resized();
  36892. }
  36893. }
  36894. void CodeEditorComponent::handleAsyncUpdate()
  36895. {
  36896. rebuildLineTokens();
  36897. }
  36898. void CodeEditorComponent::rebuildLineTokens()
  36899. {
  36900. cancelPendingUpdate();
  36901. const int numNeeded = linesOnScreen + 1;
  36902. int minLineToRepaint = numNeeded;
  36903. int maxLineToRepaint = 0;
  36904. if (numNeeded != lines.size())
  36905. {
  36906. lines.clear();
  36907. for (int i = numNeeded; --i >= 0;)
  36908. lines.add (new CodeEditorLine());
  36909. minLineToRepaint = 0;
  36910. maxLineToRepaint = numNeeded;
  36911. }
  36912. jassert (numNeeded == lines.size());
  36913. CodeDocument::Iterator source (&document);
  36914. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36915. for (int i = 0; i < numNeeded; ++i)
  36916. {
  36917. CodeEditorLine* const line = lines.getUnchecked(i);
  36918. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36919. selectionStart, selectionEnd))
  36920. {
  36921. minLineToRepaint = jmin (minLineToRepaint, i);
  36922. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36923. }
  36924. }
  36925. if (minLineToRepaint <= maxLineToRepaint)
  36926. {
  36927. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36928. verticalScrollBar.getX() - gutter,
  36929. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36930. }
  36931. }
  36932. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36933. {
  36934. caretPos = newPos;
  36935. columnToTryToMaintain = -1;
  36936. if (highlighting)
  36937. {
  36938. if (dragType == notDragging)
  36939. {
  36940. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36941. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36942. dragType = draggingSelectionStart;
  36943. else
  36944. dragType = draggingSelectionEnd;
  36945. }
  36946. if (dragType == draggingSelectionStart)
  36947. {
  36948. selectionStart = caretPos;
  36949. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36950. {
  36951. const CodeDocument::Position temp (selectionStart);
  36952. selectionStart = selectionEnd;
  36953. selectionEnd = temp;
  36954. dragType = draggingSelectionEnd;
  36955. }
  36956. }
  36957. else
  36958. {
  36959. selectionEnd = caretPos;
  36960. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36961. {
  36962. const CodeDocument::Position temp (selectionStart);
  36963. selectionStart = selectionEnd;
  36964. selectionEnd = temp;
  36965. dragType = draggingSelectionStart;
  36966. }
  36967. }
  36968. triggerAsyncUpdate();
  36969. }
  36970. else
  36971. {
  36972. deselectAll();
  36973. }
  36974. caret->updatePosition();
  36975. scrollToKeepCaretOnScreen();
  36976. updateScrollBars();
  36977. }
  36978. void CodeEditorComponent::deselectAll()
  36979. {
  36980. if (selectionStart != selectionEnd)
  36981. triggerAsyncUpdate();
  36982. selectionStart = caretPos;
  36983. selectionEnd = caretPos;
  36984. }
  36985. void CodeEditorComponent::updateScrollBars()
  36986. {
  36987. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36988. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36989. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36990. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36991. }
  36992. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36993. {
  36994. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36995. newFirstLineOnScreen);
  36996. if (newFirstLineOnScreen != firstLineOnScreen)
  36997. {
  36998. firstLineOnScreen = newFirstLineOnScreen;
  36999. caret->updatePosition();
  37000. updateCachedIterators (firstLineOnScreen);
  37001. triggerAsyncUpdate();
  37002. }
  37003. }
  37004. void CodeEditorComponent::scrollToColumnInternal (double column)
  37005. {
  37006. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37007. if (xOffset != newOffset)
  37008. {
  37009. xOffset = newOffset;
  37010. caret->updatePosition();
  37011. repaint();
  37012. }
  37013. }
  37014. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37015. {
  37016. scrollToLineInternal (newFirstLineOnScreen);
  37017. updateScrollBars();
  37018. }
  37019. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37020. {
  37021. scrollToColumnInternal (newFirstColumnOnScreen);
  37022. updateScrollBars();
  37023. }
  37024. void CodeEditorComponent::scrollBy (int deltaLines)
  37025. {
  37026. scrollToLine (firstLineOnScreen + deltaLines);
  37027. }
  37028. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37029. {
  37030. if (caretPos.getLineNumber() < firstLineOnScreen)
  37031. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37032. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37033. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37034. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37035. if (column >= xOffset + columnsOnScreen - 1)
  37036. scrollToColumn (column + 1 - columnsOnScreen);
  37037. else if (column < xOffset)
  37038. scrollToColumn (column);
  37039. }
  37040. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37041. {
  37042. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37043. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37044. roundToInt (charWidth),
  37045. lineHeight);
  37046. }
  37047. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37048. {
  37049. const int line = y / lineHeight + firstLineOnScreen;
  37050. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37051. const int index = columnToIndex (line, column);
  37052. return CodeDocument::Position (&document, line, index);
  37053. }
  37054. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37055. {
  37056. document.deleteSection (selectionStart, selectionEnd);
  37057. if (newText.isNotEmpty())
  37058. document.insertText (caretPos, newText);
  37059. scrollToKeepCaretOnScreen();
  37060. }
  37061. void CodeEditorComponent::insertTabAtCaret()
  37062. {
  37063. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37064. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37065. {
  37066. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37067. }
  37068. if (useSpacesForTabs)
  37069. {
  37070. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37071. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37072. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37073. }
  37074. else
  37075. {
  37076. insertTextAtCaret ("\t");
  37077. }
  37078. }
  37079. void CodeEditorComponent::cut()
  37080. {
  37081. insertTextAtCaret (String::empty);
  37082. }
  37083. void CodeEditorComponent::copy()
  37084. {
  37085. newTransaction();
  37086. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37087. if (selection.isNotEmpty())
  37088. SystemClipboard::copyTextToClipboard (selection);
  37089. }
  37090. void CodeEditorComponent::copyThenCut()
  37091. {
  37092. copy();
  37093. cut();
  37094. newTransaction();
  37095. }
  37096. void CodeEditorComponent::paste()
  37097. {
  37098. newTransaction();
  37099. const String clip (SystemClipboard::getTextFromClipboard());
  37100. if (clip.isNotEmpty())
  37101. insertTextAtCaret (clip);
  37102. newTransaction();
  37103. }
  37104. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37105. {
  37106. newTransaction();
  37107. if (moveInWholeWordSteps)
  37108. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37109. else
  37110. moveCaretTo (caretPos.movedBy (-1), selecting);
  37111. }
  37112. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37113. {
  37114. newTransaction();
  37115. if (moveInWholeWordSteps)
  37116. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37117. else
  37118. moveCaretTo (caretPos.movedBy (1), selecting);
  37119. }
  37120. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37121. {
  37122. CodeDocument::Position pos (caretPos);
  37123. const int newLineNum = pos.getLineNumber() + delta;
  37124. if (columnToTryToMaintain < 0)
  37125. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37126. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37127. const int colToMaintain = columnToTryToMaintain;
  37128. moveCaretTo (pos, selecting);
  37129. columnToTryToMaintain = colToMaintain;
  37130. }
  37131. void CodeEditorComponent::cursorDown (const bool selecting)
  37132. {
  37133. newTransaction();
  37134. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37135. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37136. else
  37137. moveLineDelta (1, selecting);
  37138. }
  37139. void CodeEditorComponent::cursorUp (const bool selecting)
  37140. {
  37141. newTransaction();
  37142. if (caretPos.getLineNumber() == 0)
  37143. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37144. else
  37145. moveLineDelta (-1, selecting);
  37146. }
  37147. void CodeEditorComponent::pageDown (const bool selecting)
  37148. {
  37149. newTransaction();
  37150. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37151. moveLineDelta (linesOnScreen, selecting);
  37152. }
  37153. void CodeEditorComponent::pageUp (const bool selecting)
  37154. {
  37155. newTransaction();
  37156. scrollBy (-linesOnScreen);
  37157. moveLineDelta (-linesOnScreen, selecting);
  37158. }
  37159. void CodeEditorComponent::scrollUp()
  37160. {
  37161. newTransaction();
  37162. scrollBy (1);
  37163. if (caretPos.getLineNumber() < firstLineOnScreen)
  37164. moveLineDelta (1, false);
  37165. }
  37166. void CodeEditorComponent::scrollDown()
  37167. {
  37168. newTransaction();
  37169. scrollBy (-1);
  37170. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37171. moveLineDelta (-1, false);
  37172. }
  37173. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37174. {
  37175. newTransaction();
  37176. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37177. }
  37178. namespace CodeEditorHelpers
  37179. {
  37180. int findFirstNonWhitespaceChar (const String& line) throw()
  37181. {
  37182. const int len = line.length();
  37183. for (int i = 0; i < len; ++i)
  37184. if (! CharacterFunctions::isWhitespace (line [i]))
  37185. return i;
  37186. return 0;
  37187. }
  37188. }
  37189. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37190. {
  37191. newTransaction();
  37192. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37193. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37194. index = 0;
  37195. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37196. }
  37197. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37198. {
  37199. newTransaction();
  37200. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37201. }
  37202. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37203. {
  37204. newTransaction();
  37205. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37206. }
  37207. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37208. {
  37209. if (moveInWholeWordSteps)
  37210. {
  37211. cut(); // in case something is already highlighted
  37212. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37213. }
  37214. else
  37215. {
  37216. if (selectionStart == selectionEnd)
  37217. selectionStart.moveBy (-1);
  37218. }
  37219. cut();
  37220. }
  37221. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37222. {
  37223. if (moveInWholeWordSteps)
  37224. {
  37225. cut(); // in case something is already highlighted
  37226. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37227. }
  37228. else
  37229. {
  37230. if (selectionStart == selectionEnd)
  37231. selectionEnd.moveBy (1);
  37232. else
  37233. newTransaction();
  37234. }
  37235. cut();
  37236. }
  37237. void CodeEditorComponent::selectAll()
  37238. {
  37239. newTransaction();
  37240. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37241. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37242. }
  37243. void CodeEditorComponent::undo()
  37244. {
  37245. document.undo();
  37246. scrollToKeepCaretOnScreen();
  37247. }
  37248. void CodeEditorComponent::redo()
  37249. {
  37250. document.redo();
  37251. scrollToKeepCaretOnScreen();
  37252. }
  37253. void CodeEditorComponent::newTransaction()
  37254. {
  37255. document.newTransaction();
  37256. startTimer (600);
  37257. }
  37258. void CodeEditorComponent::timerCallback()
  37259. {
  37260. newTransaction();
  37261. }
  37262. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37263. {
  37264. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37265. }
  37266. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37267. {
  37268. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37269. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37270. }
  37271. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37272. {
  37273. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37274. CodeDocument::Position (&document, range.getEnd()));
  37275. }
  37276. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37277. {
  37278. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37279. const bool shiftDown = key.getModifiers().isShiftDown();
  37280. if (key.isKeyCode (KeyPress::leftKey))
  37281. {
  37282. cursorLeft (moveInWholeWordSteps, shiftDown);
  37283. }
  37284. else if (key.isKeyCode (KeyPress::rightKey))
  37285. {
  37286. cursorRight (moveInWholeWordSteps, shiftDown);
  37287. }
  37288. else if (key.isKeyCode (KeyPress::upKey))
  37289. {
  37290. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37291. scrollDown();
  37292. #if JUCE_MAC
  37293. else if (key.getModifiers().isCommandDown())
  37294. goToStartOfDocument (shiftDown);
  37295. #endif
  37296. else
  37297. cursorUp (shiftDown);
  37298. }
  37299. else if (key.isKeyCode (KeyPress::downKey))
  37300. {
  37301. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37302. scrollUp();
  37303. #if JUCE_MAC
  37304. else if (key.getModifiers().isCommandDown())
  37305. goToEndOfDocument (shiftDown);
  37306. #endif
  37307. else
  37308. cursorDown (shiftDown);
  37309. }
  37310. else if (key.isKeyCode (KeyPress::pageDownKey))
  37311. {
  37312. pageDown (shiftDown);
  37313. }
  37314. else if (key.isKeyCode (KeyPress::pageUpKey))
  37315. {
  37316. pageUp (shiftDown);
  37317. }
  37318. else if (key.isKeyCode (KeyPress::homeKey))
  37319. {
  37320. if (moveInWholeWordSteps)
  37321. goToStartOfDocument (shiftDown);
  37322. else
  37323. goToStartOfLine (shiftDown);
  37324. }
  37325. else if (key.isKeyCode (KeyPress::endKey))
  37326. {
  37327. if (moveInWholeWordSteps)
  37328. goToEndOfDocument (shiftDown);
  37329. else
  37330. goToEndOfLine (shiftDown);
  37331. }
  37332. else if (key.isKeyCode (KeyPress::backspaceKey))
  37333. {
  37334. backspace (moveInWholeWordSteps);
  37335. }
  37336. else if (key.isKeyCode (KeyPress::deleteKey))
  37337. {
  37338. deleteForward (moveInWholeWordSteps);
  37339. }
  37340. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37341. {
  37342. copy();
  37343. }
  37344. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37345. {
  37346. copyThenCut();
  37347. }
  37348. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37349. {
  37350. paste();
  37351. }
  37352. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37353. {
  37354. undo();
  37355. }
  37356. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37357. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37358. {
  37359. redo();
  37360. }
  37361. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37362. {
  37363. selectAll();
  37364. }
  37365. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37366. {
  37367. insertTabAtCaret();
  37368. }
  37369. else if (key == KeyPress::returnKey)
  37370. {
  37371. newTransaction();
  37372. insertTextAtCaret (document.getNewLineCharacters());
  37373. }
  37374. else if (key.isKeyCode (KeyPress::escapeKey))
  37375. {
  37376. newTransaction();
  37377. }
  37378. else if (key.getTextCharacter() >= ' ')
  37379. {
  37380. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37381. }
  37382. else
  37383. {
  37384. return false;
  37385. }
  37386. return true;
  37387. }
  37388. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37389. {
  37390. newTransaction();
  37391. dragType = notDragging;
  37392. if (! e.mods.isPopupMenu())
  37393. {
  37394. beginDragAutoRepeat (100);
  37395. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37396. }
  37397. else
  37398. {
  37399. /*PopupMenu m;
  37400. addPopupMenuItems (m, &e);
  37401. const int result = m.show();
  37402. if (result != 0)
  37403. performPopupMenuAction (result);
  37404. */
  37405. }
  37406. }
  37407. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37408. {
  37409. if (! e.mods.isPopupMenu())
  37410. moveCaretTo (getPositionAt (e.x, e.y), true);
  37411. }
  37412. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37413. {
  37414. newTransaction();
  37415. beginDragAutoRepeat (0);
  37416. dragType = notDragging;
  37417. }
  37418. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37419. {
  37420. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37421. CodeDocument::Position tokenEnd (tokenStart);
  37422. if (e.getNumberOfClicks() > 2)
  37423. {
  37424. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37425. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37426. }
  37427. else
  37428. {
  37429. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37430. tokenEnd.moveBy (1);
  37431. tokenStart = tokenEnd;
  37432. while (tokenStart.getIndexInLine() > 0
  37433. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37434. tokenStart.moveBy (-1);
  37435. }
  37436. moveCaretTo (tokenEnd, false);
  37437. moveCaretTo (tokenStart, true);
  37438. }
  37439. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37440. {
  37441. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37442. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37443. {
  37444. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37445. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37446. }
  37447. else
  37448. {
  37449. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37450. }
  37451. }
  37452. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37453. {
  37454. if (scrollBarThatHasMoved == &verticalScrollBar)
  37455. scrollToLineInternal ((int) newRangeStart);
  37456. else
  37457. scrollToColumnInternal (newRangeStart);
  37458. }
  37459. void CodeEditorComponent::focusGained (FocusChangeType)
  37460. {
  37461. caret->updatePosition();
  37462. }
  37463. void CodeEditorComponent::focusLost (FocusChangeType)
  37464. {
  37465. caret->updatePosition();
  37466. }
  37467. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37468. {
  37469. useSpacesForTabs = insertSpaces;
  37470. if (spacesPerTab != numSpaces)
  37471. {
  37472. spacesPerTab = numSpaces;
  37473. triggerAsyncUpdate();
  37474. }
  37475. }
  37476. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37477. {
  37478. const String line (document.getLine (lineNum));
  37479. jassert (index <= line.length());
  37480. int col = 0;
  37481. for (int i = 0; i < index; ++i)
  37482. {
  37483. if (line[i] != '\t')
  37484. ++col;
  37485. else
  37486. col += getTabSize() - (col % getTabSize());
  37487. }
  37488. return col;
  37489. }
  37490. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37491. {
  37492. const String line (document.getLine (lineNum));
  37493. const int lineLength = line.length();
  37494. int i, col = 0;
  37495. for (i = 0; i < lineLength; ++i)
  37496. {
  37497. if (line[i] != '\t')
  37498. ++col;
  37499. else
  37500. col += getTabSize() - (col % getTabSize());
  37501. if (col > column)
  37502. break;
  37503. }
  37504. return i;
  37505. }
  37506. void CodeEditorComponent::setFont (const Font& newFont)
  37507. {
  37508. font = newFont;
  37509. charWidth = font.getStringWidthFloat ("0");
  37510. lineHeight = roundToInt (font.getHeight());
  37511. resized();
  37512. }
  37513. void CodeEditorComponent::resetToDefaultColours()
  37514. {
  37515. coloursForTokenCategories.clear();
  37516. if (codeTokeniser != 0)
  37517. {
  37518. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37519. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37520. }
  37521. }
  37522. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37523. {
  37524. jassert (tokenType < 256);
  37525. while (coloursForTokenCategories.size() < tokenType)
  37526. coloursForTokenCategories.add (Colours::black);
  37527. coloursForTokenCategories.set (tokenType, colour);
  37528. repaint();
  37529. }
  37530. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37531. {
  37532. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37533. return findColour (CodeEditorComponent::defaultTextColourId);
  37534. return coloursForTokenCategories.getReference (tokenType);
  37535. }
  37536. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37537. {
  37538. int i;
  37539. for (i = cachedIterators.size(); --i >= 0;)
  37540. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37541. break;
  37542. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37543. }
  37544. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37545. {
  37546. const int maxNumCachedPositions = 5000;
  37547. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37548. if (cachedIterators.size() == 0)
  37549. cachedIterators.add (new CodeDocument::Iterator (&document));
  37550. if (codeTokeniser == 0)
  37551. return;
  37552. for (;;)
  37553. {
  37554. CodeDocument::Iterator* last = cachedIterators.getLast();
  37555. if (last->getLine() >= maxLineNum)
  37556. break;
  37557. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37558. cachedIterators.add (t);
  37559. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37560. for (;;)
  37561. {
  37562. codeTokeniser->readNextToken (*t);
  37563. if (t->getLine() >= targetLine)
  37564. break;
  37565. if (t->isEOF())
  37566. return;
  37567. }
  37568. }
  37569. }
  37570. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37571. {
  37572. if (codeTokeniser == 0)
  37573. return;
  37574. for (int i = cachedIterators.size(); --i >= 0;)
  37575. {
  37576. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37577. if (t->getPosition() <= position)
  37578. {
  37579. source = *t;
  37580. break;
  37581. }
  37582. }
  37583. while (source.getPosition() < position)
  37584. {
  37585. const CodeDocument::Iterator original (source);
  37586. codeTokeniser->readNextToken (source);
  37587. if (source.getPosition() > position || source.isEOF())
  37588. {
  37589. source = original;
  37590. break;
  37591. }
  37592. }
  37593. }
  37594. END_JUCE_NAMESPACE
  37595. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37596. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37597. BEGIN_JUCE_NAMESPACE
  37598. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37599. {
  37600. }
  37601. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37602. {
  37603. }
  37604. namespace CppTokeniser
  37605. {
  37606. bool isIdentifierStart (const juce_wchar c) throw()
  37607. {
  37608. return CharacterFunctions::isLetter (c)
  37609. || c == '_' || c == '@';
  37610. }
  37611. bool isIdentifierBody (const juce_wchar c) throw()
  37612. {
  37613. return CharacterFunctions::isLetterOrDigit (c)
  37614. || c == '_' || c == '@';
  37615. }
  37616. bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37617. {
  37618. static const juce_wchar* const keywords2Char[] =
  37619. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37620. static const juce_wchar* const keywords3Char[] =
  37621. { 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 };
  37622. static const juce_wchar* const keywords4Char[] =
  37623. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37624. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37625. static const juce_wchar* const keywords5Char[] =
  37626. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37627. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37628. static const juce_wchar* const keywords6Char[] =
  37629. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37630. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37631. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37632. static const juce_wchar* const keywordsOther[] =
  37633. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37634. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37635. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37636. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37637. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37638. const juce_wchar* const* k;
  37639. switch (tokenLength)
  37640. {
  37641. case 2: k = keywords2Char; break;
  37642. case 3: k = keywords3Char; break;
  37643. case 4: k = keywords4Char; break;
  37644. case 5: k = keywords5Char; break;
  37645. case 6: k = keywords6Char; break;
  37646. default:
  37647. if (tokenLength < 2 || tokenLength > 16)
  37648. return false;
  37649. k = keywordsOther;
  37650. break;
  37651. }
  37652. int i = 0;
  37653. while (k[i] != 0)
  37654. {
  37655. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37656. return true;
  37657. ++i;
  37658. }
  37659. return false;
  37660. }
  37661. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37662. {
  37663. int tokenLength = 0;
  37664. juce_wchar possibleIdentifier [19];
  37665. while (isIdentifierBody (source.peekNextChar()))
  37666. {
  37667. const juce_wchar c = source.nextChar();
  37668. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37669. possibleIdentifier [tokenLength] = c;
  37670. ++tokenLength;
  37671. }
  37672. if (tokenLength > 1 && tokenLength <= 16)
  37673. {
  37674. possibleIdentifier [tokenLength] = 0;
  37675. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37676. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37677. }
  37678. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37679. }
  37680. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37681. {
  37682. const juce_wchar c = source.peekNextChar();
  37683. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37684. source.skip();
  37685. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37686. return false;
  37687. return true;
  37688. }
  37689. bool isHexDigit (const juce_wchar c) throw()
  37690. {
  37691. return (c >= '0' && c <= '9')
  37692. || (c >= 'a' && c <= 'f')
  37693. || (c >= 'A' && c <= 'F');
  37694. }
  37695. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37696. {
  37697. if (source.nextChar() != '0')
  37698. return false;
  37699. juce_wchar c = source.nextChar();
  37700. if (c != 'x' && c != 'X')
  37701. return false;
  37702. int numDigits = 0;
  37703. while (isHexDigit (source.peekNextChar()))
  37704. {
  37705. ++numDigits;
  37706. source.skip();
  37707. }
  37708. if (numDigits == 0)
  37709. return false;
  37710. return skipNumberSuffix (source);
  37711. }
  37712. bool isOctalDigit (const juce_wchar c) throw()
  37713. {
  37714. return c >= '0' && c <= '7';
  37715. }
  37716. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37717. {
  37718. if (source.nextChar() != '0')
  37719. return false;
  37720. if (! isOctalDigit (source.nextChar()))
  37721. return false;
  37722. while (isOctalDigit (source.peekNextChar()))
  37723. source.skip();
  37724. return skipNumberSuffix (source);
  37725. }
  37726. bool isDecimalDigit (const juce_wchar c) throw()
  37727. {
  37728. return c >= '0' && c <= '9';
  37729. }
  37730. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37731. {
  37732. int numChars = 0;
  37733. while (isDecimalDigit (source.peekNextChar()))
  37734. {
  37735. ++numChars;
  37736. source.skip();
  37737. }
  37738. if (numChars == 0)
  37739. return false;
  37740. return skipNumberSuffix (source);
  37741. }
  37742. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37743. {
  37744. int numDigits = 0;
  37745. while (isDecimalDigit (source.peekNextChar()))
  37746. {
  37747. source.skip();
  37748. ++numDigits;
  37749. }
  37750. const bool hasPoint = (source.peekNextChar() == '.');
  37751. if (hasPoint)
  37752. {
  37753. source.skip();
  37754. while (isDecimalDigit (source.peekNextChar()))
  37755. {
  37756. source.skip();
  37757. ++numDigits;
  37758. }
  37759. }
  37760. if (numDigits == 0)
  37761. return false;
  37762. juce_wchar c = source.peekNextChar();
  37763. const bool hasExponent = (c == 'e' || c == 'E');
  37764. if (hasExponent)
  37765. {
  37766. source.skip();
  37767. c = source.peekNextChar();
  37768. if (c == '+' || c == '-')
  37769. source.skip();
  37770. int numExpDigits = 0;
  37771. while (isDecimalDigit (source.peekNextChar()))
  37772. {
  37773. source.skip();
  37774. ++numExpDigits;
  37775. }
  37776. if (numExpDigits == 0)
  37777. return false;
  37778. }
  37779. c = source.peekNextChar();
  37780. if (c == 'f' || c == 'F')
  37781. source.skip();
  37782. else if (! (hasExponent || hasPoint))
  37783. return false;
  37784. return true;
  37785. }
  37786. int parseNumber (CodeDocument::Iterator& source)
  37787. {
  37788. const CodeDocument::Iterator original (source);
  37789. if (parseFloatLiteral (source))
  37790. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37791. source = original;
  37792. if (parseHexLiteral (source))
  37793. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37794. source = original;
  37795. if (parseOctalLiteral (source))
  37796. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37797. source = original;
  37798. if (parseDecimalLiteral (source))
  37799. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37800. source = original;
  37801. source.skip();
  37802. return CPlusPlusCodeTokeniser::tokenType_error;
  37803. }
  37804. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37805. {
  37806. const juce_wchar quote = source.nextChar();
  37807. for (;;)
  37808. {
  37809. const juce_wchar c = source.nextChar();
  37810. if (c == quote || c == 0)
  37811. break;
  37812. if (c == '\\')
  37813. source.skip();
  37814. }
  37815. }
  37816. void skipComment (CodeDocument::Iterator& source) throw()
  37817. {
  37818. bool lastWasStar = false;
  37819. for (;;)
  37820. {
  37821. const juce_wchar c = source.nextChar();
  37822. if (c == 0 || (c == '/' && lastWasStar))
  37823. break;
  37824. lastWasStar = (c == '*');
  37825. }
  37826. }
  37827. }
  37828. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37829. {
  37830. int result = tokenType_error;
  37831. source.skipWhitespace();
  37832. juce_wchar firstChar = source.peekNextChar();
  37833. switch (firstChar)
  37834. {
  37835. case 0:
  37836. source.skip();
  37837. break;
  37838. case '0':
  37839. case '1':
  37840. case '2':
  37841. case '3':
  37842. case '4':
  37843. case '5':
  37844. case '6':
  37845. case '7':
  37846. case '8':
  37847. case '9':
  37848. result = CppTokeniser::parseNumber (source);
  37849. break;
  37850. case '.':
  37851. result = CppTokeniser::parseNumber (source);
  37852. if (result == tokenType_error)
  37853. result = tokenType_punctuation;
  37854. break;
  37855. case ',':
  37856. case ';':
  37857. case ':':
  37858. source.skip();
  37859. result = tokenType_punctuation;
  37860. break;
  37861. case '(':
  37862. case ')':
  37863. case '{':
  37864. case '}':
  37865. case '[':
  37866. case ']':
  37867. source.skip();
  37868. result = tokenType_bracket;
  37869. break;
  37870. case '"':
  37871. case '\'':
  37872. CppTokeniser::skipQuotedString (source);
  37873. result = tokenType_stringLiteral;
  37874. break;
  37875. case '+':
  37876. result = tokenType_operator;
  37877. source.skip();
  37878. if (source.peekNextChar() == '+')
  37879. source.skip();
  37880. else if (source.peekNextChar() == '=')
  37881. source.skip();
  37882. break;
  37883. case '-':
  37884. source.skip();
  37885. result = CppTokeniser::parseNumber (source);
  37886. if (result == tokenType_error)
  37887. {
  37888. result = tokenType_operator;
  37889. if (source.peekNextChar() == '-')
  37890. source.skip();
  37891. else if (source.peekNextChar() == '=')
  37892. source.skip();
  37893. }
  37894. break;
  37895. case '*':
  37896. case '%':
  37897. case '=':
  37898. case '!':
  37899. result = tokenType_operator;
  37900. source.skip();
  37901. if (source.peekNextChar() == '=')
  37902. source.skip();
  37903. break;
  37904. case '/':
  37905. result = tokenType_operator;
  37906. source.skip();
  37907. if (source.peekNextChar() == '=')
  37908. {
  37909. source.skip();
  37910. }
  37911. else if (source.peekNextChar() == '/')
  37912. {
  37913. result = tokenType_comment;
  37914. source.skipToEndOfLine();
  37915. }
  37916. else if (source.peekNextChar() == '*')
  37917. {
  37918. source.skip();
  37919. result = tokenType_comment;
  37920. CppTokeniser::skipComment (source);
  37921. }
  37922. break;
  37923. case '?':
  37924. case '~':
  37925. source.skip();
  37926. result = tokenType_operator;
  37927. break;
  37928. case '<':
  37929. source.skip();
  37930. result = tokenType_operator;
  37931. if (source.peekNextChar() == '=')
  37932. {
  37933. source.skip();
  37934. }
  37935. else if (source.peekNextChar() == '<')
  37936. {
  37937. source.skip();
  37938. if (source.peekNextChar() == '=')
  37939. source.skip();
  37940. }
  37941. break;
  37942. case '>':
  37943. source.skip();
  37944. result = tokenType_operator;
  37945. if (source.peekNextChar() == '=')
  37946. {
  37947. source.skip();
  37948. }
  37949. else if (source.peekNextChar() == '<')
  37950. {
  37951. source.skip();
  37952. if (source.peekNextChar() == '=')
  37953. source.skip();
  37954. }
  37955. break;
  37956. case '|':
  37957. source.skip();
  37958. result = tokenType_operator;
  37959. if (source.peekNextChar() == '=')
  37960. {
  37961. source.skip();
  37962. }
  37963. else if (source.peekNextChar() == '|')
  37964. {
  37965. source.skip();
  37966. if (source.peekNextChar() == '=')
  37967. source.skip();
  37968. }
  37969. break;
  37970. case '&':
  37971. source.skip();
  37972. result = tokenType_operator;
  37973. if (source.peekNextChar() == '=')
  37974. {
  37975. source.skip();
  37976. }
  37977. else if (source.peekNextChar() == '&')
  37978. {
  37979. source.skip();
  37980. if (source.peekNextChar() == '=')
  37981. source.skip();
  37982. }
  37983. break;
  37984. case '^':
  37985. source.skip();
  37986. result = tokenType_operator;
  37987. if (source.peekNextChar() == '=')
  37988. {
  37989. source.skip();
  37990. }
  37991. else if (source.peekNextChar() == '^')
  37992. {
  37993. source.skip();
  37994. if (source.peekNextChar() == '=')
  37995. source.skip();
  37996. }
  37997. break;
  37998. case '#':
  37999. result = tokenType_preprocessor;
  38000. source.skipToEndOfLine();
  38001. break;
  38002. default:
  38003. if (CppTokeniser::isIdentifierStart (firstChar))
  38004. result = CppTokeniser::parseIdentifier (source);
  38005. else
  38006. source.skip();
  38007. break;
  38008. }
  38009. return result;
  38010. }
  38011. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38012. {
  38013. const char* const types[] =
  38014. {
  38015. "Error",
  38016. "Comment",
  38017. "C++ keyword",
  38018. "Identifier",
  38019. "Integer literal",
  38020. "Float literal",
  38021. "String literal",
  38022. "Operator",
  38023. "Bracket",
  38024. "Punctuation",
  38025. "Preprocessor line",
  38026. 0
  38027. };
  38028. return StringArray (types);
  38029. }
  38030. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38031. {
  38032. const uint32 colours[] =
  38033. {
  38034. 0xffcc0000, // error
  38035. 0xff00aa00, // comment
  38036. 0xff0000cc, // keyword
  38037. 0xff000000, // identifier
  38038. 0xff880000, // int literal
  38039. 0xff885500, // float literal
  38040. 0xff990099, // string literal
  38041. 0xff225500, // operator
  38042. 0xff000055, // bracket
  38043. 0xff004400, // punctuation
  38044. 0xff660000 // preprocessor
  38045. };
  38046. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38047. return Colour (colours [tokenType]);
  38048. return Colours::black;
  38049. }
  38050. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38051. {
  38052. return CppTokeniser::isReservedKeyword (token, token.length());
  38053. }
  38054. END_JUCE_NAMESPACE
  38055. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38056. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38057. BEGIN_JUCE_NAMESPACE
  38058. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  38059. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  38060. {
  38061. }
  38062. bool ComboBox::ItemInfo::isSeparator() const throw()
  38063. {
  38064. return name.isEmpty();
  38065. }
  38066. bool ComboBox::ItemInfo::isRealItem() const throw()
  38067. {
  38068. return ! (isHeading || name.isEmpty());
  38069. }
  38070. ComboBox::ComboBox (const String& name)
  38071. : Component (name),
  38072. lastCurrentId (0),
  38073. isButtonDown (false),
  38074. separatorPending (false),
  38075. menuActive (false),
  38076. noChoicesMessage (TRANS("(no choices)"))
  38077. {
  38078. setRepaintsOnMouseActivity (true);
  38079. lookAndFeelChanged();
  38080. currentId.addListener (this);
  38081. }
  38082. ComboBox::~ComboBox()
  38083. {
  38084. currentId.removeListener (this);
  38085. if (menuActive)
  38086. PopupMenu::dismissAllActiveMenus();
  38087. label = 0;
  38088. }
  38089. void ComboBox::setEditableText (const bool isEditable)
  38090. {
  38091. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38092. {
  38093. label->setEditable (isEditable, isEditable, false);
  38094. setWantsKeyboardFocus (! isEditable);
  38095. resized();
  38096. }
  38097. }
  38098. bool ComboBox::isTextEditable() const throw()
  38099. {
  38100. return label->isEditable();
  38101. }
  38102. void ComboBox::setJustificationType (const Justification& justification)
  38103. {
  38104. label->setJustificationType (justification);
  38105. }
  38106. const Justification ComboBox::getJustificationType() const throw()
  38107. {
  38108. return label->getJustificationType();
  38109. }
  38110. void ComboBox::setTooltip (const String& newTooltip)
  38111. {
  38112. SettableTooltipClient::setTooltip (newTooltip);
  38113. label->setTooltip (newTooltip);
  38114. }
  38115. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38116. {
  38117. // you can't add empty strings to the list..
  38118. jassert (newItemText.isNotEmpty());
  38119. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38120. jassert (newItemId != 0);
  38121. // you shouldn't use duplicate item IDs!
  38122. jassert (getItemForId (newItemId) == 0);
  38123. if (newItemText.isNotEmpty() && newItemId != 0)
  38124. {
  38125. if (separatorPending)
  38126. {
  38127. separatorPending = false;
  38128. items.add (new ItemInfo (String::empty, 0, false, false));
  38129. }
  38130. items.add (new ItemInfo (newItemText, newItemId, true, false));
  38131. }
  38132. }
  38133. void ComboBox::addSeparator()
  38134. {
  38135. separatorPending = (items.size() > 0);
  38136. }
  38137. void ComboBox::addSectionHeading (const String& headingName)
  38138. {
  38139. // you can't add empty strings to the list..
  38140. jassert (headingName.isNotEmpty());
  38141. if (headingName.isNotEmpty())
  38142. {
  38143. if (separatorPending)
  38144. {
  38145. separatorPending = false;
  38146. items.add (new ItemInfo (String::empty, 0, false, false));
  38147. }
  38148. items.add (new ItemInfo (headingName, 0, true, true));
  38149. }
  38150. }
  38151. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38152. {
  38153. ItemInfo* const item = getItemForId (itemId);
  38154. if (item != 0)
  38155. item->isEnabled = shouldBeEnabled;
  38156. }
  38157. void ComboBox::changeItemText (const int itemId, const String& newText)
  38158. {
  38159. ItemInfo* const item = getItemForId (itemId);
  38160. jassert (item != 0);
  38161. if (item != 0)
  38162. item->name = newText;
  38163. }
  38164. void ComboBox::clear (const bool dontSendChangeMessage)
  38165. {
  38166. items.clear();
  38167. separatorPending = false;
  38168. if (! label->isEditable())
  38169. setSelectedItemIndex (-1, dontSendChangeMessage);
  38170. }
  38171. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38172. {
  38173. if (itemId != 0)
  38174. {
  38175. for (int i = items.size(); --i >= 0;)
  38176. if (items.getUnchecked(i)->itemId == itemId)
  38177. return items.getUnchecked(i);
  38178. }
  38179. return 0;
  38180. }
  38181. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38182. {
  38183. for (int n = 0, i = 0; i < items.size(); ++i)
  38184. {
  38185. ItemInfo* const item = items.getUnchecked(i);
  38186. if (item->isRealItem())
  38187. if (n++ == index)
  38188. return item;
  38189. }
  38190. return 0;
  38191. }
  38192. int ComboBox::getNumItems() const throw()
  38193. {
  38194. int n = 0;
  38195. for (int i = items.size(); --i >= 0;)
  38196. if (items.getUnchecked(i)->isRealItem())
  38197. ++n;
  38198. return n;
  38199. }
  38200. const String ComboBox::getItemText (const int index) const
  38201. {
  38202. const ItemInfo* const item = getItemForIndex (index);
  38203. return item != 0 ? item->name : String::empty;
  38204. }
  38205. int ComboBox::getItemId (const int index) const throw()
  38206. {
  38207. const ItemInfo* const item = getItemForIndex (index);
  38208. return item != 0 ? item->itemId : 0;
  38209. }
  38210. int ComboBox::indexOfItemId (const int itemId) const throw()
  38211. {
  38212. for (int n = 0, i = 0; i < items.size(); ++i)
  38213. {
  38214. const ItemInfo* const item = items.getUnchecked(i);
  38215. if (item->isRealItem())
  38216. {
  38217. if (item->itemId == itemId)
  38218. return n;
  38219. ++n;
  38220. }
  38221. }
  38222. return -1;
  38223. }
  38224. int ComboBox::getSelectedItemIndex() const
  38225. {
  38226. int index = indexOfItemId (currentId.getValue());
  38227. if (getText() != getItemText (index))
  38228. index = -1;
  38229. return index;
  38230. }
  38231. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38232. {
  38233. setSelectedId (getItemId (index), dontSendChangeMessage);
  38234. }
  38235. int ComboBox::getSelectedId() const throw()
  38236. {
  38237. const ItemInfo* const item = getItemForId (currentId.getValue());
  38238. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38239. }
  38240. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38241. {
  38242. const ItemInfo* const item = getItemForId (newItemId);
  38243. const String newItemText (item != 0 ? item->name : String::empty);
  38244. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38245. {
  38246. if (! dontSendChangeMessage)
  38247. triggerAsyncUpdate();
  38248. label->setText (newItemText, false);
  38249. lastCurrentId = newItemId;
  38250. currentId = newItemId;
  38251. repaint(); // for the benefit of the 'none selected' text
  38252. }
  38253. }
  38254. bool ComboBox::selectIfEnabled (const int index)
  38255. {
  38256. const ItemInfo* const item = getItemForIndex (index);
  38257. if (item != 0 && item->isEnabled)
  38258. {
  38259. setSelectedItemIndex (index);
  38260. return true;
  38261. }
  38262. return false;
  38263. }
  38264. void ComboBox::valueChanged (Value&)
  38265. {
  38266. if (lastCurrentId != (int) currentId.getValue())
  38267. setSelectedId (currentId.getValue(), false);
  38268. }
  38269. const String ComboBox::getText() const
  38270. {
  38271. return label->getText();
  38272. }
  38273. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38274. {
  38275. for (int i = items.size(); --i >= 0;)
  38276. {
  38277. const ItemInfo* const item = items.getUnchecked(i);
  38278. if (item->isRealItem()
  38279. && item->name == newText)
  38280. {
  38281. setSelectedId (item->itemId, dontSendChangeMessage);
  38282. return;
  38283. }
  38284. }
  38285. lastCurrentId = 0;
  38286. currentId = 0;
  38287. if (label->getText() != newText)
  38288. {
  38289. label->setText (newText, false);
  38290. if (! dontSendChangeMessage)
  38291. triggerAsyncUpdate();
  38292. }
  38293. repaint();
  38294. }
  38295. void ComboBox::showEditor()
  38296. {
  38297. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38298. label->showEditor();
  38299. }
  38300. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38301. {
  38302. if (textWhenNothingSelected != newMessage)
  38303. {
  38304. textWhenNothingSelected = newMessage;
  38305. repaint();
  38306. }
  38307. }
  38308. const String ComboBox::getTextWhenNothingSelected() const
  38309. {
  38310. return textWhenNothingSelected;
  38311. }
  38312. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38313. {
  38314. noChoicesMessage = newMessage;
  38315. }
  38316. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38317. {
  38318. return noChoicesMessage;
  38319. }
  38320. void ComboBox::paint (Graphics& g)
  38321. {
  38322. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38323. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38324. *this);
  38325. if (textWhenNothingSelected.isNotEmpty()
  38326. && label->getText().isEmpty()
  38327. && ! label->isBeingEdited())
  38328. {
  38329. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38330. g.setFont (label->getFont());
  38331. g.drawFittedText (textWhenNothingSelected,
  38332. label->getX() + 2, label->getY() + 1,
  38333. label->getWidth() - 4, label->getHeight() - 2,
  38334. label->getJustificationType(),
  38335. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38336. }
  38337. }
  38338. void ComboBox::resized()
  38339. {
  38340. if (getHeight() > 0 && getWidth() > 0)
  38341. getLookAndFeel().positionComboBoxText (*this, *label);
  38342. }
  38343. void ComboBox::enablementChanged()
  38344. {
  38345. repaint();
  38346. }
  38347. void ComboBox::lookAndFeelChanged()
  38348. {
  38349. repaint();
  38350. {
  38351. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38352. jassert (newLabel != 0);
  38353. if (label != 0)
  38354. {
  38355. newLabel->setEditable (label->isEditable());
  38356. newLabel->setJustificationType (label->getJustificationType());
  38357. newLabel->setTooltip (label->getTooltip());
  38358. newLabel->setText (label->getText(), false);
  38359. }
  38360. label = newLabel;
  38361. }
  38362. addAndMakeVisible (label);
  38363. label->addListener (this);
  38364. label->addMouseListener (this, false);
  38365. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38366. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38367. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38368. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38369. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38370. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38371. resized();
  38372. }
  38373. void ComboBox::colourChanged()
  38374. {
  38375. lookAndFeelChanged();
  38376. }
  38377. bool ComboBox::keyPressed (const KeyPress& key)
  38378. {
  38379. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38380. {
  38381. int index = getSelectedItemIndex() - 1;
  38382. while (index >= 0 && ! selectIfEnabled (index))
  38383. --index;
  38384. return true;
  38385. }
  38386. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38387. {
  38388. int index = getSelectedItemIndex() + 1;
  38389. while (index < getNumItems() && ! selectIfEnabled (index))
  38390. ++index;
  38391. return true;
  38392. }
  38393. else if (key.isKeyCode (KeyPress::returnKey))
  38394. {
  38395. showPopup();
  38396. return true;
  38397. }
  38398. return false;
  38399. }
  38400. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38401. {
  38402. // only forward key events that aren't used by this component
  38403. return isKeyDown
  38404. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38405. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38406. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38407. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38408. }
  38409. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38410. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38411. void ComboBox::labelTextChanged (Label*)
  38412. {
  38413. triggerAsyncUpdate();
  38414. }
  38415. class ComboBox::Callback : public ModalComponentManager::Callback
  38416. {
  38417. public:
  38418. Callback (ComboBox* const box_)
  38419. : box (box_)
  38420. {
  38421. }
  38422. void modalStateFinished (int returnValue)
  38423. {
  38424. if (box != 0)
  38425. {
  38426. box->menuActive = false;
  38427. if (returnValue != 0)
  38428. box->setSelectedId (returnValue);
  38429. }
  38430. }
  38431. private:
  38432. Component::SafePointer<ComboBox> box;
  38433. JUCE_DECLARE_NON_COPYABLE (Callback);
  38434. };
  38435. void ComboBox::showPopup()
  38436. {
  38437. if (! menuActive)
  38438. {
  38439. const int selectedId = getSelectedId();
  38440. PopupMenu menu;
  38441. menu.setLookAndFeel (&getLookAndFeel());
  38442. for (int i = 0; i < items.size(); ++i)
  38443. {
  38444. const ItemInfo* const item = items.getUnchecked(i);
  38445. if (item->isSeparator())
  38446. menu.addSeparator();
  38447. else if (item->isHeading)
  38448. menu.addSectionHeader (item->name);
  38449. else
  38450. menu.addItem (item->itemId, item->name,
  38451. item->isEnabled, item->itemId == selectedId);
  38452. }
  38453. if (items.size() == 0)
  38454. menu.addItem (1, noChoicesMessage, false);
  38455. menuActive = true;
  38456. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38457. new Callback (this));
  38458. }
  38459. }
  38460. void ComboBox::mouseDown (const MouseEvent& e)
  38461. {
  38462. beginDragAutoRepeat (300);
  38463. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38464. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38465. showPopup();
  38466. }
  38467. void ComboBox::mouseDrag (const MouseEvent& e)
  38468. {
  38469. beginDragAutoRepeat (50);
  38470. if (isButtonDown && ! e.mouseWasClicked())
  38471. showPopup();
  38472. }
  38473. void ComboBox::mouseUp (const MouseEvent& e2)
  38474. {
  38475. if (isButtonDown)
  38476. {
  38477. isButtonDown = false;
  38478. repaint();
  38479. const MouseEvent e (e2.getEventRelativeTo (this));
  38480. if (reallyContains (e.getPosition(), true)
  38481. && (e2.eventComponent == this || ! label->isEditable()))
  38482. {
  38483. showPopup();
  38484. }
  38485. }
  38486. }
  38487. void ComboBox::addListener (ComboBoxListener* const listener)
  38488. {
  38489. listeners.add (listener);
  38490. }
  38491. void ComboBox::removeListener (ComboBoxListener* const listener)
  38492. {
  38493. listeners.remove (listener);
  38494. }
  38495. void ComboBox::handleAsyncUpdate()
  38496. {
  38497. Component::BailOutChecker checker (this);
  38498. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38499. }
  38500. END_JUCE_NAMESPACE
  38501. /*** End of inlined file: juce_ComboBox.cpp ***/
  38502. /*** Start of inlined file: juce_Label.cpp ***/
  38503. BEGIN_JUCE_NAMESPACE
  38504. Label::Label (const String& componentName,
  38505. const String& labelText)
  38506. : Component (componentName),
  38507. textValue (labelText),
  38508. lastTextValue (labelText),
  38509. font (15.0f),
  38510. justification (Justification::centredLeft),
  38511. ownerComponent (0),
  38512. horizontalBorderSize (5),
  38513. verticalBorderSize (1),
  38514. minimumHorizontalScale (0.7f),
  38515. editSingleClick (false),
  38516. editDoubleClick (false),
  38517. lossOfFocusDiscardsChanges (false)
  38518. {
  38519. setColour (TextEditor::textColourId, Colours::black);
  38520. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38521. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38522. textValue.addListener (this);
  38523. }
  38524. Label::~Label()
  38525. {
  38526. textValue.removeListener (this);
  38527. if (ownerComponent != 0)
  38528. ownerComponent->removeComponentListener (this);
  38529. editor = 0;
  38530. }
  38531. void Label::setText (const String& newText,
  38532. const bool broadcastChangeMessage)
  38533. {
  38534. hideEditor (true);
  38535. if (lastTextValue != newText)
  38536. {
  38537. lastTextValue = newText;
  38538. textValue = newText;
  38539. repaint();
  38540. textWasChanged();
  38541. if (ownerComponent != 0)
  38542. componentMovedOrResized (*ownerComponent, true, true);
  38543. if (broadcastChangeMessage)
  38544. callChangeListeners();
  38545. }
  38546. }
  38547. const String Label::getText (const bool returnActiveEditorContents) const
  38548. {
  38549. return (returnActiveEditorContents && isBeingEdited())
  38550. ? editor->getText()
  38551. : textValue.toString();
  38552. }
  38553. void Label::valueChanged (Value&)
  38554. {
  38555. if (lastTextValue != textValue.toString())
  38556. setText (textValue.toString(), true);
  38557. }
  38558. void Label::setFont (const Font& newFont)
  38559. {
  38560. if (font != newFont)
  38561. {
  38562. font = newFont;
  38563. repaint();
  38564. }
  38565. }
  38566. const Font& Label::getFont() const throw()
  38567. {
  38568. return font;
  38569. }
  38570. void Label::setEditable (const bool editOnSingleClick,
  38571. const bool editOnDoubleClick,
  38572. const bool lossOfFocusDiscardsChanges_)
  38573. {
  38574. editSingleClick = editOnSingleClick;
  38575. editDoubleClick = editOnDoubleClick;
  38576. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38577. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38578. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38579. }
  38580. void Label::setJustificationType (const Justification& newJustification)
  38581. {
  38582. if (justification != newJustification)
  38583. {
  38584. justification = newJustification;
  38585. repaint();
  38586. }
  38587. }
  38588. void Label::setBorderSize (int h, int v)
  38589. {
  38590. if (horizontalBorderSize != h || verticalBorderSize != v)
  38591. {
  38592. horizontalBorderSize = h;
  38593. verticalBorderSize = v;
  38594. repaint();
  38595. }
  38596. }
  38597. Component* Label::getAttachedComponent() const
  38598. {
  38599. return static_cast<Component*> (ownerComponent);
  38600. }
  38601. void Label::attachToComponent (Component* owner,
  38602. const bool onLeft)
  38603. {
  38604. if (ownerComponent != 0)
  38605. ownerComponent->removeComponentListener (this);
  38606. ownerComponent = owner;
  38607. leftOfOwnerComp = onLeft;
  38608. if (ownerComponent != 0)
  38609. {
  38610. setVisible (owner->isVisible());
  38611. ownerComponent->addComponentListener (this);
  38612. componentParentHierarchyChanged (*ownerComponent);
  38613. componentMovedOrResized (*ownerComponent, true, true);
  38614. }
  38615. }
  38616. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38617. {
  38618. if (leftOfOwnerComp)
  38619. {
  38620. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38621. component.getHeight());
  38622. setTopRightPosition (component.getX(), component.getY());
  38623. }
  38624. else
  38625. {
  38626. setSize (component.getWidth(),
  38627. 8 + roundToInt (getFont().getHeight()));
  38628. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38629. }
  38630. }
  38631. void Label::componentParentHierarchyChanged (Component& component)
  38632. {
  38633. if (component.getParentComponent() != 0)
  38634. component.getParentComponent()->addChildComponent (this);
  38635. }
  38636. void Label::componentVisibilityChanged (Component& component)
  38637. {
  38638. setVisible (component.isVisible());
  38639. }
  38640. void Label::textWasEdited()
  38641. {
  38642. }
  38643. void Label::textWasChanged()
  38644. {
  38645. }
  38646. void Label::showEditor()
  38647. {
  38648. if (editor == 0)
  38649. {
  38650. addAndMakeVisible (editor = createEditorComponent());
  38651. editor->setText (getText(), false);
  38652. editor->addListener (this);
  38653. editor->grabKeyboardFocus();
  38654. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38655. editor->addListener (this);
  38656. resized();
  38657. repaint();
  38658. editorShown (editor);
  38659. enterModalState (false);
  38660. editor->grabKeyboardFocus();
  38661. }
  38662. }
  38663. void Label::editorShown (TextEditor* /*editorComponent*/)
  38664. {
  38665. }
  38666. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38667. {
  38668. }
  38669. bool Label::updateFromTextEditorContents()
  38670. {
  38671. jassert (editor != 0);
  38672. const String newText (editor->getText());
  38673. if (textValue.toString() != newText)
  38674. {
  38675. lastTextValue = newText;
  38676. textValue = newText;
  38677. repaint();
  38678. textWasChanged();
  38679. if (ownerComponent != 0)
  38680. componentMovedOrResized (*ownerComponent, true, true);
  38681. return true;
  38682. }
  38683. return false;
  38684. }
  38685. void Label::hideEditor (const bool discardCurrentEditorContents)
  38686. {
  38687. if (editor != 0)
  38688. {
  38689. WeakReference<Component> deletionChecker (this);
  38690. editorAboutToBeHidden (editor);
  38691. const bool changed = (! discardCurrentEditorContents)
  38692. && updateFromTextEditorContents();
  38693. editor = 0;
  38694. repaint();
  38695. if (changed)
  38696. textWasEdited();
  38697. if (deletionChecker != 0)
  38698. exitModalState (0);
  38699. if (changed && deletionChecker != 0)
  38700. callChangeListeners();
  38701. }
  38702. }
  38703. void Label::inputAttemptWhenModal()
  38704. {
  38705. if (editor != 0)
  38706. {
  38707. if (lossOfFocusDiscardsChanges)
  38708. textEditorEscapeKeyPressed (*editor);
  38709. else
  38710. textEditorReturnKeyPressed (*editor);
  38711. }
  38712. }
  38713. bool Label::isBeingEdited() const throw()
  38714. {
  38715. return editor != 0;
  38716. }
  38717. TextEditor* Label::createEditorComponent()
  38718. {
  38719. TextEditor* const ed = new TextEditor (getName());
  38720. ed->setFont (font);
  38721. // copy these colours from our own settings..
  38722. const int cols[] = { TextEditor::backgroundColourId,
  38723. TextEditor::textColourId,
  38724. TextEditor::highlightColourId,
  38725. TextEditor::highlightedTextColourId,
  38726. TextEditor::caretColourId,
  38727. TextEditor::outlineColourId,
  38728. TextEditor::focusedOutlineColourId,
  38729. TextEditor::shadowColourId };
  38730. for (int i = 0; i < numElementsInArray (cols); ++i)
  38731. ed->setColour (cols[i], findColour (cols[i]));
  38732. return ed;
  38733. }
  38734. void Label::paint (Graphics& g)
  38735. {
  38736. getLookAndFeel().drawLabel (g, *this);
  38737. }
  38738. void Label::mouseUp (const MouseEvent& e)
  38739. {
  38740. if (editSingleClick
  38741. && e.mouseWasClicked()
  38742. && contains (e.getPosition())
  38743. && ! e.mods.isPopupMenu())
  38744. {
  38745. showEditor();
  38746. }
  38747. }
  38748. void Label::mouseDoubleClick (const MouseEvent& e)
  38749. {
  38750. if (editDoubleClick && ! e.mods.isPopupMenu())
  38751. showEditor();
  38752. }
  38753. void Label::resized()
  38754. {
  38755. if (editor != 0)
  38756. editor->setBoundsInset (BorderSize (0));
  38757. }
  38758. void Label::focusGained (FocusChangeType cause)
  38759. {
  38760. if (editSingleClick && cause == focusChangedByTabKey)
  38761. showEditor();
  38762. }
  38763. void Label::enablementChanged()
  38764. {
  38765. repaint();
  38766. }
  38767. void Label::colourChanged()
  38768. {
  38769. repaint();
  38770. }
  38771. void Label::setMinimumHorizontalScale (const float newScale)
  38772. {
  38773. if (minimumHorizontalScale != newScale)
  38774. {
  38775. minimumHorizontalScale = newScale;
  38776. repaint();
  38777. }
  38778. }
  38779. // We'll use a custom focus traverser here to make sure focus goes from the
  38780. // text editor to another component rather than back to the label itself.
  38781. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38782. {
  38783. public:
  38784. LabelKeyboardFocusTraverser() {}
  38785. Component* getNextComponent (Component* current)
  38786. {
  38787. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38788. ? current->getParentComponent() : current);
  38789. }
  38790. Component* getPreviousComponent (Component* current)
  38791. {
  38792. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38793. ? current->getParentComponent() : current);
  38794. }
  38795. };
  38796. KeyboardFocusTraverser* Label::createFocusTraverser()
  38797. {
  38798. return new LabelKeyboardFocusTraverser();
  38799. }
  38800. void Label::addListener (LabelListener* const listener)
  38801. {
  38802. listeners.add (listener);
  38803. }
  38804. void Label::removeListener (LabelListener* const listener)
  38805. {
  38806. listeners.remove (listener);
  38807. }
  38808. void Label::callChangeListeners()
  38809. {
  38810. Component::BailOutChecker checker (this);
  38811. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38812. }
  38813. void Label::textEditorTextChanged (TextEditor& ed)
  38814. {
  38815. if (editor != 0)
  38816. {
  38817. jassert (&ed == editor);
  38818. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38819. {
  38820. if (lossOfFocusDiscardsChanges)
  38821. textEditorEscapeKeyPressed (ed);
  38822. else
  38823. textEditorReturnKeyPressed (ed);
  38824. }
  38825. }
  38826. }
  38827. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38828. {
  38829. if (editor != 0)
  38830. {
  38831. jassert (&ed == editor);
  38832. (void) ed;
  38833. const bool changed = updateFromTextEditorContents();
  38834. hideEditor (true);
  38835. if (changed)
  38836. {
  38837. WeakReference<Component> deletionChecker (this);
  38838. textWasEdited();
  38839. if (deletionChecker != 0)
  38840. callChangeListeners();
  38841. }
  38842. }
  38843. }
  38844. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38845. {
  38846. if (editor != 0)
  38847. {
  38848. jassert (&ed == editor);
  38849. (void) ed;
  38850. editor->setText (textValue.toString(), false);
  38851. hideEditor (true);
  38852. }
  38853. }
  38854. void Label::textEditorFocusLost (TextEditor& ed)
  38855. {
  38856. textEditorTextChanged (ed);
  38857. }
  38858. END_JUCE_NAMESPACE
  38859. /*** End of inlined file: juce_Label.cpp ***/
  38860. /*** Start of inlined file: juce_ListBox.cpp ***/
  38861. BEGIN_JUCE_NAMESPACE
  38862. class ListBoxRowComponent : public Component,
  38863. public TooltipClient
  38864. {
  38865. public:
  38866. ListBoxRowComponent (ListBox& owner_)
  38867. : owner (owner_), row (-1),
  38868. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38869. {
  38870. }
  38871. void paint (Graphics& g)
  38872. {
  38873. if (owner.getModel() != 0)
  38874. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38875. }
  38876. void update (const int row_, const bool selected_)
  38877. {
  38878. if (row != row_ || selected != selected_)
  38879. {
  38880. repaint();
  38881. row = row_;
  38882. selected = selected_;
  38883. }
  38884. if (owner.getModel() != 0)
  38885. {
  38886. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38887. if (customComponent != 0)
  38888. {
  38889. addAndMakeVisible (customComponent);
  38890. customComponent->setBounds (getLocalBounds());
  38891. }
  38892. }
  38893. }
  38894. void mouseDown (const MouseEvent& e)
  38895. {
  38896. isDragging = false;
  38897. selectRowOnMouseUp = false;
  38898. if (isEnabled())
  38899. {
  38900. if (! selected)
  38901. {
  38902. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38903. if (owner.getModel() != 0)
  38904. owner.getModel()->listBoxItemClicked (row, e);
  38905. }
  38906. else
  38907. {
  38908. selectRowOnMouseUp = true;
  38909. }
  38910. }
  38911. }
  38912. void mouseUp (const MouseEvent& e)
  38913. {
  38914. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38915. {
  38916. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38917. if (owner.getModel() != 0)
  38918. owner.getModel()->listBoxItemClicked (row, e);
  38919. }
  38920. }
  38921. void mouseDoubleClick (const MouseEvent& e)
  38922. {
  38923. if (owner.getModel() != 0 && isEnabled())
  38924. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38925. }
  38926. void mouseDrag (const MouseEvent& e)
  38927. {
  38928. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38929. {
  38930. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38931. if (selectedRows.size() > 0)
  38932. {
  38933. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38934. if (dragDescription.isNotEmpty())
  38935. {
  38936. isDragging = true;
  38937. owner.startDragAndDrop (e, dragDescription);
  38938. }
  38939. }
  38940. }
  38941. }
  38942. void resized()
  38943. {
  38944. if (customComponent != 0)
  38945. customComponent->setBounds (getLocalBounds());
  38946. }
  38947. const String getTooltip()
  38948. {
  38949. if (owner.getModel() != 0)
  38950. return owner.getModel()->getTooltipForRow (row);
  38951. return String::empty;
  38952. }
  38953. ScopedPointer<Component> customComponent;
  38954. private:
  38955. ListBox& owner;
  38956. int row;
  38957. bool selected, isDragging, selectRowOnMouseUp;
  38958. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38959. };
  38960. class ListViewport : public Viewport
  38961. {
  38962. public:
  38963. ListViewport (ListBox& owner_)
  38964. : owner (owner_)
  38965. {
  38966. setWantsKeyboardFocus (false);
  38967. Component* const content = new Component();
  38968. setViewedComponent (content);
  38969. content->addMouseListener (this, false);
  38970. content->setWantsKeyboardFocus (false);
  38971. }
  38972. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38973. {
  38974. return rows [row % jmax (1, rows.size())];
  38975. }
  38976. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38977. {
  38978. return (row >= firstIndex && row < firstIndex + rows.size())
  38979. ? getComponentForRow (row) : 0;
  38980. }
  38981. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38982. {
  38983. const int index = getIndexOfChildComponent (rowComponent);
  38984. const int num = rows.size();
  38985. for (int i = num; --i >= 0;)
  38986. if (((firstIndex + i) % jmax (1, num)) == index)
  38987. return firstIndex + i;
  38988. return -1;
  38989. }
  38990. void visibleAreaChanged (const Rectangle<int>&)
  38991. {
  38992. updateVisibleArea (true);
  38993. if (owner.getModel() != 0)
  38994. owner.getModel()->listWasScrolled();
  38995. }
  38996. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38997. {
  38998. hasUpdated = false;
  38999. const int newX = getViewedComponent()->getX();
  39000. int newY = getViewedComponent()->getY();
  39001. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39002. const int newH = owner.totalItems * owner.getRowHeight();
  39003. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39004. newY = getMaximumVisibleHeight() - newH;
  39005. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39006. if (makeSureItUpdatesContent && ! hasUpdated)
  39007. updateContents();
  39008. }
  39009. void updateContents()
  39010. {
  39011. hasUpdated = true;
  39012. const int rowHeight = owner.getRowHeight();
  39013. if (rowHeight > 0)
  39014. {
  39015. const int y = getViewPositionY();
  39016. const int w = getViewedComponent()->getWidth();
  39017. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39018. rows.removeRange (numNeeded, rows.size());
  39019. while (numNeeded > rows.size())
  39020. {
  39021. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39022. rows.add (newRow);
  39023. getViewedComponent()->addAndMakeVisible (newRow);
  39024. }
  39025. firstIndex = y / rowHeight;
  39026. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39027. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39028. for (int i = 0; i < numNeeded; ++i)
  39029. {
  39030. const int row = i + firstIndex;
  39031. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39032. if (rowComp != 0)
  39033. {
  39034. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39035. rowComp->update (row, owner.isRowSelected (row));
  39036. }
  39037. }
  39038. }
  39039. if (owner.headerComponent != 0)
  39040. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39041. owner.outlineThickness,
  39042. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39043. getViewedComponent()->getWidth()),
  39044. owner.headerComponent->getHeight());
  39045. }
  39046. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39047. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39048. {
  39049. hasUpdated = false;
  39050. if (row < firstWholeIndex && ! dontScroll)
  39051. {
  39052. setViewPosition (getViewPositionX(), row * rowHeight);
  39053. }
  39054. else if (row >= lastWholeIndex && ! dontScroll)
  39055. {
  39056. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39057. if (row >= lastRowSelected + rowsOnScreen
  39058. && rowsOnScreen < totalItems - 1
  39059. && ! isMouseClick)
  39060. {
  39061. setViewPosition (getViewPositionX(),
  39062. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39063. }
  39064. else
  39065. {
  39066. setViewPosition (getViewPositionX(),
  39067. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39068. }
  39069. }
  39070. if (! hasUpdated)
  39071. updateContents();
  39072. }
  39073. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39074. {
  39075. if (row < firstWholeIndex)
  39076. {
  39077. setViewPosition (getViewPositionX(), row * rowHeight);
  39078. }
  39079. else if (row >= lastWholeIndex)
  39080. {
  39081. setViewPosition (getViewPositionX(),
  39082. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39083. }
  39084. }
  39085. void paint (Graphics& g)
  39086. {
  39087. if (isOpaque())
  39088. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39089. }
  39090. bool keyPressed (const KeyPress& key)
  39091. {
  39092. if (key.isKeyCode (KeyPress::upKey)
  39093. || key.isKeyCode (KeyPress::downKey)
  39094. || key.isKeyCode (KeyPress::pageUpKey)
  39095. || key.isKeyCode (KeyPress::pageDownKey)
  39096. || key.isKeyCode (KeyPress::homeKey)
  39097. || key.isKeyCode (KeyPress::endKey))
  39098. {
  39099. // we want to avoid these keypresses going to the viewport, and instead allow
  39100. // them to pass up to our listbox..
  39101. return false;
  39102. }
  39103. return Viewport::keyPressed (key);
  39104. }
  39105. private:
  39106. ListBox& owner;
  39107. OwnedArray<ListBoxRowComponent> rows;
  39108. int firstIndex, firstWholeIndex, lastWholeIndex;
  39109. bool hasUpdated;
  39110. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  39111. };
  39112. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39113. : Component (name),
  39114. model (model_),
  39115. totalItems (0),
  39116. rowHeight (22),
  39117. minimumRowWidth (0),
  39118. outlineThickness (0),
  39119. lastRowSelected (-1),
  39120. mouseMoveSelects (false),
  39121. multipleSelection (false),
  39122. hasDoneInitialUpdate (false)
  39123. {
  39124. addAndMakeVisible (viewport = new ListViewport (*this));
  39125. setWantsKeyboardFocus (true);
  39126. colourChanged();
  39127. }
  39128. ListBox::~ListBox()
  39129. {
  39130. headerComponent = 0;
  39131. viewport = 0;
  39132. }
  39133. void ListBox::setModel (ListBoxModel* const newModel)
  39134. {
  39135. if (model != newModel)
  39136. {
  39137. model = newModel;
  39138. repaint();
  39139. updateContent();
  39140. }
  39141. }
  39142. void ListBox::setMultipleSelectionEnabled (bool b)
  39143. {
  39144. multipleSelection = b;
  39145. }
  39146. void ListBox::setMouseMoveSelectsRows (bool b)
  39147. {
  39148. mouseMoveSelects = b;
  39149. if (b)
  39150. addMouseListener (this, true);
  39151. }
  39152. void ListBox::paint (Graphics& g)
  39153. {
  39154. if (! hasDoneInitialUpdate)
  39155. updateContent();
  39156. g.fillAll (findColour (backgroundColourId));
  39157. }
  39158. void ListBox::paintOverChildren (Graphics& g)
  39159. {
  39160. if (outlineThickness > 0)
  39161. {
  39162. g.setColour (findColour (outlineColourId));
  39163. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39164. }
  39165. }
  39166. void ListBox::resized()
  39167. {
  39168. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39169. outlineThickness,
  39170. outlineThickness,
  39171. outlineThickness));
  39172. viewport->setSingleStepSizes (20, getRowHeight());
  39173. viewport->updateVisibleArea (false);
  39174. }
  39175. void ListBox::visibilityChanged()
  39176. {
  39177. viewport->updateVisibleArea (true);
  39178. }
  39179. Viewport* ListBox::getViewport() const throw()
  39180. {
  39181. return viewport;
  39182. }
  39183. void ListBox::updateContent()
  39184. {
  39185. hasDoneInitialUpdate = true;
  39186. totalItems = (model != 0) ? model->getNumRows() : 0;
  39187. bool selectionChanged = false;
  39188. if (selected [selected.size() - 1] >= totalItems)
  39189. {
  39190. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39191. lastRowSelected = getSelectedRow (0);
  39192. selectionChanged = true;
  39193. }
  39194. viewport->updateVisibleArea (isVisible());
  39195. viewport->resized();
  39196. if (selectionChanged && model != 0)
  39197. model->selectedRowsChanged (lastRowSelected);
  39198. }
  39199. void ListBox::selectRow (const int row,
  39200. bool dontScroll,
  39201. bool deselectOthersFirst)
  39202. {
  39203. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39204. }
  39205. void ListBox::selectRowInternal (const int row,
  39206. bool dontScroll,
  39207. bool deselectOthersFirst,
  39208. bool isMouseClick)
  39209. {
  39210. if (! multipleSelection)
  39211. deselectOthersFirst = true;
  39212. if ((! isRowSelected (row))
  39213. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39214. {
  39215. if (isPositiveAndBelow (row, totalItems))
  39216. {
  39217. if (deselectOthersFirst)
  39218. selected.clear();
  39219. selected.addRange (Range<int> (row, row + 1));
  39220. if (getHeight() == 0 || getWidth() == 0)
  39221. dontScroll = true;
  39222. viewport->selectRow (row, getRowHeight(), dontScroll,
  39223. lastRowSelected, totalItems, isMouseClick);
  39224. lastRowSelected = row;
  39225. model->selectedRowsChanged (row);
  39226. }
  39227. else
  39228. {
  39229. if (deselectOthersFirst)
  39230. deselectAllRows();
  39231. }
  39232. }
  39233. }
  39234. void ListBox::deselectRow (const int row)
  39235. {
  39236. if (selected.contains (row))
  39237. {
  39238. selected.removeRange (Range <int> (row, row + 1));
  39239. if (row == lastRowSelected)
  39240. lastRowSelected = getSelectedRow (0);
  39241. viewport->updateContents();
  39242. model->selectedRowsChanged (lastRowSelected);
  39243. }
  39244. }
  39245. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39246. const bool sendNotificationEventToModel)
  39247. {
  39248. selected = setOfRowsToBeSelected;
  39249. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39250. if (! isRowSelected (lastRowSelected))
  39251. lastRowSelected = getSelectedRow (0);
  39252. viewport->updateContents();
  39253. if ((model != 0) && sendNotificationEventToModel)
  39254. model->selectedRowsChanged (lastRowSelected);
  39255. }
  39256. const SparseSet<int> ListBox::getSelectedRows() const
  39257. {
  39258. return selected;
  39259. }
  39260. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39261. {
  39262. if (multipleSelection && (firstRow != lastRow))
  39263. {
  39264. const int numRows = totalItems - 1;
  39265. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39266. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39267. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39268. jmax (firstRow, lastRow) + 1));
  39269. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39270. }
  39271. selectRowInternal (lastRow, false, false, true);
  39272. }
  39273. void ListBox::flipRowSelection (const int row)
  39274. {
  39275. if (isRowSelected (row))
  39276. deselectRow (row);
  39277. else
  39278. selectRowInternal (row, false, false, true);
  39279. }
  39280. void ListBox::deselectAllRows()
  39281. {
  39282. if (! selected.isEmpty())
  39283. {
  39284. selected.clear();
  39285. lastRowSelected = -1;
  39286. viewport->updateContents();
  39287. if (model != 0)
  39288. model->selectedRowsChanged (lastRowSelected);
  39289. }
  39290. }
  39291. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39292. const ModifierKeys& mods,
  39293. const bool isMouseUpEvent)
  39294. {
  39295. if (multipleSelection && mods.isCommandDown())
  39296. {
  39297. flipRowSelection (row);
  39298. }
  39299. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39300. {
  39301. selectRangeOfRows (lastRowSelected, row);
  39302. }
  39303. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39304. {
  39305. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39306. }
  39307. }
  39308. int ListBox::getNumSelectedRows() const
  39309. {
  39310. return selected.size();
  39311. }
  39312. int ListBox::getSelectedRow (const int index) const
  39313. {
  39314. return (isPositiveAndBelow (index, selected.size()))
  39315. ? selected [index] : -1;
  39316. }
  39317. bool ListBox::isRowSelected (const int row) const
  39318. {
  39319. return selected.contains (row);
  39320. }
  39321. int ListBox::getLastRowSelected() const
  39322. {
  39323. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39324. }
  39325. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39326. {
  39327. if (isPositiveAndBelow (x, getWidth()))
  39328. {
  39329. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39330. if (isPositiveAndBelow (row, totalItems))
  39331. return row;
  39332. }
  39333. return -1;
  39334. }
  39335. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39336. {
  39337. if (isPositiveAndBelow (x, getWidth()))
  39338. {
  39339. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39340. return jlimit (0, totalItems, row);
  39341. }
  39342. return -1;
  39343. }
  39344. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39345. {
  39346. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39347. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39348. }
  39349. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39350. {
  39351. return viewport->getRowNumberOfComponent (rowComponent);
  39352. }
  39353. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39354. const bool relativeToComponentTopLeft) const throw()
  39355. {
  39356. int y = viewport->getY() + rowHeight * rowNumber;
  39357. if (relativeToComponentTopLeft)
  39358. y -= viewport->getViewPositionY();
  39359. return Rectangle<int> (viewport->getX(), y,
  39360. viewport->getViewedComponent()->getWidth(), rowHeight);
  39361. }
  39362. void ListBox::setVerticalPosition (const double proportion)
  39363. {
  39364. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39365. viewport->setViewPosition (viewport->getViewPositionX(),
  39366. jmax (0, roundToInt (proportion * offscreen)));
  39367. }
  39368. double ListBox::getVerticalPosition() const
  39369. {
  39370. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39371. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39372. : 0;
  39373. }
  39374. int ListBox::getVisibleRowWidth() const throw()
  39375. {
  39376. return viewport->getViewWidth();
  39377. }
  39378. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39379. {
  39380. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39381. }
  39382. bool ListBox::keyPressed (const KeyPress& key)
  39383. {
  39384. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39385. const bool multiple = multipleSelection
  39386. && (lastRowSelected >= 0)
  39387. && (key.getModifiers().isShiftDown()
  39388. || key.getModifiers().isCtrlDown()
  39389. || key.getModifiers().isCommandDown());
  39390. if (key.isKeyCode (KeyPress::upKey))
  39391. {
  39392. if (multiple)
  39393. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39394. else
  39395. selectRow (jmax (0, lastRowSelected - 1));
  39396. }
  39397. else if (key.isKeyCode (KeyPress::returnKey)
  39398. && isRowSelected (lastRowSelected))
  39399. {
  39400. if (model != 0)
  39401. model->returnKeyPressed (lastRowSelected);
  39402. }
  39403. else if (key.isKeyCode (KeyPress::pageUpKey))
  39404. {
  39405. if (multiple)
  39406. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39407. else
  39408. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39409. }
  39410. else if (key.isKeyCode (KeyPress::pageDownKey))
  39411. {
  39412. if (multiple)
  39413. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39414. else
  39415. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39416. }
  39417. else if (key.isKeyCode (KeyPress::homeKey))
  39418. {
  39419. if (multiple && key.getModifiers().isShiftDown())
  39420. selectRangeOfRows (lastRowSelected, 0);
  39421. else
  39422. selectRow (0);
  39423. }
  39424. else if (key.isKeyCode (KeyPress::endKey))
  39425. {
  39426. if (multiple && key.getModifiers().isShiftDown())
  39427. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39428. else
  39429. selectRow (totalItems - 1);
  39430. }
  39431. else if (key.isKeyCode (KeyPress::downKey))
  39432. {
  39433. if (multiple)
  39434. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39435. else
  39436. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39437. }
  39438. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39439. && isRowSelected (lastRowSelected))
  39440. {
  39441. if (model != 0)
  39442. model->deleteKeyPressed (lastRowSelected);
  39443. }
  39444. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39445. {
  39446. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39447. }
  39448. else
  39449. {
  39450. return false;
  39451. }
  39452. return true;
  39453. }
  39454. bool ListBox::keyStateChanged (const bool isKeyDown)
  39455. {
  39456. return isKeyDown
  39457. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39458. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39459. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39460. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39461. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39462. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39463. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39464. }
  39465. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39466. {
  39467. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39468. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39469. }
  39470. void ListBox::mouseMove (const MouseEvent& e)
  39471. {
  39472. if (mouseMoveSelects)
  39473. {
  39474. const MouseEvent e2 (e.getEventRelativeTo (this));
  39475. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39476. }
  39477. }
  39478. void ListBox::mouseExit (const MouseEvent& e)
  39479. {
  39480. mouseMove (e);
  39481. }
  39482. void ListBox::mouseUp (const MouseEvent& e)
  39483. {
  39484. if (e.mouseWasClicked() && model != 0)
  39485. model->backgroundClicked();
  39486. }
  39487. void ListBox::setRowHeight (const int newHeight)
  39488. {
  39489. rowHeight = jmax (1, newHeight);
  39490. viewport->setSingleStepSizes (20, rowHeight);
  39491. updateContent();
  39492. }
  39493. int ListBox::getNumRowsOnScreen() const throw()
  39494. {
  39495. return viewport->getMaximumVisibleHeight() / rowHeight;
  39496. }
  39497. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39498. {
  39499. minimumRowWidth = newMinimumWidth;
  39500. updateContent();
  39501. }
  39502. int ListBox::getVisibleContentWidth() const throw()
  39503. {
  39504. return viewport->getMaximumVisibleWidth();
  39505. }
  39506. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39507. {
  39508. return viewport->getVerticalScrollBar();
  39509. }
  39510. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39511. {
  39512. return viewport->getHorizontalScrollBar();
  39513. }
  39514. void ListBox::colourChanged()
  39515. {
  39516. setOpaque (findColour (backgroundColourId).isOpaque());
  39517. viewport->setOpaque (isOpaque());
  39518. repaint();
  39519. }
  39520. void ListBox::setOutlineThickness (const int outlineThickness_)
  39521. {
  39522. outlineThickness = outlineThickness_;
  39523. resized();
  39524. }
  39525. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39526. {
  39527. if (headerComponent != newHeaderComponent)
  39528. {
  39529. headerComponent = newHeaderComponent;
  39530. addAndMakeVisible (newHeaderComponent);
  39531. ListBox::resized();
  39532. }
  39533. }
  39534. void ListBox::repaintRow (const int rowNumber) throw()
  39535. {
  39536. repaint (getRowPosition (rowNumber, true));
  39537. }
  39538. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39539. {
  39540. Rectangle<int> imageArea;
  39541. const int firstRow = getRowContainingPosition (0, 0);
  39542. int i;
  39543. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39544. {
  39545. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39546. if (rowComp != 0 && isRowSelected (firstRow + i))
  39547. {
  39548. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39549. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39550. imageArea = imageArea.getUnion (rowRect);
  39551. }
  39552. }
  39553. imageArea = imageArea.getIntersection (getLocalBounds());
  39554. imageX = imageArea.getX();
  39555. imageY = imageArea.getY();
  39556. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39557. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39558. {
  39559. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39560. if (rowComp != 0 && isRowSelected (firstRow + i))
  39561. {
  39562. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39563. Graphics g (snapshot);
  39564. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39565. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39566. rowComp->paintEntireComponent (g, false);
  39567. }
  39568. }
  39569. return snapshot;
  39570. }
  39571. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39572. {
  39573. DragAndDropContainer* const dragContainer
  39574. = DragAndDropContainer::findParentDragContainerFor (this);
  39575. if (dragContainer != 0)
  39576. {
  39577. int x, y;
  39578. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39579. dragImage.multiplyAllAlphas (0.6f);
  39580. MouseEvent e2 (e.getEventRelativeTo (this));
  39581. const Point<int> p (x - e2.x, y - e2.y);
  39582. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39583. }
  39584. else
  39585. {
  39586. // to be able to do a drag-and-drop operation, the listbox needs to
  39587. // be inside a component which is also a DragAndDropContainer.
  39588. jassertfalse;
  39589. }
  39590. }
  39591. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39592. {
  39593. (void) existingComponentToUpdate;
  39594. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39595. return 0;
  39596. }
  39597. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39598. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39599. void ListBoxModel::backgroundClicked() {}
  39600. void ListBoxModel::selectedRowsChanged (int) {}
  39601. void ListBoxModel::deleteKeyPressed (int) {}
  39602. void ListBoxModel::returnKeyPressed (int) {}
  39603. void ListBoxModel::listWasScrolled() {}
  39604. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39605. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39606. END_JUCE_NAMESPACE
  39607. /*** End of inlined file: juce_ListBox.cpp ***/
  39608. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39609. BEGIN_JUCE_NAMESPACE
  39610. ProgressBar::ProgressBar (double& progress_)
  39611. : progress (progress_),
  39612. displayPercentage (true),
  39613. lastCallbackTime (0)
  39614. {
  39615. currentValue = jlimit (0.0, 1.0, progress);
  39616. }
  39617. ProgressBar::~ProgressBar()
  39618. {
  39619. }
  39620. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39621. {
  39622. displayPercentage = shouldDisplayPercentage;
  39623. repaint();
  39624. }
  39625. void ProgressBar::setTextToDisplay (const String& text)
  39626. {
  39627. displayPercentage = false;
  39628. displayedMessage = text;
  39629. }
  39630. void ProgressBar::lookAndFeelChanged()
  39631. {
  39632. setOpaque (findColour (backgroundColourId).isOpaque());
  39633. }
  39634. void ProgressBar::colourChanged()
  39635. {
  39636. lookAndFeelChanged();
  39637. }
  39638. void ProgressBar::paint (Graphics& g)
  39639. {
  39640. String text;
  39641. if (displayPercentage)
  39642. {
  39643. if (currentValue >= 0 && currentValue <= 1.0)
  39644. text << roundToInt (currentValue * 100.0) << '%';
  39645. }
  39646. else
  39647. {
  39648. text = displayedMessage;
  39649. }
  39650. getLookAndFeel().drawProgressBar (g, *this,
  39651. getWidth(), getHeight(),
  39652. currentValue, text);
  39653. }
  39654. void ProgressBar::visibilityChanged()
  39655. {
  39656. if (isVisible())
  39657. startTimer (30);
  39658. else
  39659. stopTimer();
  39660. }
  39661. void ProgressBar::timerCallback()
  39662. {
  39663. double newProgress = progress;
  39664. const uint32 now = Time::getMillisecondCounter();
  39665. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39666. lastCallbackTime = now;
  39667. if (currentValue != newProgress
  39668. || newProgress < 0 || newProgress >= 1.0
  39669. || currentMessage != displayedMessage)
  39670. {
  39671. if (currentValue < newProgress
  39672. && newProgress >= 0 && newProgress < 1.0
  39673. && currentValue >= 0 && currentValue < 1.0)
  39674. {
  39675. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39676. newProgress);
  39677. }
  39678. currentValue = newProgress;
  39679. currentMessage = displayedMessage;
  39680. repaint();
  39681. }
  39682. }
  39683. END_JUCE_NAMESPACE
  39684. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39685. /*** Start of inlined file: juce_Slider.cpp ***/
  39686. BEGIN_JUCE_NAMESPACE
  39687. class SliderPopupDisplayComponent : public BubbleComponent
  39688. {
  39689. public:
  39690. SliderPopupDisplayComponent (Slider* const owner_)
  39691. : owner (owner_),
  39692. font (15.0f, Font::bold)
  39693. {
  39694. setAlwaysOnTop (true);
  39695. }
  39696. ~SliderPopupDisplayComponent()
  39697. {
  39698. }
  39699. void paintContent (Graphics& g, int w, int h)
  39700. {
  39701. g.setFont (font);
  39702. g.setColour (Colours::black);
  39703. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39704. }
  39705. void getContentSize (int& w, int& h)
  39706. {
  39707. w = font.getStringWidth (text) + 18;
  39708. h = (int) (font.getHeight() * 1.6f);
  39709. }
  39710. void updatePosition (const String& newText)
  39711. {
  39712. if (text != newText)
  39713. {
  39714. text = newText;
  39715. repaint();
  39716. }
  39717. BubbleComponent::setPosition (owner);
  39718. }
  39719. private:
  39720. Slider* owner;
  39721. Font font;
  39722. String text;
  39723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39724. };
  39725. Slider::Slider (const String& name)
  39726. : Component (name),
  39727. lastCurrentValue (0),
  39728. lastValueMin (0),
  39729. lastValueMax (0),
  39730. minimum (0),
  39731. maximum (10),
  39732. interval (0),
  39733. skewFactor (1.0),
  39734. velocityModeSensitivity (1.0),
  39735. velocityModeOffset (0.0),
  39736. velocityModeThreshold (1),
  39737. rotaryStart (float_Pi * 1.2f),
  39738. rotaryEnd (float_Pi * 2.8f),
  39739. numDecimalPlaces (7),
  39740. sliderRegionStart (0),
  39741. sliderRegionSize (1),
  39742. sliderBeingDragged (-1),
  39743. pixelsForFullDragExtent (250),
  39744. style (LinearHorizontal),
  39745. textBoxPos (TextBoxLeft),
  39746. textBoxWidth (80),
  39747. textBoxHeight (20),
  39748. incDecButtonMode (incDecButtonsNotDraggable),
  39749. editableText (true),
  39750. doubleClickToValue (false),
  39751. isVelocityBased (false),
  39752. userKeyOverridesVelocity (true),
  39753. rotaryStop (true),
  39754. incDecButtonsSideBySide (false),
  39755. sendChangeOnlyOnRelease (false),
  39756. popupDisplayEnabled (false),
  39757. menuEnabled (false),
  39758. menuShown (false),
  39759. scrollWheelEnabled (true),
  39760. snapsToMousePos (true),
  39761. popupDisplay (0),
  39762. parentForPopupDisplay (0)
  39763. {
  39764. setWantsKeyboardFocus (false);
  39765. setRepaintsOnMouseActivity (true);
  39766. lookAndFeelChanged();
  39767. updateText();
  39768. currentValue.addListener (this);
  39769. valueMin.addListener (this);
  39770. valueMax.addListener (this);
  39771. }
  39772. Slider::~Slider()
  39773. {
  39774. currentValue.removeListener (this);
  39775. valueMin.removeListener (this);
  39776. valueMax.removeListener (this);
  39777. popupDisplay = 0;
  39778. }
  39779. void Slider::handleAsyncUpdate()
  39780. {
  39781. cancelPendingUpdate();
  39782. Component::BailOutChecker checker (this);
  39783. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39784. }
  39785. void Slider::sendDragStart()
  39786. {
  39787. startedDragging();
  39788. Component::BailOutChecker checker (this);
  39789. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39790. }
  39791. void Slider::sendDragEnd()
  39792. {
  39793. stoppedDragging();
  39794. sliderBeingDragged = -1;
  39795. Component::BailOutChecker checker (this);
  39796. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39797. }
  39798. void Slider::addListener (SliderListener* const listener)
  39799. {
  39800. listeners.add (listener);
  39801. }
  39802. void Slider::removeListener (SliderListener* const listener)
  39803. {
  39804. listeners.remove (listener);
  39805. }
  39806. void Slider::setSliderStyle (const SliderStyle newStyle)
  39807. {
  39808. if (style != newStyle)
  39809. {
  39810. style = newStyle;
  39811. repaint();
  39812. lookAndFeelChanged();
  39813. }
  39814. }
  39815. void Slider::setRotaryParameters (const float startAngleRadians,
  39816. const float endAngleRadians,
  39817. const bool stopAtEnd)
  39818. {
  39819. // make sure the values are sensible..
  39820. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39821. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39822. jassert (rotaryStart < rotaryEnd);
  39823. rotaryStart = startAngleRadians;
  39824. rotaryEnd = endAngleRadians;
  39825. rotaryStop = stopAtEnd;
  39826. }
  39827. void Slider::setVelocityBasedMode (const bool velBased)
  39828. {
  39829. isVelocityBased = velBased;
  39830. }
  39831. void Slider::setVelocityModeParameters (const double sensitivity,
  39832. const int threshold,
  39833. const double offset,
  39834. const bool userCanPressKeyToSwapMode)
  39835. {
  39836. jassert (threshold >= 0);
  39837. jassert (sensitivity > 0);
  39838. jassert (offset >= 0);
  39839. velocityModeSensitivity = sensitivity;
  39840. velocityModeOffset = offset;
  39841. velocityModeThreshold = threshold;
  39842. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39843. }
  39844. void Slider::setSkewFactor (const double factor)
  39845. {
  39846. skewFactor = factor;
  39847. }
  39848. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39849. {
  39850. if (maximum > minimum)
  39851. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39852. / (maximum - minimum));
  39853. }
  39854. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39855. {
  39856. jassert (distanceForFullScaleDrag > 0);
  39857. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39858. }
  39859. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39860. {
  39861. if (incDecButtonMode != mode)
  39862. {
  39863. incDecButtonMode = mode;
  39864. lookAndFeelChanged();
  39865. }
  39866. }
  39867. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39868. const bool isReadOnly,
  39869. const int textEntryBoxWidth,
  39870. const int textEntryBoxHeight)
  39871. {
  39872. if (textBoxPos != newPosition
  39873. || editableText != (! isReadOnly)
  39874. || textBoxWidth != textEntryBoxWidth
  39875. || textBoxHeight != textEntryBoxHeight)
  39876. {
  39877. textBoxPos = newPosition;
  39878. editableText = ! isReadOnly;
  39879. textBoxWidth = textEntryBoxWidth;
  39880. textBoxHeight = textEntryBoxHeight;
  39881. repaint();
  39882. lookAndFeelChanged();
  39883. }
  39884. }
  39885. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39886. {
  39887. editableText = shouldBeEditable;
  39888. if (valueBox != 0)
  39889. valueBox->setEditable (shouldBeEditable && isEnabled());
  39890. }
  39891. void Slider::showTextBox()
  39892. {
  39893. jassert (editableText); // this should probably be avoided in read-only sliders.
  39894. if (valueBox != 0)
  39895. valueBox->showEditor();
  39896. }
  39897. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39898. {
  39899. if (valueBox != 0)
  39900. {
  39901. valueBox->hideEditor (discardCurrentEditorContents);
  39902. if (discardCurrentEditorContents)
  39903. updateText();
  39904. }
  39905. }
  39906. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39907. {
  39908. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39909. }
  39910. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39911. {
  39912. snapsToMousePos = shouldSnapToMouse;
  39913. }
  39914. void Slider::setPopupDisplayEnabled (const bool enabled,
  39915. Component* const parentComponentToUse)
  39916. {
  39917. popupDisplayEnabled = enabled;
  39918. parentForPopupDisplay = parentComponentToUse;
  39919. }
  39920. void Slider::colourChanged()
  39921. {
  39922. lookAndFeelChanged();
  39923. }
  39924. void Slider::lookAndFeelChanged()
  39925. {
  39926. LookAndFeel& lf = getLookAndFeel();
  39927. if (textBoxPos != NoTextBox)
  39928. {
  39929. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39930. : getTextFromValue (currentValue.getValue()));
  39931. valueBox = 0;
  39932. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39933. valueBox->setWantsKeyboardFocus (false);
  39934. valueBox->setText (previousTextBoxContent, false);
  39935. valueBox->setEditable (editableText && isEnabled());
  39936. valueBox->addListener (this);
  39937. if (style == LinearBar)
  39938. valueBox->addMouseListener (this, false);
  39939. valueBox->setTooltip (getTooltip());
  39940. }
  39941. else
  39942. {
  39943. valueBox = 0;
  39944. }
  39945. if (style == IncDecButtons)
  39946. {
  39947. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39948. incButton->addListener (this);
  39949. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39950. decButton->addListener (this);
  39951. if (incDecButtonMode != incDecButtonsNotDraggable)
  39952. {
  39953. incButton->addMouseListener (this, false);
  39954. decButton->addMouseListener (this, false);
  39955. }
  39956. else
  39957. {
  39958. incButton->setRepeatSpeed (300, 100, 20);
  39959. incButton->addMouseListener (decButton, false);
  39960. decButton->setRepeatSpeed (300, 100, 20);
  39961. decButton->addMouseListener (incButton, false);
  39962. }
  39963. incButton->setTooltip (getTooltip());
  39964. decButton->setTooltip (getTooltip());
  39965. }
  39966. else
  39967. {
  39968. incButton = 0;
  39969. decButton = 0;
  39970. }
  39971. setComponentEffect (lf.getSliderEffect());
  39972. resized();
  39973. repaint();
  39974. }
  39975. void Slider::setRange (const double newMin,
  39976. const double newMax,
  39977. const double newInt)
  39978. {
  39979. if (minimum != newMin
  39980. || maximum != newMax
  39981. || interval != newInt)
  39982. {
  39983. minimum = newMin;
  39984. maximum = newMax;
  39985. interval = newInt;
  39986. // figure out the number of DPs needed to display all values at this
  39987. // interval setting.
  39988. numDecimalPlaces = 7;
  39989. if (newInt != 0)
  39990. {
  39991. int v = abs ((int) (newInt * 10000000));
  39992. while ((v % 10) == 0)
  39993. {
  39994. --numDecimalPlaces;
  39995. v /= 10;
  39996. }
  39997. }
  39998. // keep the current values inside the new range..
  39999. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40000. {
  40001. setValue (getValue(), false, false);
  40002. }
  40003. else
  40004. {
  40005. setMinValue (getMinValue(), false, false);
  40006. setMaxValue (getMaxValue(), false, false);
  40007. }
  40008. updateText();
  40009. }
  40010. }
  40011. void Slider::triggerChangeMessage (const bool synchronous)
  40012. {
  40013. if (synchronous)
  40014. handleAsyncUpdate();
  40015. else
  40016. triggerAsyncUpdate();
  40017. valueChanged();
  40018. }
  40019. void Slider::valueChanged (Value& value)
  40020. {
  40021. if (value.refersToSameSourceAs (currentValue))
  40022. {
  40023. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40024. setValue (currentValue.getValue(), false, false);
  40025. }
  40026. else if (value.refersToSameSourceAs (valueMin))
  40027. setMinValue (valueMin.getValue(), false, false, true);
  40028. else if (value.refersToSameSourceAs (valueMax))
  40029. setMaxValue (valueMax.getValue(), false, false, true);
  40030. }
  40031. double Slider::getValue() const
  40032. {
  40033. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40034. // methods to get the two values.
  40035. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40036. return currentValue.getValue();
  40037. }
  40038. void Slider::setValue (double newValue,
  40039. const bool sendUpdateMessage,
  40040. const bool sendMessageSynchronously)
  40041. {
  40042. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40043. // methods to set the two values.
  40044. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40045. newValue = constrainedValue (newValue);
  40046. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40047. {
  40048. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40049. newValue = jlimit ((double) valueMin.getValue(),
  40050. (double) valueMax.getValue(),
  40051. newValue);
  40052. }
  40053. if (newValue != lastCurrentValue)
  40054. {
  40055. if (valueBox != 0)
  40056. valueBox->hideEditor (true);
  40057. lastCurrentValue = newValue;
  40058. currentValue = newValue;
  40059. updateText();
  40060. repaint();
  40061. if (popupDisplay != 0)
  40062. {
  40063. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40064. ->updatePosition (getTextFromValue (newValue));
  40065. popupDisplay->repaint();
  40066. }
  40067. if (sendUpdateMessage)
  40068. triggerChangeMessage (sendMessageSynchronously);
  40069. }
  40070. }
  40071. double Slider::getMinValue() const
  40072. {
  40073. // The minimum value only applies to sliders that are in two- or three-value mode.
  40074. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40075. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40076. return valueMin.getValue();
  40077. }
  40078. double Slider::getMaxValue() const
  40079. {
  40080. // The maximum value only applies to sliders that are in two- or three-value mode.
  40081. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40082. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40083. return valueMax.getValue();
  40084. }
  40085. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40086. {
  40087. // The minimum value only applies to sliders that are in two- or three-value mode.
  40088. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40089. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40090. newValue = constrainedValue (newValue);
  40091. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40092. {
  40093. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40094. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40095. newValue = jmin ((double) valueMax.getValue(), newValue);
  40096. }
  40097. else
  40098. {
  40099. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40100. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40101. newValue = jmin (lastCurrentValue, newValue);
  40102. }
  40103. if (lastValueMin != newValue)
  40104. {
  40105. lastValueMin = newValue;
  40106. valueMin = newValue;
  40107. repaint();
  40108. if (popupDisplay != 0)
  40109. {
  40110. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40111. ->updatePosition (getTextFromValue (newValue));
  40112. popupDisplay->repaint();
  40113. }
  40114. if (sendUpdateMessage)
  40115. triggerChangeMessage (sendMessageSynchronously);
  40116. }
  40117. }
  40118. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40119. {
  40120. // The maximum value only applies to sliders that are in two- or three-value mode.
  40121. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40122. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40123. newValue = constrainedValue (newValue);
  40124. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40125. {
  40126. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40127. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40128. newValue = jmax ((double) valueMin.getValue(), newValue);
  40129. }
  40130. else
  40131. {
  40132. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40133. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40134. newValue = jmax (lastCurrentValue, newValue);
  40135. }
  40136. if (lastValueMax != newValue)
  40137. {
  40138. lastValueMax = newValue;
  40139. valueMax = newValue;
  40140. repaint();
  40141. if (popupDisplay != 0)
  40142. {
  40143. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40144. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40145. popupDisplay->repaint();
  40146. }
  40147. if (sendUpdateMessage)
  40148. triggerChangeMessage (sendMessageSynchronously);
  40149. }
  40150. }
  40151. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40152. const double valueToSetOnDoubleClick)
  40153. {
  40154. doubleClickToValue = isDoubleClickEnabled;
  40155. doubleClickReturnValue = valueToSetOnDoubleClick;
  40156. }
  40157. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40158. {
  40159. isEnabled_ = doubleClickToValue;
  40160. return doubleClickReturnValue;
  40161. }
  40162. void Slider::updateText()
  40163. {
  40164. if (valueBox != 0)
  40165. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40166. }
  40167. void Slider::setTextValueSuffix (const String& suffix)
  40168. {
  40169. if (textSuffix != suffix)
  40170. {
  40171. textSuffix = suffix;
  40172. updateText();
  40173. }
  40174. }
  40175. const String Slider::getTextValueSuffix() const
  40176. {
  40177. return textSuffix;
  40178. }
  40179. const String Slider::getTextFromValue (double v)
  40180. {
  40181. if (getNumDecimalPlacesToDisplay() > 0)
  40182. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40183. else
  40184. return String (roundToInt (v)) + getTextValueSuffix();
  40185. }
  40186. double Slider::getValueFromText (const String& text)
  40187. {
  40188. String t (text.trimStart());
  40189. if (t.endsWith (textSuffix))
  40190. t = t.substring (0, t.length() - textSuffix.length());
  40191. while (t.startsWithChar ('+'))
  40192. t = t.substring (1).trimStart();
  40193. return t.initialSectionContainingOnly ("0123456789.,-")
  40194. .getDoubleValue();
  40195. }
  40196. double Slider::proportionOfLengthToValue (double proportion)
  40197. {
  40198. if (skewFactor != 1.0 && proportion > 0.0)
  40199. proportion = exp (log (proportion) / skewFactor);
  40200. return minimum + (maximum - minimum) * proportion;
  40201. }
  40202. double Slider::valueToProportionOfLength (double value)
  40203. {
  40204. const double n = (value - minimum) / (maximum - minimum);
  40205. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40206. }
  40207. double Slider::snapValue (double attemptedValue, const bool)
  40208. {
  40209. return attemptedValue;
  40210. }
  40211. void Slider::startedDragging()
  40212. {
  40213. }
  40214. void Slider::stoppedDragging()
  40215. {
  40216. }
  40217. void Slider::valueChanged()
  40218. {
  40219. }
  40220. void Slider::enablementChanged()
  40221. {
  40222. repaint();
  40223. }
  40224. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40225. {
  40226. menuEnabled = menuEnabled_;
  40227. }
  40228. void Slider::setScrollWheelEnabled (const bool enabled)
  40229. {
  40230. scrollWheelEnabled = enabled;
  40231. }
  40232. void Slider::labelTextChanged (Label* label)
  40233. {
  40234. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40235. if (newValue != (double) currentValue.getValue())
  40236. {
  40237. sendDragStart();
  40238. setValue (newValue, true, true);
  40239. sendDragEnd();
  40240. }
  40241. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40242. }
  40243. void Slider::buttonClicked (Button* button)
  40244. {
  40245. if (style == IncDecButtons)
  40246. {
  40247. sendDragStart();
  40248. if (button == incButton)
  40249. setValue (snapValue (getValue() + interval, false), true, true);
  40250. else if (button == decButton)
  40251. setValue (snapValue (getValue() - interval, false), true, true);
  40252. sendDragEnd();
  40253. }
  40254. }
  40255. double Slider::constrainedValue (double value) const
  40256. {
  40257. if (interval > 0)
  40258. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40259. if (value <= minimum || maximum <= minimum)
  40260. value = minimum;
  40261. else if (value >= maximum)
  40262. value = maximum;
  40263. return value;
  40264. }
  40265. float Slider::getLinearSliderPos (const double value)
  40266. {
  40267. double sliderPosProportional;
  40268. if (maximum > minimum)
  40269. {
  40270. if (value < minimum)
  40271. {
  40272. sliderPosProportional = 0.0;
  40273. }
  40274. else if (value > maximum)
  40275. {
  40276. sliderPosProportional = 1.0;
  40277. }
  40278. else
  40279. {
  40280. sliderPosProportional = valueToProportionOfLength (value);
  40281. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40282. }
  40283. }
  40284. else
  40285. {
  40286. sliderPosProportional = 0.5;
  40287. }
  40288. if (isVertical() || style == IncDecButtons)
  40289. sliderPosProportional = 1.0 - sliderPosProportional;
  40290. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40291. }
  40292. bool Slider::isHorizontal() const
  40293. {
  40294. return style == LinearHorizontal
  40295. || style == LinearBar
  40296. || style == TwoValueHorizontal
  40297. || style == ThreeValueHorizontal;
  40298. }
  40299. bool Slider::isVertical() const
  40300. {
  40301. return style == LinearVertical
  40302. || style == TwoValueVertical
  40303. || style == ThreeValueVertical;
  40304. }
  40305. bool Slider::incDecDragDirectionIsHorizontal() const
  40306. {
  40307. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40308. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40309. }
  40310. float Slider::getPositionOfValue (const double value)
  40311. {
  40312. if (isHorizontal() || isVertical())
  40313. {
  40314. return getLinearSliderPos (value);
  40315. }
  40316. else
  40317. {
  40318. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40319. return 0.0f;
  40320. }
  40321. }
  40322. void Slider::paint (Graphics& g)
  40323. {
  40324. if (style != IncDecButtons)
  40325. {
  40326. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40327. {
  40328. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40329. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40330. getLookAndFeel().drawRotarySlider (g,
  40331. sliderRect.getX(),
  40332. sliderRect.getY(),
  40333. sliderRect.getWidth(),
  40334. sliderRect.getHeight(),
  40335. sliderPos,
  40336. rotaryStart, rotaryEnd,
  40337. *this);
  40338. }
  40339. else
  40340. {
  40341. getLookAndFeel().drawLinearSlider (g,
  40342. sliderRect.getX(),
  40343. sliderRect.getY(),
  40344. sliderRect.getWidth(),
  40345. sliderRect.getHeight(),
  40346. getLinearSliderPos (lastCurrentValue),
  40347. getLinearSliderPos (lastValueMin),
  40348. getLinearSliderPos (lastValueMax),
  40349. style,
  40350. *this);
  40351. }
  40352. if (style == LinearBar && valueBox == 0)
  40353. {
  40354. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40355. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40356. }
  40357. }
  40358. }
  40359. void Slider::resized()
  40360. {
  40361. int minXSpace = 0;
  40362. int minYSpace = 0;
  40363. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40364. minXSpace = 30;
  40365. else
  40366. minYSpace = 15;
  40367. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40368. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40369. if (style == LinearBar)
  40370. {
  40371. if (valueBox != 0)
  40372. valueBox->setBounds (getLocalBounds());
  40373. }
  40374. else
  40375. {
  40376. if (textBoxPos == NoTextBox)
  40377. {
  40378. sliderRect = getLocalBounds();
  40379. }
  40380. else if (textBoxPos == TextBoxLeft)
  40381. {
  40382. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40383. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40384. }
  40385. else if (textBoxPos == TextBoxRight)
  40386. {
  40387. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40388. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40389. }
  40390. else if (textBoxPos == TextBoxAbove)
  40391. {
  40392. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40393. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40394. }
  40395. else if (textBoxPos == TextBoxBelow)
  40396. {
  40397. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40398. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40399. }
  40400. }
  40401. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40402. if (style == LinearBar)
  40403. {
  40404. const int barIndent = 1;
  40405. sliderRegionStart = barIndent;
  40406. sliderRegionSize = getWidth() - barIndent * 2;
  40407. sliderRect.setBounds (sliderRegionStart, barIndent,
  40408. sliderRegionSize, getHeight() - barIndent * 2);
  40409. }
  40410. else if (isHorizontal())
  40411. {
  40412. sliderRegionStart = sliderRect.getX() + indent;
  40413. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40414. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40415. sliderRegionSize, sliderRect.getHeight());
  40416. }
  40417. else if (isVertical())
  40418. {
  40419. sliderRegionStart = sliderRect.getY() + indent;
  40420. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40421. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40422. sliderRect.getWidth(), sliderRegionSize);
  40423. }
  40424. else
  40425. {
  40426. sliderRegionStart = 0;
  40427. sliderRegionSize = 100;
  40428. }
  40429. if (style == IncDecButtons)
  40430. {
  40431. Rectangle<int> buttonRect (sliderRect);
  40432. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40433. buttonRect.expand (-2, 0);
  40434. else
  40435. buttonRect.expand (0, -2);
  40436. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40437. if (incDecButtonsSideBySide)
  40438. {
  40439. decButton->setBounds (buttonRect.getX(),
  40440. buttonRect.getY(),
  40441. buttonRect.getWidth() / 2,
  40442. buttonRect.getHeight());
  40443. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40444. incButton->setBounds (buttonRect.getCentreX(),
  40445. buttonRect.getY(),
  40446. buttonRect.getWidth() / 2,
  40447. buttonRect.getHeight());
  40448. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40449. }
  40450. else
  40451. {
  40452. incButton->setBounds (buttonRect.getX(),
  40453. buttonRect.getY(),
  40454. buttonRect.getWidth(),
  40455. buttonRect.getHeight() / 2);
  40456. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40457. decButton->setBounds (buttonRect.getX(),
  40458. buttonRect.getCentreY(),
  40459. buttonRect.getWidth(),
  40460. buttonRect.getHeight() / 2);
  40461. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40462. }
  40463. }
  40464. }
  40465. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40466. {
  40467. repaint();
  40468. }
  40469. void Slider::mouseDown (const MouseEvent& e)
  40470. {
  40471. mouseWasHidden = false;
  40472. incDecDragged = false;
  40473. mouseXWhenLastDragged = e.x;
  40474. mouseYWhenLastDragged = e.y;
  40475. mouseDragStartX = e.getMouseDownX();
  40476. mouseDragStartY = e.getMouseDownY();
  40477. if (isEnabled())
  40478. {
  40479. if (e.mods.isPopupMenu() && menuEnabled)
  40480. {
  40481. menuShown = true;
  40482. PopupMenu m;
  40483. m.setLookAndFeel (&getLookAndFeel());
  40484. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40485. m.addSeparator();
  40486. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40487. {
  40488. PopupMenu rotaryMenu;
  40489. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40490. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40491. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40492. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40493. }
  40494. const int r = m.show();
  40495. if (r == 1)
  40496. {
  40497. setVelocityBasedMode (! isVelocityBased);
  40498. }
  40499. else if (r == 2)
  40500. {
  40501. setSliderStyle (Rotary);
  40502. }
  40503. else if (r == 3)
  40504. {
  40505. setSliderStyle (RotaryHorizontalDrag);
  40506. }
  40507. else if (r == 4)
  40508. {
  40509. setSliderStyle (RotaryVerticalDrag);
  40510. }
  40511. }
  40512. else if (maximum > minimum)
  40513. {
  40514. menuShown = false;
  40515. if (valueBox != 0)
  40516. valueBox->hideEditor (true);
  40517. sliderBeingDragged = 0;
  40518. if (style == TwoValueHorizontal
  40519. || style == TwoValueVertical
  40520. || style == ThreeValueHorizontal
  40521. || style == ThreeValueVertical)
  40522. {
  40523. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40524. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40525. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40526. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40527. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40528. {
  40529. if (maxPosDistance <= minPosDistance)
  40530. sliderBeingDragged = 2;
  40531. else
  40532. sliderBeingDragged = 1;
  40533. }
  40534. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40535. {
  40536. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40537. sliderBeingDragged = 1;
  40538. else if (normalPosDistance >= maxPosDistance)
  40539. sliderBeingDragged = 2;
  40540. }
  40541. }
  40542. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40543. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40544. * valueToProportionOfLength (currentValue.getValue());
  40545. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40546. : ((sliderBeingDragged == 1) ? valueMin
  40547. : currentValue)).getValue();
  40548. valueOnMouseDown = valueWhenLastDragged;
  40549. if (popupDisplayEnabled)
  40550. {
  40551. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40552. popupDisplay = popup;
  40553. if (parentForPopupDisplay != 0)
  40554. {
  40555. parentForPopupDisplay->addChildComponent (popup);
  40556. }
  40557. else
  40558. {
  40559. popup->addToDesktop (0);
  40560. }
  40561. popup->setVisible (true);
  40562. }
  40563. sendDragStart();
  40564. mouseDrag (e);
  40565. }
  40566. }
  40567. }
  40568. void Slider::mouseUp (const MouseEvent&)
  40569. {
  40570. if (isEnabled()
  40571. && (! menuShown)
  40572. && (maximum > minimum)
  40573. && (style != IncDecButtons || incDecDragged))
  40574. {
  40575. restoreMouseIfHidden();
  40576. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40577. triggerChangeMessage (false);
  40578. sendDragEnd();
  40579. popupDisplay = 0;
  40580. if (style == IncDecButtons)
  40581. {
  40582. incButton->setState (Button::buttonNormal);
  40583. decButton->setState (Button::buttonNormal);
  40584. }
  40585. }
  40586. }
  40587. void Slider::restoreMouseIfHidden()
  40588. {
  40589. if (mouseWasHidden)
  40590. {
  40591. mouseWasHidden = false;
  40592. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40593. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40594. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40595. : ((sliderBeingDragged == 1) ? getMinValue()
  40596. : (double) currentValue.getValue());
  40597. Point<int> mousePos;
  40598. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40599. {
  40600. mousePos = Desktop::getLastMouseDownPosition();
  40601. if (style == RotaryHorizontalDrag)
  40602. {
  40603. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40604. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40605. }
  40606. else
  40607. {
  40608. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40609. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40610. }
  40611. }
  40612. else
  40613. {
  40614. const int pixelPos = (int) getLinearSliderPos (pos);
  40615. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40616. isVertical() ? pixelPos : (getHeight() / 2)));
  40617. }
  40618. Desktop::setMousePosition (mousePos);
  40619. }
  40620. }
  40621. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40622. {
  40623. if (isEnabled()
  40624. && style != IncDecButtons
  40625. && style != Rotary
  40626. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40627. {
  40628. restoreMouseIfHidden();
  40629. }
  40630. }
  40631. namespace SliderHelpers
  40632. {
  40633. double smallestAngleBetween (double a1, double a2) throw()
  40634. {
  40635. return jmin (std::abs (a1 - a2),
  40636. std::abs (a1 + double_Pi * 2.0 - a2),
  40637. std::abs (a2 + double_Pi * 2.0 - a1));
  40638. }
  40639. }
  40640. void Slider::mouseDrag (const MouseEvent& e)
  40641. {
  40642. if (isEnabled()
  40643. && (! menuShown)
  40644. && (maximum > minimum))
  40645. {
  40646. if (style == Rotary)
  40647. {
  40648. int dx = e.x - sliderRect.getCentreX();
  40649. int dy = e.y - sliderRect.getCentreY();
  40650. if (dx * dx + dy * dy > 25)
  40651. {
  40652. double angle = std::atan2 ((double) dx, (double) -dy);
  40653. while (angle < 0.0)
  40654. angle += double_Pi * 2.0;
  40655. if (rotaryStop && ! e.mouseWasClicked())
  40656. {
  40657. if (std::abs (angle - lastAngle) > double_Pi)
  40658. {
  40659. if (angle >= lastAngle)
  40660. angle -= double_Pi * 2.0;
  40661. else
  40662. angle += double_Pi * 2.0;
  40663. }
  40664. if (angle >= lastAngle)
  40665. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40666. else
  40667. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40668. }
  40669. else
  40670. {
  40671. while (angle < rotaryStart)
  40672. angle += double_Pi * 2.0;
  40673. if (angle > rotaryEnd)
  40674. {
  40675. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40676. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40677. angle = rotaryStart;
  40678. else
  40679. angle = rotaryEnd;
  40680. }
  40681. }
  40682. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40683. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40684. lastAngle = angle;
  40685. }
  40686. }
  40687. else
  40688. {
  40689. if (style == LinearBar && e.mouseWasClicked()
  40690. && valueBox != 0 && valueBox->isEditable())
  40691. return;
  40692. if (style == IncDecButtons && ! incDecDragged)
  40693. {
  40694. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40695. return;
  40696. incDecDragged = true;
  40697. mouseDragStartX = e.x;
  40698. mouseDragStartY = e.y;
  40699. }
  40700. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40701. : false))
  40702. || ((maximum - minimum) / sliderRegionSize < interval))
  40703. {
  40704. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40705. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40706. if (style == RotaryHorizontalDrag
  40707. || style == RotaryVerticalDrag
  40708. || style == IncDecButtons
  40709. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40710. && ! snapsToMousePos))
  40711. {
  40712. const int mouseDiff = (style == RotaryHorizontalDrag
  40713. || style == LinearHorizontal
  40714. || style == LinearBar
  40715. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40716. ? e.x - mouseDragStartX
  40717. : mouseDragStartY - e.y;
  40718. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40719. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40720. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40721. if (style == IncDecButtons)
  40722. {
  40723. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40724. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40725. }
  40726. }
  40727. else
  40728. {
  40729. if (isVertical())
  40730. scaledMousePos = 1.0 - scaledMousePos;
  40731. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40732. }
  40733. }
  40734. else
  40735. {
  40736. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40737. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40738. ? e.x - mouseXWhenLastDragged
  40739. : e.y - mouseYWhenLastDragged;
  40740. const double maxSpeed = jmax (200, sliderRegionSize);
  40741. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40742. if (speed != 0)
  40743. {
  40744. speed = 0.2 * velocityModeSensitivity
  40745. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40746. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40747. / maxSpeed))));
  40748. if (mouseDiff < 0)
  40749. speed = -speed;
  40750. if (isVertical() || style == RotaryVerticalDrag
  40751. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40752. speed = -speed;
  40753. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40754. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40755. e.source.enableUnboundedMouseMovement (true, false);
  40756. mouseWasHidden = true;
  40757. }
  40758. }
  40759. }
  40760. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40761. if (sliderBeingDragged == 0)
  40762. {
  40763. setValue (snapValue (valueWhenLastDragged, true),
  40764. ! sendChangeOnlyOnRelease, true);
  40765. }
  40766. else if (sliderBeingDragged == 1)
  40767. {
  40768. setMinValue (snapValue (valueWhenLastDragged, true),
  40769. ! sendChangeOnlyOnRelease, false, true);
  40770. if (e.mods.isShiftDown())
  40771. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40772. else
  40773. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40774. }
  40775. else
  40776. {
  40777. jassert (sliderBeingDragged == 2);
  40778. setMaxValue (snapValue (valueWhenLastDragged, true),
  40779. ! sendChangeOnlyOnRelease, false, true);
  40780. if (e.mods.isShiftDown())
  40781. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40782. else
  40783. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40784. }
  40785. mouseXWhenLastDragged = e.x;
  40786. mouseYWhenLastDragged = e.y;
  40787. }
  40788. }
  40789. void Slider::mouseDoubleClick (const MouseEvent&)
  40790. {
  40791. if (doubleClickToValue
  40792. && isEnabled()
  40793. && style != IncDecButtons
  40794. && minimum <= doubleClickReturnValue
  40795. && maximum >= doubleClickReturnValue)
  40796. {
  40797. sendDragStart();
  40798. setValue (doubleClickReturnValue, true, true);
  40799. sendDragEnd();
  40800. }
  40801. }
  40802. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40803. {
  40804. if (scrollWheelEnabled && isEnabled()
  40805. && style != TwoValueHorizontal
  40806. && style != TwoValueVertical)
  40807. {
  40808. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40809. {
  40810. if (valueBox != 0)
  40811. valueBox->hideEditor (false);
  40812. const double value = (double) currentValue.getValue();
  40813. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40814. const double currentPos = valueToProportionOfLength (value);
  40815. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40816. double delta = (newValue != value)
  40817. ? jmax (std::abs (newValue - value), interval) : 0;
  40818. if (value > newValue)
  40819. delta = -delta;
  40820. sendDragStart();
  40821. setValue (snapValue (value + delta, false), true, true);
  40822. sendDragEnd();
  40823. }
  40824. }
  40825. else
  40826. {
  40827. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40828. }
  40829. }
  40830. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40831. {
  40832. }
  40833. void SliderListener::sliderDragEnded (Slider*)
  40834. {
  40835. }
  40836. END_JUCE_NAMESPACE
  40837. /*** End of inlined file: juce_Slider.cpp ***/
  40838. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40839. BEGIN_JUCE_NAMESPACE
  40840. class DragOverlayComp : public Component
  40841. {
  40842. public:
  40843. DragOverlayComp (const Image& image_)
  40844. : image (image_)
  40845. {
  40846. image.duplicateIfShared();
  40847. image.multiplyAllAlphas (0.8f);
  40848. setAlwaysOnTop (true);
  40849. }
  40850. void paint (Graphics& g)
  40851. {
  40852. g.drawImageAt (image, 0, 0);
  40853. }
  40854. private:
  40855. Image image;
  40856. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40857. };
  40858. TableHeaderComponent::TableHeaderComponent()
  40859. : columnsChanged (false),
  40860. columnsResized (false),
  40861. sortChanged (false),
  40862. menuActive (true),
  40863. stretchToFit (false),
  40864. columnIdBeingResized (0),
  40865. columnIdBeingDragged (0),
  40866. columnIdUnderMouse (0),
  40867. lastDeliberateWidth (0)
  40868. {
  40869. }
  40870. TableHeaderComponent::~TableHeaderComponent()
  40871. {
  40872. dragOverlayComp = 0;
  40873. }
  40874. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40875. {
  40876. menuActive = hasMenu;
  40877. }
  40878. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40879. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40880. {
  40881. if (onlyCountVisibleColumns)
  40882. {
  40883. int num = 0;
  40884. for (int i = columns.size(); --i >= 0;)
  40885. if (columns.getUnchecked(i)->isVisible())
  40886. ++num;
  40887. return num;
  40888. }
  40889. else
  40890. {
  40891. return columns.size();
  40892. }
  40893. }
  40894. const String TableHeaderComponent::getColumnName (const int columnId) const
  40895. {
  40896. const ColumnInfo* const ci = getInfoForId (columnId);
  40897. return ci != 0 ? ci->name : String::empty;
  40898. }
  40899. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40900. {
  40901. ColumnInfo* const ci = getInfoForId (columnId);
  40902. if (ci != 0 && ci->name != newName)
  40903. {
  40904. ci->name = newName;
  40905. sendColumnsChanged();
  40906. }
  40907. }
  40908. void TableHeaderComponent::addColumn (const String& columnName,
  40909. const int columnId,
  40910. const int width,
  40911. const int minimumWidth,
  40912. const int maximumWidth,
  40913. const int propertyFlags,
  40914. const int insertIndex)
  40915. {
  40916. // can't have a duplicate or null ID!
  40917. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40918. jassert (width > 0);
  40919. ColumnInfo* const ci = new ColumnInfo();
  40920. ci->name = columnName;
  40921. ci->id = columnId;
  40922. ci->width = width;
  40923. ci->lastDeliberateWidth = width;
  40924. ci->minimumWidth = minimumWidth;
  40925. ci->maximumWidth = maximumWidth;
  40926. if (ci->maximumWidth < 0)
  40927. ci->maximumWidth = std::numeric_limits<int>::max();
  40928. jassert (ci->maximumWidth >= ci->minimumWidth);
  40929. ci->propertyFlags = propertyFlags;
  40930. columns.insert (insertIndex, ci);
  40931. sendColumnsChanged();
  40932. }
  40933. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40934. {
  40935. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40936. if (index >= 0)
  40937. {
  40938. columns.remove (index);
  40939. sortChanged = true;
  40940. sendColumnsChanged();
  40941. }
  40942. }
  40943. void TableHeaderComponent::removeAllColumns()
  40944. {
  40945. if (columns.size() > 0)
  40946. {
  40947. columns.clear();
  40948. sendColumnsChanged();
  40949. }
  40950. }
  40951. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40952. {
  40953. const int currentIndex = getIndexOfColumnId (columnId, false);
  40954. newIndex = visibleIndexToTotalIndex (newIndex);
  40955. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40956. {
  40957. columns.move (currentIndex, newIndex);
  40958. sendColumnsChanged();
  40959. }
  40960. }
  40961. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40962. {
  40963. const ColumnInfo* const ci = getInfoForId (columnId);
  40964. return ci != 0 ? ci->width : 0;
  40965. }
  40966. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40967. {
  40968. ColumnInfo* const ci = getInfoForId (columnId);
  40969. if (ci != 0 && ci->width != newWidth)
  40970. {
  40971. const int numColumns = getNumColumns (true);
  40972. ci->lastDeliberateWidth = ci->width
  40973. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40974. if (stretchToFit)
  40975. {
  40976. const int index = getIndexOfColumnId (columnId, true) + 1;
  40977. if (isPositiveAndBelow (index, numColumns))
  40978. {
  40979. const int x = getColumnPosition (index).getX();
  40980. if (lastDeliberateWidth == 0)
  40981. lastDeliberateWidth = getTotalWidth();
  40982. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40983. }
  40984. }
  40985. repaint();
  40986. columnsResized = true;
  40987. triggerAsyncUpdate();
  40988. }
  40989. }
  40990. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40991. {
  40992. int n = 0;
  40993. for (int i = 0; i < columns.size(); ++i)
  40994. {
  40995. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40996. {
  40997. if (columns.getUnchecked(i)->id == columnId)
  40998. return n;
  40999. ++n;
  41000. }
  41001. }
  41002. return -1;
  41003. }
  41004. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41005. {
  41006. if (onlyCountVisibleColumns)
  41007. index = visibleIndexToTotalIndex (index);
  41008. const ColumnInfo* const ci = columns [index];
  41009. return (ci != 0) ? ci->id : 0;
  41010. }
  41011. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41012. {
  41013. int x = 0, width = 0, n = 0;
  41014. for (int i = 0; i < columns.size(); ++i)
  41015. {
  41016. x += width;
  41017. if (columns.getUnchecked(i)->isVisible())
  41018. {
  41019. width = columns.getUnchecked(i)->width;
  41020. if (n++ == index)
  41021. break;
  41022. }
  41023. else
  41024. {
  41025. width = 0;
  41026. }
  41027. }
  41028. return Rectangle<int> (x, 0, width, getHeight());
  41029. }
  41030. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41031. {
  41032. if (xToFind >= 0)
  41033. {
  41034. int x = 0;
  41035. for (int i = 0; i < columns.size(); ++i)
  41036. {
  41037. const ColumnInfo* const ci = columns.getUnchecked(i);
  41038. if (ci->isVisible())
  41039. {
  41040. x += ci->width;
  41041. if (xToFind < x)
  41042. return ci->id;
  41043. }
  41044. }
  41045. }
  41046. return 0;
  41047. }
  41048. int TableHeaderComponent::getTotalWidth() const
  41049. {
  41050. int w = 0;
  41051. for (int i = columns.size(); --i >= 0;)
  41052. if (columns.getUnchecked(i)->isVisible())
  41053. w += columns.getUnchecked(i)->width;
  41054. return w;
  41055. }
  41056. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41057. {
  41058. stretchToFit = shouldStretchToFit;
  41059. lastDeliberateWidth = getTotalWidth();
  41060. resized();
  41061. }
  41062. bool TableHeaderComponent::isStretchToFitActive() const
  41063. {
  41064. return stretchToFit;
  41065. }
  41066. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41067. {
  41068. if (stretchToFit && getWidth() > 0
  41069. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41070. {
  41071. lastDeliberateWidth = targetTotalWidth;
  41072. resizeColumnsToFit (0, targetTotalWidth);
  41073. }
  41074. }
  41075. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41076. {
  41077. targetTotalWidth = jmax (targetTotalWidth, 0);
  41078. StretchableObjectResizer sor;
  41079. int i;
  41080. for (i = firstColumnIndex; i < columns.size(); ++i)
  41081. {
  41082. ColumnInfo* const ci = columns.getUnchecked(i);
  41083. if (ci->isVisible())
  41084. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41085. }
  41086. sor.resizeToFit (targetTotalWidth);
  41087. int visIndex = 0;
  41088. for (i = firstColumnIndex; i < columns.size(); ++i)
  41089. {
  41090. ColumnInfo* const ci = columns.getUnchecked(i);
  41091. if (ci->isVisible())
  41092. {
  41093. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41094. (int) std::floor (sor.getItemSize (visIndex++)));
  41095. if (newWidth != ci->width)
  41096. {
  41097. ci->width = newWidth;
  41098. repaint();
  41099. columnsResized = true;
  41100. triggerAsyncUpdate();
  41101. }
  41102. }
  41103. }
  41104. }
  41105. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41106. {
  41107. ColumnInfo* const ci = getInfoForId (columnId);
  41108. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41109. {
  41110. if (shouldBeVisible)
  41111. ci->propertyFlags |= visible;
  41112. else
  41113. ci->propertyFlags &= ~visible;
  41114. sendColumnsChanged();
  41115. resized();
  41116. }
  41117. }
  41118. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41119. {
  41120. const ColumnInfo* const ci = getInfoForId (columnId);
  41121. return ci != 0 && ci->isVisible();
  41122. }
  41123. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41124. {
  41125. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41126. {
  41127. for (int i = columns.size(); --i >= 0;)
  41128. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41129. ColumnInfo* const ci = getInfoForId (columnId);
  41130. if (ci != 0)
  41131. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41132. reSortTable();
  41133. }
  41134. }
  41135. int TableHeaderComponent::getSortColumnId() const
  41136. {
  41137. for (int i = columns.size(); --i >= 0;)
  41138. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41139. return columns.getUnchecked(i)->id;
  41140. return 0;
  41141. }
  41142. bool TableHeaderComponent::isSortedForwards() const
  41143. {
  41144. for (int i = columns.size(); --i >= 0;)
  41145. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41146. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41147. return true;
  41148. }
  41149. void TableHeaderComponent::reSortTable()
  41150. {
  41151. sortChanged = true;
  41152. repaint();
  41153. triggerAsyncUpdate();
  41154. }
  41155. const String TableHeaderComponent::toString() const
  41156. {
  41157. String s;
  41158. XmlElement doc ("TABLELAYOUT");
  41159. doc.setAttribute ("sortedCol", getSortColumnId());
  41160. doc.setAttribute ("sortForwards", isSortedForwards());
  41161. for (int i = 0; i < columns.size(); ++i)
  41162. {
  41163. const ColumnInfo* const ci = columns.getUnchecked (i);
  41164. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41165. e->setAttribute ("id", ci->id);
  41166. e->setAttribute ("visible", ci->isVisible());
  41167. e->setAttribute ("width", ci->width);
  41168. }
  41169. return doc.createDocument (String::empty, true, false);
  41170. }
  41171. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41172. {
  41173. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41174. int index = 0;
  41175. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41176. {
  41177. forEachXmlChildElement (*storedXml, col)
  41178. {
  41179. const int tabId = col->getIntAttribute ("id");
  41180. ColumnInfo* const ci = getInfoForId (tabId);
  41181. if (ci != 0)
  41182. {
  41183. columns.move (columns.indexOf (ci), index);
  41184. ci->width = col->getIntAttribute ("width");
  41185. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41186. }
  41187. ++index;
  41188. }
  41189. columnsResized = true;
  41190. sendColumnsChanged();
  41191. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41192. storedXml->getBoolAttribute ("sortForwards", true));
  41193. }
  41194. }
  41195. void TableHeaderComponent::addListener (Listener* const newListener)
  41196. {
  41197. listeners.addIfNotAlreadyThere (newListener);
  41198. }
  41199. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41200. {
  41201. listeners.removeValue (listenerToRemove);
  41202. }
  41203. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41204. {
  41205. const ColumnInfo* const ci = getInfoForId (columnId);
  41206. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41207. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41208. }
  41209. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41210. {
  41211. for (int i = 0; i < columns.size(); ++i)
  41212. {
  41213. const ColumnInfo* const ci = columns.getUnchecked(i);
  41214. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41215. menu.addItem (ci->id, ci->name,
  41216. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41217. isColumnVisible (ci->id));
  41218. }
  41219. }
  41220. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41221. {
  41222. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41223. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41224. }
  41225. void TableHeaderComponent::paint (Graphics& g)
  41226. {
  41227. LookAndFeel& lf = getLookAndFeel();
  41228. lf.drawTableHeaderBackground (g, *this);
  41229. const Rectangle<int> clip (g.getClipBounds());
  41230. int x = 0;
  41231. for (int i = 0; i < columns.size(); ++i)
  41232. {
  41233. const ColumnInfo* const ci = columns.getUnchecked(i);
  41234. if (ci->isVisible())
  41235. {
  41236. if (x + ci->width > clip.getX()
  41237. && (ci->id != columnIdBeingDragged
  41238. || dragOverlayComp == 0
  41239. || ! dragOverlayComp->isVisible()))
  41240. {
  41241. Graphics::ScopedSaveState ss (g);
  41242. g.setOrigin (x, 0);
  41243. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41244. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41245. ci->id == columnIdUnderMouse,
  41246. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41247. ci->propertyFlags);
  41248. }
  41249. x += ci->width;
  41250. if (x >= clip.getRight())
  41251. break;
  41252. }
  41253. }
  41254. }
  41255. void TableHeaderComponent::resized()
  41256. {
  41257. }
  41258. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41259. {
  41260. updateColumnUnderMouse (e.x, e.y);
  41261. }
  41262. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41263. {
  41264. updateColumnUnderMouse (e.x, e.y);
  41265. }
  41266. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41267. {
  41268. updateColumnUnderMouse (e.x, e.y);
  41269. }
  41270. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41271. {
  41272. repaint();
  41273. columnIdBeingResized = 0;
  41274. columnIdBeingDragged = 0;
  41275. if (columnIdUnderMouse != 0)
  41276. {
  41277. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41278. if (e.mods.isPopupMenu())
  41279. columnClicked (columnIdUnderMouse, e.mods);
  41280. }
  41281. if (menuActive && e.mods.isPopupMenu())
  41282. showColumnChooserMenu (columnIdUnderMouse);
  41283. }
  41284. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41285. {
  41286. if (columnIdBeingResized == 0
  41287. && columnIdBeingDragged == 0
  41288. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41289. {
  41290. dragOverlayComp = 0;
  41291. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41292. if (columnIdBeingResized != 0)
  41293. {
  41294. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41295. initialColumnWidth = ci->width;
  41296. }
  41297. else
  41298. {
  41299. beginDrag (e);
  41300. }
  41301. }
  41302. if (columnIdBeingResized != 0)
  41303. {
  41304. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41305. if (ci != 0)
  41306. {
  41307. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41308. initialColumnWidth + e.getDistanceFromDragStartX());
  41309. if (stretchToFit)
  41310. {
  41311. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41312. int minWidthOnRight = 0;
  41313. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41314. if (columns.getUnchecked (i)->isVisible())
  41315. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41316. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41317. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41318. }
  41319. setColumnWidth (columnIdBeingResized, w);
  41320. }
  41321. }
  41322. else if (columnIdBeingDragged != 0)
  41323. {
  41324. if (e.y >= -50 && e.y < getHeight() + 50)
  41325. {
  41326. if (dragOverlayComp != 0)
  41327. {
  41328. dragOverlayComp->setVisible (true);
  41329. dragOverlayComp->setBounds (jlimit (0,
  41330. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41331. e.x - draggingColumnOffset),
  41332. 0,
  41333. dragOverlayComp->getWidth(),
  41334. getHeight());
  41335. for (int i = columns.size(); --i >= 0;)
  41336. {
  41337. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41338. int newIndex = currentIndex;
  41339. if (newIndex > 0)
  41340. {
  41341. // if the previous column isn't draggable, we can't move our column
  41342. // past it, because that'd change the undraggable column's position..
  41343. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41344. if ((previous->propertyFlags & draggable) != 0)
  41345. {
  41346. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41347. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41348. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41349. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41350. {
  41351. --newIndex;
  41352. }
  41353. }
  41354. }
  41355. if (newIndex < columns.size() - 1)
  41356. {
  41357. // if the next column isn't draggable, we can't move our column
  41358. // past it, because that'd change the undraggable column's position..
  41359. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41360. if ((nextCol->propertyFlags & draggable) != 0)
  41361. {
  41362. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41363. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41364. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41365. > abs (dragOverlayComp->getRight() - rightOfNext))
  41366. {
  41367. ++newIndex;
  41368. }
  41369. }
  41370. }
  41371. if (newIndex != currentIndex)
  41372. moveColumn (columnIdBeingDragged, newIndex);
  41373. else
  41374. break;
  41375. }
  41376. }
  41377. }
  41378. else
  41379. {
  41380. endDrag (draggingColumnOriginalIndex);
  41381. }
  41382. }
  41383. }
  41384. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41385. {
  41386. if (columnIdBeingDragged == 0)
  41387. {
  41388. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41389. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41390. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41391. {
  41392. columnIdBeingDragged = 0;
  41393. }
  41394. else
  41395. {
  41396. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41397. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41398. const int temp = columnIdBeingDragged;
  41399. columnIdBeingDragged = 0;
  41400. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41401. columnIdBeingDragged = temp;
  41402. dragOverlayComp->setBounds (columnRect);
  41403. for (int i = listeners.size(); --i >= 0;)
  41404. {
  41405. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41406. i = jmin (i, listeners.size() - 1);
  41407. }
  41408. }
  41409. }
  41410. }
  41411. void TableHeaderComponent::endDrag (const int finalIndex)
  41412. {
  41413. if (columnIdBeingDragged != 0)
  41414. {
  41415. moveColumn (columnIdBeingDragged, finalIndex);
  41416. columnIdBeingDragged = 0;
  41417. repaint();
  41418. for (int i = listeners.size(); --i >= 0;)
  41419. {
  41420. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41421. i = jmin (i, listeners.size() - 1);
  41422. }
  41423. }
  41424. }
  41425. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41426. {
  41427. mouseDrag (e);
  41428. for (int i = columns.size(); --i >= 0;)
  41429. if (columns.getUnchecked (i)->isVisible())
  41430. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41431. columnIdBeingResized = 0;
  41432. repaint();
  41433. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41434. updateColumnUnderMouse (e.x, e.y);
  41435. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41436. columnClicked (columnIdUnderMouse, e.mods);
  41437. dragOverlayComp = 0;
  41438. }
  41439. const MouseCursor TableHeaderComponent::getMouseCursor()
  41440. {
  41441. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41442. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41443. return Component::getMouseCursor();
  41444. }
  41445. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41446. {
  41447. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41448. }
  41449. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41450. {
  41451. for (int i = columns.size(); --i >= 0;)
  41452. if (columns.getUnchecked(i)->id == id)
  41453. return columns.getUnchecked(i);
  41454. return 0;
  41455. }
  41456. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41457. {
  41458. int n = 0;
  41459. for (int i = 0; i < columns.size(); ++i)
  41460. {
  41461. if (columns.getUnchecked(i)->isVisible())
  41462. {
  41463. if (n == visibleIndex)
  41464. return i;
  41465. ++n;
  41466. }
  41467. }
  41468. return -1;
  41469. }
  41470. void TableHeaderComponent::sendColumnsChanged()
  41471. {
  41472. if (stretchToFit && lastDeliberateWidth > 0)
  41473. resizeAllColumnsToFit (lastDeliberateWidth);
  41474. repaint();
  41475. columnsChanged = true;
  41476. triggerAsyncUpdate();
  41477. }
  41478. void TableHeaderComponent::handleAsyncUpdate()
  41479. {
  41480. const bool changed = columnsChanged || sortChanged;
  41481. const bool sized = columnsResized || changed;
  41482. const bool sorted = sortChanged;
  41483. columnsChanged = false;
  41484. columnsResized = false;
  41485. sortChanged = false;
  41486. if (sorted)
  41487. {
  41488. for (int i = listeners.size(); --i >= 0;)
  41489. {
  41490. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41491. i = jmin (i, listeners.size() - 1);
  41492. }
  41493. }
  41494. if (changed)
  41495. {
  41496. for (int i = listeners.size(); --i >= 0;)
  41497. {
  41498. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41499. i = jmin (i, listeners.size() - 1);
  41500. }
  41501. }
  41502. if (sized)
  41503. {
  41504. for (int i = listeners.size(); --i >= 0;)
  41505. {
  41506. listeners.getUnchecked(i)->tableColumnsResized (this);
  41507. i = jmin (i, listeners.size() - 1);
  41508. }
  41509. }
  41510. }
  41511. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41512. {
  41513. if (isPositiveAndBelow (mouseX, getWidth()))
  41514. {
  41515. const int draggableDistance = 3;
  41516. int x = 0;
  41517. for (int i = 0; i < columns.size(); ++i)
  41518. {
  41519. const ColumnInfo* const ci = columns.getUnchecked(i);
  41520. if (ci->isVisible())
  41521. {
  41522. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41523. && (ci->propertyFlags & resizable) != 0)
  41524. return ci->id;
  41525. x += ci->width;
  41526. }
  41527. }
  41528. }
  41529. return 0;
  41530. }
  41531. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41532. {
  41533. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41534. ? getColumnIdAtX (x) : 0;
  41535. if (newCol != columnIdUnderMouse)
  41536. {
  41537. columnIdUnderMouse = newCol;
  41538. repaint();
  41539. }
  41540. }
  41541. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41542. {
  41543. PopupMenu m;
  41544. addMenuItems (m, columnIdClicked);
  41545. if (m.getNumItems() > 0)
  41546. {
  41547. m.setLookAndFeel (&getLookAndFeel());
  41548. const int result = m.show();
  41549. if (result != 0)
  41550. reactToMenuItem (result, columnIdClicked);
  41551. }
  41552. }
  41553. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41554. {
  41555. }
  41556. END_JUCE_NAMESPACE
  41557. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41558. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41559. BEGIN_JUCE_NAMESPACE
  41560. class TableListRowComp : public Component,
  41561. public TooltipClient
  41562. {
  41563. public:
  41564. TableListRowComp (TableListBox& owner_)
  41565. : owner (owner_), row (-1), isSelected (false)
  41566. {
  41567. }
  41568. void paint (Graphics& g)
  41569. {
  41570. TableListBoxModel* const model = owner.getModel();
  41571. if (model != 0)
  41572. {
  41573. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41574. const TableHeaderComponent& header = owner.getHeader();
  41575. const int numColumns = header.getNumColumns (true);
  41576. for (int i = 0; i < numColumns; ++i)
  41577. {
  41578. if (columnComponents[i] == 0)
  41579. {
  41580. const int columnId = header.getColumnIdOfIndex (i, true);
  41581. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41582. Graphics::ScopedSaveState ss (g);
  41583. g.reduceClipRegion (columnRect);
  41584. g.setOrigin (columnRect.getX(), 0);
  41585. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41586. }
  41587. }
  41588. }
  41589. }
  41590. void update (const int newRow, const bool isNowSelected)
  41591. {
  41592. jassert (newRow >= 0);
  41593. if (newRow != row || isNowSelected != isSelected)
  41594. {
  41595. row = newRow;
  41596. isSelected = isNowSelected;
  41597. repaint();
  41598. }
  41599. TableListBoxModel* const model = owner.getModel();
  41600. if (model != 0 && row < owner.getNumRows())
  41601. {
  41602. const Identifier columnProperty ("_tableColumnId");
  41603. const int numColumns = owner.getHeader().getNumColumns (true);
  41604. for (int i = 0; i < numColumns; ++i)
  41605. {
  41606. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41607. Component* comp = columnComponents[i];
  41608. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41609. {
  41610. columnComponents.set (i, 0);
  41611. comp = 0;
  41612. }
  41613. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41614. columnComponents.set (i, comp, false);
  41615. if (comp != 0)
  41616. {
  41617. comp->getProperties().set (columnProperty, columnId);
  41618. addAndMakeVisible (comp);
  41619. resizeCustomComp (i);
  41620. }
  41621. }
  41622. columnComponents.removeRange (numColumns, columnComponents.size());
  41623. }
  41624. else
  41625. {
  41626. columnComponents.clear();
  41627. }
  41628. }
  41629. void resized()
  41630. {
  41631. for (int i = columnComponents.size(); --i >= 0;)
  41632. resizeCustomComp (i);
  41633. }
  41634. void resizeCustomComp (const int index)
  41635. {
  41636. Component* const c = columnComponents.getUnchecked (index);
  41637. if (c != 0)
  41638. c->setBounds (owner.getHeader().getColumnPosition (index)
  41639. .withY (0).withHeight (getHeight()));
  41640. }
  41641. void mouseDown (const MouseEvent& e)
  41642. {
  41643. isDragging = false;
  41644. selectRowOnMouseUp = false;
  41645. if (isEnabled())
  41646. {
  41647. if (! isSelected)
  41648. {
  41649. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41650. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41651. if (columnId != 0 && owner.getModel() != 0)
  41652. owner.getModel()->cellClicked (row, columnId, e);
  41653. }
  41654. else
  41655. {
  41656. selectRowOnMouseUp = true;
  41657. }
  41658. }
  41659. }
  41660. void mouseDrag (const MouseEvent& e)
  41661. {
  41662. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41663. {
  41664. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41665. if (selectedRows.size() > 0)
  41666. {
  41667. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41668. if (dragDescription.isNotEmpty())
  41669. {
  41670. isDragging = true;
  41671. owner.startDragAndDrop (e, dragDescription);
  41672. }
  41673. }
  41674. }
  41675. }
  41676. void mouseUp (const MouseEvent& e)
  41677. {
  41678. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41679. {
  41680. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41681. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41682. if (columnId != 0 && owner.getModel() != 0)
  41683. owner.getModel()->cellClicked (row, columnId, e);
  41684. }
  41685. }
  41686. void mouseDoubleClick (const MouseEvent& e)
  41687. {
  41688. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41689. if (columnId != 0 && owner.getModel() != 0)
  41690. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41691. }
  41692. const String getTooltip()
  41693. {
  41694. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41695. if (columnId != 0 && owner.getModel() != 0)
  41696. return owner.getModel()->getCellTooltip (row, columnId);
  41697. return String::empty;
  41698. }
  41699. Component* findChildComponentForColumn (const int columnId) const
  41700. {
  41701. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41702. }
  41703. private:
  41704. TableListBox& owner;
  41705. OwnedArray<Component> columnComponents;
  41706. int row;
  41707. bool isSelected, isDragging, selectRowOnMouseUp;
  41708. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41709. };
  41710. class TableListBoxHeader : public TableHeaderComponent
  41711. {
  41712. public:
  41713. TableListBoxHeader (TableListBox& owner_)
  41714. : owner (owner_)
  41715. {
  41716. }
  41717. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41718. {
  41719. if (owner.isAutoSizeMenuOptionShown())
  41720. {
  41721. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41722. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41723. menu.addSeparator();
  41724. }
  41725. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41726. }
  41727. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41728. {
  41729. switch (menuReturnId)
  41730. {
  41731. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41732. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41733. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41734. }
  41735. }
  41736. private:
  41737. TableListBox& owner;
  41738. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41739. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41740. };
  41741. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41742. : ListBox (name, 0),
  41743. model (model_),
  41744. autoSizeOptionsShown (true)
  41745. {
  41746. ListBox::model = this;
  41747. header = new TableListBoxHeader (*this);
  41748. header->setSize (100, 28);
  41749. header->addListener (this);
  41750. setHeaderComponent (header);
  41751. }
  41752. TableListBox::~TableListBox()
  41753. {
  41754. header = 0;
  41755. }
  41756. void TableListBox::setModel (TableListBoxModel* const newModel)
  41757. {
  41758. if (model != newModel)
  41759. {
  41760. model = newModel;
  41761. updateContent();
  41762. }
  41763. }
  41764. int TableListBox::getHeaderHeight() const
  41765. {
  41766. return header->getHeight();
  41767. }
  41768. void TableListBox::setHeaderHeight (const int newHeight)
  41769. {
  41770. header->setSize (header->getWidth(), newHeight);
  41771. resized();
  41772. }
  41773. void TableListBox::autoSizeColumn (const int columnId)
  41774. {
  41775. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41776. if (width > 0)
  41777. header->setColumnWidth (columnId, width);
  41778. }
  41779. void TableListBox::autoSizeAllColumns()
  41780. {
  41781. for (int i = 0; i < header->getNumColumns (true); ++i)
  41782. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41783. }
  41784. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41785. {
  41786. autoSizeOptionsShown = shouldBeShown;
  41787. }
  41788. bool TableListBox::isAutoSizeMenuOptionShown() const
  41789. {
  41790. return autoSizeOptionsShown;
  41791. }
  41792. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41793. const bool relativeToComponentTopLeft) const
  41794. {
  41795. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41796. if (relativeToComponentTopLeft)
  41797. headerCell.translate (header->getX(), 0);
  41798. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41799. .withX (headerCell.getX())
  41800. .withWidth (headerCell.getWidth());
  41801. }
  41802. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41803. {
  41804. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41805. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41806. }
  41807. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41808. {
  41809. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41810. if (scrollbar != 0)
  41811. {
  41812. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41813. double x = scrollbar->getCurrentRangeStart();
  41814. const double w = scrollbar->getCurrentRangeSize();
  41815. if (pos.getX() < x)
  41816. x = pos.getX();
  41817. else if (pos.getRight() > x + w)
  41818. x += jmax (0.0, pos.getRight() - (x + w));
  41819. scrollbar->setCurrentRangeStart (x);
  41820. }
  41821. }
  41822. int TableListBox::getNumRows()
  41823. {
  41824. return model != 0 ? model->getNumRows() : 0;
  41825. }
  41826. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41827. {
  41828. }
  41829. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41830. {
  41831. if (existingComponentToUpdate == 0)
  41832. existingComponentToUpdate = new TableListRowComp (*this);
  41833. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41834. return existingComponentToUpdate;
  41835. }
  41836. void TableListBox::selectedRowsChanged (int row)
  41837. {
  41838. if (model != 0)
  41839. model->selectedRowsChanged (row);
  41840. }
  41841. void TableListBox::deleteKeyPressed (int row)
  41842. {
  41843. if (model != 0)
  41844. model->deleteKeyPressed (row);
  41845. }
  41846. void TableListBox::returnKeyPressed (int row)
  41847. {
  41848. if (model != 0)
  41849. model->returnKeyPressed (row);
  41850. }
  41851. void TableListBox::backgroundClicked()
  41852. {
  41853. if (model != 0)
  41854. model->backgroundClicked();
  41855. }
  41856. void TableListBox::listWasScrolled()
  41857. {
  41858. if (model != 0)
  41859. model->listWasScrolled();
  41860. }
  41861. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41862. {
  41863. setMinimumContentWidth (header->getTotalWidth());
  41864. repaint();
  41865. updateColumnComponents();
  41866. }
  41867. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41868. {
  41869. setMinimumContentWidth (header->getTotalWidth());
  41870. repaint();
  41871. updateColumnComponents();
  41872. }
  41873. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41874. {
  41875. if (model != 0)
  41876. model->sortOrderChanged (header->getSortColumnId(),
  41877. header->isSortedForwards());
  41878. }
  41879. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41880. {
  41881. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41882. repaint();
  41883. }
  41884. void TableListBox::resized()
  41885. {
  41886. ListBox::resized();
  41887. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41888. setMinimumContentWidth (header->getTotalWidth());
  41889. }
  41890. void TableListBox::updateColumnComponents() const
  41891. {
  41892. const int firstRow = getRowContainingPosition (0, 0);
  41893. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41894. {
  41895. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41896. if (rowComp != 0)
  41897. rowComp->resized();
  41898. }
  41899. }
  41900. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41901. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41902. void TableListBoxModel::backgroundClicked() {}
  41903. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41904. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41905. void TableListBoxModel::selectedRowsChanged (int) {}
  41906. void TableListBoxModel::deleteKeyPressed (int) {}
  41907. void TableListBoxModel::returnKeyPressed (int) {}
  41908. void TableListBoxModel::listWasScrolled() {}
  41909. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41910. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41911. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41912. {
  41913. (void) existingComponentToUpdate;
  41914. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41915. return 0;
  41916. }
  41917. END_JUCE_NAMESPACE
  41918. /*** End of inlined file: juce_TableListBox.cpp ***/
  41919. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41920. BEGIN_JUCE_NAMESPACE
  41921. // a word or space that can't be broken down any further
  41922. struct TextAtom
  41923. {
  41924. String atomText;
  41925. float width;
  41926. int numChars;
  41927. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41928. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41929. const String getText (const juce_wchar passwordCharacter) const
  41930. {
  41931. if (passwordCharacter == 0)
  41932. return atomText;
  41933. else
  41934. return String::repeatedString (String::charToString (passwordCharacter),
  41935. atomText.length());
  41936. }
  41937. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41938. {
  41939. if (passwordCharacter == 0)
  41940. return atomText.substring (0, numChars);
  41941. else if (isNewLine())
  41942. return String::empty;
  41943. else
  41944. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41945. }
  41946. };
  41947. // a run of text with a single font and colour
  41948. class TextEditor::UniformTextSection
  41949. {
  41950. public:
  41951. UniformTextSection (const String& text,
  41952. const Font& font_,
  41953. const Colour& colour_,
  41954. const juce_wchar passwordCharacter)
  41955. : font (font_),
  41956. colour (colour_)
  41957. {
  41958. initialiseAtoms (text, passwordCharacter);
  41959. }
  41960. UniformTextSection (const UniformTextSection& other)
  41961. : font (other.font),
  41962. colour (other.colour)
  41963. {
  41964. atoms.ensureStorageAllocated (other.atoms.size());
  41965. for (int i = 0; i < other.atoms.size(); ++i)
  41966. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41967. }
  41968. ~UniformTextSection()
  41969. {
  41970. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41971. }
  41972. void clear()
  41973. {
  41974. for (int i = atoms.size(); --i >= 0;)
  41975. delete getAtom(i);
  41976. atoms.clear();
  41977. }
  41978. int getNumAtoms() const
  41979. {
  41980. return atoms.size();
  41981. }
  41982. TextAtom* getAtom (const int index) const throw()
  41983. {
  41984. return atoms.getUnchecked (index);
  41985. }
  41986. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41987. {
  41988. if (other.atoms.size() > 0)
  41989. {
  41990. TextAtom* const lastAtom = atoms.getLast();
  41991. int i = 0;
  41992. if (lastAtom != 0)
  41993. {
  41994. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41995. {
  41996. TextAtom* const first = other.getAtom(0);
  41997. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41998. {
  41999. lastAtom->atomText += first->atomText;
  42000. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42001. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42002. delete first;
  42003. ++i;
  42004. }
  42005. }
  42006. }
  42007. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42008. while (i < other.atoms.size())
  42009. {
  42010. atoms.add (other.getAtom(i));
  42011. ++i;
  42012. }
  42013. }
  42014. }
  42015. UniformTextSection* split (const int indexToBreakAt,
  42016. const juce_wchar passwordCharacter)
  42017. {
  42018. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42019. font, colour,
  42020. passwordCharacter);
  42021. int index = 0;
  42022. for (int i = 0; i < atoms.size(); ++i)
  42023. {
  42024. TextAtom* const atom = getAtom(i);
  42025. const int nextIndex = index + atom->numChars;
  42026. if (index == indexToBreakAt)
  42027. {
  42028. int j;
  42029. for (j = i; j < atoms.size(); ++j)
  42030. section2->atoms.add (getAtom (j));
  42031. for (j = atoms.size(); --j >= i;)
  42032. atoms.remove (j);
  42033. break;
  42034. }
  42035. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42036. {
  42037. TextAtom* const secondAtom = new TextAtom();
  42038. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42039. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42040. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42041. section2->atoms.add (secondAtom);
  42042. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42043. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42044. atom->numChars = (uint16) (indexToBreakAt - index);
  42045. int j;
  42046. for (j = i + 1; j < atoms.size(); ++j)
  42047. section2->atoms.add (getAtom (j));
  42048. for (j = atoms.size(); --j > i;)
  42049. atoms.remove (j);
  42050. break;
  42051. }
  42052. index = nextIndex;
  42053. }
  42054. return section2;
  42055. }
  42056. void appendAllText (String::Concatenator& concatenator) const
  42057. {
  42058. for (int i = 0; i < atoms.size(); ++i)
  42059. concatenator.append (getAtom(i)->atomText);
  42060. }
  42061. void appendSubstring (String::Concatenator& concatenator,
  42062. const Range<int>& range) const
  42063. {
  42064. int index = 0;
  42065. for (int i = 0; i < atoms.size(); ++i)
  42066. {
  42067. const TextAtom* const atom = getAtom (i);
  42068. const int nextIndex = index + atom->numChars;
  42069. if (range.getStart() < nextIndex)
  42070. {
  42071. if (range.getEnd() <= index)
  42072. break;
  42073. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42074. if (! r.isEmpty())
  42075. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42076. }
  42077. index = nextIndex;
  42078. }
  42079. }
  42080. int getTotalLength() const
  42081. {
  42082. int total = 0;
  42083. for (int i = atoms.size(); --i >= 0;)
  42084. total += getAtom(i)->numChars;
  42085. return total;
  42086. }
  42087. void setFont (const Font& newFont,
  42088. const juce_wchar passwordCharacter)
  42089. {
  42090. if (font != newFont)
  42091. {
  42092. font = newFont;
  42093. for (int i = atoms.size(); --i >= 0;)
  42094. {
  42095. TextAtom* const atom = atoms.getUnchecked(i);
  42096. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42097. }
  42098. }
  42099. }
  42100. Font font;
  42101. Colour colour;
  42102. private:
  42103. Array <TextAtom*> atoms;
  42104. void initialiseAtoms (const String& textToParse,
  42105. const juce_wchar passwordCharacter)
  42106. {
  42107. int i = 0;
  42108. const int len = textToParse.length();
  42109. const juce_wchar* const text = textToParse;
  42110. while (i < len)
  42111. {
  42112. int start = i;
  42113. // create a whitespace atom unless it starts with non-ws
  42114. if (CharacterFunctions::isWhitespace (text[i])
  42115. && text[i] != '\r'
  42116. && text[i] != '\n')
  42117. {
  42118. while (i < len
  42119. && CharacterFunctions::isWhitespace (text[i])
  42120. && text[i] != '\r'
  42121. && text[i] != '\n')
  42122. {
  42123. ++i;
  42124. }
  42125. }
  42126. else
  42127. {
  42128. if (text[i] == '\r')
  42129. {
  42130. ++i;
  42131. if ((i < len) && (text[i] == '\n'))
  42132. {
  42133. ++start;
  42134. ++i;
  42135. }
  42136. }
  42137. else if (text[i] == '\n')
  42138. {
  42139. ++i;
  42140. }
  42141. else
  42142. {
  42143. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42144. ++i;
  42145. }
  42146. }
  42147. TextAtom* const atom = new TextAtom();
  42148. atom->atomText = String (text + start, i - start);
  42149. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42150. atom->numChars = (uint16) (i - start);
  42151. atoms.add (atom);
  42152. }
  42153. }
  42154. UniformTextSection& operator= (const UniformTextSection& other);
  42155. JUCE_LEAK_DETECTOR (UniformTextSection);
  42156. };
  42157. class TextEditor::Iterator
  42158. {
  42159. public:
  42160. Iterator (const Array <UniformTextSection*>& sections_,
  42161. const float wordWrapWidth_,
  42162. const juce_wchar passwordCharacter_)
  42163. : indexInText (0),
  42164. lineY (0),
  42165. lineHeight (0),
  42166. maxDescent (0),
  42167. atomX (0),
  42168. atomRight (0),
  42169. atom (0),
  42170. currentSection (0),
  42171. sections (sections_),
  42172. sectionIndex (0),
  42173. atomIndex (0),
  42174. wordWrapWidth (wordWrapWidth_),
  42175. passwordCharacter (passwordCharacter_)
  42176. {
  42177. jassert (wordWrapWidth_ > 0);
  42178. if (sections.size() > 0)
  42179. {
  42180. currentSection = sections.getUnchecked (sectionIndex);
  42181. if (currentSection != 0)
  42182. beginNewLine();
  42183. }
  42184. }
  42185. Iterator (const Iterator& other)
  42186. : indexInText (other.indexInText),
  42187. lineY (other.lineY),
  42188. lineHeight (other.lineHeight),
  42189. maxDescent (other.maxDescent),
  42190. atomX (other.atomX),
  42191. atomRight (other.atomRight),
  42192. atom (other.atom),
  42193. currentSection (other.currentSection),
  42194. sections (other.sections),
  42195. sectionIndex (other.sectionIndex),
  42196. atomIndex (other.atomIndex),
  42197. wordWrapWidth (other.wordWrapWidth),
  42198. passwordCharacter (other.passwordCharacter),
  42199. tempAtom (other.tempAtom)
  42200. {
  42201. }
  42202. bool next()
  42203. {
  42204. if (atom == &tempAtom)
  42205. {
  42206. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42207. if (numRemaining > 0)
  42208. {
  42209. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42210. atomX = 0;
  42211. if (tempAtom.numChars > 0)
  42212. lineY += lineHeight;
  42213. indexInText += tempAtom.numChars;
  42214. GlyphArrangement g;
  42215. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42216. int split;
  42217. for (split = 0; split < g.getNumGlyphs(); ++split)
  42218. if (shouldWrap (g.getGlyph (split).getRight()))
  42219. break;
  42220. if (split > 0 && split <= numRemaining)
  42221. {
  42222. tempAtom.numChars = (uint16) split;
  42223. tempAtom.width = g.getGlyph (split - 1).getRight();
  42224. atomRight = atomX + tempAtom.width;
  42225. return true;
  42226. }
  42227. }
  42228. }
  42229. bool forceNewLine = false;
  42230. if (sectionIndex >= sections.size())
  42231. {
  42232. moveToEndOfLastAtom();
  42233. return false;
  42234. }
  42235. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42236. {
  42237. if (atomIndex >= currentSection->getNumAtoms())
  42238. {
  42239. if (++sectionIndex >= sections.size())
  42240. {
  42241. moveToEndOfLastAtom();
  42242. return false;
  42243. }
  42244. atomIndex = 0;
  42245. currentSection = sections.getUnchecked (sectionIndex);
  42246. }
  42247. else
  42248. {
  42249. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42250. if (! lastAtom->isWhitespace())
  42251. {
  42252. // handle the case where the last atom in a section is actually part of the same
  42253. // word as the first atom of the next section...
  42254. float right = atomRight + lastAtom->width;
  42255. float lineHeight2 = lineHeight;
  42256. float maxDescent2 = maxDescent;
  42257. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42258. {
  42259. const UniformTextSection* const s = sections.getUnchecked (section);
  42260. if (s->getNumAtoms() == 0)
  42261. break;
  42262. const TextAtom* const nextAtom = s->getAtom (0);
  42263. if (nextAtom->isWhitespace())
  42264. break;
  42265. right += nextAtom->width;
  42266. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42267. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42268. if (shouldWrap (right))
  42269. {
  42270. lineHeight = lineHeight2;
  42271. maxDescent = maxDescent2;
  42272. forceNewLine = true;
  42273. break;
  42274. }
  42275. if (s->getNumAtoms() > 1)
  42276. break;
  42277. }
  42278. }
  42279. }
  42280. }
  42281. if (atom != 0)
  42282. {
  42283. atomX = atomRight;
  42284. indexInText += atom->numChars;
  42285. if (atom->isNewLine())
  42286. beginNewLine();
  42287. }
  42288. atom = currentSection->getAtom (atomIndex);
  42289. atomRight = atomX + atom->width;
  42290. ++atomIndex;
  42291. if (shouldWrap (atomRight) || forceNewLine)
  42292. {
  42293. if (atom->isWhitespace())
  42294. {
  42295. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42296. atomRight = jmin (atomRight, wordWrapWidth);
  42297. }
  42298. else
  42299. {
  42300. atomRight = atom->width;
  42301. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42302. {
  42303. tempAtom = *atom;
  42304. tempAtom.width = 0;
  42305. tempAtom.numChars = 0;
  42306. atom = &tempAtom;
  42307. if (atomX > 0)
  42308. beginNewLine();
  42309. return next();
  42310. }
  42311. beginNewLine();
  42312. return true;
  42313. }
  42314. }
  42315. return true;
  42316. }
  42317. void beginNewLine()
  42318. {
  42319. atomX = 0;
  42320. lineY += lineHeight;
  42321. int tempSectionIndex = sectionIndex;
  42322. int tempAtomIndex = atomIndex;
  42323. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42324. lineHeight = section->font.getHeight();
  42325. maxDescent = section->font.getDescent();
  42326. float x = (atom != 0) ? atom->width : 0;
  42327. while (! shouldWrap (x))
  42328. {
  42329. if (tempSectionIndex >= sections.size())
  42330. break;
  42331. bool checkSize = false;
  42332. if (tempAtomIndex >= section->getNumAtoms())
  42333. {
  42334. if (++tempSectionIndex >= sections.size())
  42335. break;
  42336. tempAtomIndex = 0;
  42337. section = sections.getUnchecked (tempSectionIndex);
  42338. checkSize = true;
  42339. }
  42340. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42341. if (nextAtom == 0)
  42342. break;
  42343. x += nextAtom->width;
  42344. if (shouldWrap (x) || nextAtom->isNewLine())
  42345. break;
  42346. if (checkSize)
  42347. {
  42348. lineHeight = jmax (lineHeight, section->font.getHeight());
  42349. maxDescent = jmax (maxDescent, section->font.getDescent());
  42350. }
  42351. ++tempAtomIndex;
  42352. }
  42353. }
  42354. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42355. {
  42356. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42357. {
  42358. if (lastSection != currentSection)
  42359. {
  42360. lastSection = currentSection;
  42361. g.setColour (currentSection->colour);
  42362. g.setFont (currentSection->font);
  42363. }
  42364. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42365. GlyphArrangement ga;
  42366. ga.addLineOfText (currentSection->font,
  42367. atom->getTrimmedText (passwordCharacter),
  42368. atomX,
  42369. (float) roundToInt (lineY + lineHeight - maxDescent));
  42370. ga.draw (g);
  42371. }
  42372. }
  42373. void drawSelection (Graphics& g,
  42374. const Range<int>& selection) const
  42375. {
  42376. const int startX = roundToInt (indexToX (selection.getStart()));
  42377. const int endX = roundToInt (indexToX (selection.getEnd()));
  42378. const int y = roundToInt (lineY);
  42379. const int nextY = roundToInt (lineY + lineHeight);
  42380. g.fillRect (startX, y, endX - startX, nextY - y);
  42381. }
  42382. void drawSelectedText (Graphics& g,
  42383. const Range<int>& selection,
  42384. const Colour& selectedTextColour) const
  42385. {
  42386. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42387. {
  42388. GlyphArrangement ga;
  42389. ga.addLineOfText (currentSection->font,
  42390. atom->getTrimmedText (passwordCharacter),
  42391. atomX,
  42392. (float) roundToInt (lineY + lineHeight - maxDescent));
  42393. if (selection.getEnd() < indexInText + atom->numChars)
  42394. {
  42395. GlyphArrangement ga2 (ga);
  42396. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42397. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42398. g.setColour (currentSection->colour);
  42399. ga2.draw (g);
  42400. }
  42401. if (selection.getStart() > indexInText)
  42402. {
  42403. GlyphArrangement ga2 (ga);
  42404. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42405. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42406. g.setColour (currentSection->colour);
  42407. ga2.draw (g);
  42408. }
  42409. g.setColour (selectedTextColour);
  42410. ga.draw (g);
  42411. }
  42412. }
  42413. float indexToX (const int indexToFind) const
  42414. {
  42415. if (indexToFind <= indexInText)
  42416. return atomX;
  42417. if (indexToFind >= indexInText + atom->numChars)
  42418. return atomRight;
  42419. GlyphArrangement g;
  42420. g.addLineOfText (currentSection->font,
  42421. atom->getText (passwordCharacter),
  42422. atomX, 0.0f);
  42423. if (indexToFind - indexInText >= g.getNumGlyphs())
  42424. return atomRight;
  42425. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42426. }
  42427. int xToIndex (const float xToFind) const
  42428. {
  42429. if (xToFind <= atomX || atom->isNewLine())
  42430. return indexInText;
  42431. if (xToFind >= atomRight)
  42432. return indexInText + atom->numChars;
  42433. GlyphArrangement g;
  42434. g.addLineOfText (currentSection->font,
  42435. atom->getText (passwordCharacter),
  42436. atomX, 0.0f);
  42437. int j;
  42438. for (j = 0; j < g.getNumGlyphs(); ++j)
  42439. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42440. break;
  42441. return indexInText + j;
  42442. }
  42443. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42444. {
  42445. while (next())
  42446. {
  42447. if (indexInText + atom->numChars > index)
  42448. {
  42449. cx = indexToX (index);
  42450. cy = lineY;
  42451. lineHeight_ = lineHeight;
  42452. return true;
  42453. }
  42454. }
  42455. cx = atomX;
  42456. cy = lineY;
  42457. lineHeight_ = lineHeight;
  42458. return false;
  42459. }
  42460. int indexInText;
  42461. float lineY, lineHeight, maxDescent;
  42462. float atomX, atomRight;
  42463. const TextAtom* atom;
  42464. const UniformTextSection* currentSection;
  42465. private:
  42466. const Array <UniformTextSection*>& sections;
  42467. int sectionIndex, atomIndex;
  42468. const float wordWrapWidth;
  42469. const juce_wchar passwordCharacter;
  42470. TextAtom tempAtom;
  42471. Iterator& operator= (const Iterator&);
  42472. void moveToEndOfLastAtom()
  42473. {
  42474. if (atom != 0)
  42475. {
  42476. atomX = atomRight;
  42477. if (atom->isNewLine())
  42478. {
  42479. atomX = 0.0f;
  42480. lineY += lineHeight;
  42481. }
  42482. }
  42483. }
  42484. bool shouldWrap (const float x) const
  42485. {
  42486. return (x - 0.0001f) >= wordWrapWidth;
  42487. }
  42488. JUCE_LEAK_DETECTOR (Iterator);
  42489. };
  42490. class TextEditor::InsertAction : public UndoableAction
  42491. {
  42492. public:
  42493. InsertAction (TextEditor& owner_,
  42494. const String& text_,
  42495. const int insertIndex_,
  42496. const Font& font_,
  42497. const Colour& colour_,
  42498. const int oldCaretPos_,
  42499. const int newCaretPos_)
  42500. : owner (owner_),
  42501. text (text_),
  42502. insertIndex (insertIndex_),
  42503. oldCaretPos (oldCaretPos_),
  42504. newCaretPos (newCaretPos_),
  42505. font (font_),
  42506. colour (colour_)
  42507. {
  42508. }
  42509. bool perform()
  42510. {
  42511. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42512. return true;
  42513. }
  42514. bool undo()
  42515. {
  42516. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42517. return true;
  42518. }
  42519. int getSizeInUnits()
  42520. {
  42521. return text.length() + 16;
  42522. }
  42523. private:
  42524. TextEditor& owner;
  42525. const String text;
  42526. const int insertIndex, oldCaretPos, newCaretPos;
  42527. const Font font;
  42528. const Colour colour;
  42529. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42530. };
  42531. class TextEditor::RemoveAction : public UndoableAction
  42532. {
  42533. public:
  42534. RemoveAction (TextEditor& owner_,
  42535. const Range<int> range_,
  42536. const int oldCaretPos_,
  42537. const int newCaretPos_,
  42538. const Array <UniformTextSection*>& removedSections_)
  42539. : owner (owner_),
  42540. range (range_),
  42541. oldCaretPos (oldCaretPos_),
  42542. newCaretPos (newCaretPos_),
  42543. removedSections (removedSections_)
  42544. {
  42545. }
  42546. ~RemoveAction()
  42547. {
  42548. for (int i = removedSections.size(); --i >= 0;)
  42549. {
  42550. UniformTextSection* const section = removedSections.getUnchecked (i);
  42551. section->clear();
  42552. delete section;
  42553. }
  42554. }
  42555. bool perform()
  42556. {
  42557. owner.remove (range, 0, newCaretPos);
  42558. return true;
  42559. }
  42560. bool undo()
  42561. {
  42562. owner.reinsert (range.getStart(), removedSections);
  42563. owner.moveCursorTo (oldCaretPos, false);
  42564. return true;
  42565. }
  42566. int getSizeInUnits()
  42567. {
  42568. int n = 0;
  42569. for (int i = removedSections.size(); --i >= 0;)
  42570. n += removedSections.getUnchecked (i)->getTotalLength();
  42571. return n + 16;
  42572. }
  42573. private:
  42574. TextEditor& owner;
  42575. const Range<int> range;
  42576. const int oldCaretPos, newCaretPos;
  42577. Array <UniformTextSection*> removedSections;
  42578. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42579. };
  42580. class TextEditor::TextHolderComponent : public Component,
  42581. public Timer,
  42582. public ValueListener
  42583. {
  42584. public:
  42585. TextHolderComponent (TextEditor& owner_)
  42586. : owner (owner_)
  42587. {
  42588. setWantsKeyboardFocus (false);
  42589. setInterceptsMouseClicks (false, true);
  42590. owner.getTextValue().addListener (this);
  42591. }
  42592. ~TextHolderComponent()
  42593. {
  42594. owner.getTextValue().removeListener (this);
  42595. }
  42596. void paint (Graphics& g)
  42597. {
  42598. owner.drawContent (g);
  42599. }
  42600. void timerCallback()
  42601. {
  42602. owner.timerCallbackInt();
  42603. }
  42604. const MouseCursor getMouseCursor()
  42605. {
  42606. return owner.getMouseCursor();
  42607. }
  42608. void valueChanged (Value&)
  42609. {
  42610. owner.textWasChangedByValue();
  42611. }
  42612. private:
  42613. TextEditor& owner;
  42614. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42615. };
  42616. class TextEditorViewport : public Viewport
  42617. {
  42618. public:
  42619. TextEditorViewport (TextEditor& owner_)
  42620. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42621. {
  42622. }
  42623. void visibleAreaChanged (const Rectangle<int>&)
  42624. {
  42625. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42626. // appear and disappear, causing the wrap width to change.
  42627. {
  42628. const float wordWrapWidth = owner.getWordWrapWidth();
  42629. if (wordWrapWidth != lastWordWrapWidth)
  42630. {
  42631. lastWordWrapWidth = wordWrapWidth;
  42632. rentrant = true;
  42633. owner.updateTextHolderSize();
  42634. rentrant = false;
  42635. }
  42636. }
  42637. }
  42638. private:
  42639. TextEditor& owner;
  42640. float lastWordWrapWidth;
  42641. bool rentrant;
  42642. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42643. };
  42644. namespace TextEditorDefs
  42645. {
  42646. const int flashSpeedIntervalMs = 380;
  42647. const int textChangeMessageId = 0x10003001;
  42648. const int returnKeyMessageId = 0x10003002;
  42649. const int escapeKeyMessageId = 0x10003003;
  42650. const int focusLossMessageId = 0x10003004;
  42651. const int maxActionsPerTransaction = 100;
  42652. int getCharacterCategory (const juce_wchar character)
  42653. {
  42654. return CharacterFunctions::isLetterOrDigit (character)
  42655. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42656. }
  42657. }
  42658. TextEditor::TextEditor (const String& name,
  42659. const juce_wchar passwordCharacter_)
  42660. : Component (name),
  42661. borderSize (1, 1, 1, 3),
  42662. readOnly (false),
  42663. multiline (false),
  42664. wordWrap (false),
  42665. returnKeyStartsNewLine (false),
  42666. caretVisible (true),
  42667. popupMenuEnabled (true),
  42668. selectAllTextWhenFocused (false),
  42669. scrollbarVisible (true),
  42670. wasFocused (false),
  42671. caretFlashState (true),
  42672. keepCursorOnScreen (true),
  42673. tabKeyUsed (false),
  42674. menuActive (false),
  42675. valueTextNeedsUpdating (false),
  42676. cursorX (0),
  42677. cursorY (0),
  42678. cursorHeight (0),
  42679. maxTextLength (0),
  42680. leftIndent (4),
  42681. topIndent (4),
  42682. lastTransactionTime (0),
  42683. currentFont (14.0f),
  42684. totalNumChars (0),
  42685. caretPosition (0),
  42686. passwordCharacter (passwordCharacter_),
  42687. dragType (notDragging)
  42688. {
  42689. setOpaque (true);
  42690. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42691. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42692. viewport->setWantsKeyboardFocus (false);
  42693. viewport->setScrollBarsShown (false, false);
  42694. setMouseCursor (MouseCursor::IBeamCursor);
  42695. setWantsKeyboardFocus (true);
  42696. }
  42697. TextEditor::~TextEditor()
  42698. {
  42699. textValue.referTo (Value());
  42700. clearInternal (0);
  42701. viewport = 0;
  42702. textHolder = 0;
  42703. }
  42704. void TextEditor::newTransaction()
  42705. {
  42706. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42707. undoManager.beginNewTransaction();
  42708. }
  42709. void TextEditor::doUndoRedo (const bool isRedo)
  42710. {
  42711. if (! isReadOnly())
  42712. {
  42713. if (isRedo ? undoManager.redo()
  42714. : undoManager.undo())
  42715. {
  42716. scrollToMakeSureCursorIsVisible();
  42717. repaint();
  42718. textChanged();
  42719. }
  42720. }
  42721. }
  42722. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42723. const bool shouldWordWrap)
  42724. {
  42725. if (multiline != shouldBeMultiLine
  42726. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42727. {
  42728. multiline = shouldBeMultiLine;
  42729. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42730. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42731. scrollbarVisible && multiline);
  42732. viewport->setViewPosition (0, 0);
  42733. resized();
  42734. scrollToMakeSureCursorIsVisible();
  42735. }
  42736. }
  42737. bool TextEditor::isMultiLine() const
  42738. {
  42739. return multiline;
  42740. }
  42741. void TextEditor::setScrollbarsShown (bool shown)
  42742. {
  42743. if (scrollbarVisible != shown)
  42744. {
  42745. scrollbarVisible = shown;
  42746. shown = shown && isMultiLine();
  42747. viewport->setScrollBarsShown (shown, shown);
  42748. }
  42749. }
  42750. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42751. {
  42752. if (readOnly != shouldBeReadOnly)
  42753. {
  42754. readOnly = shouldBeReadOnly;
  42755. enablementChanged();
  42756. }
  42757. }
  42758. bool TextEditor::isReadOnly() const
  42759. {
  42760. return readOnly || ! isEnabled();
  42761. }
  42762. bool TextEditor::isTextInputActive() const
  42763. {
  42764. return ! isReadOnly();
  42765. }
  42766. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42767. {
  42768. returnKeyStartsNewLine = shouldStartNewLine;
  42769. }
  42770. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42771. {
  42772. tabKeyUsed = shouldTabKeyBeUsed;
  42773. }
  42774. void TextEditor::setPopupMenuEnabled (const bool b)
  42775. {
  42776. popupMenuEnabled = b;
  42777. }
  42778. void TextEditor::setSelectAllWhenFocused (const bool b)
  42779. {
  42780. selectAllTextWhenFocused = b;
  42781. }
  42782. const Font TextEditor::getFont() const
  42783. {
  42784. return currentFont;
  42785. }
  42786. void TextEditor::setFont (const Font& newFont)
  42787. {
  42788. currentFont = newFont;
  42789. scrollToMakeSureCursorIsVisible();
  42790. }
  42791. void TextEditor::applyFontToAllText (const Font& newFont)
  42792. {
  42793. currentFont = newFont;
  42794. const Colour overallColour (findColour (textColourId));
  42795. for (int i = sections.size(); --i >= 0;)
  42796. {
  42797. UniformTextSection* const uts = sections.getUnchecked (i);
  42798. uts->setFont (newFont, passwordCharacter);
  42799. uts->colour = overallColour;
  42800. }
  42801. coalesceSimilarSections();
  42802. updateTextHolderSize();
  42803. scrollToMakeSureCursorIsVisible();
  42804. repaint();
  42805. }
  42806. void TextEditor::colourChanged()
  42807. {
  42808. setOpaque (findColour (backgroundColourId).isOpaque());
  42809. repaint();
  42810. }
  42811. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42812. {
  42813. caretVisible = shouldCaretBeVisible;
  42814. if (shouldCaretBeVisible)
  42815. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42816. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42817. : MouseCursor::NormalCursor);
  42818. }
  42819. void TextEditor::setInputRestrictions (const int maxLen,
  42820. const String& chars)
  42821. {
  42822. maxTextLength = jmax (0, maxLen);
  42823. allowedCharacters = chars;
  42824. }
  42825. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42826. {
  42827. textToShowWhenEmpty = text;
  42828. colourForTextWhenEmpty = colourToUse;
  42829. }
  42830. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42831. {
  42832. if (passwordCharacter != newPasswordCharacter)
  42833. {
  42834. passwordCharacter = newPasswordCharacter;
  42835. resized();
  42836. repaint();
  42837. }
  42838. }
  42839. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42840. {
  42841. viewport->setScrollBarThickness (newThicknessPixels);
  42842. }
  42843. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42844. {
  42845. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42846. }
  42847. void TextEditor::clear()
  42848. {
  42849. clearInternal (0);
  42850. updateTextHolderSize();
  42851. undoManager.clearUndoHistory();
  42852. }
  42853. void TextEditor::setText (const String& newText,
  42854. const bool sendTextChangeMessage)
  42855. {
  42856. const int newLength = newText.length();
  42857. if (newLength != getTotalNumChars() || getText() != newText)
  42858. {
  42859. const int oldCursorPos = caretPosition;
  42860. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42861. clearInternal (0);
  42862. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42863. // if you're adding text with line-feeds to a single-line text editor, it
  42864. // ain't gonna look right!
  42865. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42866. if (cursorWasAtEnd && ! isMultiLine())
  42867. moveCursorTo (getTotalNumChars(), false);
  42868. else
  42869. moveCursorTo (oldCursorPos, false);
  42870. if (sendTextChangeMessage)
  42871. textChanged();
  42872. updateTextHolderSize();
  42873. scrollToMakeSureCursorIsVisible();
  42874. undoManager.clearUndoHistory();
  42875. repaint();
  42876. }
  42877. }
  42878. Value& TextEditor::getTextValue()
  42879. {
  42880. if (valueTextNeedsUpdating)
  42881. {
  42882. valueTextNeedsUpdating = false;
  42883. textValue = getText();
  42884. }
  42885. return textValue;
  42886. }
  42887. void TextEditor::textWasChangedByValue()
  42888. {
  42889. if (textValue.getValueSource().getReferenceCount() > 1)
  42890. setText (textValue.getValue());
  42891. }
  42892. void TextEditor::textChanged()
  42893. {
  42894. updateTextHolderSize();
  42895. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42896. if (textValue.getValueSource().getReferenceCount() > 1)
  42897. {
  42898. valueTextNeedsUpdating = false;
  42899. textValue = getText();
  42900. }
  42901. }
  42902. void TextEditor::returnPressed()
  42903. {
  42904. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42905. }
  42906. void TextEditor::escapePressed()
  42907. {
  42908. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42909. }
  42910. void TextEditor::addListener (TextEditorListener* const newListener)
  42911. {
  42912. listeners.add (newListener);
  42913. }
  42914. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42915. {
  42916. listeners.remove (listenerToRemove);
  42917. }
  42918. void TextEditor::timerCallbackInt()
  42919. {
  42920. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42921. if (caretFlashState != newState)
  42922. {
  42923. caretFlashState = newState;
  42924. if (caretFlashState)
  42925. wasFocused = true;
  42926. if (caretVisible
  42927. && hasKeyboardFocus (false)
  42928. && ! isReadOnly())
  42929. {
  42930. repaintCaret();
  42931. }
  42932. }
  42933. const unsigned int now = Time::getApproximateMillisecondCounter();
  42934. if (now > lastTransactionTime + 200)
  42935. newTransaction();
  42936. }
  42937. void TextEditor::repaintCaret()
  42938. {
  42939. if (! findColour (caretColourId).isTransparent())
  42940. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42941. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42942. 4,
  42943. roundToInt (cursorHeight) + 2);
  42944. }
  42945. void TextEditor::repaintText (const Range<int>& range)
  42946. {
  42947. if (! range.isEmpty())
  42948. {
  42949. float x = 0, y = 0, lh = currentFont.getHeight();
  42950. const float wordWrapWidth = getWordWrapWidth();
  42951. if (wordWrapWidth > 0)
  42952. {
  42953. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42954. i.getCharPosition (range.getStart(), x, y, lh);
  42955. const int y1 = (int) y;
  42956. int y2;
  42957. if (range.getEnd() >= getTotalNumChars())
  42958. {
  42959. y2 = textHolder->getHeight();
  42960. }
  42961. else
  42962. {
  42963. i.getCharPosition (range.getEnd(), x, y, lh);
  42964. y2 = (int) (y + lh * 2.0f);
  42965. }
  42966. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42967. }
  42968. }
  42969. }
  42970. void TextEditor::moveCaret (int newCaretPos)
  42971. {
  42972. if (newCaretPos < 0)
  42973. newCaretPos = 0;
  42974. else if (newCaretPos > getTotalNumChars())
  42975. newCaretPos = getTotalNumChars();
  42976. if (newCaretPos != getCaretPosition())
  42977. {
  42978. repaintCaret();
  42979. caretFlashState = true;
  42980. caretPosition = newCaretPos;
  42981. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42982. scrollToMakeSureCursorIsVisible();
  42983. repaintCaret();
  42984. }
  42985. }
  42986. void TextEditor::setCaretPosition (const int newIndex)
  42987. {
  42988. moveCursorTo (newIndex, false);
  42989. }
  42990. int TextEditor::getCaretPosition() const
  42991. {
  42992. return caretPosition;
  42993. }
  42994. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42995. const int desiredCaretY)
  42996. {
  42997. updateCaretPosition();
  42998. int vx = roundToInt (cursorX) - desiredCaretX;
  42999. int vy = roundToInt (cursorY) - desiredCaretY;
  43000. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43001. {
  43002. vx += desiredCaretX - proportionOfWidth (0.2f);
  43003. }
  43004. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43005. {
  43006. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43007. }
  43008. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43009. if (! isMultiLine())
  43010. {
  43011. vy = viewport->getViewPositionY();
  43012. }
  43013. else
  43014. {
  43015. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43016. const int curH = roundToInt (cursorHeight);
  43017. if (desiredCaretY < 0)
  43018. {
  43019. vy = jmax (0, desiredCaretY + vy);
  43020. }
  43021. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43022. {
  43023. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43024. }
  43025. }
  43026. viewport->setViewPosition (vx, vy);
  43027. }
  43028. const Rectangle<int> TextEditor::getCaretRectangle()
  43029. {
  43030. updateCaretPosition();
  43031. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43032. roundToInt (cursorY) - viewport->getY(),
  43033. 1, roundToInt (cursorHeight));
  43034. }
  43035. float TextEditor::getWordWrapWidth() const
  43036. {
  43037. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43038. : 1.0e10f;
  43039. }
  43040. void TextEditor::updateTextHolderSize()
  43041. {
  43042. const float wordWrapWidth = getWordWrapWidth();
  43043. if (wordWrapWidth > 0)
  43044. {
  43045. float maxWidth = 0.0f;
  43046. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43047. while (i.next())
  43048. maxWidth = jmax (maxWidth, i.atomRight);
  43049. const int w = leftIndent + roundToInt (maxWidth);
  43050. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43051. currentFont.getHeight()));
  43052. textHolder->setSize (w + 1, h + 1);
  43053. }
  43054. }
  43055. int TextEditor::getTextWidth() const
  43056. {
  43057. return textHolder->getWidth();
  43058. }
  43059. int TextEditor::getTextHeight() const
  43060. {
  43061. return textHolder->getHeight();
  43062. }
  43063. void TextEditor::setIndents (const int newLeftIndent,
  43064. const int newTopIndent)
  43065. {
  43066. leftIndent = newLeftIndent;
  43067. topIndent = newTopIndent;
  43068. }
  43069. void TextEditor::setBorder (const BorderSize& border)
  43070. {
  43071. borderSize = border;
  43072. resized();
  43073. }
  43074. const BorderSize TextEditor::getBorder() const
  43075. {
  43076. return borderSize;
  43077. }
  43078. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43079. {
  43080. keepCursorOnScreen = shouldScrollToShowCursor;
  43081. }
  43082. void TextEditor::updateCaretPosition()
  43083. {
  43084. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43085. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43086. }
  43087. void TextEditor::scrollToMakeSureCursorIsVisible()
  43088. {
  43089. updateCaretPosition();
  43090. if (keepCursorOnScreen)
  43091. {
  43092. int x = viewport->getViewPositionX();
  43093. int y = viewport->getViewPositionY();
  43094. const int relativeCursorX = roundToInt (cursorX) - x;
  43095. const int relativeCursorY = roundToInt (cursorY) - y;
  43096. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43097. {
  43098. x += relativeCursorX - proportionOfWidth (0.2f);
  43099. }
  43100. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43101. {
  43102. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43103. }
  43104. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43105. if (! isMultiLine())
  43106. {
  43107. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43108. }
  43109. else
  43110. {
  43111. const int curH = roundToInt (cursorHeight);
  43112. if (relativeCursorY < 0)
  43113. {
  43114. y = jmax (0, relativeCursorY + y);
  43115. }
  43116. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43117. {
  43118. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43119. }
  43120. }
  43121. viewport->setViewPosition (x, y);
  43122. }
  43123. }
  43124. void TextEditor::moveCursorTo (const int newPosition,
  43125. const bool isSelecting)
  43126. {
  43127. if (isSelecting)
  43128. {
  43129. moveCaret (newPosition);
  43130. const Range<int> oldSelection (selection);
  43131. if (dragType == notDragging)
  43132. {
  43133. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43134. dragType = draggingSelectionStart;
  43135. else
  43136. dragType = draggingSelectionEnd;
  43137. }
  43138. if (dragType == draggingSelectionStart)
  43139. {
  43140. if (getCaretPosition() >= selection.getEnd())
  43141. dragType = draggingSelectionEnd;
  43142. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43143. }
  43144. else
  43145. {
  43146. if (getCaretPosition() < selection.getStart())
  43147. dragType = draggingSelectionStart;
  43148. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43149. }
  43150. repaintText (selection.getUnionWith (oldSelection));
  43151. }
  43152. else
  43153. {
  43154. dragType = notDragging;
  43155. repaintText (selection);
  43156. moveCaret (newPosition);
  43157. selection = Range<int>::emptyRange (getCaretPosition());
  43158. }
  43159. }
  43160. int TextEditor::getTextIndexAt (const int x,
  43161. const int y)
  43162. {
  43163. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43164. (float) (y + viewport->getViewPositionY() - topIndent));
  43165. }
  43166. void TextEditor::insertTextAtCaret (const String& newText_)
  43167. {
  43168. String newText (newText_);
  43169. if (allowedCharacters.isNotEmpty())
  43170. newText = newText.retainCharacters (allowedCharacters);
  43171. if (! isMultiLine())
  43172. newText = newText.replaceCharacters ("\r\n", " ");
  43173. else
  43174. newText = newText.replace ("\r\n", "\n");
  43175. const int newCaretPos = selection.getStart() + newText.length();
  43176. const int insertIndex = selection.getStart();
  43177. remove (selection, getUndoManager(),
  43178. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43179. if (maxTextLength > 0)
  43180. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43181. if (newText.isNotEmpty())
  43182. insert (newText,
  43183. insertIndex,
  43184. currentFont,
  43185. findColour (textColourId),
  43186. getUndoManager(),
  43187. newCaretPos);
  43188. textChanged();
  43189. }
  43190. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43191. {
  43192. moveCursorTo (newSelection.getStart(), false);
  43193. moveCursorTo (newSelection.getEnd(), true);
  43194. }
  43195. void TextEditor::copy()
  43196. {
  43197. if (passwordCharacter == 0)
  43198. {
  43199. const String selectedText (getHighlightedText());
  43200. if (selectedText.isNotEmpty())
  43201. SystemClipboard::copyTextToClipboard (selectedText);
  43202. }
  43203. }
  43204. void TextEditor::paste()
  43205. {
  43206. if (! isReadOnly())
  43207. {
  43208. const String clip (SystemClipboard::getTextFromClipboard());
  43209. if (clip.isNotEmpty())
  43210. insertTextAtCaret (clip);
  43211. }
  43212. }
  43213. void TextEditor::cut()
  43214. {
  43215. if (! isReadOnly())
  43216. {
  43217. moveCaret (selection.getEnd());
  43218. insertTextAtCaret (String::empty);
  43219. }
  43220. }
  43221. void TextEditor::drawContent (Graphics& g)
  43222. {
  43223. const float wordWrapWidth = getWordWrapWidth();
  43224. if (wordWrapWidth > 0)
  43225. {
  43226. g.setOrigin (leftIndent, topIndent);
  43227. const Rectangle<int> clip (g.getClipBounds());
  43228. Colour selectedTextColour;
  43229. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43230. while (i.lineY + 200.0 < clip.getY() && i.next())
  43231. {}
  43232. if (! selection.isEmpty())
  43233. {
  43234. g.setColour (findColour (highlightColourId)
  43235. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43236. selectedTextColour = findColour (highlightedTextColourId);
  43237. Iterator i2 (i);
  43238. while (i2.next() && i2.lineY < clip.getBottom())
  43239. {
  43240. if (i2.lineY + i2.lineHeight >= clip.getY()
  43241. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43242. {
  43243. i2.drawSelection (g, selection);
  43244. }
  43245. }
  43246. }
  43247. const UniformTextSection* lastSection = 0;
  43248. while (i.next() && i.lineY < clip.getBottom())
  43249. {
  43250. if (i.lineY + i.lineHeight >= clip.getY())
  43251. {
  43252. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43253. {
  43254. i.drawSelectedText (g, selection, selectedTextColour);
  43255. lastSection = 0;
  43256. }
  43257. else
  43258. {
  43259. i.draw (g, lastSection);
  43260. }
  43261. }
  43262. }
  43263. }
  43264. }
  43265. void TextEditor::paint (Graphics& g)
  43266. {
  43267. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43268. }
  43269. void TextEditor::paintOverChildren (Graphics& g)
  43270. {
  43271. if (caretFlashState
  43272. && hasKeyboardFocus (false)
  43273. && caretVisible
  43274. && ! isReadOnly())
  43275. {
  43276. g.setColour (findColour (caretColourId));
  43277. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43278. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43279. 2.0f, cursorHeight);
  43280. }
  43281. if (textToShowWhenEmpty.isNotEmpty()
  43282. && (! hasKeyboardFocus (false))
  43283. && getTotalNumChars() == 0)
  43284. {
  43285. g.setColour (colourForTextWhenEmpty);
  43286. g.setFont (getFont());
  43287. if (isMultiLine())
  43288. {
  43289. g.drawText (textToShowWhenEmpty,
  43290. 0, 0, getWidth(), getHeight(),
  43291. Justification::centred, true);
  43292. }
  43293. else
  43294. {
  43295. g.drawText (textToShowWhenEmpty,
  43296. leftIndent, topIndent,
  43297. viewport->getWidth() - leftIndent,
  43298. viewport->getHeight() - topIndent,
  43299. Justification::centredLeft, true);
  43300. }
  43301. }
  43302. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43303. }
  43304. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43305. {
  43306. public:
  43307. TextEditorMenuPerformer (TextEditor* const editor_)
  43308. : editor (editor_)
  43309. {
  43310. }
  43311. void modalStateFinished (int returnValue)
  43312. {
  43313. if (editor != 0 && returnValue != 0)
  43314. editor->performPopupMenuAction (returnValue);
  43315. }
  43316. private:
  43317. Component::SafePointer<TextEditor> editor;
  43318. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43319. };
  43320. void TextEditor::mouseDown (const MouseEvent& e)
  43321. {
  43322. beginDragAutoRepeat (100);
  43323. newTransaction();
  43324. if (wasFocused || ! selectAllTextWhenFocused)
  43325. {
  43326. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43327. {
  43328. moveCursorTo (getTextIndexAt (e.x, e.y),
  43329. e.mods.isShiftDown());
  43330. }
  43331. else
  43332. {
  43333. PopupMenu m;
  43334. m.setLookAndFeel (&getLookAndFeel());
  43335. addPopupMenuItems (m, &e);
  43336. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43337. }
  43338. }
  43339. }
  43340. void TextEditor::mouseDrag (const MouseEvent& e)
  43341. {
  43342. if (wasFocused || ! selectAllTextWhenFocused)
  43343. {
  43344. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43345. {
  43346. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43347. }
  43348. }
  43349. }
  43350. void TextEditor::mouseUp (const MouseEvent& e)
  43351. {
  43352. newTransaction();
  43353. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43354. if (wasFocused || ! selectAllTextWhenFocused)
  43355. {
  43356. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43357. {
  43358. moveCaret (getTextIndexAt (e.x, e.y));
  43359. }
  43360. }
  43361. wasFocused = true;
  43362. }
  43363. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43364. {
  43365. int tokenEnd = getTextIndexAt (e.x, e.y);
  43366. int tokenStart = tokenEnd;
  43367. if (e.getNumberOfClicks() > 3)
  43368. {
  43369. tokenStart = 0;
  43370. tokenEnd = getTotalNumChars();
  43371. }
  43372. else
  43373. {
  43374. const String t (getText());
  43375. const int totalLength = getTotalNumChars();
  43376. while (tokenEnd < totalLength)
  43377. {
  43378. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43379. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43380. ++tokenEnd;
  43381. else
  43382. break;
  43383. }
  43384. tokenStart = tokenEnd;
  43385. while (tokenStart > 0)
  43386. {
  43387. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43388. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43389. --tokenStart;
  43390. else
  43391. break;
  43392. }
  43393. if (e.getNumberOfClicks() > 2)
  43394. {
  43395. while (tokenEnd < totalLength)
  43396. {
  43397. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43398. ++tokenEnd;
  43399. else
  43400. break;
  43401. }
  43402. while (tokenStart > 0)
  43403. {
  43404. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43405. --tokenStart;
  43406. else
  43407. break;
  43408. }
  43409. }
  43410. }
  43411. moveCursorTo (tokenEnd, false);
  43412. moveCursorTo (tokenStart, true);
  43413. }
  43414. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43415. {
  43416. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43417. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43418. }
  43419. bool TextEditor::keyPressed (const KeyPress& key)
  43420. {
  43421. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43422. return false;
  43423. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43424. if (key.isKeyCode (KeyPress::leftKey)
  43425. || key.isKeyCode (KeyPress::upKey))
  43426. {
  43427. newTransaction();
  43428. int newPos;
  43429. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43430. newPos = indexAtPosition (cursorX, cursorY - 1);
  43431. else if (moveInWholeWordSteps)
  43432. newPos = findWordBreakBefore (getCaretPosition());
  43433. else
  43434. newPos = getCaretPosition() - 1;
  43435. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43436. }
  43437. else if (key.isKeyCode (KeyPress::rightKey)
  43438. || key.isKeyCode (KeyPress::downKey))
  43439. {
  43440. newTransaction();
  43441. int newPos;
  43442. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43443. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43444. else if (moveInWholeWordSteps)
  43445. newPos = findWordBreakAfter (getCaretPosition());
  43446. else
  43447. newPos = getCaretPosition() + 1;
  43448. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43449. }
  43450. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43451. {
  43452. newTransaction();
  43453. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43454. key.getModifiers().isShiftDown());
  43455. }
  43456. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43457. {
  43458. newTransaction();
  43459. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43460. key.getModifiers().isShiftDown());
  43461. }
  43462. else if (key.isKeyCode (KeyPress::homeKey))
  43463. {
  43464. newTransaction();
  43465. if (isMultiLine() && ! moveInWholeWordSteps)
  43466. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43467. key.getModifiers().isShiftDown());
  43468. else
  43469. moveCursorTo (0, key.getModifiers().isShiftDown());
  43470. }
  43471. else if (key.isKeyCode (KeyPress::endKey))
  43472. {
  43473. newTransaction();
  43474. if (isMultiLine() && ! moveInWholeWordSteps)
  43475. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43476. key.getModifiers().isShiftDown());
  43477. else
  43478. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43479. }
  43480. else if (key.isKeyCode (KeyPress::backspaceKey))
  43481. {
  43482. if (moveInWholeWordSteps)
  43483. {
  43484. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43485. }
  43486. else
  43487. {
  43488. if (selection.isEmpty() && selection.getStart() > 0)
  43489. selection.setStart (selection.getEnd() - 1);
  43490. }
  43491. cut();
  43492. }
  43493. else if (key.isKeyCode (KeyPress::deleteKey))
  43494. {
  43495. if (key.getModifiers().isShiftDown())
  43496. copy();
  43497. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43498. selection.setEnd (selection.getStart() + 1);
  43499. cut();
  43500. }
  43501. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43502. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43503. {
  43504. newTransaction();
  43505. copy();
  43506. }
  43507. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43508. {
  43509. newTransaction();
  43510. copy();
  43511. cut();
  43512. }
  43513. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43514. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43515. {
  43516. newTransaction();
  43517. paste();
  43518. }
  43519. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43520. {
  43521. newTransaction();
  43522. doUndoRedo (false);
  43523. }
  43524. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43525. {
  43526. newTransaction();
  43527. doUndoRedo (true);
  43528. }
  43529. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43530. {
  43531. newTransaction();
  43532. moveCursorTo (getTotalNumChars(), false);
  43533. moveCursorTo (0, true);
  43534. }
  43535. else if (key == KeyPress::returnKey)
  43536. {
  43537. newTransaction();
  43538. if (returnKeyStartsNewLine)
  43539. insertTextAtCaret ("\n");
  43540. else
  43541. returnPressed();
  43542. }
  43543. else if (key.isKeyCode (KeyPress::escapeKey))
  43544. {
  43545. newTransaction();
  43546. moveCursorTo (getCaretPosition(), false);
  43547. escapePressed();
  43548. }
  43549. else if (key.getTextCharacter() >= ' '
  43550. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43551. {
  43552. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43553. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43554. }
  43555. else
  43556. {
  43557. return false;
  43558. }
  43559. return true;
  43560. }
  43561. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43562. {
  43563. if (! isKeyDown)
  43564. return false;
  43565. #if JUCE_WINDOWS
  43566. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43567. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43568. #endif
  43569. // (overridden to avoid forwarding key events to the parent)
  43570. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43571. }
  43572. const int baseMenuItemID = 0x7fff0000;
  43573. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43574. {
  43575. const bool writable = ! isReadOnly();
  43576. if (passwordCharacter == 0)
  43577. {
  43578. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43579. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43580. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43581. }
  43582. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43583. m.addSeparator();
  43584. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43585. m.addSeparator();
  43586. if (getUndoManager() != 0)
  43587. {
  43588. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43589. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43590. }
  43591. }
  43592. void TextEditor::performPopupMenuAction (const int menuItemID)
  43593. {
  43594. switch (menuItemID)
  43595. {
  43596. case baseMenuItemID + 1:
  43597. copy();
  43598. cut();
  43599. break;
  43600. case baseMenuItemID + 2:
  43601. copy();
  43602. break;
  43603. case baseMenuItemID + 3:
  43604. paste();
  43605. break;
  43606. case baseMenuItemID + 4:
  43607. cut();
  43608. break;
  43609. case baseMenuItemID + 5:
  43610. moveCursorTo (getTotalNumChars(), false);
  43611. moveCursorTo (0, true);
  43612. break;
  43613. case baseMenuItemID + 6:
  43614. doUndoRedo (false);
  43615. break;
  43616. case baseMenuItemID + 7:
  43617. doUndoRedo (true);
  43618. break;
  43619. default:
  43620. break;
  43621. }
  43622. }
  43623. void TextEditor::focusGained (FocusChangeType)
  43624. {
  43625. newTransaction();
  43626. caretFlashState = true;
  43627. if (selectAllTextWhenFocused)
  43628. {
  43629. moveCursorTo (0, false);
  43630. moveCursorTo (getTotalNumChars(), true);
  43631. }
  43632. repaint();
  43633. if (caretVisible)
  43634. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43635. ComponentPeer* const peer = getPeer();
  43636. if (peer != 0 && ! isReadOnly())
  43637. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43638. }
  43639. void TextEditor::focusLost (FocusChangeType)
  43640. {
  43641. newTransaction();
  43642. wasFocused = false;
  43643. textHolder->stopTimer();
  43644. caretFlashState = false;
  43645. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43646. repaint();
  43647. }
  43648. void TextEditor::resized()
  43649. {
  43650. viewport->setBoundsInset (borderSize);
  43651. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43652. updateTextHolderSize();
  43653. if (! isMultiLine())
  43654. {
  43655. scrollToMakeSureCursorIsVisible();
  43656. }
  43657. else
  43658. {
  43659. updateCaretPosition();
  43660. }
  43661. }
  43662. void TextEditor::handleCommandMessage (const int commandId)
  43663. {
  43664. Component::BailOutChecker checker (this);
  43665. switch (commandId)
  43666. {
  43667. case TextEditorDefs::textChangeMessageId:
  43668. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43669. break;
  43670. case TextEditorDefs::returnKeyMessageId:
  43671. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43672. break;
  43673. case TextEditorDefs::escapeKeyMessageId:
  43674. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43675. break;
  43676. case TextEditorDefs::focusLossMessageId:
  43677. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43678. break;
  43679. default:
  43680. jassertfalse;
  43681. break;
  43682. }
  43683. }
  43684. void TextEditor::enablementChanged()
  43685. {
  43686. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43687. : MouseCursor::IBeamCursor);
  43688. repaint();
  43689. }
  43690. UndoManager* TextEditor::getUndoManager() throw()
  43691. {
  43692. return isReadOnly() ? 0 : &undoManager;
  43693. }
  43694. void TextEditor::clearInternal (UndoManager* const um)
  43695. {
  43696. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43697. }
  43698. void TextEditor::insert (const String& text,
  43699. const int insertIndex,
  43700. const Font& font,
  43701. const Colour& colour,
  43702. UndoManager* const um,
  43703. const int caretPositionToMoveTo)
  43704. {
  43705. if (text.isNotEmpty())
  43706. {
  43707. if (um != 0)
  43708. {
  43709. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43710. newTransaction();
  43711. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43712. caretPosition, caretPositionToMoveTo));
  43713. }
  43714. else
  43715. {
  43716. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43717. // a line gets moved due to word wrap
  43718. int index = 0;
  43719. int nextIndex = 0;
  43720. for (int i = 0; i < sections.size(); ++i)
  43721. {
  43722. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43723. if (insertIndex == index)
  43724. {
  43725. sections.insert (i, new UniformTextSection (text,
  43726. font, colour,
  43727. passwordCharacter));
  43728. break;
  43729. }
  43730. else if (insertIndex > index && insertIndex < nextIndex)
  43731. {
  43732. splitSection (i, insertIndex - index);
  43733. sections.insert (i + 1, new UniformTextSection (text,
  43734. font, colour,
  43735. passwordCharacter));
  43736. break;
  43737. }
  43738. index = nextIndex;
  43739. }
  43740. if (nextIndex == insertIndex)
  43741. sections.add (new UniformTextSection (text,
  43742. font, colour,
  43743. passwordCharacter));
  43744. coalesceSimilarSections();
  43745. totalNumChars = -1;
  43746. valueTextNeedsUpdating = true;
  43747. moveCursorTo (caretPositionToMoveTo, false);
  43748. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43749. }
  43750. }
  43751. }
  43752. void TextEditor::reinsert (const int insertIndex,
  43753. const Array <UniformTextSection*>& sectionsToInsert)
  43754. {
  43755. int index = 0;
  43756. int nextIndex = 0;
  43757. for (int i = 0; i < sections.size(); ++i)
  43758. {
  43759. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43760. if (insertIndex == index)
  43761. {
  43762. for (int j = sectionsToInsert.size(); --j >= 0;)
  43763. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43764. break;
  43765. }
  43766. else if (insertIndex > index && insertIndex < nextIndex)
  43767. {
  43768. splitSection (i, insertIndex - index);
  43769. for (int j = sectionsToInsert.size(); --j >= 0;)
  43770. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43771. break;
  43772. }
  43773. index = nextIndex;
  43774. }
  43775. if (nextIndex == insertIndex)
  43776. {
  43777. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43778. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43779. }
  43780. coalesceSimilarSections();
  43781. totalNumChars = -1;
  43782. valueTextNeedsUpdating = true;
  43783. }
  43784. void TextEditor::remove (const Range<int>& range,
  43785. UndoManager* const um,
  43786. const int caretPositionToMoveTo)
  43787. {
  43788. if (! range.isEmpty())
  43789. {
  43790. int index = 0;
  43791. for (int i = 0; i < sections.size(); ++i)
  43792. {
  43793. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43794. if (range.getStart() > index && range.getStart() < nextIndex)
  43795. {
  43796. splitSection (i, range.getStart() - index);
  43797. --i;
  43798. }
  43799. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43800. {
  43801. splitSection (i, range.getEnd() - index);
  43802. --i;
  43803. }
  43804. else
  43805. {
  43806. index = nextIndex;
  43807. if (index > range.getEnd())
  43808. break;
  43809. }
  43810. }
  43811. index = 0;
  43812. if (um != 0)
  43813. {
  43814. Array <UniformTextSection*> removedSections;
  43815. for (int i = 0; i < sections.size(); ++i)
  43816. {
  43817. if (range.getEnd() <= range.getStart())
  43818. break;
  43819. UniformTextSection* const section = sections.getUnchecked (i);
  43820. const int nextIndex = index + section->getTotalLength();
  43821. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43822. removedSections.add (new UniformTextSection (*section));
  43823. index = nextIndex;
  43824. }
  43825. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43826. newTransaction();
  43827. um->perform (new RemoveAction (*this, range, caretPosition,
  43828. caretPositionToMoveTo, removedSections));
  43829. }
  43830. else
  43831. {
  43832. Range<int> remainingRange (range);
  43833. for (int i = 0; i < sections.size(); ++i)
  43834. {
  43835. UniformTextSection* const section = sections.getUnchecked (i);
  43836. const int nextIndex = index + section->getTotalLength();
  43837. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43838. {
  43839. sections.remove(i);
  43840. section->clear();
  43841. delete section;
  43842. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43843. if (remainingRange.isEmpty())
  43844. break;
  43845. --i;
  43846. }
  43847. else
  43848. {
  43849. index = nextIndex;
  43850. }
  43851. }
  43852. coalesceSimilarSections();
  43853. totalNumChars = -1;
  43854. valueTextNeedsUpdating = true;
  43855. moveCursorTo (caretPositionToMoveTo, false);
  43856. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43857. }
  43858. }
  43859. }
  43860. const String TextEditor::getText() const
  43861. {
  43862. String t;
  43863. t.preallocateStorage (getTotalNumChars());
  43864. String::Concatenator concatenator (t);
  43865. for (int i = 0; i < sections.size(); ++i)
  43866. sections.getUnchecked (i)->appendAllText (concatenator);
  43867. return t;
  43868. }
  43869. const String TextEditor::getTextInRange (const Range<int>& range) const
  43870. {
  43871. String t;
  43872. if (! range.isEmpty())
  43873. {
  43874. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43875. String::Concatenator concatenator (t);
  43876. int index = 0;
  43877. for (int i = 0; i < sections.size(); ++i)
  43878. {
  43879. const UniformTextSection* const s = sections.getUnchecked (i);
  43880. const int nextIndex = index + s->getTotalLength();
  43881. if (range.getStart() < nextIndex)
  43882. {
  43883. if (range.getEnd() <= index)
  43884. break;
  43885. s->appendSubstring (concatenator, range - index);
  43886. }
  43887. index = nextIndex;
  43888. }
  43889. }
  43890. return t;
  43891. }
  43892. const String TextEditor::getHighlightedText() const
  43893. {
  43894. return getTextInRange (selection);
  43895. }
  43896. int TextEditor::getTotalNumChars() const
  43897. {
  43898. if (totalNumChars < 0)
  43899. {
  43900. totalNumChars = 0;
  43901. for (int i = sections.size(); --i >= 0;)
  43902. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43903. }
  43904. return totalNumChars;
  43905. }
  43906. bool TextEditor::isEmpty() const
  43907. {
  43908. return getTotalNumChars() == 0;
  43909. }
  43910. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43911. {
  43912. const float wordWrapWidth = getWordWrapWidth();
  43913. if (wordWrapWidth > 0 && sections.size() > 0)
  43914. {
  43915. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43916. i.getCharPosition (index, cx, cy, lineHeight);
  43917. }
  43918. else
  43919. {
  43920. cx = cy = 0;
  43921. lineHeight = currentFont.getHeight();
  43922. }
  43923. }
  43924. int TextEditor::indexAtPosition (const float x, const float y)
  43925. {
  43926. const float wordWrapWidth = getWordWrapWidth();
  43927. if (wordWrapWidth > 0)
  43928. {
  43929. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43930. while (i.next())
  43931. {
  43932. if (i.lineY + i.lineHeight > y)
  43933. {
  43934. if (i.lineY > y)
  43935. return jmax (0, i.indexInText - 1);
  43936. if (i.atomX >= x)
  43937. return i.indexInText;
  43938. if (x < i.atomRight)
  43939. return i.xToIndex (x);
  43940. }
  43941. }
  43942. }
  43943. return getTotalNumChars();
  43944. }
  43945. int TextEditor::findWordBreakAfter (const int position) const
  43946. {
  43947. const String t (getTextInRange (Range<int> (position, position + 512)));
  43948. const int totalLength = t.length();
  43949. int i = 0;
  43950. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43951. ++i;
  43952. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43953. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43954. ++i;
  43955. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43956. ++i;
  43957. return position + i;
  43958. }
  43959. int TextEditor::findWordBreakBefore (const int position) const
  43960. {
  43961. if (position <= 0)
  43962. return 0;
  43963. const int startOfBuffer = jmax (0, position - 512);
  43964. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43965. int i = position - startOfBuffer;
  43966. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43967. --i;
  43968. if (i > 0)
  43969. {
  43970. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43971. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43972. --i;
  43973. }
  43974. jassert (startOfBuffer + i >= 0);
  43975. return startOfBuffer + i;
  43976. }
  43977. void TextEditor::splitSection (const int sectionIndex,
  43978. const int charToSplitAt)
  43979. {
  43980. jassert (sections[sectionIndex] != 0);
  43981. sections.insert (sectionIndex + 1,
  43982. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43983. }
  43984. void TextEditor::coalesceSimilarSections()
  43985. {
  43986. for (int i = 0; i < sections.size() - 1; ++i)
  43987. {
  43988. UniformTextSection* const s1 = sections.getUnchecked (i);
  43989. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43990. if (s1->font == s2->font
  43991. && s1->colour == s2->colour)
  43992. {
  43993. s1->append (*s2, passwordCharacter);
  43994. sections.remove (i + 1);
  43995. delete s2;
  43996. --i;
  43997. }
  43998. }
  43999. }
  44000. END_JUCE_NAMESPACE
  44001. /*** End of inlined file: juce_TextEditor.cpp ***/
  44002. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44003. BEGIN_JUCE_NAMESPACE
  44004. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44005. class ToolbarSpacerComp : public ToolbarItemComponent
  44006. {
  44007. public:
  44008. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44009. : ToolbarItemComponent (itemId_, String::empty, false),
  44010. fixedSize (fixedSize_),
  44011. drawBar (drawBar_)
  44012. {
  44013. }
  44014. ~ToolbarSpacerComp()
  44015. {
  44016. }
  44017. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44018. int& preferredSize, int& minSize, int& maxSize)
  44019. {
  44020. if (fixedSize <= 0)
  44021. {
  44022. preferredSize = toolbarThickness * 2;
  44023. minSize = 4;
  44024. maxSize = 32768;
  44025. }
  44026. else
  44027. {
  44028. maxSize = roundToInt (toolbarThickness * fixedSize);
  44029. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44030. preferredSize = maxSize;
  44031. if (getEditingMode() == editableOnPalette)
  44032. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44033. }
  44034. return true;
  44035. }
  44036. void paintButtonArea (Graphics&, int, int, bool, bool)
  44037. {
  44038. }
  44039. void contentAreaChanged (const Rectangle<int>&)
  44040. {
  44041. }
  44042. int getResizeOrder() const throw()
  44043. {
  44044. return fixedSize <= 0 ? 0 : 1;
  44045. }
  44046. void paint (Graphics& g)
  44047. {
  44048. const int w = getWidth();
  44049. const int h = getHeight();
  44050. if (drawBar)
  44051. {
  44052. g.setColour (findColour (Toolbar::separatorColourId, true));
  44053. const float thickness = 0.2f;
  44054. if (isToolbarVertical())
  44055. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44056. else
  44057. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44058. }
  44059. if (getEditingMode() != normalMode && ! drawBar)
  44060. {
  44061. g.setColour (findColour (Toolbar::separatorColourId, true));
  44062. const int indentX = jmin (2, (w - 3) / 2);
  44063. const int indentY = jmin (2, (h - 3) / 2);
  44064. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44065. if (fixedSize <= 0)
  44066. {
  44067. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44068. if (isToolbarVertical())
  44069. {
  44070. x1 = w * 0.5f;
  44071. y1 = h * 0.4f;
  44072. x2 = x1;
  44073. y2 = indentX * 2.0f;
  44074. x3 = x1;
  44075. y3 = h * 0.6f;
  44076. x4 = x1;
  44077. y4 = h - y2;
  44078. hw = w * 0.15f;
  44079. hl = w * 0.2f;
  44080. }
  44081. else
  44082. {
  44083. x1 = w * 0.4f;
  44084. y1 = h * 0.5f;
  44085. x2 = indentX * 2.0f;
  44086. y2 = y1;
  44087. x3 = w * 0.6f;
  44088. y3 = y1;
  44089. x4 = w - x2;
  44090. y4 = y1;
  44091. hw = h * 0.15f;
  44092. hl = h * 0.2f;
  44093. }
  44094. Path p;
  44095. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44096. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44097. g.fillPath (p);
  44098. }
  44099. }
  44100. }
  44101. private:
  44102. const float fixedSize;
  44103. const bool drawBar;
  44104. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  44105. };
  44106. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  44107. {
  44108. public:
  44109. MissingItemsComponent (Toolbar& owner_, const int height_)
  44110. : PopupMenu::CustomComponent (true),
  44111. owner (&owner_),
  44112. height (height_)
  44113. {
  44114. for (int i = owner_.items.size(); --i >= 0;)
  44115. {
  44116. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44117. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44118. {
  44119. oldIndexes.insert (0, i);
  44120. addAndMakeVisible (tc, 0);
  44121. }
  44122. }
  44123. layout (400);
  44124. }
  44125. ~MissingItemsComponent()
  44126. {
  44127. if (owner != 0)
  44128. {
  44129. for (int i = 0; i < getNumChildComponents(); ++i)
  44130. {
  44131. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44132. if (tc != 0)
  44133. {
  44134. tc->setVisible (false);
  44135. const int index = oldIndexes.remove (i);
  44136. owner->addChildComponent (tc, index);
  44137. --i;
  44138. }
  44139. }
  44140. owner->resized();
  44141. }
  44142. }
  44143. void layout (const int preferredWidth)
  44144. {
  44145. const int indent = 8;
  44146. int x = indent;
  44147. int y = indent;
  44148. int maxX = 0;
  44149. for (int i = 0; i < getNumChildComponents(); ++i)
  44150. {
  44151. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44152. if (tc != 0)
  44153. {
  44154. int preferredSize = 1, minSize = 1, maxSize = 1;
  44155. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44156. {
  44157. if (x + preferredSize > preferredWidth && x > indent)
  44158. {
  44159. x = indent;
  44160. y += height;
  44161. }
  44162. tc->setBounds (x, y, preferredSize, height);
  44163. x += preferredSize;
  44164. maxX = jmax (maxX, x);
  44165. }
  44166. }
  44167. }
  44168. setSize (maxX + 8, y + height + 8);
  44169. }
  44170. void getIdealSize (int& idealWidth, int& idealHeight)
  44171. {
  44172. idealWidth = getWidth();
  44173. idealHeight = getHeight();
  44174. }
  44175. private:
  44176. Component::SafePointer<Toolbar> owner;
  44177. const int height;
  44178. Array <int> oldIndexes;
  44179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44180. };
  44181. Toolbar::Toolbar()
  44182. : vertical (false),
  44183. isEditingActive (false),
  44184. toolbarStyle (Toolbar::iconsOnly)
  44185. {
  44186. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44187. missingItemsButton->setAlwaysOnTop (true);
  44188. missingItemsButton->addListener (this);
  44189. }
  44190. Toolbar::~Toolbar()
  44191. {
  44192. items.clear();
  44193. }
  44194. void Toolbar::setVertical (const bool shouldBeVertical)
  44195. {
  44196. if (vertical != shouldBeVertical)
  44197. {
  44198. vertical = shouldBeVertical;
  44199. resized();
  44200. }
  44201. }
  44202. void Toolbar::clear()
  44203. {
  44204. items.clear();
  44205. resized();
  44206. }
  44207. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44208. {
  44209. if (itemId == ToolbarItemFactory::separatorBarId)
  44210. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44211. else if (itemId == ToolbarItemFactory::spacerId)
  44212. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44213. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44214. return new ToolbarSpacerComp (itemId, 0, false);
  44215. return factory.createItem (itemId);
  44216. }
  44217. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44218. const int itemId,
  44219. const int insertIndex)
  44220. {
  44221. // An ID can't be zero - this might indicate a mistake somewhere?
  44222. jassert (itemId != 0);
  44223. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44224. if (tc != 0)
  44225. {
  44226. #if JUCE_DEBUG
  44227. Array <int> allowedIds;
  44228. factory.getAllToolbarItemIds (allowedIds);
  44229. // If your factory can create an item for a given ID, it must also return
  44230. // that ID from its getAllToolbarItemIds() method!
  44231. jassert (allowedIds.contains (itemId));
  44232. #endif
  44233. items.insert (insertIndex, tc);
  44234. addAndMakeVisible (tc, insertIndex);
  44235. }
  44236. }
  44237. void Toolbar::addItem (ToolbarItemFactory& factory,
  44238. const int itemId,
  44239. const int insertIndex)
  44240. {
  44241. addItemInternal (factory, itemId, insertIndex);
  44242. resized();
  44243. }
  44244. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44245. {
  44246. Array <int> ids;
  44247. factoryToUse.getDefaultItemSet (ids);
  44248. clear();
  44249. for (int i = 0; i < ids.size(); ++i)
  44250. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44251. resized();
  44252. }
  44253. void Toolbar::removeToolbarItem (const int itemIndex)
  44254. {
  44255. items.remove (itemIndex);
  44256. resized();
  44257. }
  44258. int Toolbar::getNumItems() const throw()
  44259. {
  44260. return items.size();
  44261. }
  44262. int Toolbar::getItemId (const int itemIndex) const throw()
  44263. {
  44264. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44265. return tc != 0 ? tc->getItemId() : 0;
  44266. }
  44267. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44268. {
  44269. return items [itemIndex];
  44270. }
  44271. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44272. {
  44273. for (;;)
  44274. {
  44275. index += delta;
  44276. ToolbarItemComponent* const tc = getItemComponent (index);
  44277. if (tc == 0)
  44278. break;
  44279. if (tc->isActive)
  44280. return tc;
  44281. }
  44282. return 0;
  44283. }
  44284. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44285. {
  44286. if (toolbarStyle != newStyle)
  44287. {
  44288. toolbarStyle = newStyle;
  44289. updateAllItemPositions (false);
  44290. }
  44291. }
  44292. const String Toolbar::toString() const
  44293. {
  44294. String s ("TB:");
  44295. for (int i = 0; i < getNumItems(); ++i)
  44296. s << getItemId(i) << ' ';
  44297. return s.trimEnd();
  44298. }
  44299. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44300. const String& savedVersion)
  44301. {
  44302. if (! savedVersion.startsWith ("TB:"))
  44303. return false;
  44304. StringArray tokens;
  44305. tokens.addTokens (savedVersion.substring (3), false);
  44306. clear();
  44307. for (int i = 0; i < tokens.size(); ++i)
  44308. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44309. resized();
  44310. return true;
  44311. }
  44312. void Toolbar::paint (Graphics& g)
  44313. {
  44314. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44315. }
  44316. int Toolbar::getThickness() const throw()
  44317. {
  44318. return vertical ? getWidth() : getHeight();
  44319. }
  44320. int Toolbar::getLength() const throw()
  44321. {
  44322. return vertical ? getHeight() : getWidth();
  44323. }
  44324. void Toolbar::setEditingActive (const bool active)
  44325. {
  44326. if (isEditingActive != active)
  44327. {
  44328. isEditingActive = active;
  44329. updateAllItemPositions (false);
  44330. }
  44331. }
  44332. void Toolbar::resized()
  44333. {
  44334. updateAllItemPositions (false);
  44335. }
  44336. void Toolbar::updateAllItemPositions (const bool animate)
  44337. {
  44338. if (getWidth() > 0 && getHeight() > 0)
  44339. {
  44340. StretchableObjectResizer resizer;
  44341. int i;
  44342. for (i = 0; i < items.size(); ++i)
  44343. {
  44344. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44345. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44346. : ToolbarItemComponent::normalMode);
  44347. tc->setStyle (toolbarStyle);
  44348. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44349. int preferredSize = 1, minSize = 1, maxSize = 1;
  44350. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44351. preferredSize, minSize, maxSize))
  44352. {
  44353. tc->isActive = true;
  44354. resizer.addItem (preferredSize, minSize, maxSize,
  44355. spacer != 0 ? spacer->getResizeOrder() : 2);
  44356. }
  44357. else
  44358. {
  44359. tc->isActive = false;
  44360. tc->setVisible (false);
  44361. }
  44362. }
  44363. resizer.resizeToFit (getLength());
  44364. int totalLength = 0;
  44365. for (i = 0; i < resizer.getNumItems(); ++i)
  44366. totalLength += (int) resizer.getItemSize (i);
  44367. const bool itemsOffTheEnd = totalLength > getLength();
  44368. const int extrasButtonSize = getThickness() / 2;
  44369. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44370. missingItemsButton->setVisible (itemsOffTheEnd);
  44371. missingItemsButton->setEnabled (! isEditingActive);
  44372. if (vertical)
  44373. missingItemsButton->setCentrePosition (getWidth() / 2,
  44374. getHeight() - 4 - extrasButtonSize / 2);
  44375. else
  44376. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44377. getHeight() / 2);
  44378. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44379. : missingItemsButton->getX()) - 4
  44380. : getLength();
  44381. int pos = 0, activeIndex = 0;
  44382. for (i = 0; i < items.size(); ++i)
  44383. {
  44384. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44385. if (tc->isActive)
  44386. {
  44387. const int size = (int) resizer.getItemSize (activeIndex++);
  44388. Rectangle<int> newBounds;
  44389. if (vertical)
  44390. newBounds.setBounds (0, pos, getWidth(), size);
  44391. else
  44392. newBounds.setBounds (pos, 0, size, getHeight());
  44393. if (animate)
  44394. {
  44395. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44396. }
  44397. else
  44398. {
  44399. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44400. tc->setBounds (newBounds);
  44401. }
  44402. pos += size;
  44403. tc->setVisible (pos <= maxLength
  44404. && ((! tc->isBeingDragged)
  44405. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44406. }
  44407. }
  44408. }
  44409. }
  44410. void Toolbar::buttonClicked (Button*)
  44411. {
  44412. jassert (missingItemsButton->isShowing());
  44413. if (missingItemsButton->isShowing())
  44414. {
  44415. PopupMenu m;
  44416. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44417. m.showAt (missingItemsButton);
  44418. }
  44419. }
  44420. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44421. Component* /*sourceComponent*/)
  44422. {
  44423. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44424. }
  44425. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44426. {
  44427. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44428. if (tc != 0)
  44429. {
  44430. if (! items.contains (tc))
  44431. {
  44432. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44433. {
  44434. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44435. if (palette != 0)
  44436. palette->replaceComponent (tc);
  44437. }
  44438. else
  44439. {
  44440. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44441. }
  44442. items.add (tc);
  44443. addChildComponent (tc);
  44444. updateAllItemPositions (true);
  44445. }
  44446. for (int i = getNumItems(); --i >= 0;)
  44447. {
  44448. const int currentIndex = items.indexOf (tc);
  44449. int newIndex = currentIndex;
  44450. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44451. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44452. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44453. .getComponentDestination (getChildComponent (newIndex)));
  44454. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44455. if (prev != 0)
  44456. {
  44457. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44458. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44459. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44460. {
  44461. newIndex = getIndexOfChildComponent (prev);
  44462. }
  44463. }
  44464. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44465. if (next != 0)
  44466. {
  44467. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44468. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44469. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44470. {
  44471. newIndex = getIndexOfChildComponent (next) + 1;
  44472. }
  44473. }
  44474. if (newIndex == currentIndex)
  44475. break;
  44476. items.removeObject (tc, false);
  44477. removeChildComponent (tc);
  44478. addChildComponent (tc, newIndex);
  44479. items.insert (newIndex, tc);
  44480. updateAllItemPositions (true);
  44481. }
  44482. }
  44483. }
  44484. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44485. {
  44486. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44487. if (tc != 0 && isParentOf (tc))
  44488. {
  44489. items.removeObject (tc, false);
  44490. removeChildComponent (tc);
  44491. updateAllItemPositions (true);
  44492. }
  44493. }
  44494. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44495. {
  44496. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44497. if (tc != 0)
  44498. tc->setState (Button::buttonNormal);
  44499. }
  44500. void Toolbar::mouseDown (const MouseEvent&)
  44501. {
  44502. }
  44503. class ToolbarCustomisationDialog : public DialogWindow
  44504. {
  44505. public:
  44506. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44507. Toolbar* const toolbar_,
  44508. const int optionFlags)
  44509. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44510. toolbar (toolbar_)
  44511. {
  44512. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44513. setResizable (true, true);
  44514. setResizeLimits (400, 300, 1500, 1000);
  44515. positionNearBar();
  44516. }
  44517. ~ToolbarCustomisationDialog()
  44518. {
  44519. setContentComponent (0, true);
  44520. }
  44521. void closeButtonPressed()
  44522. {
  44523. setVisible (false);
  44524. }
  44525. bool canModalEventBeSentToComponent (const Component* comp)
  44526. {
  44527. return toolbar->isParentOf (comp);
  44528. }
  44529. void positionNearBar()
  44530. {
  44531. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44532. const int tbx = toolbar->getScreenX();
  44533. const int tby = toolbar->getScreenY();
  44534. const int gap = 8;
  44535. int x, y;
  44536. if (toolbar->isVertical())
  44537. {
  44538. y = tby;
  44539. if (tbx > screenSize.getCentreX())
  44540. x = tbx - getWidth() - gap;
  44541. else
  44542. x = tbx + toolbar->getWidth() + gap;
  44543. }
  44544. else
  44545. {
  44546. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44547. if (tby > screenSize.getCentreY())
  44548. y = tby - getHeight() - gap;
  44549. else
  44550. y = tby + toolbar->getHeight() + gap;
  44551. }
  44552. setTopLeftPosition (x, y);
  44553. }
  44554. private:
  44555. Toolbar* const toolbar;
  44556. class CustomiserPanel : public Component,
  44557. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44558. private ButtonListener
  44559. {
  44560. public:
  44561. CustomiserPanel (ToolbarItemFactory& factory_,
  44562. Toolbar* const toolbar_,
  44563. const int optionFlags)
  44564. : factory (factory_),
  44565. toolbar (toolbar_),
  44566. palette (factory_, toolbar_),
  44567. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44568. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44569. defaultButton (TRANS ("Restore to default set of items"))
  44570. {
  44571. addAndMakeVisible (&palette);
  44572. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44573. | Toolbar::allowIconsWithTextChoice
  44574. | Toolbar::allowTextOnlyChoice)) != 0)
  44575. {
  44576. addAndMakeVisible (&styleBox);
  44577. styleBox.setEditableText (false);
  44578. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44579. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44580. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44581. int selectedStyle = 0;
  44582. switch (toolbar_->getStyle())
  44583. {
  44584. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44585. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44586. case Toolbar::textOnly: selectedStyle = 3; break;
  44587. }
  44588. styleBox.setSelectedId (selectedStyle);
  44589. styleBox.addListener (this);
  44590. }
  44591. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44592. {
  44593. addAndMakeVisible (&defaultButton);
  44594. defaultButton.addListener (this);
  44595. }
  44596. addAndMakeVisible (&instructions);
  44597. instructions.setFont (Font (13.0f));
  44598. setSize (500, 300);
  44599. }
  44600. void comboBoxChanged (ComboBox*)
  44601. {
  44602. switch (styleBox.getSelectedId())
  44603. {
  44604. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44605. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44606. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44607. }
  44608. palette.resized(); // to make it update the styles
  44609. }
  44610. void buttonClicked (Button*)
  44611. {
  44612. toolbar->addDefaultItems (factory);
  44613. }
  44614. void paint (Graphics& g)
  44615. {
  44616. Colour background;
  44617. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44618. if (dw != 0)
  44619. background = dw->getBackgroundColour();
  44620. g.setColour (background.contrasting().withAlpha (0.3f));
  44621. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44622. }
  44623. void resized()
  44624. {
  44625. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44626. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44627. defaultButton.changeWidthToFitText (22);
  44628. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44629. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44630. }
  44631. private:
  44632. ToolbarItemFactory& factory;
  44633. Toolbar* const toolbar;
  44634. ToolbarItemPalette palette;
  44635. Label instructions;
  44636. ComboBox styleBox;
  44637. TextButton defaultButton;
  44638. };
  44639. };
  44640. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44641. {
  44642. setEditingActive (true);
  44643. #if JUCE_DEBUG
  44644. WeakReference<Component> checker (this);
  44645. #endif
  44646. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44647. dw.runModalLoop();
  44648. #if JUCE_DEBUG
  44649. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44650. #endif
  44651. setEditingActive (false);
  44652. }
  44653. END_JUCE_NAMESPACE
  44654. /*** End of inlined file: juce_Toolbar.cpp ***/
  44655. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44656. BEGIN_JUCE_NAMESPACE
  44657. ToolbarItemFactory::ToolbarItemFactory()
  44658. {
  44659. }
  44660. ToolbarItemFactory::~ToolbarItemFactory()
  44661. {
  44662. }
  44663. class ItemDragAndDropOverlayComponent : public Component
  44664. {
  44665. public:
  44666. ItemDragAndDropOverlayComponent()
  44667. : isDragging (false)
  44668. {
  44669. setAlwaysOnTop (true);
  44670. setRepaintsOnMouseActivity (true);
  44671. setMouseCursor (MouseCursor::DraggingHandCursor);
  44672. }
  44673. void paint (Graphics& g)
  44674. {
  44675. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44676. if (isMouseOverOrDragging()
  44677. && tc != 0
  44678. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44679. {
  44680. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44681. g.drawRect (0, 0, getWidth(), getHeight(),
  44682. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44683. }
  44684. }
  44685. void mouseDown (const MouseEvent& e)
  44686. {
  44687. isDragging = false;
  44688. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44689. if (tc != 0)
  44690. {
  44691. tc->dragOffsetX = e.x;
  44692. tc->dragOffsetY = e.y;
  44693. }
  44694. }
  44695. void mouseDrag (const MouseEvent& e)
  44696. {
  44697. if (! (isDragging || e.mouseWasClicked()))
  44698. {
  44699. isDragging = true;
  44700. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44701. if (dnd != 0)
  44702. {
  44703. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44704. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44705. if (tc != 0)
  44706. {
  44707. tc->isBeingDragged = true;
  44708. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44709. tc->setVisible (false);
  44710. }
  44711. }
  44712. }
  44713. }
  44714. void mouseUp (const MouseEvent&)
  44715. {
  44716. isDragging = false;
  44717. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44718. if (tc != 0)
  44719. {
  44720. tc->isBeingDragged = false;
  44721. Toolbar* const tb = tc->getToolbar();
  44722. if (tb != 0)
  44723. tb->updateAllItemPositions (true);
  44724. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44725. delete tc;
  44726. }
  44727. }
  44728. void parentSizeChanged()
  44729. {
  44730. setBounds (0, 0, getParentWidth(), getParentHeight());
  44731. }
  44732. private:
  44733. bool isDragging;
  44734. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44735. };
  44736. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44737. const String& labelText,
  44738. const bool isBeingUsedAsAButton_)
  44739. : Button (labelText),
  44740. itemId (itemId_),
  44741. mode (normalMode),
  44742. toolbarStyle (Toolbar::iconsOnly),
  44743. dragOffsetX (0),
  44744. dragOffsetY (0),
  44745. isActive (true),
  44746. isBeingDragged (false),
  44747. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44748. {
  44749. // Your item ID can't be 0!
  44750. jassert (itemId_ != 0);
  44751. }
  44752. ToolbarItemComponent::~ToolbarItemComponent()
  44753. {
  44754. overlayComp = 0;
  44755. }
  44756. Toolbar* ToolbarItemComponent::getToolbar() const
  44757. {
  44758. return dynamic_cast <Toolbar*> (getParentComponent());
  44759. }
  44760. bool ToolbarItemComponent::isToolbarVertical() const
  44761. {
  44762. const Toolbar* const t = getToolbar();
  44763. return t != 0 && t->isVertical();
  44764. }
  44765. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44766. {
  44767. if (toolbarStyle != newStyle)
  44768. {
  44769. toolbarStyle = newStyle;
  44770. repaint();
  44771. resized();
  44772. }
  44773. }
  44774. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44775. {
  44776. if (isBeingUsedAsAButton)
  44777. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44778. over, down, *this);
  44779. if (toolbarStyle != Toolbar::iconsOnly)
  44780. {
  44781. const int indent = contentArea.getX();
  44782. int y = indent;
  44783. int h = getHeight() - indent * 2;
  44784. if (toolbarStyle == Toolbar::iconsWithText)
  44785. {
  44786. y = contentArea.getBottom() + indent / 2;
  44787. h -= contentArea.getHeight();
  44788. }
  44789. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44790. getButtonText(), *this);
  44791. }
  44792. if (! contentArea.isEmpty())
  44793. {
  44794. Graphics::ScopedSaveState ss (g);
  44795. g.reduceClipRegion (contentArea);
  44796. g.setOrigin (contentArea.getX(), contentArea.getY());
  44797. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44798. }
  44799. }
  44800. void ToolbarItemComponent::resized()
  44801. {
  44802. if (toolbarStyle != Toolbar::textOnly)
  44803. {
  44804. const int indent = jmin (proportionOfWidth (0.08f),
  44805. proportionOfHeight (0.08f));
  44806. contentArea = Rectangle<int> (indent, indent,
  44807. getWidth() - indent * 2,
  44808. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44809. : (getHeight() - indent * 2));
  44810. }
  44811. else
  44812. {
  44813. contentArea = Rectangle<int>();
  44814. }
  44815. contentAreaChanged (contentArea);
  44816. }
  44817. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44818. {
  44819. if (mode != newMode)
  44820. {
  44821. mode = newMode;
  44822. repaint();
  44823. if (mode == normalMode)
  44824. {
  44825. overlayComp = 0;
  44826. }
  44827. else if (overlayComp == 0)
  44828. {
  44829. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44830. overlayComp->parentSizeChanged();
  44831. }
  44832. resized();
  44833. }
  44834. }
  44835. END_JUCE_NAMESPACE
  44836. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44837. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44838. BEGIN_JUCE_NAMESPACE
  44839. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44840. Toolbar* const toolbar_)
  44841. : factory (factory_),
  44842. toolbar (toolbar_)
  44843. {
  44844. Component* const itemHolder = new Component();
  44845. viewport.setViewedComponent (itemHolder);
  44846. Array <int> allIds;
  44847. factory.getAllToolbarItemIds (allIds);
  44848. for (int i = 0; i < allIds.size(); ++i)
  44849. addComponent (allIds.getUnchecked (i), -1);
  44850. addAndMakeVisible (&viewport);
  44851. }
  44852. ToolbarItemPalette::~ToolbarItemPalette()
  44853. {
  44854. }
  44855. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44856. {
  44857. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44858. jassert (tc != 0);
  44859. if (tc != 0)
  44860. {
  44861. items.insert (index, tc);
  44862. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44863. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44864. }
  44865. }
  44866. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44867. {
  44868. const int index = items.indexOf (comp);
  44869. jassert (index >= 0);
  44870. items.removeObject (comp, false);
  44871. addComponent (comp->getItemId(), index);
  44872. resized();
  44873. }
  44874. void ToolbarItemPalette::resized()
  44875. {
  44876. viewport.setBoundsInset (BorderSize (1));
  44877. Component* const itemHolder = viewport.getViewedComponent();
  44878. const int indent = 8;
  44879. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44880. const int height = toolbar->getThickness();
  44881. int x = indent;
  44882. int y = indent;
  44883. int maxX = 0;
  44884. for (int i = 0; i < items.size(); ++i)
  44885. {
  44886. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44887. tc->setStyle (toolbar->getStyle());
  44888. int preferredSize = 1, minSize = 1, maxSize = 1;
  44889. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44890. {
  44891. if (x + preferredSize > preferredWidth && x > indent)
  44892. {
  44893. x = indent;
  44894. y += height;
  44895. }
  44896. tc->setBounds (x, y, preferredSize, height);
  44897. x += preferredSize + 8;
  44898. maxX = jmax (maxX, x);
  44899. }
  44900. }
  44901. itemHolder->setSize (maxX, y + height + 8);
  44902. }
  44903. END_JUCE_NAMESPACE
  44904. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44905. /*** Start of inlined file: juce_TreeView.cpp ***/
  44906. BEGIN_JUCE_NAMESPACE
  44907. class TreeViewContentComponent : public Component,
  44908. public TooltipClient
  44909. {
  44910. public:
  44911. TreeViewContentComponent (TreeView& owner_)
  44912. : owner (owner_),
  44913. buttonUnderMouse (0),
  44914. isDragging (false)
  44915. {
  44916. }
  44917. void mouseDown (const MouseEvent& e)
  44918. {
  44919. updateButtonUnderMouse (e);
  44920. isDragging = false;
  44921. needSelectionOnMouseUp = false;
  44922. Rectangle<int> pos;
  44923. TreeViewItem* const item = findItemAt (e.y, pos);
  44924. if (item == 0)
  44925. return;
  44926. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44927. // as selection clicks)
  44928. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44929. {
  44930. if (e.x >= pos.getX() - owner.getIndentSize())
  44931. item->setOpen (! item->isOpen());
  44932. // (clicks to the left of an open/close button are ignored)
  44933. }
  44934. else
  44935. {
  44936. // mouse-down inside the body of the item..
  44937. if (! owner.isMultiSelectEnabled())
  44938. item->setSelected (true, true);
  44939. else if (item->isSelected())
  44940. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44941. else
  44942. selectBasedOnModifiers (item, e.mods);
  44943. if (e.x >= pos.getX())
  44944. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44945. }
  44946. }
  44947. void mouseUp (const MouseEvent& e)
  44948. {
  44949. updateButtonUnderMouse (e);
  44950. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44951. {
  44952. Rectangle<int> pos;
  44953. TreeViewItem* const item = findItemAt (e.y, pos);
  44954. if (item != 0)
  44955. selectBasedOnModifiers (item, e.mods);
  44956. }
  44957. }
  44958. void mouseDoubleClick (const MouseEvent& e)
  44959. {
  44960. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44961. {
  44962. Rectangle<int> pos;
  44963. TreeViewItem* const item = findItemAt (e.y, pos);
  44964. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44965. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44966. }
  44967. }
  44968. void mouseDrag (const MouseEvent& e)
  44969. {
  44970. if (isEnabled()
  44971. && ! (isDragging || e.mouseWasClicked()
  44972. || e.getDistanceFromDragStart() < 5
  44973. || e.mods.isPopupMenu()))
  44974. {
  44975. isDragging = true;
  44976. Rectangle<int> pos;
  44977. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44978. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44979. {
  44980. const String dragDescription (item->getDragSourceDescription());
  44981. if (dragDescription.isNotEmpty())
  44982. {
  44983. DragAndDropContainer* const dragContainer
  44984. = DragAndDropContainer::findParentDragContainerFor (this);
  44985. if (dragContainer != 0)
  44986. {
  44987. pos.setSize (pos.getWidth(), item->itemHeight);
  44988. Image dragImage (Component::createComponentSnapshot (pos, true));
  44989. dragImage.multiplyAllAlphas (0.6f);
  44990. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44991. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44992. }
  44993. else
  44994. {
  44995. // to be able to do a drag-and-drop operation, the treeview needs to
  44996. // be inside a component which is also a DragAndDropContainer.
  44997. jassertfalse;
  44998. }
  44999. }
  45000. }
  45001. }
  45002. }
  45003. void mouseMove (const MouseEvent& e)
  45004. {
  45005. updateButtonUnderMouse (e);
  45006. }
  45007. void mouseExit (const MouseEvent& e)
  45008. {
  45009. updateButtonUnderMouse (e);
  45010. }
  45011. void paint (Graphics& g)
  45012. {
  45013. if (owner.rootItem != 0)
  45014. {
  45015. owner.handleAsyncUpdate();
  45016. if (! owner.rootItemVisible)
  45017. g.setOrigin (0, -owner.rootItem->itemHeight);
  45018. owner.rootItem->paintRecursively (g, getWidth());
  45019. }
  45020. }
  45021. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45022. {
  45023. if (owner.rootItem != 0)
  45024. {
  45025. owner.handleAsyncUpdate();
  45026. if (! owner.rootItemVisible)
  45027. y += owner.rootItem->itemHeight;
  45028. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45029. if (ti != 0)
  45030. itemPosition = ti->getItemPosition (false);
  45031. return ti;
  45032. }
  45033. return 0;
  45034. }
  45035. void updateComponents()
  45036. {
  45037. const int visibleTop = -getY();
  45038. const int visibleBottom = visibleTop + getParentHeight();
  45039. {
  45040. for (int i = items.size(); --i >= 0;)
  45041. items.getUnchecked(i)->shouldKeep = false;
  45042. }
  45043. {
  45044. TreeViewItem* item = owner.rootItem;
  45045. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45046. while (item != 0 && y < visibleBottom)
  45047. {
  45048. y += item->itemHeight;
  45049. if (y >= visibleTop)
  45050. {
  45051. RowItem* const ri = findItem (item->uid);
  45052. if (ri != 0)
  45053. {
  45054. ri->shouldKeep = true;
  45055. }
  45056. else
  45057. {
  45058. Component* const comp = item->createItemComponent();
  45059. if (comp != 0)
  45060. {
  45061. items.add (new RowItem (item, comp, item->uid));
  45062. addAndMakeVisible (comp);
  45063. }
  45064. }
  45065. }
  45066. item = item->getNextVisibleItem (true);
  45067. }
  45068. }
  45069. for (int i = items.size(); --i >= 0;)
  45070. {
  45071. RowItem* const ri = items.getUnchecked(i);
  45072. bool keep = false;
  45073. if (isParentOf (ri->component))
  45074. {
  45075. if (ri->shouldKeep)
  45076. {
  45077. Rectangle<int> pos (ri->item->getItemPosition (false));
  45078. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45079. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45080. {
  45081. keep = true;
  45082. ri->component->setBounds (pos);
  45083. }
  45084. }
  45085. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45086. {
  45087. keep = true;
  45088. ri->component->setSize (0, 0);
  45089. }
  45090. }
  45091. if (! keep)
  45092. items.remove (i);
  45093. }
  45094. }
  45095. void updateButtonUnderMouse (const MouseEvent& e)
  45096. {
  45097. TreeViewItem* newItem = 0;
  45098. if (owner.openCloseButtonsVisible)
  45099. {
  45100. Rectangle<int> pos;
  45101. TreeViewItem* item = findItemAt (e.y, pos);
  45102. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45103. {
  45104. newItem = item;
  45105. if (! newItem->mightContainSubItems())
  45106. newItem = 0;
  45107. }
  45108. }
  45109. if (buttonUnderMouse != newItem)
  45110. {
  45111. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45112. {
  45113. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45114. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45115. }
  45116. buttonUnderMouse = newItem;
  45117. if (buttonUnderMouse != 0)
  45118. {
  45119. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45120. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45121. }
  45122. }
  45123. }
  45124. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45125. {
  45126. return item == buttonUnderMouse;
  45127. }
  45128. void resized()
  45129. {
  45130. owner.itemsChanged();
  45131. }
  45132. const String getTooltip()
  45133. {
  45134. Rectangle<int> pos;
  45135. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45136. if (item != 0)
  45137. return item->getTooltip();
  45138. return owner.getTooltip();
  45139. }
  45140. private:
  45141. TreeView& owner;
  45142. struct RowItem
  45143. {
  45144. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45145. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45146. {
  45147. }
  45148. ~RowItem()
  45149. {
  45150. delete component.get();
  45151. }
  45152. WeakReference<Component> component;
  45153. TreeViewItem* item;
  45154. int uid;
  45155. bool shouldKeep;
  45156. };
  45157. OwnedArray <RowItem> items;
  45158. TreeViewItem* buttonUnderMouse;
  45159. bool isDragging, needSelectionOnMouseUp;
  45160. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45161. {
  45162. TreeViewItem* firstSelected = 0;
  45163. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45164. {
  45165. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45166. jassert (lastSelected != 0);
  45167. int rowStart = firstSelected->getRowNumberInTree();
  45168. int rowEnd = lastSelected->getRowNumberInTree();
  45169. if (rowStart > rowEnd)
  45170. swapVariables (rowStart, rowEnd);
  45171. int ourRow = item->getRowNumberInTree();
  45172. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45173. if (ourRow > otherEnd)
  45174. swapVariables (ourRow, otherEnd);
  45175. for (int i = ourRow; i <= otherEnd; ++i)
  45176. owner.getItemOnRow (i)->setSelected (true, false);
  45177. }
  45178. else
  45179. {
  45180. const bool cmd = modifiers.isCommandDown();
  45181. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45182. }
  45183. }
  45184. bool containsItem (TreeViewItem* const item) const throw()
  45185. {
  45186. for (int i = items.size(); --i >= 0;)
  45187. if (items.getUnchecked(i)->item == item)
  45188. return true;
  45189. return false;
  45190. }
  45191. RowItem* findItem (const int uid) const throw()
  45192. {
  45193. for (int i = items.size(); --i >= 0;)
  45194. {
  45195. RowItem* const ri = items.getUnchecked(i);
  45196. if (ri->uid == uid)
  45197. return ri;
  45198. }
  45199. return 0;
  45200. }
  45201. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45202. {
  45203. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45204. {
  45205. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45206. if (source->isDragging())
  45207. {
  45208. Component* const underMouse = source->getComponentUnderMouse();
  45209. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45210. return true;
  45211. }
  45212. }
  45213. return false;
  45214. }
  45215. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45216. };
  45217. class TreeView::TreeViewport : public Viewport
  45218. {
  45219. public:
  45220. TreeViewport() throw() : lastX (-1) {}
  45221. void updateComponents (const bool triggerResize = false)
  45222. {
  45223. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45224. if (tvc != 0)
  45225. {
  45226. if (triggerResize)
  45227. tvc->resized();
  45228. else
  45229. tvc->updateComponents();
  45230. }
  45231. repaint();
  45232. }
  45233. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45234. {
  45235. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45236. lastX = newVisibleArea.getX();
  45237. updateComponents (hasScrolledSideways);
  45238. }
  45239. private:
  45240. int lastX;
  45241. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45242. };
  45243. TreeView::TreeView (const String& componentName)
  45244. : Component (componentName),
  45245. rootItem (0),
  45246. indentSize (24),
  45247. defaultOpenness (false),
  45248. needsRecalculating (true),
  45249. rootItemVisible (true),
  45250. multiSelectEnabled (false),
  45251. openCloseButtonsVisible (true)
  45252. {
  45253. addAndMakeVisible (viewport = new TreeViewport());
  45254. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45255. viewport->setWantsKeyboardFocus (false);
  45256. setWantsKeyboardFocus (true);
  45257. }
  45258. TreeView::~TreeView()
  45259. {
  45260. if (rootItem != 0)
  45261. rootItem->setOwnerView (0);
  45262. }
  45263. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45264. {
  45265. if (rootItem != newRootItem)
  45266. {
  45267. if (newRootItem != 0)
  45268. {
  45269. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45270. if (newRootItem->ownerView != 0)
  45271. newRootItem->ownerView->setRootItem (0);
  45272. }
  45273. if (rootItem != 0)
  45274. rootItem->setOwnerView (0);
  45275. rootItem = newRootItem;
  45276. if (newRootItem != 0)
  45277. newRootItem->setOwnerView (this);
  45278. needsRecalculating = true;
  45279. handleAsyncUpdate();
  45280. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45281. {
  45282. rootItem->setOpen (false); // force a re-open
  45283. rootItem->setOpen (true);
  45284. }
  45285. }
  45286. }
  45287. void TreeView::deleteRootItem()
  45288. {
  45289. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45290. setRootItem (0);
  45291. }
  45292. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45293. {
  45294. rootItemVisible = shouldBeVisible;
  45295. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45296. {
  45297. rootItem->setOpen (false); // force a re-open
  45298. rootItem->setOpen (true);
  45299. }
  45300. itemsChanged();
  45301. }
  45302. void TreeView::colourChanged()
  45303. {
  45304. setOpaque (findColour (backgroundColourId).isOpaque());
  45305. repaint();
  45306. }
  45307. void TreeView::setIndentSize (const int newIndentSize)
  45308. {
  45309. if (indentSize != newIndentSize)
  45310. {
  45311. indentSize = newIndentSize;
  45312. resized();
  45313. }
  45314. }
  45315. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45316. {
  45317. if (defaultOpenness != isOpenByDefault)
  45318. {
  45319. defaultOpenness = isOpenByDefault;
  45320. itemsChanged();
  45321. }
  45322. }
  45323. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45324. {
  45325. multiSelectEnabled = canMultiSelect;
  45326. }
  45327. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45328. {
  45329. if (openCloseButtonsVisible != shouldBeVisible)
  45330. {
  45331. openCloseButtonsVisible = shouldBeVisible;
  45332. itemsChanged();
  45333. }
  45334. }
  45335. Viewport* TreeView::getViewport() const throw()
  45336. {
  45337. return viewport;
  45338. }
  45339. void TreeView::clearSelectedItems()
  45340. {
  45341. if (rootItem != 0)
  45342. rootItem->deselectAllRecursively();
  45343. }
  45344. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45345. {
  45346. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45347. }
  45348. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45349. {
  45350. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45351. }
  45352. int TreeView::getNumRowsInTree() const
  45353. {
  45354. if (rootItem != 0)
  45355. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45356. return 0;
  45357. }
  45358. TreeViewItem* TreeView::getItemOnRow (int index) const
  45359. {
  45360. if (! rootItemVisible)
  45361. ++index;
  45362. if (rootItem != 0 && index >= 0)
  45363. return rootItem->getItemOnRow (index);
  45364. return 0;
  45365. }
  45366. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45367. {
  45368. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45369. Rectangle<int> pos;
  45370. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45371. }
  45372. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45373. {
  45374. if (rootItem == 0)
  45375. return 0;
  45376. return rootItem->findItemFromIdentifierString (identifierString);
  45377. }
  45378. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45379. {
  45380. XmlElement* e = 0;
  45381. if (rootItem != 0)
  45382. {
  45383. e = rootItem->getOpennessState();
  45384. if (e != 0 && alsoIncludeScrollPosition)
  45385. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45386. }
  45387. return e;
  45388. }
  45389. void TreeView::restoreOpennessState (const XmlElement& newState)
  45390. {
  45391. if (rootItem != 0)
  45392. {
  45393. rootItem->restoreOpennessState (newState);
  45394. if (newState.hasAttribute ("scrollPos"))
  45395. viewport->setViewPosition (viewport->getViewPositionX(),
  45396. newState.getIntAttribute ("scrollPos"));
  45397. }
  45398. }
  45399. void TreeView::paint (Graphics& g)
  45400. {
  45401. g.fillAll (findColour (backgroundColourId));
  45402. }
  45403. void TreeView::resized()
  45404. {
  45405. viewport->setBounds (getLocalBounds());
  45406. itemsChanged();
  45407. handleAsyncUpdate();
  45408. }
  45409. void TreeView::enablementChanged()
  45410. {
  45411. repaint();
  45412. }
  45413. void TreeView::moveSelectedRow (int delta)
  45414. {
  45415. if (delta == 0)
  45416. return;
  45417. int rowSelected = 0;
  45418. TreeViewItem* const firstSelected = getSelectedItem (0);
  45419. if (firstSelected != 0)
  45420. rowSelected = firstSelected->getRowNumberInTree();
  45421. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45422. for (;;)
  45423. {
  45424. TreeViewItem* item = getItemOnRow (rowSelected);
  45425. if (item != 0)
  45426. {
  45427. if (! item->canBeSelected())
  45428. {
  45429. // if the row we want to highlight doesn't allow it, try skipping
  45430. // to the next item..
  45431. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45432. rowSelected + (delta < 0 ? -1 : 1));
  45433. if (rowSelected != nextRowToTry)
  45434. {
  45435. rowSelected = nextRowToTry;
  45436. continue;
  45437. }
  45438. else
  45439. {
  45440. break;
  45441. }
  45442. }
  45443. item->setSelected (true, true);
  45444. scrollToKeepItemVisible (item);
  45445. }
  45446. break;
  45447. }
  45448. }
  45449. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45450. {
  45451. if (item != 0 && item->ownerView == this)
  45452. {
  45453. handleAsyncUpdate();
  45454. item = item->getDeepestOpenParentItem();
  45455. int y = item->y;
  45456. int viewTop = viewport->getViewPositionY();
  45457. if (y < viewTop)
  45458. {
  45459. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45460. }
  45461. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45462. {
  45463. viewport->setViewPosition (viewport->getViewPositionX(),
  45464. (y + item->itemHeight) - viewport->getViewHeight());
  45465. }
  45466. }
  45467. }
  45468. bool TreeView::keyPressed (const KeyPress& key)
  45469. {
  45470. if (key.isKeyCode (KeyPress::upKey))
  45471. {
  45472. moveSelectedRow (-1);
  45473. }
  45474. else if (key.isKeyCode (KeyPress::downKey))
  45475. {
  45476. moveSelectedRow (1);
  45477. }
  45478. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45479. {
  45480. if (rootItem != 0)
  45481. {
  45482. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45483. if (key.isKeyCode (KeyPress::pageUpKey))
  45484. rowsOnScreen = -rowsOnScreen;
  45485. moveSelectedRow (rowsOnScreen);
  45486. }
  45487. }
  45488. else if (key.isKeyCode (KeyPress::homeKey))
  45489. {
  45490. moveSelectedRow (-0x3fffffff);
  45491. }
  45492. else if (key.isKeyCode (KeyPress::endKey))
  45493. {
  45494. moveSelectedRow (0x3fffffff);
  45495. }
  45496. else if (key.isKeyCode (KeyPress::returnKey))
  45497. {
  45498. TreeViewItem* const firstSelected = getSelectedItem (0);
  45499. if (firstSelected != 0)
  45500. firstSelected->setOpen (! firstSelected->isOpen());
  45501. }
  45502. else if (key.isKeyCode (KeyPress::leftKey))
  45503. {
  45504. TreeViewItem* const firstSelected = getSelectedItem (0);
  45505. if (firstSelected != 0)
  45506. {
  45507. if (firstSelected->isOpen())
  45508. {
  45509. firstSelected->setOpen (false);
  45510. }
  45511. else
  45512. {
  45513. TreeViewItem* parent = firstSelected->parentItem;
  45514. if ((! rootItemVisible) && parent == rootItem)
  45515. parent = 0;
  45516. if (parent != 0)
  45517. {
  45518. parent->setSelected (true, true);
  45519. scrollToKeepItemVisible (parent);
  45520. }
  45521. }
  45522. }
  45523. }
  45524. else if (key.isKeyCode (KeyPress::rightKey))
  45525. {
  45526. TreeViewItem* const firstSelected = getSelectedItem (0);
  45527. if (firstSelected != 0)
  45528. {
  45529. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45530. moveSelectedRow (1);
  45531. else
  45532. firstSelected->setOpen (true);
  45533. }
  45534. }
  45535. else
  45536. {
  45537. return false;
  45538. }
  45539. return true;
  45540. }
  45541. void TreeView::itemsChanged() throw()
  45542. {
  45543. needsRecalculating = true;
  45544. repaint();
  45545. triggerAsyncUpdate();
  45546. }
  45547. void TreeView::handleAsyncUpdate()
  45548. {
  45549. if (needsRecalculating)
  45550. {
  45551. needsRecalculating = false;
  45552. const ScopedLock sl (nodeAlterationLock);
  45553. if (rootItem != 0)
  45554. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45555. viewport->updateComponents();
  45556. if (rootItem != 0)
  45557. {
  45558. viewport->getViewedComponent()
  45559. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45560. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45561. }
  45562. else
  45563. {
  45564. viewport->getViewedComponent()->setSize (0, 0);
  45565. }
  45566. }
  45567. }
  45568. class TreeView::InsertPointHighlight : public Component
  45569. {
  45570. public:
  45571. InsertPointHighlight()
  45572. : lastItem (0)
  45573. {
  45574. setSize (100, 12);
  45575. setAlwaysOnTop (true);
  45576. setInterceptsMouseClicks (false, false);
  45577. }
  45578. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45579. {
  45580. lastItem = item;
  45581. lastIndex = insertIndex;
  45582. const int offset = getHeight() / 2;
  45583. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45584. }
  45585. void paint (Graphics& g)
  45586. {
  45587. Path p;
  45588. const float h = (float) getHeight();
  45589. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45590. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45591. p.lineTo ((float) getWidth(), h / 2.0f);
  45592. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45593. g.strokePath (p, PathStrokeType (2.0f));
  45594. }
  45595. TreeViewItem* lastItem;
  45596. int lastIndex;
  45597. private:
  45598. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45599. };
  45600. class TreeView::TargetGroupHighlight : public Component
  45601. {
  45602. public:
  45603. TargetGroupHighlight()
  45604. {
  45605. setAlwaysOnTop (true);
  45606. setInterceptsMouseClicks (false, false);
  45607. }
  45608. void setTargetPosition (TreeViewItem* const item) throw()
  45609. {
  45610. Rectangle<int> r (item->getItemPosition (true));
  45611. r.setHeight (item->getItemHeight());
  45612. setBounds (r);
  45613. }
  45614. void paint (Graphics& g)
  45615. {
  45616. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45617. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45618. }
  45619. private:
  45620. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45621. };
  45622. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45623. {
  45624. beginDragAutoRepeat (100);
  45625. if (dragInsertPointHighlight == 0)
  45626. {
  45627. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45628. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45629. }
  45630. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45631. dragTargetGroupHighlight->setTargetPosition (item);
  45632. }
  45633. void TreeView::hideDragHighlight() throw()
  45634. {
  45635. dragInsertPointHighlight = 0;
  45636. dragTargetGroupHighlight = 0;
  45637. }
  45638. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45639. const StringArray& files, const String& sourceDescription,
  45640. Component* sourceComponent) const throw()
  45641. {
  45642. insertIndex = 0;
  45643. TreeViewItem* item = getItemAt (y);
  45644. if (item == 0)
  45645. return 0;
  45646. Rectangle<int> itemPos (item->getItemPosition (true));
  45647. insertIndex = item->getIndexInParent();
  45648. const int oldY = y;
  45649. y = itemPos.getY();
  45650. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45651. {
  45652. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45653. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45654. {
  45655. // Check if we're trying to drag into an empty group item..
  45656. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45657. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45658. {
  45659. insertIndex = 0;
  45660. x = itemPos.getX() + getIndentSize();
  45661. y = itemPos.getBottom();
  45662. return item;
  45663. }
  45664. }
  45665. }
  45666. if (oldY > itemPos.getCentreY())
  45667. {
  45668. y += item->getItemHeight();
  45669. while (item->isLastOfSiblings() && item->parentItem != 0
  45670. && item->parentItem->parentItem != 0)
  45671. {
  45672. if (x > itemPos.getX())
  45673. break;
  45674. item = item->parentItem;
  45675. itemPos = item->getItemPosition (true);
  45676. insertIndex = item->getIndexInParent();
  45677. }
  45678. ++insertIndex;
  45679. }
  45680. x = itemPos.getX();
  45681. return item->parentItem;
  45682. }
  45683. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45684. {
  45685. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45686. int insertIndex;
  45687. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45688. if (item != 0)
  45689. {
  45690. if (scrolled || dragInsertPointHighlight == 0
  45691. || dragInsertPointHighlight->lastItem != item
  45692. || dragInsertPointHighlight->lastIndex != insertIndex)
  45693. {
  45694. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45695. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45696. showDragHighlight (item, insertIndex, x, y);
  45697. else
  45698. hideDragHighlight();
  45699. }
  45700. }
  45701. else
  45702. {
  45703. hideDragHighlight();
  45704. }
  45705. }
  45706. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45707. {
  45708. hideDragHighlight();
  45709. int insertIndex;
  45710. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45711. if (item != 0)
  45712. {
  45713. if (files.size() > 0)
  45714. {
  45715. if (item->isInterestedInFileDrag (files))
  45716. item->filesDropped (files, insertIndex);
  45717. }
  45718. else
  45719. {
  45720. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45721. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45722. }
  45723. }
  45724. }
  45725. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45726. {
  45727. return true;
  45728. }
  45729. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45730. {
  45731. fileDragMove (files, x, y);
  45732. }
  45733. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45734. {
  45735. handleDrag (files, String::empty, 0, x, y);
  45736. }
  45737. void TreeView::fileDragExit (const StringArray&)
  45738. {
  45739. hideDragHighlight();
  45740. }
  45741. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45742. {
  45743. handleDrop (files, String::empty, 0, x, y);
  45744. }
  45745. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45746. {
  45747. return true;
  45748. }
  45749. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45750. {
  45751. itemDragMove (sourceDescription, sourceComponent, x, y);
  45752. }
  45753. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45754. {
  45755. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45756. }
  45757. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45758. {
  45759. hideDragHighlight();
  45760. }
  45761. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45762. {
  45763. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45764. }
  45765. enum TreeViewOpenness
  45766. {
  45767. opennessDefault = 0,
  45768. opennessClosed = 1,
  45769. opennessOpen = 2
  45770. };
  45771. TreeViewItem::TreeViewItem()
  45772. : ownerView (0),
  45773. parentItem (0),
  45774. y (0),
  45775. itemHeight (0),
  45776. totalHeight (0),
  45777. selected (false),
  45778. redrawNeeded (true),
  45779. drawLinesInside (true),
  45780. drawsInLeftMargin (false),
  45781. openness (opennessDefault)
  45782. {
  45783. static int nextUID = 0;
  45784. uid = nextUID++;
  45785. }
  45786. TreeViewItem::~TreeViewItem()
  45787. {
  45788. }
  45789. const String TreeViewItem::getUniqueName() const
  45790. {
  45791. return String::empty;
  45792. }
  45793. void TreeViewItem::itemOpennessChanged (bool)
  45794. {
  45795. }
  45796. int TreeViewItem::getNumSubItems() const throw()
  45797. {
  45798. return subItems.size();
  45799. }
  45800. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45801. {
  45802. return subItems [index];
  45803. }
  45804. void TreeViewItem::clearSubItems()
  45805. {
  45806. if (subItems.size() > 0)
  45807. {
  45808. if (ownerView != 0)
  45809. {
  45810. const ScopedLock sl (ownerView->nodeAlterationLock);
  45811. subItems.clear();
  45812. treeHasChanged();
  45813. }
  45814. else
  45815. {
  45816. subItems.clear();
  45817. }
  45818. }
  45819. }
  45820. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45821. {
  45822. if (newItem != 0)
  45823. {
  45824. newItem->parentItem = this;
  45825. newItem->setOwnerView (ownerView);
  45826. newItem->y = 0;
  45827. newItem->itemHeight = newItem->getItemHeight();
  45828. newItem->totalHeight = 0;
  45829. newItem->itemWidth = newItem->getItemWidth();
  45830. newItem->totalWidth = 0;
  45831. if (ownerView != 0)
  45832. {
  45833. const ScopedLock sl (ownerView->nodeAlterationLock);
  45834. subItems.insert (insertPosition, newItem);
  45835. treeHasChanged();
  45836. if (newItem->isOpen())
  45837. newItem->itemOpennessChanged (true);
  45838. }
  45839. else
  45840. {
  45841. subItems.insert (insertPosition, newItem);
  45842. if (newItem->isOpen())
  45843. newItem->itemOpennessChanged (true);
  45844. }
  45845. }
  45846. }
  45847. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45848. {
  45849. if (ownerView != 0)
  45850. {
  45851. const ScopedLock sl (ownerView->nodeAlterationLock);
  45852. if (isPositiveAndBelow (index, subItems.size()))
  45853. {
  45854. subItems.remove (index, deleteItem);
  45855. treeHasChanged();
  45856. }
  45857. }
  45858. else
  45859. {
  45860. subItems.remove (index, deleteItem);
  45861. }
  45862. }
  45863. bool TreeViewItem::isOpen() const throw()
  45864. {
  45865. if (openness == opennessDefault)
  45866. return ownerView != 0 && ownerView->defaultOpenness;
  45867. else
  45868. return openness == opennessOpen;
  45869. }
  45870. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45871. {
  45872. if (isOpen() != shouldBeOpen)
  45873. {
  45874. openness = shouldBeOpen ? opennessOpen
  45875. : opennessClosed;
  45876. treeHasChanged();
  45877. itemOpennessChanged (isOpen());
  45878. }
  45879. }
  45880. bool TreeViewItem::isSelected() const throw()
  45881. {
  45882. return selected;
  45883. }
  45884. void TreeViewItem::deselectAllRecursively()
  45885. {
  45886. setSelected (false, false);
  45887. for (int i = 0; i < subItems.size(); ++i)
  45888. subItems.getUnchecked(i)->deselectAllRecursively();
  45889. }
  45890. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45891. const bool deselectOtherItemsFirst)
  45892. {
  45893. if (shouldBeSelected && ! canBeSelected())
  45894. return;
  45895. if (deselectOtherItemsFirst)
  45896. getTopLevelItem()->deselectAllRecursively();
  45897. if (shouldBeSelected != selected)
  45898. {
  45899. selected = shouldBeSelected;
  45900. if (ownerView != 0)
  45901. ownerView->repaint();
  45902. itemSelectionChanged (shouldBeSelected);
  45903. }
  45904. }
  45905. void TreeViewItem::paintItem (Graphics&, int, int)
  45906. {
  45907. }
  45908. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45909. {
  45910. ownerView->getLookAndFeel()
  45911. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45912. }
  45913. void TreeViewItem::itemClicked (const MouseEvent&)
  45914. {
  45915. }
  45916. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45917. {
  45918. if (mightContainSubItems())
  45919. setOpen (! isOpen());
  45920. }
  45921. void TreeViewItem::itemSelectionChanged (bool)
  45922. {
  45923. }
  45924. const String TreeViewItem::getTooltip()
  45925. {
  45926. return String::empty;
  45927. }
  45928. const String TreeViewItem::getDragSourceDescription()
  45929. {
  45930. return String::empty;
  45931. }
  45932. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45933. {
  45934. return false;
  45935. }
  45936. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45937. {
  45938. }
  45939. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45940. {
  45941. return false;
  45942. }
  45943. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45944. {
  45945. }
  45946. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45947. {
  45948. const int indentX = getIndentX();
  45949. int width = itemWidth;
  45950. if (ownerView != 0 && width < 0)
  45951. width = ownerView->viewport->getViewWidth() - indentX;
  45952. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45953. if (relativeToTreeViewTopLeft)
  45954. r -= ownerView->viewport->getViewPosition();
  45955. return r;
  45956. }
  45957. void TreeViewItem::treeHasChanged() const throw()
  45958. {
  45959. if (ownerView != 0)
  45960. ownerView->itemsChanged();
  45961. }
  45962. void TreeViewItem::repaintItem() const
  45963. {
  45964. if (ownerView != 0 && areAllParentsOpen())
  45965. {
  45966. Rectangle<int> r (getItemPosition (true));
  45967. r.setLeft (0);
  45968. ownerView->viewport->repaint (r);
  45969. }
  45970. }
  45971. bool TreeViewItem::areAllParentsOpen() const throw()
  45972. {
  45973. return parentItem == 0
  45974. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45975. }
  45976. void TreeViewItem::updatePositions (int newY)
  45977. {
  45978. y = newY;
  45979. itemHeight = getItemHeight();
  45980. totalHeight = itemHeight;
  45981. itemWidth = getItemWidth();
  45982. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45983. if (isOpen())
  45984. {
  45985. newY += totalHeight;
  45986. for (int i = 0; i < subItems.size(); ++i)
  45987. {
  45988. TreeViewItem* const ti = subItems.getUnchecked(i);
  45989. ti->updatePositions (newY);
  45990. newY += ti->totalHeight;
  45991. totalHeight += ti->totalHeight;
  45992. totalWidth = jmax (totalWidth, ti->totalWidth);
  45993. }
  45994. }
  45995. }
  45996. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45997. {
  45998. TreeViewItem* result = this;
  45999. TreeViewItem* item = this;
  46000. while (item->parentItem != 0)
  46001. {
  46002. item = item->parentItem;
  46003. if (! item->isOpen())
  46004. result = item;
  46005. }
  46006. return result;
  46007. }
  46008. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46009. {
  46010. ownerView = newOwner;
  46011. for (int i = subItems.size(); --i >= 0;)
  46012. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46013. }
  46014. int TreeViewItem::getIndentX() const throw()
  46015. {
  46016. const int indentWidth = ownerView->getIndentSize();
  46017. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46018. if (! ownerView->openCloseButtonsVisible)
  46019. x -= indentWidth;
  46020. TreeViewItem* p = parentItem;
  46021. while (p != 0)
  46022. {
  46023. x += indentWidth;
  46024. p = p->parentItem;
  46025. }
  46026. return x;
  46027. }
  46028. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46029. {
  46030. drawsInLeftMargin = canDrawInLeftMargin;
  46031. }
  46032. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46033. {
  46034. jassert (ownerView != 0);
  46035. if (ownerView == 0)
  46036. return;
  46037. const int indent = getIndentX();
  46038. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46039. {
  46040. Graphics::ScopedSaveState ss (g);
  46041. g.setOrigin (indent, 0);
  46042. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46043. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46044. paintItem (g, itemW, itemHeight);
  46045. }
  46046. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46047. const float halfH = itemHeight * 0.5f;
  46048. int depth = 0;
  46049. TreeViewItem* p = parentItem;
  46050. while (p != 0)
  46051. {
  46052. ++depth;
  46053. p = p->parentItem;
  46054. }
  46055. if (! ownerView->rootItemVisible)
  46056. --depth;
  46057. const int indentWidth = ownerView->getIndentSize();
  46058. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46059. {
  46060. float x = (depth + 0.5f) * indentWidth;
  46061. if (depth >= 0)
  46062. {
  46063. if (parentItem != 0 && parentItem->drawLinesInside)
  46064. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46065. if ((parentItem != 0 && parentItem->drawLinesInside)
  46066. || (parentItem == 0 && drawLinesInside))
  46067. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46068. }
  46069. p = parentItem;
  46070. int d = depth;
  46071. while (p != 0 && --d >= 0)
  46072. {
  46073. x -= (float) indentWidth;
  46074. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46075. && ! p->isLastOfSiblings())
  46076. {
  46077. g.drawLine (x, 0, x, (float) itemHeight);
  46078. }
  46079. p = p->parentItem;
  46080. }
  46081. if (mightContainSubItems())
  46082. {
  46083. Graphics::ScopedSaveState ss (g);
  46084. g.setOrigin (depth * indentWidth, 0);
  46085. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46086. paintOpenCloseButton (g, indentWidth, itemHeight,
  46087. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46088. ->isMouseOverButton (this));
  46089. }
  46090. }
  46091. if (isOpen())
  46092. {
  46093. const Rectangle<int> clip (g.getClipBounds());
  46094. for (int i = 0; i < subItems.size(); ++i)
  46095. {
  46096. TreeViewItem* const ti = subItems.getUnchecked(i);
  46097. const int relY = ti->y - y;
  46098. if (relY >= clip.getBottom())
  46099. break;
  46100. if (relY + ti->totalHeight >= clip.getY())
  46101. {
  46102. Graphics::ScopedSaveState ss (g);
  46103. g.setOrigin (0, relY);
  46104. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46105. ti->paintRecursively (g, width);
  46106. }
  46107. }
  46108. }
  46109. }
  46110. bool TreeViewItem::isLastOfSiblings() const throw()
  46111. {
  46112. return parentItem == 0
  46113. || parentItem->subItems.getLast() == this;
  46114. }
  46115. int TreeViewItem::getIndexInParent() const throw()
  46116. {
  46117. return parentItem == 0 ? 0
  46118. : parentItem->subItems.indexOf (this);
  46119. }
  46120. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46121. {
  46122. return parentItem == 0 ? this
  46123. : parentItem->getTopLevelItem();
  46124. }
  46125. int TreeViewItem::getNumRows() const throw()
  46126. {
  46127. int num = 1;
  46128. if (isOpen())
  46129. {
  46130. for (int i = subItems.size(); --i >= 0;)
  46131. num += subItems.getUnchecked(i)->getNumRows();
  46132. }
  46133. return num;
  46134. }
  46135. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46136. {
  46137. if (index == 0)
  46138. return this;
  46139. if (index > 0 && isOpen())
  46140. {
  46141. --index;
  46142. for (int i = 0; i < subItems.size(); ++i)
  46143. {
  46144. TreeViewItem* const item = subItems.getUnchecked(i);
  46145. if (index == 0)
  46146. return item;
  46147. const int numRows = item->getNumRows();
  46148. if (numRows > index)
  46149. return item->getItemOnRow (index);
  46150. index -= numRows;
  46151. }
  46152. }
  46153. return 0;
  46154. }
  46155. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46156. {
  46157. if (isPositiveAndBelow (targetY, totalHeight))
  46158. {
  46159. const int h = itemHeight;
  46160. if (targetY < h)
  46161. return this;
  46162. if (isOpen())
  46163. {
  46164. targetY -= h;
  46165. for (int i = 0; i < subItems.size(); ++i)
  46166. {
  46167. TreeViewItem* const ti = subItems.getUnchecked(i);
  46168. if (targetY < ti->totalHeight)
  46169. return ti->findItemRecursively (targetY);
  46170. targetY -= ti->totalHeight;
  46171. }
  46172. }
  46173. }
  46174. return 0;
  46175. }
  46176. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46177. {
  46178. int total = isSelected() ? 1 : 0;
  46179. if (depth != 0)
  46180. for (int i = subItems.size(); --i >= 0;)
  46181. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46182. return total;
  46183. }
  46184. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46185. {
  46186. if (isSelected())
  46187. {
  46188. if (index == 0)
  46189. return this;
  46190. --index;
  46191. }
  46192. if (index >= 0)
  46193. {
  46194. for (int i = 0; i < subItems.size(); ++i)
  46195. {
  46196. TreeViewItem* const item = subItems.getUnchecked(i);
  46197. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46198. if (found != 0)
  46199. return found;
  46200. index -= item->countSelectedItemsRecursively (-1);
  46201. }
  46202. }
  46203. return 0;
  46204. }
  46205. int TreeViewItem::getRowNumberInTree() const throw()
  46206. {
  46207. if (parentItem != 0 && ownerView != 0)
  46208. {
  46209. int n = 1 + parentItem->getRowNumberInTree();
  46210. int ourIndex = parentItem->subItems.indexOf (this);
  46211. jassert (ourIndex >= 0);
  46212. while (--ourIndex >= 0)
  46213. n += parentItem->subItems [ourIndex]->getNumRows();
  46214. if (parentItem->parentItem == 0
  46215. && ! ownerView->rootItemVisible)
  46216. --n;
  46217. return n;
  46218. }
  46219. else
  46220. {
  46221. return 0;
  46222. }
  46223. }
  46224. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46225. {
  46226. drawLinesInside = drawLines;
  46227. }
  46228. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46229. {
  46230. if (recurse && isOpen() && subItems.size() > 0)
  46231. return subItems [0];
  46232. if (parentItem != 0)
  46233. {
  46234. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46235. if (nextIndex >= parentItem->subItems.size())
  46236. return parentItem->getNextVisibleItem (false);
  46237. return parentItem->subItems [nextIndex];
  46238. }
  46239. return 0;
  46240. }
  46241. const String TreeViewItem::getItemIdentifierString() const
  46242. {
  46243. String s;
  46244. if (parentItem != 0)
  46245. s = parentItem->getItemIdentifierString();
  46246. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46247. }
  46248. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46249. {
  46250. const String thisId (getUniqueName());
  46251. if (thisId == identifierString)
  46252. return this;
  46253. if (identifierString.startsWith (thisId + "/"))
  46254. {
  46255. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46256. bool wasOpen = isOpen();
  46257. setOpen (true);
  46258. for (int i = subItems.size(); --i >= 0;)
  46259. {
  46260. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46261. if (item != 0)
  46262. return item;
  46263. }
  46264. setOpen (wasOpen);
  46265. }
  46266. return 0;
  46267. }
  46268. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46269. {
  46270. if (e.hasTagName ("CLOSED"))
  46271. {
  46272. setOpen (false);
  46273. }
  46274. else if (e.hasTagName ("OPEN"))
  46275. {
  46276. setOpen (true);
  46277. forEachXmlChildElement (e, n)
  46278. {
  46279. const String id (n->getStringAttribute ("id"));
  46280. for (int i = 0; i < subItems.size(); ++i)
  46281. {
  46282. TreeViewItem* const ti = subItems.getUnchecked(i);
  46283. if (ti->getUniqueName() == id)
  46284. {
  46285. ti->restoreOpennessState (*n);
  46286. break;
  46287. }
  46288. }
  46289. }
  46290. }
  46291. }
  46292. XmlElement* TreeViewItem::getOpennessState() const throw()
  46293. {
  46294. const String name (getUniqueName());
  46295. if (name.isNotEmpty())
  46296. {
  46297. XmlElement* e;
  46298. if (isOpen())
  46299. {
  46300. e = new XmlElement ("OPEN");
  46301. for (int i = 0; i < subItems.size(); ++i)
  46302. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46303. }
  46304. else
  46305. {
  46306. e = new XmlElement ("CLOSED");
  46307. }
  46308. e->setAttribute ("id", name);
  46309. return e;
  46310. }
  46311. else
  46312. {
  46313. // trying to save the openness for an element that has no name - this won't
  46314. // work because it needs the names to identify what to open.
  46315. jassertfalse;
  46316. }
  46317. return 0;
  46318. }
  46319. END_JUCE_NAMESPACE
  46320. /*** End of inlined file: juce_TreeView.cpp ***/
  46321. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46322. BEGIN_JUCE_NAMESPACE
  46323. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46324. : fileList (listToShow)
  46325. {
  46326. }
  46327. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46328. {
  46329. }
  46330. FileBrowserListener::~FileBrowserListener()
  46331. {
  46332. }
  46333. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46334. {
  46335. listeners.add (listener);
  46336. }
  46337. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46338. {
  46339. listeners.remove (listener);
  46340. }
  46341. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46342. {
  46343. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46344. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46345. }
  46346. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46347. {
  46348. if (fileList.getDirectory().exists())
  46349. {
  46350. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46351. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46352. }
  46353. }
  46354. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46355. {
  46356. if (fileList.getDirectory().exists())
  46357. {
  46358. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46359. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46360. }
  46361. }
  46362. END_JUCE_NAMESPACE
  46363. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46364. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46365. BEGIN_JUCE_NAMESPACE
  46366. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46367. TimeSliceThread& thread_)
  46368. : fileFilter (fileFilter_),
  46369. thread (thread_),
  46370. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46371. fileFindHandle (0),
  46372. shouldStop (true)
  46373. {
  46374. }
  46375. DirectoryContentsList::~DirectoryContentsList()
  46376. {
  46377. clear();
  46378. }
  46379. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46380. {
  46381. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46382. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46383. }
  46384. bool DirectoryContentsList::ignoresHiddenFiles() const
  46385. {
  46386. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46387. }
  46388. const File& DirectoryContentsList::getDirectory() const
  46389. {
  46390. return root;
  46391. }
  46392. void DirectoryContentsList::setDirectory (const File& directory,
  46393. const bool includeDirectories,
  46394. const bool includeFiles)
  46395. {
  46396. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46397. if (directory != root)
  46398. {
  46399. clear();
  46400. root = directory;
  46401. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46402. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46403. }
  46404. int newFlags = fileTypeFlags;
  46405. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46406. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46407. setTypeFlags (newFlags);
  46408. }
  46409. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46410. {
  46411. if (fileTypeFlags != newFlags)
  46412. {
  46413. fileTypeFlags = newFlags;
  46414. refresh();
  46415. }
  46416. }
  46417. void DirectoryContentsList::clear()
  46418. {
  46419. shouldStop = true;
  46420. thread.removeTimeSliceClient (this);
  46421. fileFindHandle = 0;
  46422. if (files.size() > 0)
  46423. {
  46424. files.clear();
  46425. changed();
  46426. }
  46427. }
  46428. void DirectoryContentsList::refresh()
  46429. {
  46430. clear();
  46431. if (root.isDirectory())
  46432. {
  46433. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46434. shouldStop = false;
  46435. thread.addTimeSliceClient (this);
  46436. }
  46437. }
  46438. int DirectoryContentsList::getNumFiles() const
  46439. {
  46440. return files.size();
  46441. }
  46442. bool DirectoryContentsList::getFileInfo (const int index,
  46443. FileInfo& result) const
  46444. {
  46445. const ScopedLock sl (fileListLock);
  46446. const FileInfo* const info = files [index];
  46447. if (info != 0)
  46448. {
  46449. result = *info;
  46450. return true;
  46451. }
  46452. return false;
  46453. }
  46454. const File DirectoryContentsList::getFile (const int index) const
  46455. {
  46456. const ScopedLock sl (fileListLock);
  46457. const FileInfo* const info = files [index];
  46458. if (info != 0)
  46459. return root.getChildFile (info->filename);
  46460. return File::nonexistent;
  46461. }
  46462. bool DirectoryContentsList::isStillLoading() const
  46463. {
  46464. return fileFindHandle != 0;
  46465. }
  46466. void DirectoryContentsList::changed()
  46467. {
  46468. sendChangeMessage();
  46469. }
  46470. bool DirectoryContentsList::useTimeSlice()
  46471. {
  46472. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46473. bool hasChanged = false;
  46474. for (int i = 100; --i >= 0;)
  46475. {
  46476. if (! checkNextFile (hasChanged))
  46477. {
  46478. if (hasChanged)
  46479. changed();
  46480. return false;
  46481. }
  46482. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46483. break;
  46484. }
  46485. if (hasChanged)
  46486. changed();
  46487. return true;
  46488. }
  46489. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46490. {
  46491. if (fileFindHandle != 0)
  46492. {
  46493. bool fileFoundIsDir, isHidden, isReadOnly;
  46494. int64 fileSize;
  46495. Time modTime, creationTime;
  46496. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46497. &modTime, &creationTime, &isReadOnly))
  46498. {
  46499. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46500. fileSize, modTime, creationTime, isReadOnly))
  46501. {
  46502. hasChanged = true;
  46503. }
  46504. return true;
  46505. }
  46506. else
  46507. {
  46508. fileFindHandle = 0;
  46509. }
  46510. }
  46511. return false;
  46512. }
  46513. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46514. const DirectoryContentsList::FileInfo* const second)
  46515. {
  46516. #if JUCE_WINDOWS
  46517. if (first->isDirectory != second->isDirectory)
  46518. return first->isDirectory ? -1 : 1;
  46519. #endif
  46520. return first->filename.compareIgnoreCase (second->filename);
  46521. }
  46522. bool DirectoryContentsList::addFile (const File& file,
  46523. const bool isDir,
  46524. const int64 fileSize,
  46525. const Time& modTime,
  46526. const Time& creationTime,
  46527. const bool isReadOnly)
  46528. {
  46529. if (fileFilter == 0
  46530. || ((! isDir) && fileFilter->isFileSuitable (file))
  46531. || (isDir && fileFilter->isDirectorySuitable (file)))
  46532. {
  46533. ScopedPointer <FileInfo> info (new FileInfo());
  46534. info->filename = file.getFileName();
  46535. info->fileSize = fileSize;
  46536. info->modificationTime = modTime;
  46537. info->creationTime = creationTime;
  46538. info->isDirectory = isDir;
  46539. info->isReadOnly = isReadOnly;
  46540. const ScopedLock sl (fileListLock);
  46541. for (int i = files.size(); --i >= 0;)
  46542. if (files.getUnchecked(i)->filename == info->filename)
  46543. return false;
  46544. files.addSorted (*this, info.release());
  46545. return true;
  46546. }
  46547. return false;
  46548. }
  46549. END_JUCE_NAMESPACE
  46550. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46551. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46552. BEGIN_JUCE_NAMESPACE
  46553. FileBrowserComponent::FileBrowserComponent (int flags_,
  46554. const File& initialFileOrDirectory,
  46555. const FileFilter* fileFilter_,
  46556. FilePreviewComponent* previewComp_)
  46557. : FileFilter (String::empty),
  46558. fileFilter (fileFilter_),
  46559. flags (flags_),
  46560. previewComp (previewComp_),
  46561. currentPathBox ("path"),
  46562. fileLabel ("f", TRANS ("file:")),
  46563. thread ("Juce FileBrowser")
  46564. {
  46565. // You need to specify one or other of the open/save flags..
  46566. jassert ((flags & (saveMode | openMode)) != 0);
  46567. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46568. // You need to specify at least one of these flags..
  46569. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46570. String filename;
  46571. if (initialFileOrDirectory == File::nonexistent)
  46572. {
  46573. currentRoot = File::getCurrentWorkingDirectory();
  46574. }
  46575. else if (initialFileOrDirectory.isDirectory())
  46576. {
  46577. currentRoot = initialFileOrDirectory;
  46578. }
  46579. else
  46580. {
  46581. chosenFiles.add (initialFileOrDirectory);
  46582. currentRoot = initialFileOrDirectory.getParentDirectory();
  46583. filename = initialFileOrDirectory.getFileName();
  46584. }
  46585. fileList = new DirectoryContentsList (this, thread);
  46586. if ((flags & useTreeView) != 0)
  46587. {
  46588. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46589. fileListComponent = tree;
  46590. if ((flags & canSelectMultipleItems) != 0)
  46591. tree->setMultiSelectEnabled (true);
  46592. addAndMakeVisible (tree);
  46593. }
  46594. else
  46595. {
  46596. FileListComponent* const list = new FileListComponent (*fileList);
  46597. fileListComponent = list;
  46598. list->setOutlineThickness (1);
  46599. if ((flags & canSelectMultipleItems) != 0)
  46600. list->setMultipleSelectionEnabled (true);
  46601. addAndMakeVisible (list);
  46602. }
  46603. fileListComponent->addListener (this);
  46604. addAndMakeVisible (&currentPathBox);
  46605. currentPathBox.setEditableText (true);
  46606. StringArray rootNames, rootPaths;
  46607. getRoots (rootNames, rootPaths);
  46608. for (int i = 0; i < rootNames.size(); ++i)
  46609. {
  46610. if (rootNames[i].isEmpty())
  46611. currentPathBox.addSeparator();
  46612. else
  46613. currentPathBox.addItem (rootNames[i], i + 1);
  46614. }
  46615. currentPathBox.addSeparator();
  46616. currentPathBox.addListener (this);
  46617. addAndMakeVisible (&filenameBox);
  46618. filenameBox.setMultiLine (false);
  46619. filenameBox.setSelectAllWhenFocused (true);
  46620. filenameBox.setText (filename, false);
  46621. filenameBox.addListener (this);
  46622. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46623. addAndMakeVisible (&fileLabel);
  46624. fileLabel.attachToComponent (&filenameBox, true);
  46625. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46626. goUpButton->addListener (this);
  46627. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46628. if (previewComp != 0)
  46629. addAndMakeVisible (previewComp);
  46630. setRoot (currentRoot);
  46631. thread.startThread (4);
  46632. }
  46633. FileBrowserComponent::~FileBrowserComponent()
  46634. {
  46635. fileListComponent = 0;
  46636. fileList = 0;
  46637. thread.stopThread (10000);
  46638. }
  46639. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46640. {
  46641. listeners.add (newListener);
  46642. }
  46643. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46644. {
  46645. listeners.remove (listener);
  46646. }
  46647. bool FileBrowserComponent::isSaveMode() const throw()
  46648. {
  46649. return (flags & saveMode) != 0;
  46650. }
  46651. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46652. {
  46653. if (chosenFiles.size() == 0 && currentFileIsValid())
  46654. return 1;
  46655. return chosenFiles.size();
  46656. }
  46657. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46658. {
  46659. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46660. return currentRoot;
  46661. if (! filenameBox.isReadOnly())
  46662. return currentRoot.getChildFile (filenameBox.getText());
  46663. return chosenFiles[index];
  46664. }
  46665. bool FileBrowserComponent::currentFileIsValid() const
  46666. {
  46667. if (isSaveMode())
  46668. return ! getSelectedFile (0).isDirectory();
  46669. else
  46670. return getSelectedFile (0).exists();
  46671. }
  46672. const File FileBrowserComponent::getHighlightedFile() const throw()
  46673. {
  46674. return fileListComponent->getSelectedFile (0);
  46675. }
  46676. void FileBrowserComponent::deselectAllFiles()
  46677. {
  46678. fileListComponent->deselectAllFiles();
  46679. }
  46680. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46681. {
  46682. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46683. }
  46684. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46685. {
  46686. return true;
  46687. }
  46688. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46689. {
  46690. if (f.isDirectory())
  46691. return (flags & canSelectDirectories) != 0
  46692. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46693. return (flags & canSelectFiles) != 0 && f.exists()
  46694. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46695. }
  46696. const File FileBrowserComponent::getRoot() const
  46697. {
  46698. return currentRoot;
  46699. }
  46700. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46701. {
  46702. if (currentRoot != newRootDirectory)
  46703. {
  46704. fileListComponent->scrollToTop();
  46705. String path (newRootDirectory.getFullPathName());
  46706. if (path.isEmpty())
  46707. path = File::separatorString;
  46708. StringArray rootNames, rootPaths;
  46709. getRoots (rootNames, rootPaths);
  46710. if (! rootPaths.contains (path, true))
  46711. {
  46712. bool alreadyListed = false;
  46713. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46714. {
  46715. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46716. {
  46717. alreadyListed = true;
  46718. break;
  46719. }
  46720. }
  46721. if (! alreadyListed)
  46722. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46723. }
  46724. }
  46725. currentRoot = newRootDirectory;
  46726. fileList->setDirectory (currentRoot, true, true);
  46727. String currentRootName (currentRoot.getFullPathName());
  46728. if (currentRootName.isEmpty())
  46729. currentRootName = File::separatorString;
  46730. currentPathBox.setText (currentRootName, true);
  46731. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46732. && currentRoot.getParentDirectory() != currentRoot);
  46733. }
  46734. void FileBrowserComponent::goUp()
  46735. {
  46736. setRoot (getRoot().getParentDirectory());
  46737. }
  46738. void FileBrowserComponent::refresh()
  46739. {
  46740. fileList->refresh();
  46741. }
  46742. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46743. {
  46744. if (fileFilter != newFileFilter)
  46745. {
  46746. fileFilter = newFileFilter;
  46747. refresh();
  46748. }
  46749. }
  46750. const String FileBrowserComponent::getActionVerb() const
  46751. {
  46752. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46753. }
  46754. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46755. {
  46756. return previewComp;
  46757. }
  46758. void FileBrowserComponent::resized()
  46759. {
  46760. getLookAndFeel()
  46761. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46762. &currentPathBox, &filenameBox, goUpButton);
  46763. }
  46764. void FileBrowserComponent::sendListenerChangeMessage()
  46765. {
  46766. Component::BailOutChecker checker (this);
  46767. if (previewComp != 0)
  46768. previewComp->selectedFileChanged (getSelectedFile (0));
  46769. // You shouldn't delete the browser when the file gets changed!
  46770. jassert (! checker.shouldBailOut());
  46771. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46772. }
  46773. void FileBrowserComponent::selectionChanged()
  46774. {
  46775. StringArray newFilenames;
  46776. bool resetChosenFiles = true;
  46777. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46778. {
  46779. const File f (fileListComponent->getSelectedFile (i));
  46780. if (isFileOrDirSuitable (f))
  46781. {
  46782. if (resetChosenFiles)
  46783. {
  46784. chosenFiles.clear();
  46785. resetChosenFiles = false;
  46786. }
  46787. chosenFiles.add (f);
  46788. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46789. }
  46790. }
  46791. if (newFilenames.size() > 0)
  46792. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46793. sendListenerChangeMessage();
  46794. }
  46795. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46796. {
  46797. Component::BailOutChecker checker (this);
  46798. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46799. }
  46800. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46801. {
  46802. if (f.isDirectory())
  46803. {
  46804. setRoot (f);
  46805. if ((flags & canSelectDirectories) != 0)
  46806. filenameBox.setText (String::empty);
  46807. }
  46808. else
  46809. {
  46810. Component::BailOutChecker checker (this);
  46811. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46812. }
  46813. }
  46814. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46815. {
  46816. (void) key;
  46817. #if JUCE_LINUX || JUCE_WINDOWS
  46818. if (key.getModifiers().isCommandDown()
  46819. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46820. {
  46821. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46822. fileList->refresh();
  46823. return true;
  46824. }
  46825. #endif
  46826. return false;
  46827. }
  46828. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46829. {
  46830. sendListenerChangeMessage();
  46831. }
  46832. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46833. {
  46834. if (filenameBox.getText().containsChar (File::separator))
  46835. {
  46836. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46837. if (f.isDirectory())
  46838. {
  46839. setRoot (f);
  46840. chosenFiles.clear();
  46841. filenameBox.setText (String::empty);
  46842. }
  46843. else
  46844. {
  46845. setRoot (f.getParentDirectory());
  46846. chosenFiles.clear();
  46847. chosenFiles.add (f);
  46848. filenameBox.setText (f.getFileName());
  46849. }
  46850. }
  46851. else
  46852. {
  46853. fileDoubleClicked (getSelectedFile (0));
  46854. }
  46855. }
  46856. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46857. {
  46858. }
  46859. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46860. {
  46861. if (! isSaveMode())
  46862. selectionChanged();
  46863. }
  46864. void FileBrowserComponent::buttonClicked (Button*)
  46865. {
  46866. goUp();
  46867. }
  46868. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46869. {
  46870. const String newText (currentPathBox.getText().trim().unquoted());
  46871. if (newText.isNotEmpty())
  46872. {
  46873. const int index = currentPathBox.getSelectedId() - 1;
  46874. StringArray rootNames, rootPaths;
  46875. getRoots (rootNames, rootPaths);
  46876. if (rootPaths [index].isNotEmpty())
  46877. {
  46878. setRoot (File (rootPaths [index]));
  46879. }
  46880. else
  46881. {
  46882. File f (newText);
  46883. for (;;)
  46884. {
  46885. if (f.isDirectory())
  46886. {
  46887. setRoot (f);
  46888. break;
  46889. }
  46890. if (f.getParentDirectory() == f)
  46891. break;
  46892. f = f.getParentDirectory();
  46893. }
  46894. }
  46895. }
  46896. }
  46897. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46898. {
  46899. #if JUCE_WINDOWS
  46900. Array<File> roots;
  46901. File::findFileSystemRoots (roots);
  46902. rootPaths.clear();
  46903. for (int i = 0; i < roots.size(); ++i)
  46904. {
  46905. const File& drive = roots.getReference(i);
  46906. String name (drive.getFullPathName());
  46907. rootPaths.add (name);
  46908. if (drive.isOnHardDisk())
  46909. {
  46910. String volume (drive.getVolumeLabel());
  46911. if (volume.isEmpty())
  46912. volume = TRANS("Hard Drive");
  46913. name << " [" << volume << ']';
  46914. }
  46915. else if (drive.isOnCDRomDrive())
  46916. {
  46917. name << TRANS(" [CD/DVD drive]");
  46918. }
  46919. rootNames.add (name);
  46920. }
  46921. rootPaths.add (String::empty);
  46922. rootNames.add (String::empty);
  46923. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46924. rootNames.add ("Documents");
  46925. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46926. rootNames.add ("Desktop");
  46927. #endif
  46928. #if JUCE_MAC
  46929. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46930. rootNames.add ("Home folder");
  46931. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46932. rootNames.add ("Documents");
  46933. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46934. rootNames.add ("Desktop");
  46935. rootPaths.add (String::empty);
  46936. rootNames.add (String::empty);
  46937. Array <File> volumes;
  46938. File vol ("/Volumes");
  46939. vol.findChildFiles (volumes, File::findDirectories, false);
  46940. for (int i = 0; i < volumes.size(); ++i)
  46941. {
  46942. const File& volume = volumes.getReference(i);
  46943. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46944. {
  46945. rootPaths.add (volume.getFullPathName());
  46946. rootNames.add (volume.getFileName());
  46947. }
  46948. }
  46949. #endif
  46950. #if JUCE_LINUX
  46951. rootPaths.add ("/");
  46952. rootNames.add ("/");
  46953. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46954. rootNames.add ("Home folder");
  46955. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46956. rootNames.add ("Desktop");
  46957. #endif
  46958. }
  46959. END_JUCE_NAMESPACE
  46960. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46961. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46962. BEGIN_JUCE_NAMESPACE
  46963. FileChooser::FileChooser (const String& chooserBoxTitle,
  46964. const File& currentFileOrDirectory,
  46965. const String& fileFilters,
  46966. const bool useNativeDialogBox_)
  46967. : title (chooserBoxTitle),
  46968. filters (fileFilters),
  46969. startingFile (currentFileOrDirectory),
  46970. useNativeDialogBox (useNativeDialogBox_)
  46971. {
  46972. #if JUCE_LINUX
  46973. useNativeDialogBox = false;
  46974. #endif
  46975. if (! fileFilters.containsNonWhitespaceChars())
  46976. filters = "*";
  46977. }
  46978. FileChooser::~FileChooser()
  46979. {
  46980. }
  46981. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46982. {
  46983. return showDialog (false, true, false, false, false, previewComponent);
  46984. }
  46985. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46986. {
  46987. return showDialog (false, true, false, false, true, previewComponent);
  46988. }
  46989. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46990. {
  46991. return showDialog (true, true, false, false, true, previewComponent);
  46992. }
  46993. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46994. {
  46995. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46996. }
  46997. bool FileChooser::browseForDirectory()
  46998. {
  46999. return showDialog (true, false, false, false, false, 0);
  47000. }
  47001. const File FileChooser::getResult() const
  47002. {
  47003. // if you've used a multiple-file select, you should use the getResults() method
  47004. // to retrieve all the files that were chosen.
  47005. jassert (results.size() <= 1);
  47006. return results.getFirst();
  47007. }
  47008. const Array<File>& FileChooser::getResults() const
  47009. {
  47010. return results;
  47011. }
  47012. bool FileChooser::showDialog (const bool selectsDirectories,
  47013. const bool selectsFiles,
  47014. const bool isSave,
  47015. const bool warnAboutOverwritingExistingFiles,
  47016. const bool selectMultipleFiles,
  47017. FilePreviewComponent* const previewComponent)
  47018. {
  47019. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47020. results.clear();
  47021. // the preview component needs to be the right size before you pass it in here..
  47022. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47023. && previewComponent->getHeight() > 10));
  47024. #if JUCE_WINDOWS
  47025. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47026. #elif JUCE_MAC
  47027. if (useNativeDialogBox && (previewComponent == 0))
  47028. #else
  47029. if (false)
  47030. #endif
  47031. {
  47032. showPlatformDialog (results, title, startingFile, filters,
  47033. selectsDirectories, selectsFiles, isSave,
  47034. warnAboutOverwritingExistingFiles,
  47035. selectMultipleFiles,
  47036. previewComponent);
  47037. }
  47038. else
  47039. {
  47040. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47041. selectsDirectories ? "*" : String::empty,
  47042. String::empty);
  47043. int flags = isSave ? FileBrowserComponent::saveMode
  47044. : FileBrowserComponent::openMode;
  47045. if (selectsFiles)
  47046. flags |= FileBrowserComponent::canSelectFiles;
  47047. if (selectsDirectories)
  47048. {
  47049. flags |= FileBrowserComponent::canSelectDirectories;
  47050. if (! isSave)
  47051. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47052. }
  47053. if (selectMultipleFiles)
  47054. flags |= FileBrowserComponent::canSelectMultipleItems;
  47055. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47056. FileChooserDialogBox box (title, String::empty,
  47057. browserComponent,
  47058. warnAboutOverwritingExistingFiles,
  47059. browserComponent.findColour (AlertWindow::backgroundColourId));
  47060. if (box.show())
  47061. {
  47062. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47063. results.add (browserComponent.getSelectedFile (i));
  47064. }
  47065. }
  47066. if (previouslyFocused != 0)
  47067. previouslyFocused->grabKeyboardFocus();
  47068. return results.size() > 0;
  47069. }
  47070. FilePreviewComponent::FilePreviewComponent()
  47071. {
  47072. }
  47073. FilePreviewComponent::~FilePreviewComponent()
  47074. {
  47075. }
  47076. END_JUCE_NAMESPACE
  47077. /*** End of inlined file: juce_FileChooser.cpp ***/
  47078. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47079. BEGIN_JUCE_NAMESPACE
  47080. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47081. const String& instructions,
  47082. FileBrowserComponent& chooserComponent,
  47083. const bool warnAboutOverwritingExistingFiles_,
  47084. const Colour& backgroundColour)
  47085. : ResizableWindow (name, backgroundColour, true),
  47086. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47087. {
  47088. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47089. setResizable (true, true);
  47090. setResizeLimits (300, 300, 1200, 1000);
  47091. content->okButton.addListener (this);
  47092. content->cancelButton.addListener (this);
  47093. content->newFolderButton.addListener (this);
  47094. content->chooserComponent.addListener (this);
  47095. selectionChanged();
  47096. }
  47097. FileChooserDialogBox::~FileChooserDialogBox()
  47098. {
  47099. content->chooserComponent.removeListener (this);
  47100. }
  47101. bool FileChooserDialogBox::show (int w, int h)
  47102. {
  47103. return showAt (-1, -1, w, h);
  47104. }
  47105. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47106. {
  47107. if (w <= 0)
  47108. {
  47109. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47110. if (previewComp != 0)
  47111. w = 400 + previewComp->getWidth();
  47112. else
  47113. w = 600;
  47114. }
  47115. if (h <= 0)
  47116. h = 500;
  47117. if (x < 0 || y < 0)
  47118. centreWithSize (w, h);
  47119. else
  47120. setBounds (x, y, w, h);
  47121. const bool ok = (runModalLoop() != 0);
  47122. setVisible (false);
  47123. return ok;
  47124. }
  47125. void FileChooserDialogBox::buttonClicked (Button* button)
  47126. {
  47127. if (button == &(content->okButton))
  47128. {
  47129. okButtonPressed();
  47130. }
  47131. else if (button == &(content->cancelButton))
  47132. {
  47133. closeButtonPressed();
  47134. }
  47135. else if (button == &(content->newFolderButton))
  47136. {
  47137. createNewFolder();
  47138. }
  47139. }
  47140. void FileChooserDialogBox::closeButtonPressed()
  47141. {
  47142. setVisible (false);
  47143. }
  47144. void FileChooserDialogBox::selectionChanged()
  47145. {
  47146. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47147. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47148. && content->chooserComponent.getRoot().isDirectory());
  47149. }
  47150. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47151. {
  47152. }
  47153. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47154. {
  47155. selectionChanged();
  47156. content->okButton.triggerClick();
  47157. }
  47158. void FileChooserDialogBox::okButtonPressed()
  47159. {
  47160. if ((! (warnAboutOverwritingExistingFiles
  47161. && content->chooserComponent.isSaveMode()
  47162. && content->chooserComponent.getSelectedFile(0).exists()))
  47163. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47164. TRANS("File already exists"),
  47165. TRANS("There's already a file called:")
  47166. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47167. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47168. TRANS("overwrite"),
  47169. TRANS("cancel")))
  47170. {
  47171. exitModalState (1);
  47172. }
  47173. }
  47174. void FileChooserDialogBox::createNewFolder()
  47175. {
  47176. File parent (content->chooserComponent.getRoot());
  47177. if (parent.isDirectory())
  47178. {
  47179. AlertWindow aw (TRANS("New Folder"),
  47180. TRANS("Please enter the name for the folder"),
  47181. AlertWindow::NoIcon, this);
  47182. aw.addTextEditor ("name", String::empty, String::empty, false);
  47183. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47184. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47185. if (aw.runModalLoop() != 0)
  47186. {
  47187. aw.setVisible (false);
  47188. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47189. if (! name.isEmpty())
  47190. {
  47191. if (! parent.getChildFile (name).createDirectory())
  47192. {
  47193. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47194. TRANS ("New Folder"),
  47195. TRANS ("Couldn't create the folder!"));
  47196. }
  47197. content->chooserComponent.refresh();
  47198. }
  47199. }
  47200. }
  47201. }
  47202. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47203. : Component (name), instructions (instructions_),
  47204. chooserComponent (chooserComponent_),
  47205. okButton (chooserComponent_.getActionVerb()),
  47206. cancelButton (TRANS ("Cancel")),
  47207. newFolderButton (TRANS ("New Folder"))
  47208. {
  47209. addAndMakeVisible (&chooserComponent);
  47210. addAndMakeVisible (&okButton);
  47211. okButton.addShortcut (KeyPress::returnKey);
  47212. addAndMakeVisible (&cancelButton);
  47213. cancelButton.addShortcut (KeyPress::escapeKey);
  47214. addChildComponent (&newFolderButton);
  47215. setInterceptsMouseClicks (false, true);
  47216. }
  47217. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47218. {
  47219. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47220. text.draw (g);
  47221. }
  47222. void FileChooserDialogBox::ContentComponent::resized()
  47223. {
  47224. const int buttonHeight = 26;
  47225. Rectangle<int> area (getLocalBounds());
  47226. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47227. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47228. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47229. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47230. Rectangle<int> buttonArea (area.reduced (16, 10));
  47231. okButton.changeWidthToFitText (buttonHeight);
  47232. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47233. buttonArea.removeFromRight (16);
  47234. cancelButton.changeWidthToFitText (buttonHeight);
  47235. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47236. newFolderButton.changeWidthToFitText (buttonHeight);
  47237. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47238. }
  47239. END_JUCE_NAMESPACE
  47240. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47241. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47242. BEGIN_JUCE_NAMESPACE
  47243. FileFilter::FileFilter (const String& filterDescription)
  47244. : description (filterDescription)
  47245. {
  47246. }
  47247. FileFilter::~FileFilter()
  47248. {
  47249. }
  47250. const String& FileFilter::getDescription() const throw()
  47251. {
  47252. return description;
  47253. }
  47254. END_JUCE_NAMESPACE
  47255. /*** End of inlined file: juce_FileFilter.cpp ***/
  47256. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47257. BEGIN_JUCE_NAMESPACE
  47258. const Image juce_createIconForFile (const File& file);
  47259. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47260. : ListBox (String::empty, 0),
  47261. DirectoryContentsDisplayComponent (listToShow)
  47262. {
  47263. setModel (this);
  47264. fileList.addChangeListener (this);
  47265. }
  47266. FileListComponent::~FileListComponent()
  47267. {
  47268. fileList.removeChangeListener (this);
  47269. }
  47270. int FileListComponent::getNumSelectedFiles() const
  47271. {
  47272. return getNumSelectedRows();
  47273. }
  47274. const File FileListComponent::getSelectedFile (int index) const
  47275. {
  47276. return fileList.getFile (getSelectedRow (index));
  47277. }
  47278. void FileListComponent::deselectAllFiles()
  47279. {
  47280. deselectAllRows();
  47281. }
  47282. void FileListComponent::scrollToTop()
  47283. {
  47284. getVerticalScrollBar()->setCurrentRangeStart (0);
  47285. }
  47286. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47287. {
  47288. updateContent();
  47289. if (lastDirectory != fileList.getDirectory())
  47290. {
  47291. lastDirectory = fileList.getDirectory();
  47292. deselectAllRows();
  47293. }
  47294. }
  47295. class FileListItemComponent : public Component,
  47296. public TimeSliceClient,
  47297. public AsyncUpdater
  47298. {
  47299. public:
  47300. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47301. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47302. {
  47303. }
  47304. ~FileListItemComponent()
  47305. {
  47306. thread.removeTimeSliceClient (this);
  47307. }
  47308. void paint (Graphics& g)
  47309. {
  47310. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47311. file.getFileName(),
  47312. &icon, fileSize, modTime,
  47313. isDirectory, highlighted,
  47314. index, owner);
  47315. }
  47316. void mouseDown (const MouseEvent& e)
  47317. {
  47318. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47319. owner.sendMouseClickMessage (file, e);
  47320. }
  47321. void mouseDoubleClick (const MouseEvent&)
  47322. {
  47323. owner.sendDoubleClickMessage (file);
  47324. }
  47325. void update (const File& root,
  47326. const DirectoryContentsList::FileInfo* const fileInfo,
  47327. const int index_,
  47328. const bool highlighted_)
  47329. {
  47330. thread.removeTimeSliceClient (this);
  47331. if (highlighted_ != highlighted || index_ != index)
  47332. {
  47333. index = index_;
  47334. highlighted = highlighted_;
  47335. repaint();
  47336. }
  47337. File newFile;
  47338. String newFileSize, newModTime;
  47339. if (fileInfo != 0)
  47340. {
  47341. newFile = root.getChildFile (fileInfo->filename);
  47342. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47343. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47344. }
  47345. if (newFile != file
  47346. || fileSize != newFileSize
  47347. || modTime != newModTime)
  47348. {
  47349. file = newFile;
  47350. fileSize = newFileSize;
  47351. modTime = newModTime;
  47352. icon = Image::null;
  47353. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47354. repaint();
  47355. }
  47356. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47357. {
  47358. updateIcon (true);
  47359. if (! icon.isValid())
  47360. thread.addTimeSliceClient (this);
  47361. }
  47362. }
  47363. bool useTimeSlice()
  47364. {
  47365. updateIcon (false);
  47366. return false;
  47367. }
  47368. void handleAsyncUpdate()
  47369. {
  47370. repaint();
  47371. }
  47372. private:
  47373. FileListComponent& owner;
  47374. TimeSliceThread& thread;
  47375. File file;
  47376. String fileSize, modTime;
  47377. Image icon;
  47378. int index;
  47379. bool highlighted, isDirectory;
  47380. void updateIcon (const bool onlyUpdateIfCached)
  47381. {
  47382. if (icon.isNull())
  47383. {
  47384. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47385. Image im (ImageCache::getFromHashCode (hashCode));
  47386. if (im.isNull() && ! onlyUpdateIfCached)
  47387. {
  47388. im = juce_createIconForFile (file);
  47389. if (im.isValid())
  47390. ImageCache::addImageToCache (im, hashCode);
  47391. }
  47392. if (im.isValid())
  47393. {
  47394. icon = im;
  47395. triggerAsyncUpdate();
  47396. }
  47397. }
  47398. }
  47399. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47400. };
  47401. int FileListComponent::getNumRows()
  47402. {
  47403. return fileList.getNumFiles();
  47404. }
  47405. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47406. {
  47407. }
  47408. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47409. {
  47410. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47411. if (comp == 0)
  47412. {
  47413. delete existingComponentToUpdate;
  47414. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47415. }
  47416. DirectoryContentsList::FileInfo fileInfo;
  47417. if (fileList.getFileInfo (row, fileInfo))
  47418. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47419. else
  47420. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47421. return comp;
  47422. }
  47423. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47424. {
  47425. sendSelectionChangeMessage();
  47426. }
  47427. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47428. {
  47429. }
  47430. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47431. {
  47432. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47433. }
  47434. END_JUCE_NAMESPACE
  47435. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47436. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47437. BEGIN_JUCE_NAMESPACE
  47438. FilenameComponent::FilenameComponent (const String& name,
  47439. const File& currentFile,
  47440. const bool canEditFilename,
  47441. const bool isDirectory,
  47442. const bool isForSaving,
  47443. const String& fileBrowserWildcard,
  47444. const String& enforcedSuffix_,
  47445. const String& textWhenNothingSelected)
  47446. : Component (name),
  47447. maxRecentFiles (30),
  47448. isDir (isDirectory),
  47449. isSaving (isForSaving),
  47450. isFileDragOver (false),
  47451. wildcard (fileBrowserWildcard),
  47452. enforcedSuffix (enforcedSuffix_)
  47453. {
  47454. addAndMakeVisible (&filenameBox);
  47455. filenameBox.setEditableText (canEditFilename);
  47456. filenameBox.addListener (this);
  47457. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47458. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47459. setBrowseButtonText ("...");
  47460. setCurrentFile (currentFile, true);
  47461. }
  47462. FilenameComponent::~FilenameComponent()
  47463. {
  47464. }
  47465. void FilenameComponent::paintOverChildren (Graphics& g)
  47466. {
  47467. if (isFileDragOver)
  47468. {
  47469. g.setColour (Colours::red.withAlpha (0.2f));
  47470. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47471. }
  47472. }
  47473. void FilenameComponent::resized()
  47474. {
  47475. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47476. }
  47477. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47478. {
  47479. browseButtonText = newBrowseButtonText;
  47480. lookAndFeelChanged();
  47481. }
  47482. void FilenameComponent::lookAndFeelChanged()
  47483. {
  47484. browseButton = 0;
  47485. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47486. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47487. resized();
  47488. browseButton->addListener (this);
  47489. }
  47490. void FilenameComponent::setTooltip (const String& newTooltip)
  47491. {
  47492. SettableTooltipClient::setTooltip (newTooltip);
  47493. filenameBox.setTooltip (newTooltip);
  47494. }
  47495. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47496. {
  47497. defaultBrowseFile = newDefaultDirectory;
  47498. }
  47499. void FilenameComponent::buttonClicked (Button*)
  47500. {
  47501. FileChooser fc (TRANS("Choose a new file"),
  47502. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47503. : getCurrentFile(),
  47504. wildcard);
  47505. if (isDir ? fc.browseForDirectory()
  47506. : (isSaving ? fc.browseForFileToSave (false)
  47507. : fc.browseForFileToOpen()))
  47508. {
  47509. setCurrentFile (fc.getResult(), true);
  47510. }
  47511. }
  47512. void FilenameComponent::comboBoxChanged (ComboBox*)
  47513. {
  47514. setCurrentFile (getCurrentFile(), true);
  47515. }
  47516. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47517. {
  47518. return true;
  47519. }
  47520. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47521. {
  47522. isFileDragOver = false;
  47523. repaint();
  47524. const File f (filenames[0]);
  47525. if (f.exists() && (f.isDirectory() == isDir))
  47526. setCurrentFile (f, true);
  47527. }
  47528. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47529. {
  47530. isFileDragOver = true;
  47531. repaint();
  47532. }
  47533. void FilenameComponent::fileDragExit (const StringArray&)
  47534. {
  47535. isFileDragOver = false;
  47536. repaint();
  47537. }
  47538. const File FilenameComponent::getCurrentFile() const
  47539. {
  47540. File f (filenameBox.getText());
  47541. if (enforcedSuffix.isNotEmpty())
  47542. f = f.withFileExtension (enforcedSuffix);
  47543. return f;
  47544. }
  47545. void FilenameComponent::setCurrentFile (File newFile,
  47546. const bool addToRecentlyUsedList,
  47547. const bool sendChangeNotification)
  47548. {
  47549. if (enforcedSuffix.isNotEmpty())
  47550. newFile = newFile.withFileExtension (enforcedSuffix);
  47551. if (newFile.getFullPathName() != lastFilename)
  47552. {
  47553. lastFilename = newFile.getFullPathName();
  47554. if (addToRecentlyUsedList)
  47555. addRecentlyUsedFile (newFile);
  47556. filenameBox.setText (lastFilename, true);
  47557. if (sendChangeNotification)
  47558. triggerAsyncUpdate();
  47559. }
  47560. }
  47561. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47562. {
  47563. filenameBox.setEditableText (shouldBeEditable);
  47564. }
  47565. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47566. {
  47567. StringArray names;
  47568. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47569. names.add (filenameBox.getItemText (i));
  47570. return names;
  47571. }
  47572. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47573. {
  47574. if (filenames != getRecentlyUsedFilenames())
  47575. {
  47576. filenameBox.clear();
  47577. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47578. filenameBox.addItem (filenames[i], i + 1);
  47579. }
  47580. }
  47581. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47582. {
  47583. maxRecentFiles = jmax (1, newMaximum);
  47584. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47585. }
  47586. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47587. {
  47588. StringArray files (getRecentlyUsedFilenames());
  47589. if (file.getFullPathName().isNotEmpty())
  47590. {
  47591. files.removeString (file.getFullPathName(), true);
  47592. files.insert (0, file.getFullPathName());
  47593. setRecentlyUsedFilenames (files);
  47594. }
  47595. }
  47596. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47597. {
  47598. listeners.add (listener);
  47599. }
  47600. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47601. {
  47602. listeners.remove (listener);
  47603. }
  47604. void FilenameComponent::handleAsyncUpdate()
  47605. {
  47606. Component::BailOutChecker checker (this);
  47607. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47608. }
  47609. END_JUCE_NAMESPACE
  47610. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47611. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47612. BEGIN_JUCE_NAMESPACE
  47613. FileSearchPathListComponent::FileSearchPathListComponent()
  47614. : addButton ("+"),
  47615. removeButton ("-"),
  47616. changeButton (TRANS ("change...")),
  47617. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47618. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47619. {
  47620. listBox.setModel (this);
  47621. addAndMakeVisible (&listBox);
  47622. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47623. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47624. listBox.setOutlineThickness (1);
  47625. addAndMakeVisible (&addButton);
  47626. addButton.addListener (this);
  47627. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47628. addAndMakeVisible (&removeButton);
  47629. removeButton.addListener (this);
  47630. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47631. addAndMakeVisible (&changeButton);
  47632. changeButton.addListener (this);
  47633. addAndMakeVisible (&upButton);
  47634. upButton.addListener (this);
  47635. {
  47636. Path arrowPath;
  47637. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47638. DrawablePath arrowImage;
  47639. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47640. arrowImage.setPath (arrowPath);
  47641. upButton.setImages (&arrowImage);
  47642. }
  47643. addAndMakeVisible (&downButton);
  47644. downButton.addListener (this);
  47645. {
  47646. Path arrowPath;
  47647. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47648. DrawablePath arrowImage;
  47649. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47650. arrowImage.setPath (arrowPath);
  47651. downButton.setImages (&arrowImage);
  47652. }
  47653. updateButtons();
  47654. }
  47655. FileSearchPathListComponent::~FileSearchPathListComponent()
  47656. {
  47657. }
  47658. void FileSearchPathListComponent::updateButtons()
  47659. {
  47660. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47661. removeButton.setEnabled (anythingSelected);
  47662. changeButton.setEnabled (anythingSelected);
  47663. upButton.setEnabled (anythingSelected);
  47664. downButton.setEnabled (anythingSelected);
  47665. }
  47666. void FileSearchPathListComponent::changed()
  47667. {
  47668. listBox.updateContent();
  47669. listBox.repaint();
  47670. updateButtons();
  47671. }
  47672. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47673. {
  47674. if (newPath.toString() != path.toString())
  47675. {
  47676. path = newPath;
  47677. changed();
  47678. }
  47679. }
  47680. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47681. {
  47682. defaultBrowseTarget = newDefaultDirectory;
  47683. }
  47684. int FileSearchPathListComponent::getNumRows()
  47685. {
  47686. return path.getNumPaths();
  47687. }
  47688. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47689. {
  47690. if (rowIsSelected)
  47691. g.fillAll (findColour (TextEditor::highlightColourId));
  47692. g.setColour (findColour (ListBox::textColourId));
  47693. Font f (height * 0.7f);
  47694. f.setHorizontalScale (0.9f);
  47695. g.setFont (f);
  47696. g.drawText (path [rowNumber].getFullPathName(),
  47697. 4, 0, width - 6, height,
  47698. Justification::centredLeft, true);
  47699. }
  47700. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47701. {
  47702. if (isPositiveAndBelow (row, path.getNumPaths()))
  47703. {
  47704. path.remove (row);
  47705. changed();
  47706. }
  47707. }
  47708. void FileSearchPathListComponent::returnKeyPressed (int row)
  47709. {
  47710. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47711. if (chooser.browseForDirectory())
  47712. {
  47713. path.remove (row);
  47714. path.add (chooser.getResult(), row);
  47715. changed();
  47716. }
  47717. }
  47718. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47719. {
  47720. returnKeyPressed (row);
  47721. }
  47722. void FileSearchPathListComponent::selectedRowsChanged (int)
  47723. {
  47724. updateButtons();
  47725. }
  47726. void FileSearchPathListComponent::paint (Graphics& g)
  47727. {
  47728. g.fillAll (findColour (backgroundColourId));
  47729. }
  47730. void FileSearchPathListComponent::resized()
  47731. {
  47732. const int buttonH = 22;
  47733. const int buttonY = getHeight() - buttonH - 4;
  47734. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47735. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47736. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47737. changeButton.changeWidthToFitText (buttonH);
  47738. downButton.setSize (buttonH * 2, buttonH);
  47739. upButton.setSize (buttonH * 2, buttonH);
  47740. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47741. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47742. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47743. }
  47744. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47745. {
  47746. return true;
  47747. }
  47748. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47749. {
  47750. for (int i = filenames.size(); --i >= 0;)
  47751. {
  47752. const File f (filenames[i]);
  47753. if (f.isDirectory())
  47754. {
  47755. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47756. path.add (f, row);
  47757. changed();
  47758. }
  47759. }
  47760. }
  47761. void FileSearchPathListComponent::buttonClicked (Button* button)
  47762. {
  47763. const int currentRow = listBox.getSelectedRow();
  47764. if (button == &removeButton)
  47765. {
  47766. deleteKeyPressed (currentRow);
  47767. }
  47768. else if (button == &addButton)
  47769. {
  47770. File start (defaultBrowseTarget);
  47771. if (start == File::nonexistent)
  47772. start = path [0];
  47773. if (start == File::nonexistent)
  47774. start = File::getCurrentWorkingDirectory();
  47775. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47776. if (chooser.browseForDirectory())
  47777. {
  47778. path.add (chooser.getResult(), currentRow);
  47779. }
  47780. }
  47781. else if (button == &changeButton)
  47782. {
  47783. returnKeyPressed (currentRow);
  47784. }
  47785. else if (button == &upButton)
  47786. {
  47787. if (currentRow > 0 && currentRow < path.getNumPaths())
  47788. {
  47789. const File f (path[currentRow]);
  47790. path.remove (currentRow);
  47791. path.add (f, currentRow - 1);
  47792. listBox.selectRow (currentRow - 1);
  47793. }
  47794. }
  47795. else if (button == &downButton)
  47796. {
  47797. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47798. {
  47799. const File f (path[currentRow]);
  47800. path.remove (currentRow);
  47801. path.add (f, currentRow + 1);
  47802. listBox.selectRow (currentRow + 1);
  47803. }
  47804. }
  47805. changed();
  47806. }
  47807. END_JUCE_NAMESPACE
  47808. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47809. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47810. BEGIN_JUCE_NAMESPACE
  47811. const Image juce_createIconForFile (const File& file);
  47812. class FileListTreeItem : public TreeViewItem,
  47813. public TimeSliceClient,
  47814. public AsyncUpdater,
  47815. public ChangeListener
  47816. {
  47817. public:
  47818. FileListTreeItem (FileTreeComponent& owner_,
  47819. DirectoryContentsList* const parentContentsList_,
  47820. const int indexInContentsList_,
  47821. const File& file_,
  47822. TimeSliceThread& thread_)
  47823. : file (file_),
  47824. owner (owner_),
  47825. parentContentsList (parentContentsList_),
  47826. indexInContentsList (indexInContentsList_),
  47827. subContentsList (0),
  47828. canDeleteSubContentsList (false),
  47829. thread (thread_),
  47830. icon (0)
  47831. {
  47832. DirectoryContentsList::FileInfo fileInfo;
  47833. if (parentContentsList_ != 0
  47834. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47835. {
  47836. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47837. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47838. isDirectory = fileInfo.isDirectory;
  47839. }
  47840. else
  47841. {
  47842. isDirectory = true;
  47843. }
  47844. }
  47845. ~FileListTreeItem()
  47846. {
  47847. thread.removeTimeSliceClient (this);
  47848. clearSubItems();
  47849. if (canDeleteSubContentsList)
  47850. delete subContentsList;
  47851. }
  47852. bool mightContainSubItems() { return isDirectory; }
  47853. const String getUniqueName() const { return file.getFullPathName(); }
  47854. int getItemHeight() const { return 22; }
  47855. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47856. void itemOpennessChanged (bool isNowOpen)
  47857. {
  47858. if (isNowOpen)
  47859. {
  47860. clearSubItems();
  47861. isDirectory = file.isDirectory();
  47862. if (isDirectory)
  47863. {
  47864. if (subContentsList == 0)
  47865. {
  47866. jassert (parentContentsList != 0);
  47867. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47868. l->setDirectory (file, true, true);
  47869. setSubContentsList (l);
  47870. canDeleteSubContentsList = true;
  47871. }
  47872. changeListenerCallback (0);
  47873. }
  47874. }
  47875. }
  47876. void setSubContentsList (DirectoryContentsList* newList)
  47877. {
  47878. jassert (subContentsList == 0);
  47879. subContentsList = newList;
  47880. newList->addChangeListener (this);
  47881. }
  47882. void changeListenerCallback (ChangeBroadcaster*)
  47883. {
  47884. clearSubItems();
  47885. if (isOpen() && subContentsList != 0)
  47886. {
  47887. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47888. {
  47889. FileListTreeItem* const item
  47890. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47891. addSubItem (item);
  47892. }
  47893. }
  47894. }
  47895. void paintItem (Graphics& g, int width, int height)
  47896. {
  47897. if (file != File::nonexistent)
  47898. {
  47899. updateIcon (true);
  47900. if (icon.isNull())
  47901. thread.addTimeSliceClient (this);
  47902. }
  47903. owner.getLookAndFeel()
  47904. .drawFileBrowserRow (g, width, height,
  47905. file.getFileName(),
  47906. &icon, fileSize, modTime,
  47907. isDirectory, isSelected(),
  47908. indexInContentsList, owner);
  47909. }
  47910. void itemClicked (const MouseEvent& e)
  47911. {
  47912. owner.sendMouseClickMessage (file, e);
  47913. }
  47914. void itemDoubleClicked (const MouseEvent& e)
  47915. {
  47916. TreeViewItem::itemDoubleClicked (e);
  47917. owner.sendDoubleClickMessage (file);
  47918. }
  47919. void itemSelectionChanged (bool)
  47920. {
  47921. owner.sendSelectionChangeMessage();
  47922. }
  47923. bool useTimeSlice()
  47924. {
  47925. updateIcon (false);
  47926. thread.removeTimeSliceClient (this);
  47927. return false;
  47928. }
  47929. void handleAsyncUpdate()
  47930. {
  47931. owner.repaint();
  47932. }
  47933. const File file;
  47934. private:
  47935. FileTreeComponent& owner;
  47936. DirectoryContentsList* parentContentsList;
  47937. int indexInContentsList;
  47938. DirectoryContentsList* subContentsList;
  47939. bool isDirectory, canDeleteSubContentsList;
  47940. TimeSliceThread& thread;
  47941. Image icon;
  47942. String fileSize;
  47943. String modTime;
  47944. void updateIcon (const bool onlyUpdateIfCached)
  47945. {
  47946. if (icon.isNull())
  47947. {
  47948. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47949. Image im (ImageCache::getFromHashCode (hashCode));
  47950. if (im.isNull() && ! onlyUpdateIfCached)
  47951. {
  47952. im = juce_createIconForFile (file);
  47953. if (im.isValid())
  47954. ImageCache::addImageToCache (im, hashCode);
  47955. }
  47956. if (im.isValid())
  47957. {
  47958. icon = im;
  47959. triggerAsyncUpdate();
  47960. }
  47961. }
  47962. }
  47963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47964. };
  47965. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47966. : DirectoryContentsDisplayComponent (listToShow)
  47967. {
  47968. FileListTreeItem* const root
  47969. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47970. listToShow.getTimeSliceThread());
  47971. root->setSubContentsList (&listToShow);
  47972. setRootItemVisible (false);
  47973. setRootItem (root);
  47974. }
  47975. FileTreeComponent::~FileTreeComponent()
  47976. {
  47977. deleteRootItem();
  47978. }
  47979. const File FileTreeComponent::getSelectedFile (const int index) const
  47980. {
  47981. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47982. return item != 0 ? item->file
  47983. : File::nonexistent;
  47984. }
  47985. void FileTreeComponent::deselectAllFiles()
  47986. {
  47987. clearSelectedItems();
  47988. }
  47989. void FileTreeComponent::scrollToTop()
  47990. {
  47991. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47992. }
  47993. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47994. {
  47995. dragAndDropDescription = description;
  47996. }
  47997. END_JUCE_NAMESPACE
  47998. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47999. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48000. BEGIN_JUCE_NAMESPACE
  48001. ImagePreviewComponent::ImagePreviewComponent()
  48002. {
  48003. }
  48004. ImagePreviewComponent::~ImagePreviewComponent()
  48005. {
  48006. }
  48007. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48008. {
  48009. const int availableW = proportionOfWidth (0.97f);
  48010. const int availableH = getHeight() - 13 * 4;
  48011. const double scale = jmin (1.0,
  48012. availableW / (double) w,
  48013. availableH / (double) h);
  48014. w = roundToInt (scale * w);
  48015. h = roundToInt (scale * h);
  48016. }
  48017. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48018. {
  48019. if (fileToLoad != file)
  48020. {
  48021. fileToLoad = file;
  48022. startTimer (100);
  48023. }
  48024. }
  48025. void ImagePreviewComponent::timerCallback()
  48026. {
  48027. stopTimer();
  48028. currentThumbnail = Image::null;
  48029. currentDetails = String::empty;
  48030. repaint();
  48031. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48032. if (in != 0)
  48033. {
  48034. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48035. if (format != 0)
  48036. {
  48037. currentThumbnail = format->decodeImage (*in);
  48038. if (currentThumbnail.isValid())
  48039. {
  48040. int w = currentThumbnail.getWidth();
  48041. int h = currentThumbnail.getHeight();
  48042. currentDetails
  48043. << fileToLoad.getFileName() << "\n"
  48044. << format->getFormatName() << "\n"
  48045. << w << " x " << h << " pixels\n"
  48046. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48047. getThumbSize (w, h);
  48048. currentThumbnail = currentThumbnail.rescaled (w, h);
  48049. }
  48050. }
  48051. }
  48052. }
  48053. void ImagePreviewComponent::paint (Graphics& g)
  48054. {
  48055. if (currentThumbnail.isValid())
  48056. {
  48057. g.setFont (13.0f);
  48058. int w = currentThumbnail.getWidth();
  48059. int h = currentThumbnail.getHeight();
  48060. getThumbSize (w, h);
  48061. const int numLines = 4;
  48062. const int totalH = 13 * numLines + h + 4;
  48063. const int y = (getHeight() - totalH) / 2;
  48064. g.drawImageWithin (currentThumbnail,
  48065. (getWidth() - w) / 2, y, w, h,
  48066. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48067. false);
  48068. g.drawFittedText (currentDetails,
  48069. 0, y + h + 4, getWidth(), 100,
  48070. Justification::centredTop, numLines);
  48071. }
  48072. }
  48073. END_JUCE_NAMESPACE
  48074. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48075. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48076. BEGIN_JUCE_NAMESPACE
  48077. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48078. const String& directoryWildcardPatterns,
  48079. const String& description_)
  48080. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48081. : (description_ + " (" + fileWildcardPatterns + ")"))
  48082. {
  48083. parse (fileWildcardPatterns, fileWildcards);
  48084. parse (directoryWildcardPatterns, directoryWildcards);
  48085. }
  48086. WildcardFileFilter::~WildcardFileFilter()
  48087. {
  48088. }
  48089. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48090. {
  48091. return match (file, fileWildcards);
  48092. }
  48093. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48094. {
  48095. return match (file, directoryWildcards);
  48096. }
  48097. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48098. {
  48099. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48100. result.trim();
  48101. result.removeEmptyStrings();
  48102. // special case for *.*, because people use it to mean "any file", but it
  48103. // would actually ignore files with no extension.
  48104. for (int i = result.size(); --i >= 0;)
  48105. if (result[i] == "*.*")
  48106. result.set (i, "*");
  48107. }
  48108. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48109. {
  48110. const String filename (file.getFileName());
  48111. for (int i = wildcards.size(); --i >= 0;)
  48112. if (filename.matchesWildcard (wildcards[i], true))
  48113. return true;
  48114. return false;
  48115. }
  48116. END_JUCE_NAMESPACE
  48117. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48118. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48119. BEGIN_JUCE_NAMESPACE
  48120. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48121. {
  48122. }
  48123. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48124. {
  48125. }
  48126. namespace KeyboardFocusHelpers
  48127. {
  48128. // This will sort a set of components, so that they are ordered in terms of
  48129. // left-to-right and then top-to-bottom.
  48130. class ScreenPositionComparator
  48131. {
  48132. public:
  48133. ScreenPositionComparator() {}
  48134. static int compareElements (const Component* const first, const Component* const second)
  48135. {
  48136. int explicitOrder1 = first->getExplicitFocusOrder();
  48137. if (explicitOrder1 <= 0)
  48138. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48139. int explicitOrder2 = second->getExplicitFocusOrder();
  48140. if (explicitOrder2 <= 0)
  48141. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48142. if (explicitOrder1 != explicitOrder2)
  48143. return explicitOrder1 - explicitOrder2;
  48144. const int diff = first->getY() - second->getY();
  48145. return (diff == 0) ? first->getX() - second->getX()
  48146. : diff;
  48147. }
  48148. };
  48149. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48150. {
  48151. if (parent->getNumChildComponents() > 0)
  48152. {
  48153. Array <Component*> localComps;
  48154. ScreenPositionComparator comparator;
  48155. int i;
  48156. for (i = parent->getNumChildComponents(); --i >= 0;)
  48157. {
  48158. Component* const c = parent->getChildComponent (i);
  48159. if (c->isVisible() && c->isEnabled())
  48160. localComps.addSorted (comparator, c);
  48161. }
  48162. for (i = 0; i < localComps.size(); ++i)
  48163. {
  48164. Component* const c = localComps.getUnchecked (i);
  48165. if (c->getWantsKeyboardFocus())
  48166. comps.add (c);
  48167. if (! c->isFocusContainer())
  48168. findAllFocusableComponents (c, comps);
  48169. }
  48170. }
  48171. }
  48172. }
  48173. namespace KeyboardFocusHelpers
  48174. {
  48175. Component* getIncrementedComponent (Component* const current, const int delta)
  48176. {
  48177. Component* focusContainer = current->getParentComponent();
  48178. if (focusContainer != 0)
  48179. {
  48180. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48181. focusContainer = focusContainer->getParentComponent();
  48182. if (focusContainer != 0)
  48183. {
  48184. Array <Component*> comps;
  48185. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48186. if (comps.size() > 0)
  48187. {
  48188. const int index = comps.indexOf (current);
  48189. return comps [(index + comps.size() + delta) % comps.size()];
  48190. }
  48191. }
  48192. }
  48193. return 0;
  48194. }
  48195. }
  48196. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48197. {
  48198. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48199. }
  48200. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48201. {
  48202. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48203. }
  48204. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48205. {
  48206. Array <Component*> comps;
  48207. if (parentComponent != 0)
  48208. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48209. return comps.getFirst();
  48210. }
  48211. END_JUCE_NAMESPACE
  48212. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48213. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48214. BEGIN_JUCE_NAMESPACE
  48215. bool KeyListener::keyStateChanged (const bool, Component*)
  48216. {
  48217. return false;
  48218. }
  48219. END_JUCE_NAMESPACE
  48220. /*** End of inlined file: juce_KeyListener.cpp ***/
  48221. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48222. BEGIN_JUCE_NAMESPACE
  48223. // N.B. these two includes are put here deliberately to avoid problems with
  48224. // old GCCs failing on long include paths
  48225. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48226. {
  48227. public:
  48228. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48229. const CommandID commandID_,
  48230. const String& keyName,
  48231. const int keyNum_)
  48232. : Button (keyName),
  48233. owner (owner_),
  48234. commandID (commandID_),
  48235. keyNum (keyNum_)
  48236. {
  48237. setWantsKeyboardFocus (false);
  48238. setTriggeredOnMouseDown (keyNum >= 0);
  48239. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48240. : TRANS("click to change this key-mapping"));
  48241. }
  48242. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48243. {
  48244. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48245. keyNum >= 0 ? getName() : String::empty);
  48246. }
  48247. void clicked()
  48248. {
  48249. if (keyNum >= 0)
  48250. {
  48251. // existing key clicked..
  48252. PopupMenu m;
  48253. m.addItem (1, TRANS("change this key-mapping"));
  48254. m.addSeparator();
  48255. m.addItem (2, TRANS("remove this key-mapping"));
  48256. switch (m.show())
  48257. {
  48258. case 1: assignNewKey(); break;
  48259. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48260. default: break;
  48261. }
  48262. }
  48263. else
  48264. {
  48265. assignNewKey(); // + button pressed..
  48266. }
  48267. }
  48268. void fitToContent (const int h) throw()
  48269. {
  48270. if (keyNum < 0)
  48271. {
  48272. setSize (h, h);
  48273. }
  48274. else
  48275. {
  48276. Font f (h * 0.6f);
  48277. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48278. }
  48279. }
  48280. class KeyEntryWindow : public AlertWindow
  48281. {
  48282. public:
  48283. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48284. : AlertWindow (TRANS("New key-mapping"),
  48285. TRANS("Please press a key combination now..."),
  48286. AlertWindow::NoIcon),
  48287. owner (owner_)
  48288. {
  48289. addButton (TRANS("Ok"), 1);
  48290. addButton (TRANS("Cancel"), 0);
  48291. // (avoid return + escape keys getting processed by the buttons..)
  48292. for (int i = getNumChildComponents(); --i >= 0;)
  48293. getChildComponent (i)->setWantsKeyboardFocus (false);
  48294. setWantsKeyboardFocus (true);
  48295. grabKeyboardFocus();
  48296. }
  48297. bool keyPressed (const KeyPress& key)
  48298. {
  48299. lastPress = key;
  48300. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48301. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48302. if (previousCommand != 0)
  48303. message << "\n\n" << TRANS("(Currently assigned to \"")
  48304. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48305. setMessage (message);
  48306. return true;
  48307. }
  48308. bool keyStateChanged (bool)
  48309. {
  48310. return true;
  48311. }
  48312. KeyPress lastPress;
  48313. private:
  48314. KeyMappingEditorComponent& owner;
  48315. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48316. };
  48317. void assignNewKey()
  48318. {
  48319. KeyEntryWindow entryWindow (owner);
  48320. if (entryWindow.runModalLoop() != 0)
  48321. {
  48322. entryWindow.setVisible (false);
  48323. if (entryWindow.lastPress.isValid())
  48324. {
  48325. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48326. if (previousCommand == 0
  48327. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48328. TRANS("Change key-mapping"),
  48329. TRANS("This key is already assigned to the command \"")
  48330. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48331. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48332. TRANS("Re-assign"),
  48333. TRANS("Cancel")))
  48334. {
  48335. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48336. if (keyNum >= 0)
  48337. owner.getMappings().removeKeyPress (commandID, keyNum);
  48338. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48339. }
  48340. }
  48341. }
  48342. }
  48343. private:
  48344. KeyMappingEditorComponent& owner;
  48345. const CommandID commandID;
  48346. const int keyNum;
  48347. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48348. };
  48349. class KeyMappingEditorComponent::ItemComponent : public Component
  48350. {
  48351. public:
  48352. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48353. : owner (owner_), commandID (commandID_)
  48354. {
  48355. setInterceptsMouseClicks (false, true);
  48356. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48357. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48358. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48359. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48360. addKeyPressButton (String::empty, -1, isReadOnly);
  48361. }
  48362. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48363. {
  48364. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48365. keyChangeButtons.add (b);
  48366. b->setEnabled (! isReadOnly);
  48367. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48368. addChildComponent (b);
  48369. }
  48370. void paint (Graphics& g)
  48371. {
  48372. g.setFont (getHeight() * 0.7f);
  48373. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48374. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48375. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48376. Justification::centredLeft, true);
  48377. }
  48378. void resized()
  48379. {
  48380. int x = getWidth() - 4;
  48381. for (int i = keyChangeButtons.size(); --i >= 0;)
  48382. {
  48383. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48384. b->fitToContent (getHeight() - 2);
  48385. b->setTopRightPosition (x, 1);
  48386. x = b->getX() - 5;
  48387. }
  48388. }
  48389. private:
  48390. KeyMappingEditorComponent& owner;
  48391. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48392. const CommandID commandID;
  48393. enum { maxNumAssignments = 3 };
  48394. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48395. };
  48396. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48397. {
  48398. public:
  48399. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48400. : owner (owner_), commandID (commandID_)
  48401. {
  48402. }
  48403. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48404. bool mightContainSubItems() { return false; }
  48405. int getItemHeight() const { return 20; }
  48406. Component* createItemComponent()
  48407. {
  48408. return new ItemComponent (owner, commandID);
  48409. }
  48410. private:
  48411. KeyMappingEditorComponent& owner;
  48412. const CommandID commandID;
  48413. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48414. };
  48415. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48416. {
  48417. public:
  48418. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48419. : owner (owner_), categoryName (name)
  48420. {
  48421. }
  48422. const String getUniqueName() const { return categoryName + "_cat"; }
  48423. bool mightContainSubItems() { return true; }
  48424. int getItemHeight() const { return 28; }
  48425. void paintItem (Graphics& g, int width, int height)
  48426. {
  48427. g.setFont (height * 0.6f, Font::bold);
  48428. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48429. g.drawText (categoryName,
  48430. 2, 0, width - 2, height,
  48431. Justification::centredLeft, true);
  48432. }
  48433. void itemOpennessChanged (bool isNowOpen)
  48434. {
  48435. if (isNowOpen)
  48436. {
  48437. if (getNumSubItems() == 0)
  48438. {
  48439. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48440. for (int i = 0; i < commands.size(); ++i)
  48441. {
  48442. if (owner.shouldCommandBeIncluded (commands[i]))
  48443. addSubItem (new MappingItem (owner, commands[i]));
  48444. }
  48445. }
  48446. }
  48447. else
  48448. {
  48449. clearSubItems();
  48450. }
  48451. }
  48452. private:
  48453. KeyMappingEditorComponent& owner;
  48454. String categoryName;
  48455. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48456. };
  48457. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48458. public ChangeListener,
  48459. public ButtonListener
  48460. {
  48461. public:
  48462. TopLevelItem (KeyMappingEditorComponent& owner_)
  48463. : owner (owner_)
  48464. {
  48465. setLinesDrawnForSubItems (false);
  48466. owner.getMappings().addChangeListener (this);
  48467. }
  48468. ~TopLevelItem()
  48469. {
  48470. owner.getMappings().removeChangeListener (this);
  48471. }
  48472. bool mightContainSubItems() { return true; }
  48473. const String getUniqueName() const { return "keys"; }
  48474. void changeListenerCallback (ChangeBroadcaster*)
  48475. {
  48476. const ScopedPointer <XmlElement> oldOpenness (owner.tree.getOpennessState (true));
  48477. clearSubItems();
  48478. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48479. for (int i = 0; i < categories.size(); ++i)
  48480. {
  48481. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48482. int count = 0;
  48483. for (int j = 0; j < commands.size(); ++j)
  48484. if (owner.shouldCommandBeIncluded (commands[j]))
  48485. ++count;
  48486. if (count > 0)
  48487. addSubItem (new CategoryItem (owner, categories[i]));
  48488. }
  48489. if (oldOpenness != 0)
  48490. owner.tree.restoreOpennessState (*oldOpenness);
  48491. }
  48492. void buttonClicked (Button*)
  48493. {
  48494. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48495. TRANS("Reset to defaults"),
  48496. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48497. TRANS("Reset")))
  48498. {
  48499. owner.getMappings().resetToDefaultMappings();
  48500. }
  48501. }
  48502. private:
  48503. KeyMappingEditorComponent& owner;
  48504. };
  48505. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48506. const bool showResetToDefaultButton)
  48507. : mappings (mappingManager),
  48508. resetButton (TRANS ("reset to defaults"))
  48509. {
  48510. treeItem = new TopLevelItem (*this);
  48511. if (showResetToDefaultButton)
  48512. {
  48513. addAndMakeVisible (&resetButton);
  48514. resetButton.addListener (treeItem);
  48515. }
  48516. addAndMakeVisible (&tree);
  48517. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48518. tree.setRootItemVisible (false);
  48519. tree.setDefaultOpenness (true);
  48520. tree.setRootItem (treeItem);
  48521. }
  48522. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48523. {
  48524. tree.setRootItem (0);
  48525. }
  48526. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48527. const Colour& textColour)
  48528. {
  48529. setColour (backgroundColourId, mainBackground);
  48530. setColour (textColourId, textColour);
  48531. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48532. }
  48533. void KeyMappingEditorComponent::parentHierarchyChanged()
  48534. {
  48535. treeItem->changeListenerCallback (0);
  48536. }
  48537. void KeyMappingEditorComponent::resized()
  48538. {
  48539. int h = getHeight();
  48540. if (resetButton.isVisible())
  48541. {
  48542. const int buttonHeight = 20;
  48543. h -= buttonHeight + 8;
  48544. int x = getWidth() - 8;
  48545. resetButton.changeWidthToFitText (buttonHeight);
  48546. resetButton.setTopRightPosition (x, h + 6);
  48547. }
  48548. tree.setBounds (0, 0, getWidth(), h);
  48549. }
  48550. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48551. {
  48552. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48553. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48554. }
  48555. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48556. {
  48557. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48558. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48559. }
  48560. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48561. {
  48562. return key.getTextDescription();
  48563. }
  48564. END_JUCE_NAMESPACE
  48565. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48566. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48567. BEGIN_JUCE_NAMESPACE
  48568. KeyPress::KeyPress() throw()
  48569. : keyCode (0),
  48570. mods (0),
  48571. textCharacter (0)
  48572. {
  48573. }
  48574. KeyPress::KeyPress (const int keyCode_,
  48575. const ModifierKeys& mods_,
  48576. const juce_wchar textCharacter_) throw()
  48577. : keyCode (keyCode_),
  48578. mods (mods_),
  48579. textCharacter (textCharacter_)
  48580. {
  48581. }
  48582. KeyPress::KeyPress (const int keyCode_) throw()
  48583. : keyCode (keyCode_),
  48584. textCharacter (0)
  48585. {
  48586. }
  48587. KeyPress::KeyPress (const KeyPress& other) throw()
  48588. : keyCode (other.keyCode),
  48589. mods (other.mods),
  48590. textCharacter (other.textCharacter)
  48591. {
  48592. }
  48593. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48594. {
  48595. keyCode = other.keyCode;
  48596. mods = other.mods;
  48597. textCharacter = other.textCharacter;
  48598. return *this;
  48599. }
  48600. bool KeyPress::operator== (const KeyPress& other) const throw()
  48601. {
  48602. return mods.getRawFlags() == other.mods.getRawFlags()
  48603. && (textCharacter == other.textCharacter
  48604. || textCharacter == 0
  48605. || other.textCharacter == 0)
  48606. && (keyCode == other.keyCode
  48607. || (keyCode < 256
  48608. && other.keyCode < 256
  48609. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48610. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48611. }
  48612. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48613. {
  48614. return ! operator== (other);
  48615. }
  48616. bool KeyPress::isCurrentlyDown() const
  48617. {
  48618. return isKeyCurrentlyDown (keyCode)
  48619. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48620. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48621. }
  48622. namespace KeyPressHelpers
  48623. {
  48624. struct KeyNameAndCode
  48625. {
  48626. const char* name;
  48627. int code;
  48628. };
  48629. const KeyNameAndCode translations[] =
  48630. {
  48631. { "spacebar", KeyPress::spaceKey },
  48632. { "return", KeyPress::returnKey },
  48633. { "escape", KeyPress::escapeKey },
  48634. { "backspace", KeyPress::backspaceKey },
  48635. { "cursor left", KeyPress::leftKey },
  48636. { "cursor right", KeyPress::rightKey },
  48637. { "cursor up", KeyPress::upKey },
  48638. { "cursor down", KeyPress::downKey },
  48639. { "page up", KeyPress::pageUpKey },
  48640. { "page down", KeyPress::pageDownKey },
  48641. { "home", KeyPress::homeKey },
  48642. { "end", KeyPress::endKey },
  48643. { "delete", KeyPress::deleteKey },
  48644. { "insert", KeyPress::insertKey },
  48645. { "tab", KeyPress::tabKey },
  48646. { "play", KeyPress::playKey },
  48647. { "stop", KeyPress::stopKey },
  48648. { "fast forward", KeyPress::fastForwardKey },
  48649. { "rewind", KeyPress::rewindKey }
  48650. };
  48651. const String numberPadPrefix() { return "numpad "; }
  48652. }
  48653. const KeyPress KeyPress::createFromDescription (const String& desc)
  48654. {
  48655. int modifiers = 0;
  48656. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48657. || desc.containsWholeWordIgnoreCase ("control")
  48658. || desc.containsWholeWordIgnoreCase ("ctl"))
  48659. modifiers |= ModifierKeys::ctrlModifier;
  48660. if (desc.containsWholeWordIgnoreCase ("shift")
  48661. || desc.containsWholeWordIgnoreCase ("shft"))
  48662. modifiers |= ModifierKeys::shiftModifier;
  48663. if (desc.containsWholeWordIgnoreCase ("alt")
  48664. || desc.containsWholeWordIgnoreCase ("option"))
  48665. modifiers |= ModifierKeys::altModifier;
  48666. if (desc.containsWholeWordIgnoreCase ("command")
  48667. || desc.containsWholeWordIgnoreCase ("cmd"))
  48668. modifiers |= ModifierKeys::commandModifier;
  48669. int key = 0;
  48670. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48671. {
  48672. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48673. {
  48674. key = KeyPressHelpers::translations[i].code;
  48675. break;
  48676. }
  48677. }
  48678. if (key == 0)
  48679. {
  48680. // see if it's a numpad key..
  48681. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48682. {
  48683. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48684. if (lastChar >= '0' && lastChar <= '9')
  48685. key = numberPad0 + lastChar - '0';
  48686. else if (lastChar == '+')
  48687. key = numberPadAdd;
  48688. else if (lastChar == '-')
  48689. key = numberPadSubtract;
  48690. else if (lastChar == '*')
  48691. key = numberPadMultiply;
  48692. else if (lastChar == '/')
  48693. key = numberPadDivide;
  48694. else if (lastChar == '.')
  48695. key = numberPadDecimalPoint;
  48696. else if (lastChar == '=')
  48697. key = numberPadEquals;
  48698. else if (desc.endsWith ("separator"))
  48699. key = numberPadSeparator;
  48700. else if (desc.endsWith ("delete"))
  48701. key = numberPadDelete;
  48702. }
  48703. if (key == 0)
  48704. {
  48705. // see if it's a function key..
  48706. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48707. for (int i = 1; i <= 12; ++i)
  48708. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48709. key = F1Key + i - 1;
  48710. if (key == 0)
  48711. {
  48712. // give up and use the hex code..
  48713. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48714. .toLowerCase()
  48715. .retainCharacters ("0123456789abcdef")
  48716. .getHexValue32();
  48717. if (hexCode > 0)
  48718. key = hexCode;
  48719. else
  48720. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48721. }
  48722. }
  48723. }
  48724. return KeyPress (key, ModifierKeys (modifiers), 0);
  48725. }
  48726. const String KeyPress::getTextDescription() const
  48727. {
  48728. String desc;
  48729. if (keyCode > 0)
  48730. {
  48731. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48732. // want to store it as being a slash, not shift+whatever.
  48733. if (textCharacter == '/')
  48734. return "/";
  48735. if (mods.isCtrlDown())
  48736. desc << "ctrl + ";
  48737. if (mods.isShiftDown())
  48738. desc << "shift + ";
  48739. #if JUCE_MAC
  48740. // only do this on the mac, because on Windows ctrl and command are the same,
  48741. // and this would get confusing
  48742. if (mods.isCommandDown())
  48743. desc << "command + ";
  48744. if (mods.isAltDown())
  48745. desc << "option + ";
  48746. #else
  48747. if (mods.isAltDown())
  48748. desc << "alt + ";
  48749. #endif
  48750. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48751. if (keyCode == KeyPressHelpers::translations[i].code)
  48752. return desc + KeyPressHelpers::translations[i].name;
  48753. if (keyCode >= F1Key && keyCode <= F16Key)
  48754. desc << 'F' << (1 + keyCode - F1Key);
  48755. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48756. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48757. else if (keyCode >= 33 && keyCode < 176)
  48758. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48759. else if (keyCode == numberPadAdd)
  48760. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48761. else if (keyCode == numberPadSubtract)
  48762. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48763. else if (keyCode == numberPadMultiply)
  48764. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48765. else if (keyCode == numberPadDivide)
  48766. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48767. else if (keyCode == numberPadSeparator)
  48768. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48769. else if (keyCode == numberPadDecimalPoint)
  48770. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48771. else if (keyCode == numberPadDelete)
  48772. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48773. else
  48774. desc << '#' << String::toHexString (keyCode);
  48775. }
  48776. return desc;
  48777. }
  48778. END_JUCE_NAMESPACE
  48779. /*** End of inlined file: juce_KeyPress.cpp ***/
  48780. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48781. BEGIN_JUCE_NAMESPACE
  48782. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48783. : commandManager (commandManager_)
  48784. {
  48785. // A manager is needed to get the descriptions of commands, and will be called when
  48786. // a command is invoked. So you can't leave this null..
  48787. jassert (commandManager_ != 0);
  48788. Desktop::getInstance().addFocusChangeListener (this);
  48789. }
  48790. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48791. : commandManager (other.commandManager)
  48792. {
  48793. Desktop::getInstance().addFocusChangeListener (this);
  48794. }
  48795. KeyPressMappingSet::~KeyPressMappingSet()
  48796. {
  48797. Desktop::getInstance().removeFocusChangeListener (this);
  48798. }
  48799. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48800. {
  48801. for (int i = 0; i < mappings.size(); ++i)
  48802. if (mappings.getUnchecked(i)->commandID == commandID)
  48803. return mappings.getUnchecked (i)->keypresses;
  48804. return Array <KeyPress> ();
  48805. }
  48806. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48807. const KeyPress& newKeyPress,
  48808. int insertIndex)
  48809. {
  48810. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48811. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48812. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48813. && ! newKeyPress.getModifiers().isShiftDown()));
  48814. if (findCommandForKeyPress (newKeyPress) != commandID)
  48815. {
  48816. removeKeyPress (newKeyPress);
  48817. if (newKeyPress.isValid())
  48818. {
  48819. for (int i = mappings.size(); --i >= 0;)
  48820. {
  48821. if (mappings.getUnchecked(i)->commandID == commandID)
  48822. {
  48823. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48824. sendChangeMessage();
  48825. return;
  48826. }
  48827. }
  48828. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48829. if (ci != 0)
  48830. {
  48831. CommandMapping* const cm = new CommandMapping();
  48832. cm->commandID = commandID;
  48833. cm->keypresses.add (newKeyPress);
  48834. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48835. mappings.add (cm);
  48836. sendChangeMessage();
  48837. }
  48838. }
  48839. }
  48840. }
  48841. void KeyPressMappingSet::resetToDefaultMappings()
  48842. {
  48843. mappings.clear();
  48844. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48845. {
  48846. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48847. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48848. {
  48849. addKeyPress (ci->commandID,
  48850. ci->defaultKeypresses.getReference (j));
  48851. }
  48852. }
  48853. sendChangeMessage();
  48854. }
  48855. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48856. {
  48857. clearAllKeyPresses (commandID);
  48858. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48859. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48860. {
  48861. addKeyPress (ci->commandID,
  48862. ci->defaultKeypresses.getReference (j));
  48863. }
  48864. }
  48865. void KeyPressMappingSet::clearAllKeyPresses()
  48866. {
  48867. if (mappings.size() > 0)
  48868. {
  48869. sendChangeMessage();
  48870. mappings.clear();
  48871. }
  48872. }
  48873. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48874. {
  48875. for (int i = mappings.size(); --i >= 0;)
  48876. {
  48877. if (mappings.getUnchecked(i)->commandID == commandID)
  48878. {
  48879. mappings.remove (i);
  48880. sendChangeMessage();
  48881. }
  48882. }
  48883. }
  48884. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48885. {
  48886. if (keypress.isValid())
  48887. {
  48888. for (int i = mappings.size(); --i >= 0;)
  48889. {
  48890. CommandMapping* const cm = mappings.getUnchecked(i);
  48891. for (int j = cm->keypresses.size(); --j >= 0;)
  48892. {
  48893. if (keypress == cm->keypresses [j])
  48894. {
  48895. cm->keypresses.remove (j);
  48896. sendChangeMessage();
  48897. }
  48898. }
  48899. }
  48900. }
  48901. }
  48902. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48903. {
  48904. for (int i = mappings.size(); --i >= 0;)
  48905. {
  48906. if (mappings.getUnchecked(i)->commandID == commandID)
  48907. {
  48908. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48909. sendChangeMessage();
  48910. break;
  48911. }
  48912. }
  48913. }
  48914. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48915. {
  48916. for (int i = 0; i < mappings.size(); ++i)
  48917. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48918. return mappings.getUnchecked(i)->commandID;
  48919. return 0;
  48920. }
  48921. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48922. {
  48923. for (int i = mappings.size(); --i >= 0;)
  48924. if (mappings.getUnchecked(i)->commandID == commandID)
  48925. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48926. return false;
  48927. }
  48928. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48929. const KeyPress& key,
  48930. const bool isKeyDown,
  48931. const int millisecsSinceKeyPressed,
  48932. Component* const originatingComponent) const
  48933. {
  48934. ApplicationCommandTarget::InvocationInfo info (commandID);
  48935. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48936. info.isKeyDown = isKeyDown;
  48937. info.keyPress = key;
  48938. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48939. info.originatingComponent = originatingComponent;
  48940. commandManager->invoke (info, false);
  48941. }
  48942. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48943. {
  48944. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48945. {
  48946. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48947. {
  48948. // if the XML was created as a set of differences from the default mappings,
  48949. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48950. resetToDefaultMappings();
  48951. }
  48952. else
  48953. {
  48954. // if the XML was created calling createXml (false), then we need to clear all
  48955. // the keys and treat the xml as describing the entire set of mappings.
  48956. clearAllKeyPresses();
  48957. }
  48958. forEachXmlChildElement (xmlVersion, map)
  48959. {
  48960. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48961. if (commandId != 0)
  48962. {
  48963. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48964. if (map->hasTagName ("MAPPING"))
  48965. {
  48966. addKeyPress (commandId, key);
  48967. }
  48968. else if (map->hasTagName ("UNMAPPING"))
  48969. {
  48970. if (containsMapping (commandId, key))
  48971. removeKeyPress (key);
  48972. }
  48973. }
  48974. }
  48975. return true;
  48976. }
  48977. return false;
  48978. }
  48979. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48980. {
  48981. ScopedPointer <KeyPressMappingSet> defaultSet;
  48982. if (saveDifferencesFromDefaultSet)
  48983. {
  48984. defaultSet = new KeyPressMappingSet (commandManager);
  48985. defaultSet->resetToDefaultMappings();
  48986. }
  48987. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48988. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48989. int i;
  48990. for (i = 0; i < mappings.size(); ++i)
  48991. {
  48992. const CommandMapping* const cm = mappings.getUnchecked(i);
  48993. for (int j = 0; j < cm->keypresses.size(); ++j)
  48994. {
  48995. if (defaultSet == 0
  48996. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48997. {
  48998. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48999. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49000. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49001. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49002. }
  49003. }
  49004. }
  49005. if (defaultSet != 0)
  49006. {
  49007. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49008. {
  49009. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49010. for (int j = 0; j < cm->keypresses.size(); ++j)
  49011. {
  49012. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49013. {
  49014. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49015. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49016. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49017. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49018. }
  49019. }
  49020. }
  49021. }
  49022. return doc;
  49023. }
  49024. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49025. Component* originatingComponent)
  49026. {
  49027. bool used = false;
  49028. const CommandID commandID = findCommandForKeyPress (key);
  49029. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49030. if (ci != 0
  49031. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49032. {
  49033. ApplicationCommandInfo info (0);
  49034. if (commandManager->getTargetForCommand (commandID, info) != 0
  49035. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49036. {
  49037. invokeCommand (commandID, key, true, 0, originatingComponent);
  49038. used = true;
  49039. }
  49040. else
  49041. {
  49042. if (originatingComponent != 0)
  49043. originatingComponent->getLookAndFeel().playAlertSound();
  49044. }
  49045. }
  49046. return used;
  49047. }
  49048. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49049. {
  49050. bool used = false;
  49051. const uint32 now = Time::getMillisecondCounter();
  49052. for (int i = mappings.size(); --i >= 0;)
  49053. {
  49054. CommandMapping* const cm = mappings.getUnchecked(i);
  49055. if (cm->wantsKeyUpDownCallbacks)
  49056. {
  49057. for (int j = cm->keypresses.size(); --j >= 0;)
  49058. {
  49059. const KeyPress key (cm->keypresses.getReference (j));
  49060. const bool isDown = key.isCurrentlyDown();
  49061. int keyPressEntryIndex = 0;
  49062. bool wasDown = false;
  49063. for (int k = keysDown.size(); --k >= 0;)
  49064. {
  49065. if (key == keysDown.getUnchecked(k)->key)
  49066. {
  49067. keyPressEntryIndex = k;
  49068. wasDown = true;
  49069. used = true;
  49070. break;
  49071. }
  49072. }
  49073. if (isDown != wasDown)
  49074. {
  49075. int millisecs = 0;
  49076. if (isDown)
  49077. {
  49078. KeyPressTime* const k = new KeyPressTime();
  49079. k->key = key;
  49080. k->timeWhenPressed = now;
  49081. keysDown.add (k);
  49082. }
  49083. else
  49084. {
  49085. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49086. if (now > pressTime)
  49087. millisecs = now - pressTime;
  49088. keysDown.remove (keyPressEntryIndex);
  49089. }
  49090. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49091. used = true;
  49092. }
  49093. }
  49094. }
  49095. }
  49096. return used;
  49097. }
  49098. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49099. {
  49100. if (focusedComponent != 0)
  49101. focusedComponent->keyStateChanged (false);
  49102. }
  49103. END_JUCE_NAMESPACE
  49104. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49105. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49106. BEGIN_JUCE_NAMESPACE
  49107. ModifierKeys::ModifierKeys (const int flags_) throw()
  49108. : flags (flags_)
  49109. {
  49110. }
  49111. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49112. : flags (other.flags)
  49113. {
  49114. }
  49115. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49116. {
  49117. flags = other.flags;
  49118. return *this;
  49119. }
  49120. ModifierKeys ModifierKeys::currentModifiers;
  49121. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49122. {
  49123. return currentModifiers;
  49124. }
  49125. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49126. {
  49127. int num = 0;
  49128. if (isLeftButtonDown()) ++num;
  49129. if (isRightButtonDown()) ++num;
  49130. if (isMiddleButtonDown()) ++num;
  49131. return num;
  49132. }
  49133. END_JUCE_NAMESPACE
  49134. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49135. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49136. BEGIN_JUCE_NAMESPACE
  49137. class ComponentAnimator::AnimationTask
  49138. {
  49139. public:
  49140. AnimationTask (Component* const comp)
  49141. : component (comp)
  49142. {
  49143. }
  49144. void reset (const Rectangle<int>& finalBounds,
  49145. float finalAlpha,
  49146. int millisecondsToSpendMoving,
  49147. bool useProxyComponent,
  49148. double startSpeed_, double endSpeed_)
  49149. {
  49150. msElapsed = 0;
  49151. msTotal = jmax (1, millisecondsToSpendMoving);
  49152. lastProgress = 0;
  49153. destination = finalBounds;
  49154. destAlpha = finalAlpha;
  49155. isMoving = (finalBounds != component->getBounds());
  49156. isChangingAlpha = (finalAlpha != component->getAlpha());
  49157. left = component->getX();
  49158. top = component->getY();
  49159. right = component->getRight();
  49160. bottom = component->getBottom();
  49161. alpha = component->getAlpha();
  49162. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49163. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49164. midSpeed = invTotalDistance;
  49165. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49166. if (useProxyComponent)
  49167. proxy = new ProxyComponent (*component);
  49168. else
  49169. proxy = 0;
  49170. component->setVisible (! useProxyComponent);
  49171. }
  49172. bool useTimeslice (const int elapsed)
  49173. {
  49174. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49175. : static_cast <Component*> (component);
  49176. if (c != 0)
  49177. {
  49178. msElapsed += elapsed;
  49179. double newProgress = msElapsed / (double) msTotal;
  49180. if (newProgress >= 0 && newProgress < 1.0)
  49181. {
  49182. newProgress = timeToDistance (newProgress);
  49183. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49184. jassert (newProgress >= lastProgress);
  49185. lastProgress = newProgress;
  49186. if (delta < 1.0)
  49187. {
  49188. bool stillBusy = false;
  49189. if (isMoving)
  49190. {
  49191. left += (destination.getX() - left) * delta;
  49192. top += (destination.getY() - top) * delta;
  49193. right += (destination.getRight() - right) * delta;
  49194. bottom += (destination.getBottom() - bottom) * delta;
  49195. const Rectangle<int> newBounds (roundToInt (left),
  49196. roundToInt (top),
  49197. roundToInt (right - left),
  49198. roundToInt (bottom - top));
  49199. if (newBounds != destination)
  49200. {
  49201. c->setBounds (newBounds);
  49202. stillBusy = true;
  49203. }
  49204. }
  49205. if (isChangingAlpha)
  49206. {
  49207. alpha += (destAlpha - alpha) * delta;
  49208. c->setAlpha ((float) alpha);
  49209. stillBusy = true;
  49210. }
  49211. if (stillBusy)
  49212. return true;
  49213. }
  49214. }
  49215. }
  49216. moveToFinalDestination();
  49217. return false;
  49218. }
  49219. void moveToFinalDestination()
  49220. {
  49221. if (component != 0)
  49222. {
  49223. component->setAlpha ((float) destAlpha);
  49224. component->setBounds (destination);
  49225. }
  49226. }
  49227. class ProxyComponent : public Component
  49228. {
  49229. public:
  49230. ProxyComponent (Component& component)
  49231. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49232. {
  49233. setBounds (component.getBounds());
  49234. setAlpha (component.getAlpha());
  49235. setInterceptsMouseClicks (false, false);
  49236. Component* const parent = component.getParentComponent();
  49237. if (parent != 0)
  49238. parent->addAndMakeVisible (this);
  49239. else if (component.isOnDesktop() && component.getPeer() != 0)
  49240. addToDesktop (component.getPeer()->getStyleFlags());
  49241. else
  49242. jassertfalse; // seem to be trying to animate a component that's not visible..
  49243. setVisible (true);
  49244. toBehind (&component);
  49245. }
  49246. void paint (Graphics& g)
  49247. {
  49248. g.setOpacity (1.0f);
  49249. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49250. 0, 0, image.getWidth(), image.getHeight());
  49251. }
  49252. private:
  49253. Image image;
  49254. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49255. };
  49256. WeakReference<Component> component;
  49257. ScopedPointer<Component> proxy;
  49258. Rectangle<int> destination;
  49259. double destAlpha;
  49260. int msElapsed, msTotal;
  49261. double startSpeed, midSpeed, endSpeed, lastProgress;
  49262. double left, top, right, bottom, alpha;
  49263. bool isMoving, isChangingAlpha;
  49264. private:
  49265. double timeToDistance (const double time) const throw()
  49266. {
  49267. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49268. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49269. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49270. }
  49271. };
  49272. ComponentAnimator::ComponentAnimator()
  49273. : lastTime (0)
  49274. {
  49275. }
  49276. ComponentAnimator::~ComponentAnimator()
  49277. {
  49278. }
  49279. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49280. {
  49281. for (int i = tasks.size(); --i >= 0;)
  49282. if (component == tasks.getUnchecked(i)->component.get())
  49283. return tasks.getUnchecked(i);
  49284. return 0;
  49285. }
  49286. void ComponentAnimator::animateComponent (Component* const component,
  49287. const Rectangle<int>& finalBounds,
  49288. const float finalAlpha,
  49289. const int millisecondsToSpendMoving,
  49290. const bool useProxyComponent,
  49291. const double startSpeed,
  49292. const double endSpeed)
  49293. {
  49294. // the speeds must be 0 or greater!
  49295. jassert (startSpeed >= 0 && endSpeed >= 0)
  49296. if (component != 0)
  49297. {
  49298. AnimationTask* at = findTaskFor (component);
  49299. if (at == 0)
  49300. {
  49301. at = new AnimationTask (component);
  49302. tasks.add (at);
  49303. sendChangeMessage();
  49304. }
  49305. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49306. useProxyComponent, startSpeed, endSpeed);
  49307. if (! isTimerRunning())
  49308. {
  49309. lastTime = Time::getMillisecondCounter();
  49310. startTimer (1000 / 50);
  49311. }
  49312. }
  49313. }
  49314. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49315. {
  49316. if (component != 0)
  49317. {
  49318. if (component->isShowing() && millisecondsToTake > 0)
  49319. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49320. component->setVisible (false);
  49321. }
  49322. }
  49323. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49324. {
  49325. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49326. {
  49327. component->setAlpha (0.0f);
  49328. component->setVisible (true);
  49329. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49330. }
  49331. }
  49332. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49333. {
  49334. if (tasks.size() > 0)
  49335. {
  49336. if (moveComponentsToTheirFinalPositions)
  49337. for (int i = tasks.size(); --i >= 0;)
  49338. tasks.getUnchecked(i)->moveToFinalDestination();
  49339. tasks.clear();
  49340. sendChangeMessage();
  49341. }
  49342. }
  49343. void ComponentAnimator::cancelAnimation (Component* const component,
  49344. const bool moveComponentToItsFinalPosition)
  49345. {
  49346. AnimationTask* const at = findTaskFor (component);
  49347. if (at != 0)
  49348. {
  49349. if (moveComponentToItsFinalPosition)
  49350. at->moveToFinalDestination();
  49351. tasks.removeObject (at);
  49352. sendChangeMessage();
  49353. }
  49354. }
  49355. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49356. {
  49357. jassert (component != 0);
  49358. AnimationTask* const at = findTaskFor (component);
  49359. if (at != 0)
  49360. return at->destination;
  49361. return component->getBounds();
  49362. }
  49363. bool ComponentAnimator::isAnimating (Component* component) const
  49364. {
  49365. return findTaskFor (component) != 0;
  49366. }
  49367. void ComponentAnimator::timerCallback()
  49368. {
  49369. const uint32 timeNow = Time::getMillisecondCounter();
  49370. if (lastTime == 0 || lastTime == timeNow)
  49371. lastTime = timeNow;
  49372. const int elapsed = timeNow - lastTime;
  49373. for (int i = tasks.size(); --i >= 0;)
  49374. {
  49375. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49376. {
  49377. tasks.remove (i);
  49378. sendChangeMessage();
  49379. }
  49380. }
  49381. lastTime = timeNow;
  49382. if (tasks.size() == 0)
  49383. stopTimer();
  49384. }
  49385. END_JUCE_NAMESPACE
  49386. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49387. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49388. BEGIN_JUCE_NAMESPACE
  49389. namespace ComponentBuilderHelpers
  49390. {
  49391. const String getStateId (const ValueTree& state)
  49392. {
  49393. return state [ComponentBuilder::idProperty].toString();
  49394. }
  49395. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49396. {
  49397. jassert (compId.isNotEmpty());
  49398. for (int i = components.size(); --i >= 0;)
  49399. {
  49400. Component* const c = components.getUnchecked (i);
  49401. if (c->getComponentID() == compId)
  49402. return components.removeAndReturn (i);
  49403. }
  49404. return 0;
  49405. }
  49406. Component* findComponentWithID (Component* const c, const String& compId)
  49407. {
  49408. jassert (compId.isNotEmpty());
  49409. if (c->getComponentID() == compId)
  49410. return c;
  49411. for (int i = c->getNumChildComponents(); --i >= 0;)
  49412. {
  49413. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49414. if (child != 0)
  49415. return child;
  49416. }
  49417. return 0;
  49418. }
  49419. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49420. const ValueTree& state, Component* parent)
  49421. {
  49422. Component* const c = type.addNewComponentFromState (state, parent);
  49423. jassert (c != 0);
  49424. c->setComponentID (getStateId (state));
  49425. return c;
  49426. }
  49427. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49428. {
  49429. Component* topLevelComp = builder.getManagedComponent();
  49430. if (topLevelComp != 0)
  49431. {
  49432. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49433. const String uid (getStateId (state));
  49434. if (type == 0 || uid.isEmpty())
  49435. {
  49436. // ..handle the case where a child of the actual state node has changed.
  49437. if (state.getParent().isValid())
  49438. updateComponent (builder, state.getParent());
  49439. }
  49440. else
  49441. {
  49442. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49443. if (changedComp != 0)
  49444. type->updateComponentFromState (changedComp, state);
  49445. }
  49446. }
  49447. }
  49448. }
  49449. const Identifier ComponentBuilder::idProperty ("id");
  49450. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49451. : state (state_), imageProvider (0)
  49452. {
  49453. state.addListener (this);
  49454. }
  49455. ComponentBuilder::~ComponentBuilder()
  49456. {
  49457. state.removeListener (this);
  49458. #if JUCE_DEBUG
  49459. // Don't delete the managed component!! The builder owns that component, and will delete
  49460. // it automatically when it gets deleted.
  49461. jassert (componentRef.get() == static_cast <Component*> (component));
  49462. #endif
  49463. }
  49464. Component* ComponentBuilder::getManagedComponent()
  49465. {
  49466. if (component == 0)
  49467. {
  49468. component = createComponent();
  49469. #if JUCE_DEBUG
  49470. componentRef = component;
  49471. #endif
  49472. }
  49473. return component;
  49474. }
  49475. Component* ComponentBuilder::createComponent()
  49476. {
  49477. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49478. TypeHandler* const type = getHandlerForState (state);
  49479. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49480. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49481. }
  49482. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49483. {
  49484. jassert (type != 0);
  49485. // Don't try to move your types around! Once a type has been added to a builder, the
  49486. // builder owns it, and you should leave it alone!
  49487. jassert (type->builder == 0);
  49488. types.add (type);
  49489. type->builder = this;
  49490. }
  49491. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49492. {
  49493. const Identifier targetType (s.getType());
  49494. for (int i = 0; i < types.size(); ++i)
  49495. {
  49496. TypeHandler* const t = types.getUnchecked(i);
  49497. if (t->getType() == targetType)
  49498. return t;
  49499. }
  49500. return 0;
  49501. }
  49502. int ComponentBuilder::getNumHandlers() const throw()
  49503. {
  49504. return types.size();
  49505. }
  49506. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49507. {
  49508. return types [index];
  49509. }
  49510. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49511. {
  49512. imageProvider = newImageProvider;
  49513. }
  49514. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49515. {
  49516. return imageProvider;
  49517. }
  49518. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49519. {
  49520. ComponentBuilderHelpers::updateComponent (*this, tree);
  49521. }
  49522. void ComponentBuilder::valueTreeChildrenChanged (ValueTree& tree)
  49523. {
  49524. ComponentBuilderHelpers::updateComponent (*this, tree);
  49525. }
  49526. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49527. {
  49528. ComponentBuilderHelpers::updateComponent (*this, tree);
  49529. }
  49530. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49531. : builder (0), valueTreeType (valueTreeType_)
  49532. {
  49533. }
  49534. ComponentBuilder::TypeHandler::~TypeHandler()
  49535. {
  49536. }
  49537. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49538. {
  49539. // A type handler needs to be registered with a ComponentBuilder before using it!
  49540. jassert (builder != 0);
  49541. return builder;
  49542. }
  49543. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49544. {
  49545. using namespace ComponentBuilderHelpers;
  49546. const int numExistingChildComps = parent.getNumChildComponents();
  49547. Array <Component*> componentsInOrder;
  49548. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49549. {
  49550. OwnedArray<Component> existingComponents;
  49551. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49552. int i;
  49553. for (i = 0; i < numExistingChildComps; ++i)
  49554. existingComponents.add (parent.getChildComponent (i));
  49555. const int newNumChildren = children.getNumChildren();
  49556. for (i = 0; i < newNumChildren; ++i)
  49557. {
  49558. const ValueTree childState (children.getChild (i));
  49559. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49560. jassert (type != 0);
  49561. if (type != 0)
  49562. {
  49563. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49564. if (c == 0)
  49565. c = createNewComponent (*type, childState, &parent);
  49566. componentsInOrder.add (c);
  49567. }
  49568. }
  49569. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49570. }
  49571. // Make sure the z-order is correct..
  49572. if (componentsInOrder.size() > 0)
  49573. {
  49574. componentsInOrder.getLast()->toFront (false);
  49575. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49576. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49577. }
  49578. }
  49579. END_JUCE_NAMESPACE
  49580. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49581. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49582. BEGIN_JUCE_NAMESPACE
  49583. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49584. : minW (0),
  49585. maxW (0x3fffffff),
  49586. minH (0),
  49587. maxH (0x3fffffff),
  49588. minOffTop (0),
  49589. minOffLeft (0),
  49590. minOffBottom (0),
  49591. minOffRight (0),
  49592. aspectRatio (0.0)
  49593. {
  49594. }
  49595. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49596. {
  49597. }
  49598. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49599. {
  49600. minW = minimumWidth;
  49601. }
  49602. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49603. {
  49604. maxW = maximumWidth;
  49605. }
  49606. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49607. {
  49608. minH = minimumHeight;
  49609. }
  49610. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49611. {
  49612. maxH = maximumHeight;
  49613. }
  49614. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49615. {
  49616. jassert (maxW >= minimumWidth);
  49617. jassert (maxH >= minimumHeight);
  49618. jassert (minimumWidth > 0 && minimumHeight > 0);
  49619. minW = minimumWidth;
  49620. minH = minimumHeight;
  49621. if (minW > maxW)
  49622. maxW = minW;
  49623. if (minH > maxH)
  49624. maxH = minH;
  49625. }
  49626. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49627. {
  49628. jassert (maximumWidth >= minW);
  49629. jassert (maximumHeight >= minH);
  49630. jassert (maximumWidth > 0 && maximumHeight > 0);
  49631. maxW = jmax (minW, maximumWidth);
  49632. maxH = jmax (minH, maximumHeight);
  49633. }
  49634. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49635. const int minimumHeight,
  49636. const int maximumWidth,
  49637. const int maximumHeight) throw()
  49638. {
  49639. jassert (maximumWidth >= minimumWidth);
  49640. jassert (maximumHeight >= minimumHeight);
  49641. jassert (maximumWidth > 0 && maximumHeight > 0);
  49642. jassert (minimumWidth > 0 && minimumHeight > 0);
  49643. minW = jmax (0, minimumWidth);
  49644. minH = jmax (0, minimumHeight);
  49645. maxW = jmax (minW, maximumWidth);
  49646. maxH = jmax (minH, maximumHeight);
  49647. }
  49648. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49649. const int minimumWhenOffTheLeft,
  49650. const int minimumWhenOffTheBottom,
  49651. const int minimumWhenOffTheRight) throw()
  49652. {
  49653. minOffTop = minimumWhenOffTheTop;
  49654. minOffLeft = minimumWhenOffTheLeft;
  49655. minOffBottom = minimumWhenOffTheBottom;
  49656. minOffRight = minimumWhenOffTheRight;
  49657. }
  49658. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49659. {
  49660. aspectRatio = jmax (0.0, widthOverHeight);
  49661. }
  49662. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49663. {
  49664. return aspectRatio;
  49665. }
  49666. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49667. const Rectangle<int>& targetBounds,
  49668. const bool isStretchingTop,
  49669. const bool isStretchingLeft,
  49670. const bool isStretchingBottom,
  49671. const bool isStretchingRight)
  49672. {
  49673. jassert (component != 0);
  49674. Rectangle<int> limits, bounds (targetBounds);
  49675. BorderSize border;
  49676. Component* const parent = component->getParentComponent();
  49677. if (parent == 0)
  49678. {
  49679. ComponentPeer* peer = component->getPeer();
  49680. if (peer != 0)
  49681. border = peer->getFrameSize();
  49682. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49683. }
  49684. else
  49685. {
  49686. limits.setSize (parent->getWidth(), parent->getHeight());
  49687. }
  49688. border.addTo (bounds);
  49689. checkBounds (bounds,
  49690. border.addedTo (component->getBounds()), limits,
  49691. isStretchingTop, isStretchingLeft,
  49692. isStretchingBottom, isStretchingRight);
  49693. border.subtractFrom (bounds);
  49694. applyBoundsToComponent (component, bounds);
  49695. }
  49696. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49697. {
  49698. setBoundsForComponent (component, component->getBounds(),
  49699. false, false, false, false);
  49700. }
  49701. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49702. const Rectangle<int>& bounds)
  49703. {
  49704. component->setBounds (bounds);
  49705. }
  49706. void ComponentBoundsConstrainer::resizeStart()
  49707. {
  49708. }
  49709. void ComponentBoundsConstrainer::resizeEnd()
  49710. {
  49711. }
  49712. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49713. const Rectangle<int>& old,
  49714. const Rectangle<int>& limits,
  49715. const bool isStretchingTop,
  49716. const bool isStretchingLeft,
  49717. const bool isStretchingBottom,
  49718. const bool isStretchingRight)
  49719. {
  49720. // constrain the size if it's being stretched..
  49721. if (isStretchingLeft)
  49722. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49723. if (isStretchingRight)
  49724. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49725. if (isStretchingTop)
  49726. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49727. if (isStretchingBottom)
  49728. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49729. if (bounds.isEmpty())
  49730. return;
  49731. if (minOffTop > 0)
  49732. {
  49733. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49734. if (bounds.getY() < limit)
  49735. {
  49736. if (isStretchingTop)
  49737. bounds.setTop (limits.getY());
  49738. else
  49739. bounds.setY (limit);
  49740. }
  49741. }
  49742. if (minOffLeft > 0)
  49743. {
  49744. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49745. if (bounds.getX() < limit)
  49746. {
  49747. if (isStretchingLeft)
  49748. bounds.setLeft (limits.getX());
  49749. else
  49750. bounds.setX (limit);
  49751. }
  49752. }
  49753. if (minOffBottom > 0)
  49754. {
  49755. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49756. if (bounds.getY() > limit)
  49757. {
  49758. if (isStretchingBottom)
  49759. bounds.setBottom (limits.getBottom());
  49760. else
  49761. bounds.setY (limit);
  49762. }
  49763. }
  49764. if (minOffRight > 0)
  49765. {
  49766. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49767. if (bounds.getX() > limit)
  49768. {
  49769. if (isStretchingRight)
  49770. bounds.setRight (limits.getRight());
  49771. else
  49772. bounds.setX (limit);
  49773. }
  49774. }
  49775. // constrain the aspect ratio if one has been specified..
  49776. if (aspectRatio > 0.0)
  49777. {
  49778. bool adjustWidth;
  49779. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49780. {
  49781. adjustWidth = true;
  49782. }
  49783. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49784. {
  49785. adjustWidth = false;
  49786. }
  49787. else
  49788. {
  49789. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49790. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49791. adjustWidth = (oldRatio > newRatio);
  49792. }
  49793. if (adjustWidth)
  49794. {
  49795. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49796. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49797. {
  49798. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49799. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49800. }
  49801. }
  49802. else
  49803. {
  49804. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49805. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49806. {
  49807. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49808. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49809. }
  49810. }
  49811. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49812. {
  49813. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49814. }
  49815. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49816. {
  49817. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49818. }
  49819. else
  49820. {
  49821. if (isStretchingLeft)
  49822. bounds.setX (old.getRight() - bounds.getWidth());
  49823. if (isStretchingTop)
  49824. bounds.setY (old.getBottom() - bounds.getHeight());
  49825. }
  49826. }
  49827. jassert (! bounds.isEmpty());
  49828. }
  49829. END_JUCE_NAMESPACE
  49830. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49831. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49832. BEGIN_JUCE_NAMESPACE
  49833. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49834. : component (component_),
  49835. lastPeer (0),
  49836. reentrant (false)
  49837. {
  49838. jassert (component != 0); // can't use this with a null pointer..
  49839. component->addComponentListener (this);
  49840. registerWithParentComps();
  49841. }
  49842. ComponentMovementWatcher::~ComponentMovementWatcher()
  49843. {
  49844. component->removeComponentListener (this);
  49845. unregister();
  49846. }
  49847. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49848. {
  49849. // agh! don't delete the target component without deleting this object first!
  49850. jassert (component != 0);
  49851. if (! reentrant)
  49852. {
  49853. reentrant = true;
  49854. ComponentPeer* const peer = component->getPeer();
  49855. if (peer != lastPeer)
  49856. {
  49857. componentPeerChanged();
  49858. if (component == 0)
  49859. return;
  49860. lastPeer = peer;
  49861. }
  49862. unregister();
  49863. registerWithParentComps();
  49864. reentrant = false;
  49865. componentMovedOrResized (*component, true, true);
  49866. }
  49867. }
  49868. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49869. {
  49870. // agh! don't delete the target component without deleting this object first!
  49871. jassert (component != 0);
  49872. if (wasMoved)
  49873. {
  49874. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49875. wasMoved = lastBounds.getPosition() != pos;
  49876. lastBounds.setPosition (pos);
  49877. }
  49878. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49879. lastBounds.setSize (component->getWidth(), component->getHeight());
  49880. if (wasMoved || wasResized)
  49881. componentMovedOrResized (wasMoved, wasResized);
  49882. }
  49883. void ComponentMovementWatcher::registerWithParentComps()
  49884. {
  49885. Component* p = component->getParentComponent();
  49886. while (p != 0)
  49887. {
  49888. p->addComponentListener (this);
  49889. registeredParentComps.add (p);
  49890. p = p->getParentComponent();
  49891. }
  49892. }
  49893. void ComponentMovementWatcher::unregister()
  49894. {
  49895. for (int i = registeredParentComps.size(); --i >= 0;)
  49896. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49897. registeredParentComps.clear();
  49898. }
  49899. END_JUCE_NAMESPACE
  49900. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49901. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49902. BEGIN_JUCE_NAMESPACE
  49903. GroupComponent::GroupComponent (const String& componentName,
  49904. const String& labelText)
  49905. : Component (componentName),
  49906. text (labelText),
  49907. justification (Justification::left)
  49908. {
  49909. setInterceptsMouseClicks (false, true);
  49910. }
  49911. GroupComponent::~GroupComponent()
  49912. {
  49913. }
  49914. void GroupComponent::setText (const String& newText)
  49915. {
  49916. if (text != newText)
  49917. {
  49918. text = newText;
  49919. repaint();
  49920. }
  49921. }
  49922. const String GroupComponent::getText() const
  49923. {
  49924. return text;
  49925. }
  49926. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49927. {
  49928. if (justification != newJustification)
  49929. {
  49930. justification = newJustification;
  49931. repaint();
  49932. }
  49933. }
  49934. void GroupComponent::paint (Graphics& g)
  49935. {
  49936. getLookAndFeel()
  49937. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49938. text, justification,
  49939. *this);
  49940. }
  49941. void GroupComponent::enablementChanged()
  49942. {
  49943. repaint();
  49944. }
  49945. void GroupComponent::colourChanged()
  49946. {
  49947. repaint();
  49948. }
  49949. END_JUCE_NAMESPACE
  49950. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49951. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49952. BEGIN_JUCE_NAMESPACE
  49953. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49954. : DocumentWindow (String::empty, backgroundColour,
  49955. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49956. {
  49957. }
  49958. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49959. {
  49960. }
  49961. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49962. {
  49963. MultiDocumentPanel* const owner = getOwner();
  49964. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49965. if (owner != 0)
  49966. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49967. }
  49968. void MultiDocumentPanelWindow::closeButtonPressed()
  49969. {
  49970. MultiDocumentPanel* const owner = getOwner();
  49971. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49972. if (owner != 0)
  49973. owner->closeDocument (getContentComponent(), true);
  49974. }
  49975. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49976. {
  49977. DocumentWindow::activeWindowStatusChanged();
  49978. updateOrder();
  49979. }
  49980. void MultiDocumentPanelWindow::broughtToFront()
  49981. {
  49982. DocumentWindow::broughtToFront();
  49983. updateOrder();
  49984. }
  49985. void MultiDocumentPanelWindow::updateOrder()
  49986. {
  49987. MultiDocumentPanel* const owner = getOwner();
  49988. if (owner != 0)
  49989. owner->updateOrder();
  49990. }
  49991. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49992. {
  49993. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49994. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49995. }
  49996. class MDITabbedComponentInternal : public TabbedComponent
  49997. {
  49998. public:
  49999. MDITabbedComponentInternal()
  50000. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50001. {
  50002. }
  50003. ~MDITabbedComponentInternal()
  50004. {
  50005. }
  50006. void currentTabChanged (int, const String&)
  50007. {
  50008. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50009. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50010. if (owner != 0)
  50011. owner->updateOrder();
  50012. }
  50013. };
  50014. MultiDocumentPanel::MultiDocumentPanel()
  50015. : mode (MaximisedWindowsWithTabs),
  50016. backgroundColour (Colours::lightblue),
  50017. maximumNumDocuments (0),
  50018. numDocsBeforeTabsUsed (0)
  50019. {
  50020. setOpaque (true);
  50021. }
  50022. MultiDocumentPanel::~MultiDocumentPanel()
  50023. {
  50024. closeAllDocuments (false);
  50025. }
  50026. namespace MultiDocHelpers
  50027. {
  50028. bool shouldDeleteComp (Component* const c)
  50029. {
  50030. return c->getProperties() ["mdiDocumentDelete_"];
  50031. }
  50032. }
  50033. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50034. {
  50035. while (components.size() > 0)
  50036. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50037. return false;
  50038. return true;
  50039. }
  50040. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50041. {
  50042. return new MultiDocumentPanelWindow (backgroundColour);
  50043. }
  50044. void MultiDocumentPanel::addWindow (Component* component)
  50045. {
  50046. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50047. dw->setResizable (true, false);
  50048. dw->setContentComponent (component, false, true);
  50049. dw->setName (component->getName());
  50050. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50051. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50052. int x = 4;
  50053. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50054. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50055. x += 16;
  50056. dw->setTopLeftPosition (x, x);
  50057. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50058. if (pos.toString().isNotEmpty())
  50059. dw->restoreWindowStateFromString (pos.toString());
  50060. addAndMakeVisible (dw);
  50061. dw->toFront (true);
  50062. }
  50063. bool MultiDocumentPanel::addDocument (Component* const component,
  50064. const Colour& docColour,
  50065. const bool deleteWhenRemoved)
  50066. {
  50067. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50068. // with a frame-within-a-frame! Just pass in the bare content component.
  50069. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50070. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50071. return false;
  50072. components.add (component);
  50073. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50074. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50075. component->addComponentListener (this);
  50076. if (mode == FloatingWindows)
  50077. {
  50078. if (isFullscreenWhenOneDocument())
  50079. {
  50080. if (components.size() == 1)
  50081. {
  50082. addAndMakeVisible (component);
  50083. }
  50084. else
  50085. {
  50086. if (components.size() == 2)
  50087. addWindow (components.getFirst());
  50088. addWindow (component);
  50089. }
  50090. }
  50091. else
  50092. {
  50093. addWindow (component);
  50094. }
  50095. }
  50096. else
  50097. {
  50098. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50099. {
  50100. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50101. Array <Component*> temp (components);
  50102. for (int i = 0; i < temp.size(); ++i)
  50103. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50104. resized();
  50105. }
  50106. else
  50107. {
  50108. if (tabComponent != 0)
  50109. tabComponent->addTab (component->getName(), docColour, component, false);
  50110. else
  50111. addAndMakeVisible (component);
  50112. }
  50113. setActiveDocument (component);
  50114. }
  50115. resized();
  50116. activeDocumentChanged();
  50117. return true;
  50118. }
  50119. bool MultiDocumentPanel::closeDocument (Component* component,
  50120. const bool checkItsOkToCloseFirst)
  50121. {
  50122. if (components.contains (component))
  50123. {
  50124. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50125. return false;
  50126. component->removeComponentListener (this);
  50127. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50128. component->getProperties().remove ("mdiDocumentDelete_");
  50129. component->getProperties().remove ("mdiDocumentBkg_");
  50130. if (mode == FloatingWindows)
  50131. {
  50132. for (int i = getNumChildComponents(); --i >= 0;)
  50133. {
  50134. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50135. if (dw != 0 && dw->getContentComponent() == component)
  50136. {
  50137. dw->setContentComponent (0, false);
  50138. delete dw;
  50139. break;
  50140. }
  50141. }
  50142. if (shouldDelete)
  50143. delete component;
  50144. components.removeValue (component);
  50145. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50146. {
  50147. for (int i = getNumChildComponents(); --i >= 0;)
  50148. {
  50149. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50150. if (dw != 0)
  50151. {
  50152. dw->setContentComponent (0, false);
  50153. delete dw;
  50154. }
  50155. }
  50156. addAndMakeVisible (components.getFirst());
  50157. }
  50158. }
  50159. else
  50160. {
  50161. jassert (components.indexOf (component) >= 0);
  50162. if (tabComponent != 0)
  50163. {
  50164. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50165. if (tabComponent->getTabContentComponent (i) == component)
  50166. tabComponent->removeTab (i);
  50167. }
  50168. else
  50169. {
  50170. removeChildComponent (component);
  50171. }
  50172. if (shouldDelete)
  50173. delete component;
  50174. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50175. tabComponent = 0;
  50176. components.removeValue (component);
  50177. if (components.size() > 0 && tabComponent == 0)
  50178. addAndMakeVisible (components.getFirst());
  50179. }
  50180. resized();
  50181. activeDocumentChanged();
  50182. }
  50183. else
  50184. {
  50185. jassertfalse;
  50186. }
  50187. return true;
  50188. }
  50189. int MultiDocumentPanel::getNumDocuments() const throw()
  50190. {
  50191. return components.size();
  50192. }
  50193. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50194. {
  50195. return components [index];
  50196. }
  50197. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50198. {
  50199. if (mode == FloatingWindows)
  50200. {
  50201. for (int i = getNumChildComponents(); --i >= 0;)
  50202. {
  50203. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50204. if (dw != 0 && dw->isActiveWindow())
  50205. return dw->getContentComponent();
  50206. }
  50207. }
  50208. return components.getLast();
  50209. }
  50210. void MultiDocumentPanel::setActiveDocument (Component* component)
  50211. {
  50212. if (mode == FloatingWindows)
  50213. {
  50214. component = getContainerComp (component);
  50215. if (component != 0)
  50216. component->toFront (true);
  50217. }
  50218. else if (tabComponent != 0)
  50219. {
  50220. jassert (components.indexOf (component) >= 0);
  50221. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50222. {
  50223. if (tabComponent->getTabContentComponent (i) == component)
  50224. {
  50225. tabComponent->setCurrentTabIndex (i);
  50226. break;
  50227. }
  50228. }
  50229. }
  50230. else
  50231. {
  50232. component->grabKeyboardFocus();
  50233. }
  50234. }
  50235. void MultiDocumentPanel::activeDocumentChanged()
  50236. {
  50237. }
  50238. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50239. {
  50240. maximumNumDocuments = newNumber;
  50241. }
  50242. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50243. {
  50244. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50245. }
  50246. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50247. {
  50248. return numDocsBeforeTabsUsed != 0;
  50249. }
  50250. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50251. {
  50252. if (mode != newLayoutMode)
  50253. {
  50254. mode = newLayoutMode;
  50255. if (mode == FloatingWindows)
  50256. {
  50257. tabComponent = 0;
  50258. }
  50259. else
  50260. {
  50261. for (int i = getNumChildComponents(); --i >= 0;)
  50262. {
  50263. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50264. if (dw != 0)
  50265. {
  50266. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50267. dw->setContentComponent (0, false);
  50268. delete dw;
  50269. }
  50270. }
  50271. }
  50272. resized();
  50273. const Array <Component*> tempComps (components);
  50274. components.clear();
  50275. for (int i = 0; i < tempComps.size(); ++i)
  50276. {
  50277. Component* const c = tempComps.getUnchecked(i);
  50278. addDocument (c,
  50279. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50280. MultiDocHelpers::shouldDeleteComp (c));
  50281. }
  50282. }
  50283. }
  50284. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50285. {
  50286. if (backgroundColour != newBackgroundColour)
  50287. {
  50288. backgroundColour = newBackgroundColour;
  50289. setOpaque (newBackgroundColour.isOpaque());
  50290. repaint();
  50291. }
  50292. }
  50293. void MultiDocumentPanel::paint (Graphics& g)
  50294. {
  50295. g.fillAll (backgroundColour);
  50296. }
  50297. void MultiDocumentPanel::resized()
  50298. {
  50299. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50300. {
  50301. for (int i = getNumChildComponents(); --i >= 0;)
  50302. getChildComponent (i)->setBounds (getLocalBounds());
  50303. }
  50304. setWantsKeyboardFocus (components.size() == 0);
  50305. }
  50306. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50307. {
  50308. if (mode == FloatingWindows)
  50309. {
  50310. for (int i = 0; i < getNumChildComponents(); ++i)
  50311. {
  50312. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50313. if (dw != 0 && dw->getContentComponent() == c)
  50314. {
  50315. c = dw;
  50316. break;
  50317. }
  50318. }
  50319. }
  50320. return c;
  50321. }
  50322. void MultiDocumentPanel::componentNameChanged (Component&)
  50323. {
  50324. if (mode == FloatingWindows)
  50325. {
  50326. for (int i = 0; i < getNumChildComponents(); ++i)
  50327. {
  50328. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50329. if (dw != 0)
  50330. dw->setName (dw->getContentComponent()->getName());
  50331. }
  50332. }
  50333. else if (tabComponent != 0)
  50334. {
  50335. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50336. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50337. }
  50338. }
  50339. void MultiDocumentPanel::updateOrder()
  50340. {
  50341. const Array <Component*> oldList (components);
  50342. if (mode == FloatingWindows)
  50343. {
  50344. components.clear();
  50345. for (int i = 0; i < getNumChildComponents(); ++i)
  50346. {
  50347. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50348. if (dw != 0)
  50349. components.add (dw->getContentComponent());
  50350. }
  50351. }
  50352. else
  50353. {
  50354. if (tabComponent != 0)
  50355. {
  50356. Component* const current = tabComponent->getCurrentContentComponent();
  50357. if (current != 0)
  50358. {
  50359. components.removeValue (current);
  50360. components.add (current);
  50361. }
  50362. }
  50363. }
  50364. if (components != oldList)
  50365. activeDocumentChanged();
  50366. }
  50367. END_JUCE_NAMESPACE
  50368. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50369. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50370. BEGIN_JUCE_NAMESPACE
  50371. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50372. : zone (zoneFlags)
  50373. {}
  50374. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50375. : zone (other.zone)
  50376. {}
  50377. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50378. {
  50379. zone = other.zone;
  50380. return *this;
  50381. }
  50382. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50383. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50384. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50385. const BorderSize& border,
  50386. const Point<int>& position)
  50387. {
  50388. int z = 0;
  50389. if (totalSize.contains (position)
  50390. && ! border.subtractedFrom (totalSize).contains (position))
  50391. {
  50392. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50393. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50394. z |= left;
  50395. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50396. z |= right;
  50397. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50398. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50399. z |= top;
  50400. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50401. z |= bottom;
  50402. }
  50403. return Zone (z);
  50404. }
  50405. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50406. {
  50407. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50408. switch (zone)
  50409. {
  50410. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50411. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50412. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50413. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50414. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50415. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50416. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50417. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50418. default: break;
  50419. }
  50420. return mc;
  50421. }
  50422. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50423. ComponentBoundsConstrainer* const constrainer_)
  50424. : component (componentToResize),
  50425. constrainer (constrainer_),
  50426. borderSize (5),
  50427. mouseZone (0)
  50428. {
  50429. }
  50430. ResizableBorderComponent::~ResizableBorderComponent()
  50431. {
  50432. }
  50433. void ResizableBorderComponent::paint (Graphics& g)
  50434. {
  50435. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50436. }
  50437. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50438. {
  50439. updateMouseZone (e);
  50440. }
  50441. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50442. {
  50443. updateMouseZone (e);
  50444. }
  50445. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50446. {
  50447. if (component == 0)
  50448. {
  50449. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50450. return;
  50451. }
  50452. updateMouseZone (e);
  50453. originalBounds = component->getBounds();
  50454. if (constrainer != 0)
  50455. constrainer->resizeStart();
  50456. }
  50457. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50458. {
  50459. if (component == 0)
  50460. {
  50461. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50462. return;
  50463. }
  50464. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50465. if (constrainer != 0)
  50466. constrainer->setBoundsForComponent (component, bounds,
  50467. mouseZone.isDraggingTopEdge(),
  50468. mouseZone.isDraggingLeftEdge(),
  50469. mouseZone.isDraggingBottomEdge(),
  50470. mouseZone.isDraggingRightEdge());
  50471. else
  50472. component->setBounds (bounds);
  50473. }
  50474. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50475. {
  50476. if (constrainer != 0)
  50477. constrainer->resizeEnd();
  50478. }
  50479. bool ResizableBorderComponent::hitTest (int x, int y)
  50480. {
  50481. return x < borderSize.getLeft()
  50482. || x >= getWidth() - borderSize.getRight()
  50483. || y < borderSize.getTop()
  50484. || y >= getHeight() - borderSize.getBottom();
  50485. }
  50486. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50487. {
  50488. if (borderSize != newBorderSize)
  50489. {
  50490. borderSize = newBorderSize;
  50491. repaint();
  50492. }
  50493. }
  50494. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50495. {
  50496. return borderSize;
  50497. }
  50498. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50499. {
  50500. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50501. if (mouseZone != newZone)
  50502. {
  50503. mouseZone = newZone;
  50504. setMouseCursor (newZone.getMouseCursor());
  50505. }
  50506. }
  50507. END_JUCE_NAMESPACE
  50508. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50509. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50510. BEGIN_JUCE_NAMESPACE
  50511. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50512. ComponentBoundsConstrainer* const constrainer_)
  50513. : component (componentToResize),
  50514. constrainer (constrainer_)
  50515. {
  50516. setRepaintsOnMouseActivity (true);
  50517. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50518. }
  50519. ResizableCornerComponent::~ResizableCornerComponent()
  50520. {
  50521. }
  50522. void ResizableCornerComponent::paint (Graphics& g)
  50523. {
  50524. getLookAndFeel()
  50525. .drawCornerResizer (g, getWidth(), getHeight(),
  50526. isMouseOverOrDragging(),
  50527. isMouseButtonDown());
  50528. }
  50529. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50530. {
  50531. if (component == 0)
  50532. {
  50533. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50534. return;
  50535. }
  50536. originalBounds = component->getBounds();
  50537. if (constrainer != 0)
  50538. constrainer->resizeStart();
  50539. }
  50540. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50541. {
  50542. if (component == 0)
  50543. {
  50544. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50545. return;
  50546. }
  50547. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50548. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50549. if (constrainer != 0)
  50550. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50551. else
  50552. component->setBounds (r);
  50553. }
  50554. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50555. {
  50556. if (constrainer != 0)
  50557. constrainer->resizeStart();
  50558. }
  50559. bool ResizableCornerComponent::hitTest (int x, int y)
  50560. {
  50561. if (getWidth() <= 0)
  50562. return false;
  50563. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50564. return y >= yAtX - getHeight() / 4;
  50565. }
  50566. END_JUCE_NAMESPACE
  50567. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50568. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50569. BEGIN_JUCE_NAMESPACE
  50570. class ScrollBar::ScrollbarButton : public Button
  50571. {
  50572. public:
  50573. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50574. : Button (String::empty),
  50575. direction (direction_),
  50576. owner (owner_)
  50577. {
  50578. setWantsKeyboardFocus (false);
  50579. }
  50580. void paintButton (Graphics& g, bool over, bool down)
  50581. {
  50582. getLookAndFeel()
  50583. .drawScrollbarButton (g, owner,
  50584. getWidth(), getHeight(),
  50585. direction,
  50586. owner.isVertical(),
  50587. over, down);
  50588. }
  50589. void clicked()
  50590. {
  50591. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50592. }
  50593. int direction;
  50594. private:
  50595. ScrollBar& owner;
  50596. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50597. };
  50598. ScrollBar::ScrollBar (const bool vertical_,
  50599. const bool buttonsAreVisible)
  50600. : totalRange (0.0, 1.0),
  50601. visibleRange (0.0, 0.1),
  50602. singleStepSize (0.1),
  50603. thumbAreaStart (0),
  50604. thumbAreaSize (0),
  50605. thumbStart (0),
  50606. thumbSize (0),
  50607. initialDelayInMillisecs (100),
  50608. repeatDelayInMillisecs (50),
  50609. minimumDelayInMillisecs (10),
  50610. vertical (vertical_),
  50611. isDraggingThumb (false),
  50612. autohides (true)
  50613. {
  50614. setButtonVisibility (buttonsAreVisible);
  50615. setRepaintsOnMouseActivity (true);
  50616. setFocusContainer (true);
  50617. }
  50618. ScrollBar::~ScrollBar()
  50619. {
  50620. upButton = 0;
  50621. downButton = 0;
  50622. }
  50623. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50624. {
  50625. if (totalRange != newRangeLimit)
  50626. {
  50627. totalRange = newRangeLimit;
  50628. setCurrentRange (visibleRange);
  50629. updateThumbPosition();
  50630. }
  50631. }
  50632. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50633. {
  50634. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50635. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50636. }
  50637. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50638. {
  50639. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50640. if (visibleRange != constrainedRange)
  50641. {
  50642. visibleRange = constrainedRange;
  50643. updateThumbPosition();
  50644. triggerAsyncUpdate();
  50645. }
  50646. }
  50647. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50648. {
  50649. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50650. }
  50651. void ScrollBar::setCurrentRangeStart (const double newStart)
  50652. {
  50653. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50654. }
  50655. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50656. {
  50657. singleStepSize = newSingleStepSize;
  50658. }
  50659. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50660. {
  50661. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50662. }
  50663. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50664. {
  50665. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50666. }
  50667. void ScrollBar::scrollToTop()
  50668. {
  50669. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50670. }
  50671. void ScrollBar::scrollToBottom()
  50672. {
  50673. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50674. }
  50675. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50676. const int repeatDelayInMillisecs_,
  50677. const int minimumDelayInMillisecs_)
  50678. {
  50679. initialDelayInMillisecs = initialDelayInMillisecs_;
  50680. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50681. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50682. if (upButton != 0)
  50683. {
  50684. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50685. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50686. }
  50687. }
  50688. void ScrollBar::addListener (Listener* const listener)
  50689. {
  50690. listeners.add (listener);
  50691. }
  50692. void ScrollBar::removeListener (Listener* const listener)
  50693. {
  50694. listeners.remove (listener);
  50695. }
  50696. void ScrollBar::handleAsyncUpdate()
  50697. {
  50698. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50699. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50700. }
  50701. void ScrollBar::updateThumbPosition()
  50702. {
  50703. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50704. : thumbAreaSize);
  50705. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50706. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50707. if (newThumbSize > thumbAreaSize)
  50708. newThumbSize = thumbAreaSize;
  50709. int newThumbStart = thumbAreaStart;
  50710. if (totalRange.getLength() > visibleRange.getLength())
  50711. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50712. / (totalRange.getLength() - visibleRange.getLength()));
  50713. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50714. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50715. {
  50716. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50717. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50718. if (vertical)
  50719. repaint (0, repaintStart, getWidth(), repaintSize);
  50720. else
  50721. repaint (repaintStart, 0, repaintSize, getHeight());
  50722. thumbStart = newThumbStart;
  50723. thumbSize = newThumbSize;
  50724. }
  50725. }
  50726. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50727. {
  50728. if (vertical != shouldBeVertical)
  50729. {
  50730. vertical = shouldBeVertical;
  50731. if (upButton != 0)
  50732. {
  50733. upButton->direction = vertical ? 0 : 3;
  50734. downButton->direction = vertical ? 2 : 1;
  50735. }
  50736. updateThumbPosition();
  50737. }
  50738. }
  50739. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50740. {
  50741. upButton = 0;
  50742. downButton = 0;
  50743. if (buttonsAreVisible)
  50744. {
  50745. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50746. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50747. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50748. }
  50749. updateThumbPosition();
  50750. }
  50751. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50752. {
  50753. autohides = shouldHideWhenFullRange;
  50754. updateThumbPosition();
  50755. }
  50756. bool ScrollBar::autoHides() const throw()
  50757. {
  50758. return autohides;
  50759. }
  50760. void ScrollBar::paint (Graphics& g)
  50761. {
  50762. if (thumbAreaSize > 0)
  50763. {
  50764. LookAndFeel& lf = getLookAndFeel();
  50765. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50766. ? thumbSize : 0;
  50767. if (vertical)
  50768. {
  50769. lf.drawScrollbar (g, *this,
  50770. 0, thumbAreaStart,
  50771. getWidth(), thumbAreaSize,
  50772. vertical,
  50773. thumbStart, thumb,
  50774. isMouseOver(), isMouseButtonDown());
  50775. }
  50776. else
  50777. {
  50778. lf.drawScrollbar (g, *this,
  50779. thumbAreaStart, 0,
  50780. thumbAreaSize, getHeight(),
  50781. vertical,
  50782. thumbStart, thumb,
  50783. isMouseOver(), isMouseButtonDown());
  50784. }
  50785. }
  50786. }
  50787. void ScrollBar::lookAndFeelChanged()
  50788. {
  50789. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50790. }
  50791. void ScrollBar::resized()
  50792. {
  50793. const int length = ((vertical) ? getHeight() : getWidth());
  50794. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50795. : 0;
  50796. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50797. {
  50798. thumbAreaStart = length >> 1;
  50799. thumbAreaSize = 0;
  50800. }
  50801. else
  50802. {
  50803. thumbAreaStart = buttonSize;
  50804. thumbAreaSize = length - (buttonSize << 1);
  50805. }
  50806. if (upButton != 0)
  50807. {
  50808. if (vertical)
  50809. {
  50810. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50811. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50812. }
  50813. else
  50814. {
  50815. upButton->setBounds (0, 0, buttonSize, getHeight());
  50816. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50817. }
  50818. }
  50819. updateThumbPosition();
  50820. }
  50821. void ScrollBar::mouseDown (const MouseEvent& e)
  50822. {
  50823. isDraggingThumb = false;
  50824. lastMousePos = vertical ? e.y : e.x;
  50825. dragStartMousePos = lastMousePos;
  50826. dragStartRange = visibleRange.getStart();
  50827. if (dragStartMousePos < thumbStart)
  50828. {
  50829. moveScrollbarInPages (-1);
  50830. startTimer (400);
  50831. }
  50832. else if (dragStartMousePos >= thumbStart + thumbSize)
  50833. {
  50834. moveScrollbarInPages (1);
  50835. startTimer (400);
  50836. }
  50837. else
  50838. {
  50839. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50840. && (thumbAreaSize > thumbSize);
  50841. }
  50842. }
  50843. void ScrollBar::mouseDrag (const MouseEvent& e)
  50844. {
  50845. const int mousePos = vertical ? e.y : e.x;
  50846. if (isDraggingThumb && lastMousePos != mousePos)
  50847. {
  50848. const int deltaPixels = mousePos - dragStartMousePos;
  50849. setCurrentRangeStart (dragStartRange
  50850. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50851. / (thumbAreaSize - thumbSize));
  50852. }
  50853. lastMousePos = mousePos;
  50854. }
  50855. void ScrollBar::mouseUp (const MouseEvent&)
  50856. {
  50857. isDraggingThumb = false;
  50858. stopTimer();
  50859. repaint();
  50860. }
  50861. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50862. float wheelIncrementX,
  50863. float wheelIncrementY)
  50864. {
  50865. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50866. if (increment < 0)
  50867. increment = jmin (increment * 10.0f, -1.0f);
  50868. else if (increment > 0)
  50869. increment = jmax (increment * 10.0f, 1.0f);
  50870. setCurrentRange (visibleRange - singleStepSize * increment);
  50871. }
  50872. void ScrollBar::timerCallback()
  50873. {
  50874. if (isMouseButtonDown())
  50875. {
  50876. startTimer (40);
  50877. if (lastMousePos < thumbStart)
  50878. setCurrentRange (visibleRange - visibleRange.getLength());
  50879. else if (lastMousePos > thumbStart + thumbSize)
  50880. setCurrentRangeStart (visibleRange.getEnd());
  50881. }
  50882. else
  50883. {
  50884. stopTimer();
  50885. }
  50886. }
  50887. bool ScrollBar::keyPressed (const KeyPress& key)
  50888. {
  50889. if (! isVisible())
  50890. return false;
  50891. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50892. moveScrollbarInSteps (-1);
  50893. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50894. moveScrollbarInSteps (1);
  50895. else if (key.isKeyCode (KeyPress::pageUpKey))
  50896. moveScrollbarInPages (-1);
  50897. else if (key.isKeyCode (KeyPress::pageDownKey))
  50898. moveScrollbarInPages (1);
  50899. else if (key.isKeyCode (KeyPress::homeKey))
  50900. scrollToTop();
  50901. else if (key.isKeyCode (KeyPress::endKey))
  50902. scrollToBottom();
  50903. else
  50904. return false;
  50905. return true;
  50906. }
  50907. END_JUCE_NAMESPACE
  50908. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50909. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50910. BEGIN_JUCE_NAMESPACE
  50911. StretchableLayoutManager::StretchableLayoutManager()
  50912. : totalSize (0)
  50913. {
  50914. }
  50915. StretchableLayoutManager::~StretchableLayoutManager()
  50916. {
  50917. }
  50918. void StretchableLayoutManager::clearAllItems()
  50919. {
  50920. items.clear();
  50921. totalSize = 0;
  50922. }
  50923. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50924. const double minimumSize,
  50925. const double maximumSize,
  50926. const double preferredSize)
  50927. {
  50928. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50929. if (layout == 0)
  50930. {
  50931. layout = new ItemLayoutProperties();
  50932. layout->itemIndex = itemIndex;
  50933. int i;
  50934. for (i = 0; i < items.size(); ++i)
  50935. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50936. break;
  50937. items.insert (i, layout);
  50938. }
  50939. layout->minSize = minimumSize;
  50940. layout->maxSize = maximumSize;
  50941. layout->preferredSize = preferredSize;
  50942. layout->currentSize = 0;
  50943. }
  50944. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50945. double& minimumSize,
  50946. double& maximumSize,
  50947. double& preferredSize) const
  50948. {
  50949. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50950. if (layout != 0)
  50951. {
  50952. minimumSize = layout->minSize;
  50953. maximumSize = layout->maxSize;
  50954. preferredSize = layout->preferredSize;
  50955. return true;
  50956. }
  50957. return false;
  50958. }
  50959. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50960. {
  50961. totalSize = newTotalSize;
  50962. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50963. }
  50964. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50965. {
  50966. int pos = 0;
  50967. for (int i = 0; i < itemIndex; ++i)
  50968. {
  50969. const ItemLayoutProperties* const layout = getInfoFor (i);
  50970. if (layout != 0)
  50971. pos += layout->currentSize;
  50972. }
  50973. return pos;
  50974. }
  50975. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50976. {
  50977. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50978. if (layout != 0)
  50979. return layout->currentSize;
  50980. return 0;
  50981. }
  50982. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50983. {
  50984. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50985. if (layout != 0)
  50986. return -layout->currentSize / (double) totalSize;
  50987. return 0;
  50988. }
  50989. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50990. int newPosition)
  50991. {
  50992. for (int i = items.size(); --i >= 0;)
  50993. {
  50994. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50995. if (layout->itemIndex == itemIndex)
  50996. {
  50997. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50998. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50999. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51000. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51001. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51002. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51003. endPos += layout->currentSize;
  51004. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51005. updatePrefSizesToMatchCurrentPositions();
  51006. break;
  51007. }
  51008. }
  51009. }
  51010. void StretchableLayoutManager::layOutComponents (Component** const components,
  51011. int numComponents,
  51012. int x, int y, int w, int h,
  51013. const bool vertically,
  51014. const bool resizeOtherDimension)
  51015. {
  51016. setTotalSize (vertically ? h : w);
  51017. int pos = vertically ? y : x;
  51018. for (int i = 0; i < numComponents; ++i)
  51019. {
  51020. const ItemLayoutProperties* const layout = getInfoFor (i);
  51021. if (layout != 0)
  51022. {
  51023. Component* const c = components[i];
  51024. if (c != 0)
  51025. {
  51026. if (i == numComponents - 1)
  51027. {
  51028. // if it's the last item, crop it to exactly fit the available space..
  51029. if (resizeOtherDimension)
  51030. {
  51031. if (vertically)
  51032. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51033. else
  51034. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51035. }
  51036. else
  51037. {
  51038. if (vertically)
  51039. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51040. else
  51041. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51042. }
  51043. }
  51044. else
  51045. {
  51046. if (resizeOtherDimension)
  51047. {
  51048. if (vertically)
  51049. c->setBounds (x, pos, w, layout->currentSize);
  51050. else
  51051. c->setBounds (pos, y, layout->currentSize, h);
  51052. }
  51053. else
  51054. {
  51055. if (vertically)
  51056. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51057. else
  51058. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51059. }
  51060. }
  51061. }
  51062. pos += layout->currentSize;
  51063. }
  51064. }
  51065. }
  51066. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51067. {
  51068. for (int i = items.size(); --i >= 0;)
  51069. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51070. return items.getUnchecked(i);
  51071. return 0;
  51072. }
  51073. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51074. const int endIndex,
  51075. const int availableSpace,
  51076. int startPos)
  51077. {
  51078. // calculate the total sizes
  51079. int i;
  51080. double totalIdealSize = 0.0;
  51081. int totalMinimums = 0;
  51082. for (i = startIndex; i < endIndex; ++i)
  51083. {
  51084. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51085. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51086. totalMinimums += layout->currentSize;
  51087. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51088. }
  51089. if (totalIdealSize <= 0)
  51090. totalIdealSize = 1.0;
  51091. // now calc the best sizes..
  51092. int extraSpace = availableSpace - totalMinimums;
  51093. while (extraSpace > 0)
  51094. {
  51095. int numWantingMoreSpace = 0;
  51096. int numHavingTakenExtraSpace = 0;
  51097. // first figure out how many comps want a slice of the extra space..
  51098. for (i = startIndex; i < endIndex; ++i)
  51099. {
  51100. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51101. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51102. const int bestSize = jlimit (layout->currentSize,
  51103. jmax (layout->currentSize,
  51104. sizeToRealSize (layout->maxSize, totalSize)),
  51105. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51106. if (bestSize > layout->currentSize)
  51107. ++numWantingMoreSpace;
  51108. }
  51109. // ..share out the extra space..
  51110. for (i = startIndex; i < endIndex; ++i)
  51111. {
  51112. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51113. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51114. int bestSize = jlimit (layout->currentSize,
  51115. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51116. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51117. const int extraWanted = bestSize - layout->currentSize;
  51118. if (extraWanted > 0)
  51119. {
  51120. const int extraAllowed = jmin (extraWanted,
  51121. extraSpace / jmax (1, numWantingMoreSpace));
  51122. if (extraAllowed > 0)
  51123. {
  51124. ++numHavingTakenExtraSpace;
  51125. --numWantingMoreSpace;
  51126. layout->currentSize += extraAllowed;
  51127. extraSpace -= extraAllowed;
  51128. }
  51129. }
  51130. }
  51131. if (numHavingTakenExtraSpace <= 0)
  51132. break;
  51133. }
  51134. // ..and calculate the end position
  51135. for (i = startIndex; i < endIndex; ++i)
  51136. {
  51137. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51138. startPos += layout->currentSize;
  51139. }
  51140. return startPos;
  51141. }
  51142. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51143. const int endIndex) const
  51144. {
  51145. int totalMinimums = 0;
  51146. for (int i = startIndex; i < endIndex; ++i)
  51147. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51148. return totalMinimums;
  51149. }
  51150. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51151. {
  51152. int totalMaximums = 0;
  51153. for (int i = startIndex; i < endIndex; ++i)
  51154. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51155. return totalMaximums;
  51156. }
  51157. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51158. {
  51159. for (int i = 0; i < items.size(); ++i)
  51160. {
  51161. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51162. layout->preferredSize
  51163. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51164. : getItemCurrentAbsoluteSize (i);
  51165. }
  51166. }
  51167. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51168. {
  51169. if (size < 0)
  51170. size *= -totalSpace;
  51171. return roundToInt (size);
  51172. }
  51173. END_JUCE_NAMESPACE
  51174. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51175. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51176. BEGIN_JUCE_NAMESPACE
  51177. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51178. const int itemIndex_,
  51179. const bool isVertical_)
  51180. : layout (layout_),
  51181. itemIndex (itemIndex_),
  51182. isVertical (isVertical_)
  51183. {
  51184. setRepaintsOnMouseActivity (true);
  51185. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51186. : MouseCursor::UpDownResizeCursor));
  51187. }
  51188. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51189. {
  51190. }
  51191. void StretchableLayoutResizerBar::paint (Graphics& g)
  51192. {
  51193. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51194. getWidth(), getHeight(),
  51195. isVertical,
  51196. isMouseOver(),
  51197. isMouseButtonDown());
  51198. }
  51199. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51200. {
  51201. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51202. }
  51203. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51204. {
  51205. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51206. : e.getDistanceFromDragStartY());
  51207. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51208. {
  51209. layout->setItemPosition (itemIndex, desiredPos);
  51210. hasBeenMoved();
  51211. }
  51212. }
  51213. void StretchableLayoutResizerBar::hasBeenMoved()
  51214. {
  51215. if (getParentComponent() != 0)
  51216. getParentComponent()->resized();
  51217. }
  51218. END_JUCE_NAMESPACE
  51219. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51220. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51221. BEGIN_JUCE_NAMESPACE
  51222. StretchableObjectResizer::StretchableObjectResizer()
  51223. {
  51224. }
  51225. StretchableObjectResizer::~StretchableObjectResizer()
  51226. {
  51227. }
  51228. void StretchableObjectResizer::addItem (const double size,
  51229. const double minSize, const double maxSize,
  51230. const int order)
  51231. {
  51232. // the order must be >= 0 but less than the maximum integer value.
  51233. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51234. Item* const item = new Item();
  51235. item->size = size;
  51236. item->minSize = minSize;
  51237. item->maxSize = maxSize;
  51238. item->order = order;
  51239. items.add (item);
  51240. }
  51241. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51242. {
  51243. const Item* const it = items [index];
  51244. return it != 0 ? it->size : 0;
  51245. }
  51246. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51247. {
  51248. int order = 0;
  51249. for (;;)
  51250. {
  51251. double currentSize = 0;
  51252. double minSize = 0;
  51253. double maxSize = 0;
  51254. int nextHighestOrder = std::numeric_limits<int>::max();
  51255. for (int i = 0; i < items.size(); ++i)
  51256. {
  51257. const Item* const it = items.getUnchecked(i);
  51258. currentSize += it->size;
  51259. if (it->order <= order)
  51260. {
  51261. minSize += it->minSize;
  51262. maxSize += it->maxSize;
  51263. }
  51264. else
  51265. {
  51266. minSize += it->size;
  51267. maxSize += it->size;
  51268. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51269. }
  51270. }
  51271. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51272. if (thisIterationTarget >= currentSize)
  51273. {
  51274. const double availableExtraSpace = maxSize - currentSize;
  51275. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51276. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51277. for (int i = 0; i < items.size(); ++i)
  51278. {
  51279. Item* const it = items.getUnchecked(i);
  51280. if (it->order <= order)
  51281. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51282. }
  51283. }
  51284. else
  51285. {
  51286. const double amountOfSlack = currentSize - minSize;
  51287. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51288. const double scale = targetAmountOfSlack / amountOfSlack;
  51289. for (int i = 0; i < items.size(); ++i)
  51290. {
  51291. Item* const it = items.getUnchecked(i);
  51292. if (it->order <= order)
  51293. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51294. }
  51295. }
  51296. if (nextHighestOrder < std::numeric_limits<int>::max())
  51297. order = nextHighestOrder;
  51298. else
  51299. break;
  51300. }
  51301. }
  51302. END_JUCE_NAMESPACE
  51303. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51304. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51305. BEGIN_JUCE_NAMESPACE
  51306. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51307. : Button (name),
  51308. owner (owner_),
  51309. overlapPixels (0)
  51310. {
  51311. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51312. setComponentEffect (&shadow);
  51313. setWantsKeyboardFocus (false);
  51314. }
  51315. TabBarButton::~TabBarButton()
  51316. {
  51317. }
  51318. int TabBarButton::getIndex() const
  51319. {
  51320. return owner.indexOfTabButton (this);
  51321. }
  51322. void TabBarButton::paintButton (Graphics& g,
  51323. bool isMouseOverButton,
  51324. bool isButtonDown)
  51325. {
  51326. const Rectangle<int> area (getActiveArea());
  51327. g.setOrigin (area.getX(), area.getY());
  51328. getLookAndFeel()
  51329. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51330. owner.getTabBackgroundColour (getIndex()),
  51331. getIndex(), getButtonText(), *this,
  51332. owner.getOrientation(),
  51333. isMouseOverButton, isButtonDown,
  51334. getToggleState());
  51335. }
  51336. void TabBarButton::clicked (const ModifierKeys& mods)
  51337. {
  51338. if (mods.isPopupMenu())
  51339. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51340. else
  51341. owner.setCurrentTabIndex (getIndex());
  51342. }
  51343. bool TabBarButton::hitTest (int mx, int my)
  51344. {
  51345. const Rectangle<int> area (getActiveArea());
  51346. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51347. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51348. {
  51349. if (isPositiveAndBelow (mx, getWidth())
  51350. && my >= area.getY() + overlapPixels
  51351. && my < area.getBottom() - overlapPixels)
  51352. return true;
  51353. }
  51354. else
  51355. {
  51356. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51357. && isPositiveAndBelow (my, getHeight()))
  51358. return true;
  51359. }
  51360. Path p;
  51361. getLookAndFeel()
  51362. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51363. owner.getOrientation(), false, false, getToggleState());
  51364. return p.contains ((float) (mx - area.getX()),
  51365. (float) (my - area.getY()));
  51366. }
  51367. int TabBarButton::getBestTabLength (const int depth)
  51368. {
  51369. return jlimit (depth * 2,
  51370. depth * 7,
  51371. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51372. }
  51373. const Rectangle<int> TabBarButton::getActiveArea()
  51374. {
  51375. Rectangle<int> r (getLocalBounds());
  51376. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51377. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51378. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51379. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51380. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51381. return r;
  51382. }
  51383. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51384. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51385. {
  51386. public:
  51387. BehindFrontTabComp (TabbedButtonBar& owner_)
  51388. : owner (owner_)
  51389. {
  51390. setInterceptsMouseClicks (false, false);
  51391. }
  51392. void paint (Graphics& g)
  51393. {
  51394. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51395. owner, owner.getOrientation());
  51396. }
  51397. void enablementChanged()
  51398. {
  51399. repaint();
  51400. }
  51401. void buttonClicked (Button*)
  51402. {
  51403. owner.showExtraItemsMenu();
  51404. }
  51405. private:
  51406. TabbedButtonBar& owner;
  51407. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51408. };
  51409. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51410. : orientation (orientation_),
  51411. minimumScale (0.7),
  51412. currentTabIndex (-1)
  51413. {
  51414. setInterceptsMouseClicks (false, true);
  51415. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51416. setFocusContainer (true);
  51417. }
  51418. TabbedButtonBar::~TabbedButtonBar()
  51419. {
  51420. tabs.clear();
  51421. extraTabsButton = 0;
  51422. }
  51423. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51424. {
  51425. orientation = newOrientation;
  51426. for (int i = getNumChildComponents(); --i >= 0;)
  51427. getChildComponent (i)->resized();
  51428. resized();
  51429. }
  51430. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51431. {
  51432. return new TabBarButton (name, *this);
  51433. }
  51434. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51435. {
  51436. minimumScale = newMinimumScale;
  51437. resized();
  51438. }
  51439. void TabbedButtonBar::clearTabs()
  51440. {
  51441. tabs.clear();
  51442. extraTabsButton = 0;
  51443. setCurrentTabIndex (-1);
  51444. }
  51445. void TabbedButtonBar::addTab (const String& tabName,
  51446. const Colour& tabBackgroundColour,
  51447. int insertIndex)
  51448. {
  51449. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51450. if (tabName.isNotEmpty())
  51451. {
  51452. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51453. insertIndex = tabs.size();
  51454. TabInfo* newTab = new TabInfo();
  51455. newTab->name = tabName;
  51456. newTab->colour = tabBackgroundColour;
  51457. newTab->component = createTabButton (tabName, insertIndex);
  51458. jassert (newTab->component != 0);
  51459. tabs.insert (insertIndex, newTab);
  51460. addAndMakeVisible (newTab->component, insertIndex);
  51461. resized();
  51462. if (currentTabIndex < 0)
  51463. setCurrentTabIndex (0);
  51464. }
  51465. }
  51466. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51467. {
  51468. TabInfo* const tab = tabs [tabIndex];
  51469. if (tab != 0 && tab->name != newName)
  51470. {
  51471. tab->name = newName;
  51472. tab->component->setButtonText (newName);
  51473. resized();
  51474. }
  51475. }
  51476. void TabbedButtonBar::removeTab (const int tabIndex)
  51477. {
  51478. if (tabs [tabIndex] != 0)
  51479. {
  51480. const int oldTabIndex = currentTabIndex;
  51481. if (currentTabIndex == tabIndex)
  51482. currentTabIndex = -1;
  51483. tabs.remove (tabIndex);
  51484. resized();
  51485. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51486. }
  51487. }
  51488. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51489. {
  51490. tabs.move (currentIndex, newIndex);
  51491. resized();
  51492. }
  51493. int TabbedButtonBar::getNumTabs() const
  51494. {
  51495. return tabs.size();
  51496. }
  51497. const String TabbedButtonBar::getCurrentTabName() const
  51498. {
  51499. TabInfo* tab = tabs [currentTabIndex];
  51500. return tab == 0 ? String::empty : tab->name;
  51501. }
  51502. const StringArray TabbedButtonBar::getTabNames() const
  51503. {
  51504. StringArray names;
  51505. for (int i = 0; i < tabs.size(); ++i)
  51506. names.add (tabs.getUnchecked(i)->name);
  51507. return names;
  51508. }
  51509. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51510. {
  51511. if (currentTabIndex != newIndex)
  51512. {
  51513. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51514. newIndex = -1;
  51515. currentTabIndex = newIndex;
  51516. for (int i = 0; i < tabs.size(); ++i)
  51517. {
  51518. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51519. tb->setToggleState (i == newIndex, false);
  51520. }
  51521. resized();
  51522. if (sendChangeMessage_)
  51523. sendChangeMessage();
  51524. currentTabChanged (newIndex, getCurrentTabName());
  51525. }
  51526. }
  51527. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51528. {
  51529. TabInfo* const tab = tabs[index];
  51530. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51531. }
  51532. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51533. {
  51534. for (int i = tabs.size(); --i >= 0;)
  51535. if (tabs.getUnchecked(i)->component == button)
  51536. return i;
  51537. return -1;
  51538. }
  51539. void TabbedButtonBar::lookAndFeelChanged()
  51540. {
  51541. extraTabsButton = 0;
  51542. resized();
  51543. }
  51544. void TabbedButtonBar::resized()
  51545. {
  51546. int depth = getWidth();
  51547. int length = getHeight();
  51548. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51549. swapVariables (depth, length);
  51550. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51551. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51552. int i, totalLength = overlap;
  51553. int numVisibleButtons = tabs.size();
  51554. for (i = 0; i < tabs.size(); ++i)
  51555. {
  51556. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51557. totalLength += tb->getBestTabLength (depth) - overlap;
  51558. tb->overlapPixels = overlap / 2;
  51559. }
  51560. double scale = 1.0;
  51561. if (totalLength > length)
  51562. scale = jmax (minimumScale, length / (double) totalLength);
  51563. const bool isTooBig = totalLength * scale > length;
  51564. int tabsButtonPos = 0;
  51565. if (isTooBig)
  51566. {
  51567. if (extraTabsButton == 0)
  51568. {
  51569. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51570. extraTabsButton->addListener (behindFrontTab);
  51571. extraTabsButton->setAlwaysOnTop (true);
  51572. extraTabsButton->setTriggeredOnMouseDown (true);
  51573. }
  51574. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51575. extraTabsButton->setSize (buttonSize, buttonSize);
  51576. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51577. {
  51578. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51579. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51580. }
  51581. else
  51582. {
  51583. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51584. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51585. }
  51586. totalLength = 0;
  51587. for (i = 0; i < tabs.size(); ++i)
  51588. {
  51589. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51590. const int newLength = totalLength + tb->getBestTabLength (depth);
  51591. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51592. {
  51593. totalLength += overlap;
  51594. break;
  51595. }
  51596. numVisibleButtons = i + 1;
  51597. totalLength = newLength - overlap;
  51598. }
  51599. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51600. }
  51601. else
  51602. {
  51603. extraTabsButton = 0;
  51604. }
  51605. int pos = 0;
  51606. TabBarButton* frontTab = 0;
  51607. for (i = 0; i < tabs.size(); ++i)
  51608. {
  51609. TabBarButton* const tb = getTabButton (i);
  51610. if (tb != 0)
  51611. {
  51612. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51613. if (i < numVisibleButtons)
  51614. {
  51615. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51616. tb->setBounds (pos, 0, bestLength, getHeight());
  51617. else
  51618. tb->setBounds (0, pos, getWidth(), bestLength);
  51619. tb->toBack();
  51620. if (i == currentTabIndex)
  51621. frontTab = tb;
  51622. tb->setVisible (true);
  51623. }
  51624. else
  51625. {
  51626. tb->setVisible (false);
  51627. }
  51628. pos += bestLength - overlap;
  51629. }
  51630. }
  51631. behindFrontTab->setBounds (getLocalBounds());
  51632. if (frontTab != 0)
  51633. {
  51634. frontTab->toFront (false);
  51635. behindFrontTab->toBehind (frontTab);
  51636. }
  51637. }
  51638. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51639. {
  51640. TabInfo* const tab = tabs [tabIndex];
  51641. return tab == 0 ? Colours::white : tab->colour;
  51642. }
  51643. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51644. {
  51645. TabInfo* const tab = tabs [tabIndex];
  51646. if (tab != 0 && tab->colour != newColour)
  51647. {
  51648. tab->colour = newColour;
  51649. repaint();
  51650. }
  51651. }
  51652. void TabbedButtonBar::showExtraItemsMenu()
  51653. {
  51654. PopupMenu m;
  51655. for (int i = 0; i < tabs.size(); ++i)
  51656. {
  51657. const TabInfo* const tab = tabs.getUnchecked(i);
  51658. if (! tab->component->isVisible())
  51659. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51660. }
  51661. const int res = m.showAt (extraTabsButton);
  51662. if (res != 0)
  51663. setCurrentTabIndex (res - 1);
  51664. }
  51665. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51666. {
  51667. }
  51668. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51669. {
  51670. }
  51671. END_JUCE_NAMESPACE
  51672. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51673. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51674. BEGIN_JUCE_NAMESPACE
  51675. namespace TabbedComponentHelpers
  51676. {
  51677. const Identifier deleteComponentId ("deleteByTabComp_");
  51678. void deleteIfNecessary (Component* const comp)
  51679. {
  51680. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51681. delete comp;
  51682. }
  51683. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize& outline,
  51684. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51685. {
  51686. switch (orientation)
  51687. {
  51688. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51689. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51690. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51691. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51692. default: jassertfalse; break;
  51693. }
  51694. return Rectangle<int>();
  51695. }
  51696. }
  51697. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51698. {
  51699. public:
  51700. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51701. : TabbedButtonBar (orientation_),
  51702. owner (owner_)
  51703. {
  51704. }
  51705. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51706. {
  51707. owner.changeCallback (newCurrentTabIndex, newTabName);
  51708. }
  51709. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51710. {
  51711. owner.popupMenuClickOnTab (tabIndex, tabName);
  51712. }
  51713. const Colour getTabBackgroundColour (const int tabIndex)
  51714. {
  51715. return owner.tabs->getTabBackgroundColour (tabIndex);
  51716. }
  51717. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51718. {
  51719. return owner.createTabButton (tabName, tabIndex);
  51720. }
  51721. private:
  51722. TabbedComponent& owner;
  51723. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51724. };
  51725. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51726. : tabDepth (30),
  51727. outlineThickness (1),
  51728. edgeIndent (0)
  51729. {
  51730. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51731. }
  51732. TabbedComponent::~TabbedComponent()
  51733. {
  51734. clearTabs();
  51735. tabs = 0;
  51736. }
  51737. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51738. {
  51739. tabs->setOrientation (orientation);
  51740. resized();
  51741. }
  51742. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51743. {
  51744. return tabs->getOrientation();
  51745. }
  51746. void TabbedComponent::setTabBarDepth (const int newDepth)
  51747. {
  51748. if (tabDepth != newDepth)
  51749. {
  51750. tabDepth = newDepth;
  51751. resized();
  51752. }
  51753. }
  51754. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51755. {
  51756. return new TabBarButton (tabName, *tabs);
  51757. }
  51758. void TabbedComponent::clearTabs()
  51759. {
  51760. if (panelComponent != 0)
  51761. {
  51762. panelComponent->setVisible (false);
  51763. removeChildComponent (panelComponent);
  51764. panelComponent = 0;
  51765. }
  51766. tabs->clearTabs();
  51767. for (int i = contentComponents.size(); --i >= 0;)
  51768. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51769. contentComponents.clear();
  51770. }
  51771. void TabbedComponent::addTab (const String& tabName,
  51772. const Colour& tabBackgroundColour,
  51773. Component* const contentComponent,
  51774. const bool deleteComponentWhenNotNeeded,
  51775. const int insertIndex)
  51776. {
  51777. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51778. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51779. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51780. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51781. }
  51782. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51783. {
  51784. tabs->setTabName (tabIndex, newName);
  51785. }
  51786. void TabbedComponent::removeTab (const int tabIndex)
  51787. {
  51788. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51789. {
  51790. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51791. contentComponents.remove (tabIndex);
  51792. tabs->removeTab (tabIndex);
  51793. }
  51794. }
  51795. int TabbedComponent::getNumTabs() const
  51796. {
  51797. return tabs->getNumTabs();
  51798. }
  51799. const StringArray TabbedComponent::getTabNames() const
  51800. {
  51801. return tabs->getTabNames();
  51802. }
  51803. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51804. {
  51805. return contentComponents [tabIndex];
  51806. }
  51807. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51808. {
  51809. return tabs->getTabBackgroundColour (tabIndex);
  51810. }
  51811. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51812. {
  51813. tabs->setTabBackgroundColour (tabIndex, newColour);
  51814. if (getCurrentTabIndex() == tabIndex)
  51815. repaint();
  51816. }
  51817. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51818. {
  51819. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51820. }
  51821. int TabbedComponent::getCurrentTabIndex() const
  51822. {
  51823. return tabs->getCurrentTabIndex();
  51824. }
  51825. const String TabbedComponent::getCurrentTabName() const
  51826. {
  51827. return tabs->getCurrentTabName();
  51828. }
  51829. void TabbedComponent::setOutline (const int thickness)
  51830. {
  51831. outlineThickness = thickness;
  51832. resized();
  51833. repaint();
  51834. }
  51835. void TabbedComponent::setIndent (const int indentThickness)
  51836. {
  51837. edgeIndent = indentThickness;
  51838. resized();
  51839. repaint();
  51840. }
  51841. void TabbedComponent::paint (Graphics& g)
  51842. {
  51843. g.fillAll (findColour (backgroundColourId));
  51844. Rectangle<int> content (getLocalBounds());
  51845. BorderSize outline (outlineThickness);
  51846. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51847. g.reduceClipRegion (content);
  51848. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51849. if (outlineThickness > 0)
  51850. {
  51851. RectangleList rl (content);
  51852. rl.subtract (outline.subtractedFrom (content));
  51853. g.reduceClipRegion (rl);
  51854. g.fillAll (findColour (outlineColourId));
  51855. }
  51856. }
  51857. void TabbedComponent::resized()
  51858. {
  51859. Rectangle<int> content (getLocalBounds());
  51860. BorderSize outline (outlineThickness);
  51861. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51862. content = BorderSize (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51863. for (int i = contentComponents.size(); --i >= 0;)
  51864. if (contentComponents.getReference (i) != 0)
  51865. contentComponents.getReference (i)->setBounds (content);
  51866. }
  51867. void TabbedComponent::lookAndFeelChanged()
  51868. {
  51869. for (int i = contentComponents.size(); --i >= 0;)
  51870. if (contentComponents.getReference (i) != 0)
  51871. contentComponents.getReference (i)->lookAndFeelChanged();
  51872. }
  51873. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51874. {
  51875. if (panelComponent != 0)
  51876. {
  51877. panelComponent->setVisible (false);
  51878. removeChildComponent (panelComponent);
  51879. panelComponent = 0;
  51880. }
  51881. if (getCurrentTabIndex() >= 0)
  51882. {
  51883. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51884. if (panelComponent != 0)
  51885. {
  51886. // do these ops as two stages instead of addAndMakeVisible() so that the
  51887. // component has always got a parent when it gets the visibilityChanged() callback
  51888. addChildComponent (panelComponent);
  51889. panelComponent->setVisible (true);
  51890. panelComponent->toFront (true);
  51891. }
  51892. repaint();
  51893. }
  51894. resized();
  51895. currentTabChanged (newCurrentTabIndex, newTabName);
  51896. }
  51897. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51898. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51899. END_JUCE_NAMESPACE
  51900. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51901. /*** Start of inlined file: juce_Viewport.cpp ***/
  51902. BEGIN_JUCE_NAMESPACE
  51903. Viewport::Viewport (const String& componentName)
  51904. : Component (componentName),
  51905. scrollBarThickness (0),
  51906. singleStepX (16),
  51907. singleStepY (16),
  51908. showHScrollbar (true),
  51909. showVScrollbar (true),
  51910. verticalScrollBar (true),
  51911. horizontalScrollBar (false)
  51912. {
  51913. // content holder is used to clip the contents so they don't overlap the scrollbars
  51914. addAndMakeVisible (&contentHolder);
  51915. contentHolder.setInterceptsMouseClicks (false, true);
  51916. addChildComponent (&verticalScrollBar);
  51917. addChildComponent (&horizontalScrollBar);
  51918. verticalScrollBar.addListener (this);
  51919. horizontalScrollBar.addListener (this);
  51920. setInterceptsMouseClicks (false, true);
  51921. setWantsKeyboardFocus (true);
  51922. }
  51923. Viewport::~Viewport()
  51924. {
  51925. deleteContentComp();
  51926. }
  51927. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51928. {
  51929. }
  51930. void Viewport::deleteContentComp()
  51931. {
  51932. // This sets the content comp to a null pointer before deleting the old one, in case
  51933. // anything tries to use the old one while it's in mid-deletion..
  51934. ScopedPointer<Component> oldCompDeleter (contentComp);
  51935. contentComp = 0;
  51936. }
  51937. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51938. {
  51939. if (contentComp.get() != newViewedComponent)
  51940. {
  51941. deleteContentComp();
  51942. contentComp = newViewedComponent;
  51943. if (contentComp != 0)
  51944. {
  51945. contentHolder.addAndMakeVisible (contentComp);
  51946. setViewPosition (0, 0);
  51947. contentComp->addComponentListener (this);
  51948. }
  51949. updateVisibleArea();
  51950. }
  51951. }
  51952. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51953. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51954. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51955. {
  51956. if (contentComp != 0)
  51957. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51958. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51959. }
  51960. void Viewport::setViewPosition (const Point<int>& newPosition)
  51961. {
  51962. setViewPosition (newPosition.getX(), newPosition.getY());
  51963. }
  51964. void Viewport::setViewPositionProportionately (const double x, const double y)
  51965. {
  51966. if (contentComp != 0)
  51967. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51968. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51969. }
  51970. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51971. {
  51972. if (contentComp != 0)
  51973. {
  51974. int dx = 0, dy = 0;
  51975. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51976. {
  51977. if (mouseX < activeBorderThickness)
  51978. dx = activeBorderThickness - mouseX;
  51979. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51980. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51981. if (dx < 0)
  51982. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51983. else
  51984. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51985. }
  51986. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51987. {
  51988. if (mouseY < activeBorderThickness)
  51989. dy = activeBorderThickness - mouseY;
  51990. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51991. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51992. if (dy < 0)
  51993. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51994. else
  51995. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51996. }
  51997. if (dx != 0 || dy != 0)
  51998. {
  51999. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52000. contentComp->getY() + dy);
  52001. return true;
  52002. }
  52003. }
  52004. return false;
  52005. }
  52006. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52007. {
  52008. updateVisibleArea();
  52009. }
  52010. void Viewport::resized()
  52011. {
  52012. updateVisibleArea();
  52013. }
  52014. void Viewport::updateVisibleArea()
  52015. {
  52016. const int scrollbarWidth = getScrollBarThickness();
  52017. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52018. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52019. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52020. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52021. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52022. Rectangle<int> contentArea (getLocalBounds());
  52023. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52024. {
  52025. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52026. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52027. if (vBarVisible)
  52028. contentArea.setWidth (getWidth() - scrollbarWidth);
  52029. if (hBarVisible)
  52030. contentArea.setHeight (getHeight() - scrollbarWidth);
  52031. if (! contentArea.contains (contentComp->getBounds()))
  52032. {
  52033. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52034. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52035. }
  52036. }
  52037. if (vBarVisible)
  52038. contentArea.setWidth (getWidth() - scrollbarWidth);
  52039. if (hBarVisible)
  52040. contentArea.setHeight (getHeight() - scrollbarWidth);
  52041. contentHolder.setBounds (contentArea);
  52042. Rectangle<int> contentBounds;
  52043. if (contentComp != 0)
  52044. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  52045. Point<int> visibleOrigin (-contentBounds.getPosition());
  52046. if (hBarVisible)
  52047. {
  52048. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52049. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52050. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52051. horizontalScrollBar.setSingleStepSize (singleStepX);
  52052. horizontalScrollBar.cancelPendingUpdate();
  52053. }
  52054. else
  52055. {
  52056. visibleOrigin.setX (0);
  52057. }
  52058. if (vBarVisible)
  52059. {
  52060. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52061. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52062. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52063. verticalScrollBar.setSingleStepSize (singleStepY);
  52064. verticalScrollBar.cancelPendingUpdate();
  52065. }
  52066. else
  52067. {
  52068. visibleOrigin.setY (0);
  52069. }
  52070. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52071. horizontalScrollBar.setVisible (hBarVisible);
  52072. verticalScrollBar.setVisible (vBarVisible);
  52073. setViewPosition (visibleOrigin);
  52074. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52075. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52076. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52077. if (lastVisibleArea != visibleArea)
  52078. {
  52079. lastVisibleArea = visibleArea;
  52080. visibleAreaChanged (visibleArea);
  52081. }
  52082. horizontalScrollBar.handleUpdateNowIfNeeded();
  52083. verticalScrollBar.handleUpdateNowIfNeeded();
  52084. }
  52085. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52086. {
  52087. if (singleStepX != stepX || singleStepY != stepY)
  52088. {
  52089. singleStepX = stepX;
  52090. singleStepY = stepY;
  52091. updateVisibleArea();
  52092. }
  52093. }
  52094. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52095. const bool showHorizontalScrollbarIfNeeded)
  52096. {
  52097. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52098. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52099. {
  52100. showVScrollbar = showVerticalScrollbarIfNeeded;
  52101. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52102. updateVisibleArea();
  52103. }
  52104. }
  52105. void Viewport::setScrollBarThickness (const int thickness)
  52106. {
  52107. if (scrollBarThickness != thickness)
  52108. {
  52109. scrollBarThickness = thickness;
  52110. updateVisibleArea();
  52111. }
  52112. }
  52113. int Viewport::getScrollBarThickness() const
  52114. {
  52115. return scrollBarThickness > 0 ? scrollBarThickness
  52116. : getLookAndFeel().getDefaultScrollbarWidth();
  52117. }
  52118. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52119. {
  52120. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52121. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52122. }
  52123. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52124. {
  52125. const int newRangeStartInt = roundToInt (newRangeStart);
  52126. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52127. {
  52128. setViewPosition (newRangeStartInt, getViewPositionY());
  52129. }
  52130. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52131. {
  52132. setViewPosition (getViewPositionX(), newRangeStartInt);
  52133. }
  52134. }
  52135. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52136. {
  52137. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52138. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52139. }
  52140. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52141. {
  52142. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52143. {
  52144. const bool hasVertBar = verticalScrollBar.isVisible();
  52145. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52146. if (hasHorzBar || hasVertBar)
  52147. {
  52148. if (wheelIncrementX != 0)
  52149. {
  52150. wheelIncrementX *= 14.0f * singleStepX;
  52151. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52152. : jmax (wheelIncrementX, 1.0f);
  52153. }
  52154. if (wheelIncrementY != 0)
  52155. {
  52156. wheelIncrementY *= 14.0f * singleStepY;
  52157. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52158. : jmax (wheelIncrementY, 1.0f);
  52159. }
  52160. Point<int> pos (getViewPosition());
  52161. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52162. {
  52163. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52164. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52165. }
  52166. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52167. {
  52168. if (wheelIncrementX == 0 && ! hasVertBar)
  52169. wheelIncrementX = wheelIncrementY;
  52170. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52171. }
  52172. else if (hasVertBar && wheelIncrementY != 0)
  52173. {
  52174. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52175. }
  52176. if (pos != getViewPosition())
  52177. {
  52178. setViewPosition (pos);
  52179. return true;
  52180. }
  52181. }
  52182. }
  52183. return false;
  52184. }
  52185. bool Viewport::keyPressed (const KeyPress& key)
  52186. {
  52187. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52188. || key.isKeyCode (KeyPress::downKey)
  52189. || key.isKeyCode (KeyPress::pageUpKey)
  52190. || key.isKeyCode (KeyPress::pageDownKey)
  52191. || key.isKeyCode (KeyPress::homeKey)
  52192. || key.isKeyCode (KeyPress::endKey);
  52193. if (verticalScrollBar.isVisible() && isUpDownKey)
  52194. return verticalScrollBar.keyPressed (key);
  52195. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52196. || key.isKeyCode (KeyPress::rightKey);
  52197. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52198. return horizontalScrollBar.keyPressed (key);
  52199. return false;
  52200. }
  52201. END_JUCE_NAMESPACE
  52202. /*** End of inlined file: juce_Viewport.cpp ***/
  52203. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52204. BEGIN_JUCE_NAMESPACE
  52205. namespace LookAndFeelHelpers
  52206. {
  52207. void createRoundedPath (Path& p,
  52208. const float x, const float y,
  52209. const float w, const float h,
  52210. const float cs,
  52211. const bool curveTopLeft, const bool curveTopRight,
  52212. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52213. {
  52214. const float cs2 = 2.0f * cs;
  52215. if (curveTopLeft)
  52216. {
  52217. p.startNewSubPath (x, y + cs);
  52218. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52219. }
  52220. else
  52221. {
  52222. p.startNewSubPath (x, y);
  52223. }
  52224. if (curveTopRight)
  52225. {
  52226. p.lineTo (x + w - cs, y);
  52227. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52228. }
  52229. else
  52230. {
  52231. p.lineTo (x + w, y);
  52232. }
  52233. if (curveBottomRight)
  52234. {
  52235. p.lineTo (x + w, y + h - cs);
  52236. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52237. }
  52238. else
  52239. {
  52240. p.lineTo (x + w, y + h);
  52241. }
  52242. if (curveBottomLeft)
  52243. {
  52244. p.lineTo (x + cs, y + h);
  52245. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52246. }
  52247. else
  52248. {
  52249. p.lineTo (x, y + h);
  52250. }
  52251. p.closeSubPath();
  52252. }
  52253. const Colour createBaseColour (const Colour& buttonColour,
  52254. const bool hasKeyboardFocus,
  52255. const bool isMouseOverButton,
  52256. const bool isButtonDown) throw()
  52257. {
  52258. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52259. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52260. if (isButtonDown)
  52261. return baseColour.contrasting (0.2f);
  52262. else if (isMouseOverButton)
  52263. return baseColour.contrasting (0.1f);
  52264. return baseColour;
  52265. }
  52266. const TextLayout layoutTooltipText (const String& text) throw()
  52267. {
  52268. const float tooltipFontSize = 12.0f;
  52269. const int maxToolTipWidth = 400;
  52270. const Font f (tooltipFontSize, Font::bold);
  52271. TextLayout tl (text, f);
  52272. tl.layout (maxToolTipWidth, Justification::left, true);
  52273. return tl;
  52274. }
  52275. LookAndFeel* defaultLF = 0;
  52276. LookAndFeel* currentDefaultLF = 0;
  52277. }
  52278. LookAndFeel::LookAndFeel()
  52279. {
  52280. /* if this fails it means you're trying to create a LookAndFeel object before
  52281. the static Colours have been initialised. That ain't gonna work. It probably
  52282. means that you're using a static LookAndFeel object and that your compiler has
  52283. decided to intialise it before the Colours class.
  52284. */
  52285. jassert (Colours::white == Colour (0xffffffff));
  52286. // set up the standard set of colours..
  52287. const int textButtonColour = 0xffbbbbff;
  52288. const int textHighlightColour = 0x401111ee;
  52289. const int standardOutlineColour = 0xb2808080;
  52290. static const int standardColours[] =
  52291. {
  52292. TextButton::buttonColourId, textButtonColour,
  52293. TextButton::buttonOnColourId, 0xff4444ff,
  52294. TextButton::textColourOnId, 0xff000000,
  52295. TextButton::textColourOffId, 0xff000000,
  52296. ComboBox::buttonColourId, 0xffbbbbff,
  52297. ComboBox::outlineColourId, standardOutlineColour,
  52298. ToggleButton::textColourId, 0xff000000,
  52299. TextEditor::backgroundColourId, 0xffffffff,
  52300. TextEditor::textColourId, 0xff000000,
  52301. TextEditor::highlightColourId, textHighlightColour,
  52302. TextEditor::highlightedTextColourId, 0xff000000,
  52303. TextEditor::caretColourId, 0xff000000,
  52304. TextEditor::outlineColourId, 0x00000000,
  52305. TextEditor::focusedOutlineColourId, textButtonColour,
  52306. TextEditor::shadowColourId, 0x38000000,
  52307. Label::backgroundColourId, 0x00000000,
  52308. Label::textColourId, 0xff000000,
  52309. Label::outlineColourId, 0x00000000,
  52310. ScrollBar::backgroundColourId, 0x00000000,
  52311. ScrollBar::thumbColourId, 0xffffffff,
  52312. TreeView::linesColourId, 0x4c000000,
  52313. TreeView::backgroundColourId, 0x00000000,
  52314. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52315. PopupMenu::backgroundColourId, 0xffffffff,
  52316. PopupMenu::textColourId, 0xff000000,
  52317. PopupMenu::headerTextColourId, 0xff000000,
  52318. PopupMenu::highlightedTextColourId, 0xffffffff,
  52319. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52320. ComboBox::textColourId, 0xff000000,
  52321. ComboBox::backgroundColourId, 0xffffffff,
  52322. ComboBox::arrowColourId, 0x99000000,
  52323. ListBox::backgroundColourId, 0xffffffff,
  52324. ListBox::outlineColourId, standardOutlineColour,
  52325. ListBox::textColourId, 0xff000000,
  52326. Slider::backgroundColourId, 0x00000000,
  52327. Slider::thumbColourId, textButtonColour,
  52328. Slider::trackColourId, 0x7fffffff,
  52329. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52330. Slider::rotarySliderOutlineColourId, 0x66000000,
  52331. Slider::textBoxTextColourId, 0xff000000,
  52332. Slider::textBoxBackgroundColourId, 0xffffffff,
  52333. Slider::textBoxHighlightColourId, textHighlightColour,
  52334. Slider::textBoxOutlineColourId, standardOutlineColour,
  52335. ResizableWindow::backgroundColourId, 0xff777777,
  52336. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52337. AlertWindow::backgroundColourId, 0xffededed,
  52338. AlertWindow::textColourId, 0xff000000,
  52339. AlertWindow::outlineColourId, 0xff666666,
  52340. ProgressBar::backgroundColourId, 0xffeeeeee,
  52341. ProgressBar::foregroundColourId, 0xffaaaaee,
  52342. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52343. TooltipWindow::textColourId, 0xff000000,
  52344. TooltipWindow::outlineColourId, 0x4c000000,
  52345. TabbedComponent::backgroundColourId, 0x00000000,
  52346. TabbedComponent::outlineColourId, 0xff777777,
  52347. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52348. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52349. Toolbar::backgroundColourId, 0xfff6f8f9,
  52350. Toolbar::separatorColourId, 0x4c000000,
  52351. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52352. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52353. Toolbar::labelTextColourId, 0xff000000,
  52354. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52355. HyperlinkButton::textColourId, 0xcc1111ee,
  52356. GroupComponent::outlineColourId, 0x66000000,
  52357. GroupComponent::textColourId, 0xff000000,
  52358. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52359. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52360. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52361. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52362. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52363. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52364. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52365. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52366. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52367. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52368. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52369. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52370. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52371. CodeEditorComponent::caretColourId, 0xff000000,
  52372. CodeEditorComponent::highlightColourId, textHighlightColour,
  52373. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52374. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52375. ColourSelector::labelTextColourId, 0xff000000,
  52376. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52377. KeyMappingEditorComponent::textColourId, 0xff000000,
  52378. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52379. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52380. DrawableButton::textColourId, 0xff000000,
  52381. };
  52382. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52383. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52384. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52385. if (defaultSansName.isEmpty())
  52386. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52387. defaultSans = defaultSansName;
  52388. defaultSerif = defaultSerifName;
  52389. defaultFixed = defaultFixedName;
  52390. Font::setFallbackFontName (defaultFallback);
  52391. }
  52392. LookAndFeel::~LookAndFeel()
  52393. {
  52394. if (this == LookAndFeelHelpers::currentDefaultLF)
  52395. setDefaultLookAndFeel (0);
  52396. }
  52397. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52398. {
  52399. const int index = colourIds.indexOf (colourId);
  52400. if (index >= 0)
  52401. return colours [index];
  52402. jassertfalse;
  52403. return Colours::black;
  52404. }
  52405. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52406. {
  52407. const int index = colourIds.indexOf (colourId);
  52408. if (index >= 0)
  52409. {
  52410. colours.set (index, colour);
  52411. }
  52412. else
  52413. {
  52414. colourIds.add (colourId);
  52415. colours.add (colour);
  52416. }
  52417. }
  52418. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52419. {
  52420. return colourIds.contains (colourId);
  52421. }
  52422. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52423. {
  52424. // if this happens, your app hasn't initialised itself properly.. if you're
  52425. // trying to hack your own main() function, have a look at
  52426. // JUCEApplication::initialiseForGUI()
  52427. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52428. return *LookAndFeelHelpers::currentDefaultLF;
  52429. }
  52430. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52431. {
  52432. using namespace LookAndFeelHelpers;
  52433. if (newDefaultLookAndFeel == 0)
  52434. {
  52435. if (defaultLF == 0)
  52436. defaultLF = new LookAndFeel();
  52437. newDefaultLookAndFeel = defaultLF;
  52438. }
  52439. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52440. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52441. {
  52442. Component* const c = Desktop::getInstance().getComponent (i);
  52443. if (c != 0)
  52444. c->sendLookAndFeelChange();
  52445. }
  52446. }
  52447. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52448. {
  52449. using namespace LookAndFeelHelpers;
  52450. if (currentDefaultLF == defaultLF)
  52451. currentDefaultLF = 0;
  52452. deleteAndZero (defaultLF);
  52453. }
  52454. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52455. {
  52456. String faceName (font.getTypefaceName());
  52457. if (faceName == Font::getDefaultSansSerifFontName())
  52458. faceName = defaultSans;
  52459. else if (faceName == Font::getDefaultSerifFontName())
  52460. faceName = defaultSerif;
  52461. else if (faceName == Font::getDefaultMonospacedFontName())
  52462. faceName = defaultFixed;
  52463. Font f (font);
  52464. f.setTypefaceName (faceName);
  52465. return Typeface::createSystemTypefaceFor (f);
  52466. }
  52467. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52468. {
  52469. defaultSans = newName;
  52470. }
  52471. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52472. {
  52473. return component.getMouseCursor();
  52474. }
  52475. void LookAndFeel::drawButtonBackground (Graphics& g,
  52476. Button& button,
  52477. const Colour& backgroundColour,
  52478. bool isMouseOverButton,
  52479. bool isButtonDown)
  52480. {
  52481. const int width = button.getWidth();
  52482. const int height = button.getHeight();
  52483. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52484. const float halfThickness = outlineThickness * 0.5f;
  52485. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52486. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52487. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52488. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52489. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52490. button.hasKeyboardFocus (true),
  52491. isMouseOverButton, isButtonDown)
  52492. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52493. drawGlassLozenge (g,
  52494. indentL,
  52495. indentT,
  52496. width - indentL - indentR,
  52497. height - indentT - indentB,
  52498. baseColour, outlineThickness, -1.0f,
  52499. button.isConnectedOnLeft(),
  52500. button.isConnectedOnRight(),
  52501. button.isConnectedOnTop(),
  52502. button.isConnectedOnBottom());
  52503. }
  52504. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52505. {
  52506. return button.getFont();
  52507. }
  52508. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52509. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52510. {
  52511. Font font (getFontForTextButton (button));
  52512. g.setFont (font);
  52513. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52514. : TextButton::textColourOffId)
  52515. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52516. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52517. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52518. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52519. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52520. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52521. g.drawFittedText (button.getButtonText(),
  52522. leftIndent,
  52523. yIndent,
  52524. button.getWidth() - leftIndent - rightIndent,
  52525. button.getHeight() - yIndent * 2,
  52526. Justification::centred, 2);
  52527. }
  52528. void LookAndFeel::drawTickBox (Graphics& g,
  52529. Component& component,
  52530. float x, float y, float w, float h,
  52531. const bool ticked,
  52532. const bool isEnabled,
  52533. const bool isMouseOverButton,
  52534. const bool isButtonDown)
  52535. {
  52536. const float boxSize = w * 0.7f;
  52537. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52538. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52539. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52540. true, isMouseOverButton, isButtonDown),
  52541. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52542. if (ticked)
  52543. {
  52544. Path tick;
  52545. tick.startNewSubPath (1.5f, 3.0f);
  52546. tick.lineTo (3.0f, 6.0f);
  52547. tick.lineTo (6.0f, 0.0f);
  52548. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52549. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52550. .translated (x, y));
  52551. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52552. }
  52553. }
  52554. void LookAndFeel::drawToggleButton (Graphics& g,
  52555. ToggleButton& button,
  52556. bool isMouseOverButton,
  52557. bool isButtonDown)
  52558. {
  52559. if (button.hasKeyboardFocus (true))
  52560. {
  52561. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52562. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52563. }
  52564. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52565. const float tickWidth = fontSize * 1.1f;
  52566. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52567. tickWidth, tickWidth,
  52568. button.getToggleState(),
  52569. button.isEnabled(),
  52570. isMouseOverButton,
  52571. isButtonDown);
  52572. g.setColour (button.findColour (ToggleButton::textColourId));
  52573. g.setFont (fontSize);
  52574. if (! button.isEnabled())
  52575. g.setOpacity (0.5f);
  52576. const int textX = (int) tickWidth + 5;
  52577. g.drawFittedText (button.getButtonText(),
  52578. textX, 0,
  52579. button.getWidth() - textX - 2, button.getHeight(),
  52580. Justification::centredLeft, 10);
  52581. }
  52582. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52583. {
  52584. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52585. const int tickWidth = jmin (24, button.getHeight());
  52586. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52587. button.getHeight());
  52588. }
  52589. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52590. const String& message,
  52591. const String& button1,
  52592. const String& button2,
  52593. const String& button3,
  52594. AlertWindow::AlertIconType iconType,
  52595. int numButtons,
  52596. Component* associatedComponent)
  52597. {
  52598. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52599. if (numButtons == 1)
  52600. {
  52601. aw->addButton (button1, 0,
  52602. KeyPress (KeyPress::escapeKey, 0, 0),
  52603. KeyPress (KeyPress::returnKey, 0, 0));
  52604. }
  52605. else
  52606. {
  52607. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52608. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52609. if (button1ShortCut == button2ShortCut)
  52610. button2ShortCut = KeyPress();
  52611. if (numButtons == 2)
  52612. {
  52613. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52614. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52615. }
  52616. else if (numButtons == 3)
  52617. {
  52618. aw->addButton (button1, 1, button1ShortCut);
  52619. aw->addButton (button2, 2, button2ShortCut);
  52620. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52621. }
  52622. }
  52623. return aw;
  52624. }
  52625. void LookAndFeel::drawAlertBox (Graphics& g,
  52626. AlertWindow& alert,
  52627. const Rectangle<int>& textArea,
  52628. TextLayout& textLayout)
  52629. {
  52630. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52631. int iconSpaceUsed = 0;
  52632. Justification alignment (Justification::horizontallyCentred);
  52633. const int iconWidth = 80;
  52634. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52635. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52636. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52637. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52638. iconSize, iconSize);
  52639. if (alert.getAlertType() != AlertWindow::NoIcon)
  52640. {
  52641. Path icon;
  52642. uint32 colour;
  52643. char character;
  52644. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52645. {
  52646. colour = 0x55ff5555;
  52647. character = '!';
  52648. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52649. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52650. (float) iconRect.getX(), (float) iconRect.getBottom());
  52651. icon = icon.createPathWithRoundedCorners (5.0f);
  52652. }
  52653. else
  52654. {
  52655. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52656. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52657. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52658. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52659. }
  52660. GlyphArrangement ga;
  52661. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52662. String::charToString (character),
  52663. (float) iconRect.getX(), (float) iconRect.getY(),
  52664. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52665. Justification::centred, false);
  52666. ga.createPath (icon);
  52667. icon.setUsingNonZeroWinding (false);
  52668. g.setColour (Colour (colour));
  52669. g.fillPath (icon);
  52670. iconSpaceUsed = iconWidth;
  52671. alignment = Justification::left;
  52672. }
  52673. g.setColour (alert.findColour (AlertWindow::textColourId));
  52674. textLayout.drawWithin (g,
  52675. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52676. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52677. alignment.getFlags() | Justification::top);
  52678. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52679. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52680. }
  52681. int LookAndFeel::getAlertBoxWindowFlags()
  52682. {
  52683. return ComponentPeer::windowAppearsOnTaskbar
  52684. | ComponentPeer::windowHasDropShadow;
  52685. }
  52686. int LookAndFeel::getAlertWindowButtonHeight()
  52687. {
  52688. return 28;
  52689. }
  52690. const Font LookAndFeel::getAlertWindowMessageFont()
  52691. {
  52692. return Font (15.0f);
  52693. }
  52694. const Font LookAndFeel::getAlertWindowFont()
  52695. {
  52696. return Font (12.0f);
  52697. }
  52698. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52699. int width, int height,
  52700. double progress, const String& textToShow)
  52701. {
  52702. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52703. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52704. g.fillAll (background);
  52705. if (progress >= 0.0f && progress < 1.0f)
  52706. {
  52707. drawGlassLozenge (g, 1.0f, 1.0f,
  52708. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52709. (float) (height - 2),
  52710. foreground,
  52711. 0.5f, 0.0f,
  52712. true, true, true, true);
  52713. }
  52714. else
  52715. {
  52716. // spinning bar..
  52717. g.setColour (foreground);
  52718. const int stripeWidth = height * 2;
  52719. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52720. Path p;
  52721. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52722. p.addQuadrilateral (x, 0.0f,
  52723. x + stripeWidth * 0.5f, 0.0f,
  52724. x, (float) height,
  52725. x - stripeWidth * 0.5f, (float) height);
  52726. Image im (Image::ARGB, width, height, true);
  52727. {
  52728. Graphics g2 (im);
  52729. drawGlassLozenge (g2, 1.0f, 1.0f,
  52730. (float) (width - 2),
  52731. (float) (height - 2),
  52732. foreground,
  52733. 0.5f, 0.0f,
  52734. true, true, true, true);
  52735. }
  52736. g.setTiledImageFill (im, 0, 0, 0.85f);
  52737. g.fillPath (p);
  52738. }
  52739. if (textToShow.isNotEmpty())
  52740. {
  52741. g.setColour (Colour::contrasting (background, foreground));
  52742. g.setFont (height * 0.6f);
  52743. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52744. }
  52745. }
  52746. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52747. {
  52748. const float radius = jmin (w, h) * 0.4f;
  52749. const float thickness = radius * 0.15f;
  52750. Path p;
  52751. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52752. radius * 0.6f, thickness,
  52753. thickness * 0.5f);
  52754. const float cx = x + w * 0.5f;
  52755. const float cy = y + h * 0.5f;
  52756. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52757. for (int i = 0; i < 12; ++i)
  52758. {
  52759. const int n = (i + 12 - animationIndex) % 12;
  52760. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52761. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52762. .translated (cx, cy));
  52763. }
  52764. }
  52765. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52766. ScrollBar& scrollbar,
  52767. int width, int height,
  52768. int buttonDirection,
  52769. bool /*isScrollbarVertical*/,
  52770. bool /*isMouseOverButton*/,
  52771. bool isButtonDown)
  52772. {
  52773. Path p;
  52774. if (buttonDirection == 0)
  52775. p.addTriangle (width * 0.5f, height * 0.2f,
  52776. width * 0.1f, height * 0.7f,
  52777. width * 0.9f, height * 0.7f);
  52778. else if (buttonDirection == 1)
  52779. p.addTriangle (width * 0.8f, height * 0.5f,
  52780. width * 0.3f, height * 0.1f,
  52781. width * 0.3f, height * 0.9f);
  52782. else if (buttonDirection == 2)
  52783. p.addTriangle (width * 0.5f, height * 0.8f,
  52784. width * 0.1f, height * 0.3f,
  52785. width * 0.9f, height * 0.3f);
  52786. else if (buttonDirection == 3)
  52787. p.addTriangle (width * 0.2f, height * 0.5f,
  52788. width * 0.7f, height * 0.1f,
  52789. width * 0.7f, height * 0.9f);
  52790. if (isButtonDown)
  52791. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52792. else
  52793. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52794. g.fillPath (p);
  52795. g.setColour (Colour (0x80000000));
  52796. g.strokePath (p, PathStrokeType (0.5f));
  52797. }
  52798. void LookAndFeel::drawScrollbar (Graphics& g,
  52799. ScrollBar& scrollbar,
  52800. int x, int y,
  52801. int width, int height,
  52802. bool isScrollbarVertical,
  52803. int thumbStartPosition,
  52804. int thumbSize,
  52805. bool /*isMouseOver*/,
  52806. bool /*isMouseDown*/)
  52807. {
  52808. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52809. Path slotPath, thumbPath;
  52810. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52811. const float slotIndentx2 = slotIndent * 2.0f;
  52812. const float thumbIndent = slotIndent + 1.0f;
  52813. const float thumbIndentx2 = thumbIndent * 2.0f;
  52814. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52815. if (isScrollbarVertical)
  52816. {
  52817. slotPath.addRoundedRectangle (x + slotIndent,
  52818. y + slotIndent,
  52819. width - slotIndentx2,
  52820. height - slotIndentx2,
  52821. (width - slotIndentx2) * 0.5f);
  52822. if (thumbSize > 0)
  52823. thumbPath.addRoundedRectangle (x + thumbIndent,
  52824. thumbStartPosition + thumbIndent,
  52825. width - thumbIndentx2,
  52826. thumbSize - thumbIndentx2,
  52827. (width - thumbIndentx2) * 0.5f);
  52828. gx1 = (float) x;
  52829. gx2 = x + width * 0.7f;
  52830. }
  52831. else
  52832. {
  52833. slotPath.addRoundedRectangle (x + slotIndent,
  52834. y + slotIndent,
  52835. width - slotIndentx2,
  52836. height - slotIndentx2,
  52837. (height - slotIndentx2) * 0.5f);
  52838. if (thumbSize > 0)
  52839. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52840. y + thumbIndent,
  52841. thumbSize - thumbIndentx2,
  52842. height - thumbIndentx2,
  52843. (height - thumbIndentx2) * 0.5f);
  52844. gy1 = (float) y;
  52845. gy2 = y + height * 0.7f;
  52846. }
  52847. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52848. Colour trackColour1, trackColour2;
  52849. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52850. {
  52851. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52852. }
  52853. else
  52854. {
  52855. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52856. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52857. }
  52858. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52859. trackColour2, gx2, gy2, false));
  52860. g.fillPath (slotPath);
  52861. if (isScrollbarVertical)
  52862. {
  52863. gx1 = x + width * 0.6f;
  52864. gx2 = (float) x + width;
  52865. }
  52866. else
  52867. {
  52868. gy1 = y + height * 0.6f;
  52869. gy2 = (float) y + height;
  52870. }
  52871. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52872. Colour (0x19000000), gx2, gy2, false));
  52873. g.fillPath (slotPath);
  52874. g.setColour (thumbColour);
  52875. g.fillPath (thumbPath);
  52876. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52877. Colours::transparentBlack, gx2, gy2, false));
  52878. g.saveState();
  52879. if (isScrollbarVertical)
  52880. g.reduceClipRegion (x + width / 2, y, width, height);
  52881. else
  52882. g.reduceClipRegion (x, y + height / 2, width, height);
  52883. g.fillPath (thumbPath);
  52884. g.restoreState();
  52885. g.setColour (Colour (0x4c000000));
  52886. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52887. }
  52888. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52889. {
  52890. return 0;
  52891. }
  52892. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52893. {
  52894. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52895. }
  52896. int LookAndFeel::getDefaultScrollbarWidth()
  52897. {
  52898. return 18;
  52899. }
  52900. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52901. {
  52902. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52903. : scrollbar.getHeight());
  52904. }
  52905. const Path LookAndFeel::getTickShape (const float height)
  52906. {
  52907. static const unsigned char tickShapeData[] =
  52908. {
  52909. 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,
  52910. 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,
  52911. 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,
  52912. 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,
  52913. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52914. };
  52915. Path p;
  52916. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52917. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52918. return p;
  52919. }
  52920. const Path LookAndFeel::getCrossShape (const float height)
  52921. {
  52922. static const unsigned char crossShapeData[] =
  52923. {
  52924. 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,
  52925. 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,
  52926. 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,
  52927. 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,
  52928. 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,
  52929. 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,
  52930. 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
  52931. };
  52932. Path p;
  52933. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52934. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52935. return p;
  52936. }
  52937. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52938. {
  52939. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52940. x += (w - boxSize) >> 1;
  52941. y += (h - boxSize) >> 1;
  52942. w = boxSize;
  52943. h = boxSize;
  52944. g.setColour (Colour (0xe5ffffff));
  52945. g.fillRect (x, y, w, h);
  52946. g.setColour (Colour (0x80000000));
  52947. g.drawRect (x, y, w, h);
  52948. const float size = boxSize / 2 + 1.0f;
  52949. const float centre = (float) (boxSize / 2);
  52950. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52951. if (isPlus)
  52952. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52953. }
  52954. void LookAndFeel::drawBubble (Graphics& g,
  52955. float tipX, float tipY,
  52956. float boxX, float boxY,
  52957. float boxW, float boxH)
  52958. {
  52959. int side = 0;
  52960. if (tipX < boxX)
  52961. side = 1;
  52962. else if (tipX > boxX + boxW)
  52963. side = 3;
  52964. else if (tipY > boxY + boxH)
  52965. side = 2;
  52966. const float indent = 2.0f;
  52967. Path p;
  52968. p.addBubble (boxX + indent,
  52969. boxY + indent,
  52970. boxW - indent * 2.0f,
  52971. boxH - indent * 2.0f,
  52972. 5.0f,
  52973. tipX, tipY,
  52974. side,
  52975. 0.5f,
  52976. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52977. //xxx need to take comp as param for colour
  52978. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52979. g.fillPath (p);
  52980. //xxx as above
  52981. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52982. g.strokePath (p, PathStrokeType (1.33f));
  52983. }
  52984. const Font LookAndFeel::getPopupMenuFont()
  52985. {
  52986. return Font (17.0f);
  52987. }
  52988. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52989. const bool isSeparator,
  52990. int standardMenuItemHeight,
  52991. int& idealWidth,
  52992. int& idealHeight)
  52993. {
  52994. if (isSeparator)
  52995. {
  52996. idealWidth = 50;
  52997. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52998. }
  52999. else
  53000. {
  53001. Font font (getPopupMenuFont());
  53002. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53003. font.setHeight (standardMenuItemHeight / 1.3f);
  53004. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53005. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53006. }
  53007. }
  53008. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53009. {
  53010. const Colour background (findColour (PopupMenu::backgroundColourId));
  53011. g.fillAll (background);
  53012. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53013. for (int i = 0; i < height; i += 3)
  53014. g.fillRect (0, i, width, 1);
  53015. #if ! JUCE_MAC
  53016. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53017. g.drawRect (0, 0, width, height);
  53018. #endif
  53019. }
  53020. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53021. int width, int height,
  53022. bool isScrollUpArrow)
  53023. {
  53024. const Colour background (findColour (PopupMenu::backgroundColourId));
  53025. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53026. background.withAlpha (0.0f),
  53027. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53028. false));
  53029. g.fillRect (1, 1, width - 2, height - 2);
  53030. const float hw = width * 0.5f;
  53031. const float arrowW = height * 0.3f;
  53032. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53033. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53034. Path p;
  53035. p.addTriangle (hw - arrowW, y1,
  53036. hw + arrowW, y1,
  53037. hw, y2);
  53038. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53039. g.fillPath (p);
  53040. }
  53041. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53042. int width, int height,
  53043. const bool isSeparator,
  53044. const bool isActive,
  53045. const bool isHighlighted,
  53046. const bool isTicked,
  53047. const bool hasSubMenu,
  53048. const String& text,
  53049. const String& shortcutKeyText,
  53050. Image* image,
  53051. const Colour* const textColourToUse)
  53052. {
  53053. const float halfH = height * 0.5f;
  53054. if (isSeparator)
  53055. {
  53056. const float separatorIndent = 5.5f;
  53057. g.setColour (Colour (0x33000000));
  53058. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53059. g.setColour (Colour (0x66ffffff));
  53060. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53061. }
  53062. else
  53063. {
  53064. Colour textColour (findColour (PopupMenu::textColourId));
  53065. if (textColourToUse != 0)
  53066. textColour = *textColourToUse;
  53067. if (isHighlighted)
  53068. {
  53069. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53070. g.fillRect (1, 1, width - 2, height - 2);
  53071. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53072. }
  53073. else
  53074. {
  53075. g.setColour (textColour);
  53076. }
  53077. if (! isActive)
  53078. g.setOpacity (0.3f);
  53079. Font font (getPopupMenuFont());
  53080. if (font.getHeight() > height / 1.3f)
  53081. font.setHeight (height / 1.3f);
  53082. g.setFont (font);
  53083. const int leftBorder = (height * 5) / 4;
  53084. const int rightBorder = 4;
  53085. if (image != 0)
  53086. {
  53087. g.drawImageWithin (*image,
  53088. 2, 1, leftBorder - 4, height - 2,
  53089. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53090. }
  53091. else if (isTicked)
  53092. {
  53093. const Path tick (getTickShape (1.0f));
  53094. const float th = font.getAscent();
  53095. const float ty = halfH - th * 0.5f;
  53096. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53097. th, true));
  53098. }
  53099. g.drawFittedText (text,
  53100. leftBorder, 0,
  53101. width - (leftBorder + rightBorder), height,
  53102. Justification::centredLeft, 1);
  53103. if (shortcutKeyText.isNotEmpty())
  53104. {
  53105. Font f2 (font);
  53106. f2.setHeight (f2.getHeight() * 0.75f);
  53107. f2.setHorizontalScale (0.95f);
  53108. g.setFont (f2);
  53109. g.drawText (shortcutKeyText,
  53110. leftBorder,
  53111. 0,
  53112. width - (leftBorder + rightBorder + 4),
  53113. height,
  53114. Justification::centredRight,
  53115. true);
  53116. }
  53117. if (hasSubMenu)
  53118. {
  53119. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53120. const float x = width - height * 0.6f;
  53121. Path p;
  53122. p.addTriangle (x, halfH - arrowH * 0.5f,
  53123. x, halfH + arrowH * 0.5f,
  53124. x + arrowH * 0.6f, halfH);
  53125. g.fillPath (p);
  53126. }
  53127. }
  53128. }
  53129. int LookAndFeel::getMenuWindowFlags()
  53130. {
  53131. return ComponentPeer::windowHasDropShadow;
  53132. }
  53133. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53134. bool, MenuBarComponent& menuBar)
  53135. {
  53136. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53137. if (menuBar.isEnabled())
  53138. {
  53139. drawShinyButtonShape (g,
  53140. -4.0f, 0.0f,
  53141. width + 8.0f, (float) height,
  53142. 0.0f,
  53143. baseColour,
  53144. 0.4f,
  53145. true, true, true, true);
  53146. }
  53147. else
  53148. {
  53149. g.fillAll (baseColour);
  53150. }
  53151. }
  53152. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53153. {
  53154. return Font (menuBar.getHeight() * 0.7f);
  53155. }
  53156. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53157. {
  53158. return getMenuBarFont (menuBar, itemIndex, itemText)
  53159. .getStringWidth (itemText) + menuBar.getHeight();
  53160. }
  53161. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53162. int width, int height,
  53163. int itemIndex,
  53164. const String& itemText,
  53165. bool isMouseOverItem,
  53166. bool isMenuOpen,
  53167. bool /*isMouseOverBar*/,
  53168. MenuBarComponent& menuBar)
  53169. {
  53170. if (! menuBar.isEnabled())
  53171. {
  53172. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53173. .withMultipliedAlpha (0.5f));
  53174. }
  53175. else if (isMenuOpen || isMouseOverItem)
  53176. {
  53177. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53178. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53179. }
  53180. else
  53181. {
  53182. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53183. }
  53184. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53185. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53186. }
  53187. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53188. TextEditor& textEditor)
  53189. {
  53190. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53191. }
  53192. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53193. {
  53194. if (textEditor.isEnabled())
  53195. {
  53196. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53197. {
  53198. const int border = 2;
  53199. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53200. g.drawRect (0, 0, width, height, border);
  53201. g.setOpacity (1.0f);
  53202. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53203. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53204. }
  53205. else
  53206. {
  53207. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53208. g.drawRect (0, 0, width, height);
  53209. g.setOpacity (1.0f);
  53210. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53211. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53212. }
  53213. }
  53214. }
  53215. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53216. const bool isButtonDown,
  53217. int buttonX, int buttonY,
  53218. int buttonW, int buttonH,
  53219. ComboBox& box)
  53220. {
  53221. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53222. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53223. {
  53224. g.setColour (box.findColour (TextButton::buttonColourId));
  53225. g.drawRect (0, 0, width, height, 2);
  53226. }
  53227. else
  53228. {
  53229. g.setColour (box.findColour (ComboBox::outlineColourId));
  53230. g.drawRect (0, 0, width, height);
  53231. }
  53232. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53233. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53234. box.hasKeyboardFocus (true),
  53235. false, isButtonDown)
  53236. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53237. drawGlassLozenge (g,
  53238. buttonX + outlineThickness, buttonY + outlineThickness,
  53239. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53240. baseColour, outlineThickness, -1.0f,
  53241. true, true, true, true);
  53242. if (box.isEnabled())
  53243. {
  53244. const float arrowX = 0.3f;
  53245. const float arrowH = 0.2f;
  53246. Path p;
  53247. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53248. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53249. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53250. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53251. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53252. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53253. g.setColour (box.findColour (ComboBox::arrowColourId));
  53254. g.fillPath (p);
  53255. }
  53256. }
  53257. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53258. {
  53259. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53260. }
  53261. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53262. {
  53263. return new Label (String::empty, String::empty);
  53264. }
  53265. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53266. {
  53267. label.setBounds (1, 1,
  53268. box.getWidth() + 3 - box.getHeight(),
  53269. box.getHeight() - 2);
  53270. label.setFont (getComboBoxFont (box));
  53271. }
  53272. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53273. {
  53274. g.fillAll (label.findColour (Label::backgroundColourId));
  53275. if (! label.isBeingEdited())
  53276. {
  53277. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53278. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53279. g.setFont (label.getFont());
  53280. g.drawFittedText (label.getText(),
  53281. label.getHorizontalBorderSize(),
  53282. label.getVerticalBorderSize(),
  53283. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53284. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53285. label.getJustificationType(),
  53286. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53287. label.getMinimumHorizontalScale());
  53288. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53289. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53290. }
  53291. else if (label.isEnabled())
  53292. {
  53293. g.setColour (label.findColour (Label::outlineColourId));
  53294. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53295. }
  53296. }
  53297. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53298. int x, int y,
  53299. int width, int height,
  53300. float /*sliderPos*/,
  53301. float /*minSliderPos*/,
  53302. float /*maxSliderPos*/,
  53303. const Slider::SliderStyle /*style*/,
  53304. Slider& slider)
  53305. {
  53306. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53307. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53308. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53309. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53310. Path indent;
  53311. if (slider.isHorizontal())
  53312. {
  53313. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53314. const float ih = sliderRadius;
  53315. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53316. gradCol2, 0.0f, iy + ih, false));
  53317. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53318. width + sliderRadius, ih,
  53319. 5.0f);
  53320. g.fillPath (indent);
  53321. }
  53322. else
  53323. {
  53324. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53325. const float iw = sliderRadius;
  53326. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53327. gradCol2, ix + iw, 0.0f, false));
  53328. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53329. iw, height + sliderRadius,
  53330. 5.0f);
  53331. g.fillPath (indent);
  53332. }
  53333. g.setColour (Colour (0x4c000000));
  53334. g.strokePath (indent, PathStrokeType (0.5f));
  53335. }
  53336. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53337. int x, int y,
  53338. int width, int height,
  53339. float sliderPos,
  53340. float minSliderPos,
  53341. float maxSliderPos,
  53342. const Slider::SliderStyle style,
  53343. Slider& slider)
  53344. {
  53345. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53346. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53347. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53348. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53349. slider.isMouseButtonDown() && slider.isEnabled()));
  53350. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53351. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53352. {
  53353. float kx, ky;
  53354. if (style == Slider::LinearVertical)
  53355. {
  53356. kx = x + width * 0.5f;
  53357. ky = sliderPos;
  53358. }
  53359. else
  53360. {
  53361. kx = sliderPos;
  53362. ky = y + height * 0.5f;
  53363. }
  53364. drawGlassSphere (g,
  53365. kx - sliderRadius,
  53366. ky - sliderRadius,
  53367. sliderRadius * 2.0f,
  53368. knobColour, outlineThickness);
  53369. }
  53370. else
  53371. {
  53372. if (style == Slider::ThreeValueVertical)
  53373. {
  53374. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53375. sliderPos - sliderRadius,
  53376. sliderRadius * 2.0f,
  53377. knobColour, outlineThickness);
  53378. }
  53379. else if (style == Slider::ThreeValueHorizontal)
  53380. {
  53381. drawGlassSphere (g,sliderPos - sliderRadius,
  53382. y + height * 0.5f - sliderRadius,
  53383. sliderRadius * 2.0f,
  53384. knobColour, outlineThickness);
  53385. }
  53386. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53387. {
  53388. const float sr = jmin (sliderRadius, width * 0.4f);
  53389. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53390. minSliderPos - sliderRadius,
  53391. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53392. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53393. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53394. }
  53395. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53396. {
  53397. const float sr = jmin (sliderRadius, height * 0.4f);
  53398. drawGlassPointer (g, minSliderPos - sr,
  53399. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53400. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53401. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53402. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53403. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53404. }
  53405. }
  53406. }
  53407. void LookAndFeel::drawLinearSlider (Graphics& g,
  53408. int x, int y,
  53409. int width, int height,
  53410. float sliderPos,
  53411. float minSliderPos,
  53412. float maxSliderPos,
  53413. const Slider::SliderStyle style,
  53414. Slider& slider)
  53415. {
  53416. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53417. if (style == Slider::LinearBar)
  53418. {
  53419. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53420. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53421. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53422. false, isMouseOver,
  53423. isMouseOver || slider.isMouseButtonDown()));
  53424. drawShinyButtonShape (g,
  53425. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53426. baseColour,
  53427. slider.isEnabled() ? 0.9f : 0.3f,
  53428. true, true, true, true);
  53429. }
  53430. else
  53431. {
  53432. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53433. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53434. }
  53435. }
  53436. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53437. {
  53438. return jmin (7,
  53439. slider.getHeight() / 2,
  53440. slider.getWidth() / 2) + 2;
  53441. }
  53442. void LookAndFeel::drawRotarySlider (Graphics& g,
  53443. int x, int y,
  53444. int width, int height,
  53445. float sliderPos,
  53446. const float rotaryStartAngle,
  53447. const float rotaryEndAngle,
  53448. Slider& slider)
  53449. {
  53450. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53451. const float centreX = x + width * 0.5f;
  53452. const float centreY = y + height * 0.5f;
  53453. const float rx = centreX - radius;
  53454. const float ry = centreY - radius;
  53455. const float rw = radius * 2.0f;
  53456. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53457. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53458. if (radius > 12.0f)
  53459. {
  53460. if (slider.isEnabled())
  53461. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53462. else
  53463. g.setColour (Colour (0x80808080));
  53464. const float thickness = 0.7f;
  53465. {
  53466. Path filledArc;
  53467. filledArc.addPieSegment (rx, ry, rw, rw,
  53468. rotaryStartAngle,
  53469. angle,
  53470. thickness);
  53471. g.fillPath (filledArc);
  53472. }
  53473. if (thickness > 0)
  53474. {
  53475. const float innerRadius = radius * 0.2f;
  53476. Path p;
  53477. p.addTriangle (-innerRadius, 0.0f,
  53478. 0.0f, -radius * thickness * 1.1f,
  53479. innerRadius, 0.0f);
  53480. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53481. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53482. }
  53483. if (slider.isEnabled())
  53484. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53485. else
  53486. g.setColour (Colour (0x80808080));
  53487. Path outlineArc;
  53488. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53489. outlineArc.closeSubPath();
  53490. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53491. }
  53492. else
  53493. {
  53494. if (slider.isEnabled())
  53495. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53496. else
  53497. g.setColour (Colour (0x80808080));
  53498. Path p;
  53499. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53500. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53501. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53502. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53503. }
  53504. }
  53505. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53506. {
  53507. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53508. }
  53509. class SliderLabelComp : public Label
  53510. {
  53511. public:
  53512. SliderLabelComp() : Label (String::empty, String::empty) {}
  53513. ~SliderLabelComp() {}
  53514. void mouseWheelMove (const MouseEvent&, float, float) {}
  53515. };
  53516. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53517. {
  53518. Label* const l = new SliderLabelComp();
  53519. l->setJustificationType (Justification::centred);
  53520. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53521. l->setColour (Label::backgroundColourId,
  53522. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53523. : slider.findColour (Slider::textBoxBackgroundColourId));
  53524. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53525. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53526. l->setColour (TextEditor::backgroundColourId,
  53527. slider.findColour (Slider::textBoxBackgroundColourId)
  53528. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53529. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53530. return l;
  53531. }
  53532. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53533. {
  53534. return 0;
  53535. }
  53536. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53537. {
  53538. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53539. width = tl.getWidth() + 14;
  53540. height = tl.getHeight() + 6;
  53541. }
  53542. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53543. {
  53544. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53545. const Colour textCol (findColour (TooltipWindow::textColourId));
  53546. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53547. g.setColour (findColour (TooltipWindow::outlineColourId));
  53548. g.drawRect (0, 0, width, height, 1);
  53549. #endif
  53550. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53551. g.setColour (findColour (TooltipWindow::textColourId));
  53552. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53553. }
  53554. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53555. {
  53556. return new TextButton (text, TRANS("click to browse for a different file"));
  53557. }
  53558. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53559. ComboBox* filenameBox,
  53560. Button* browseButton)
  53561. {
  53562. browseButton->setSize (80, filenameComp.getHeight());
  53563. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53564. if (tb != 0)
  53565. tb->changeWidthToFitText();
  53566. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53567. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53568. }
  53569. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53570. int imageX, int imageY, int imageW, int imageH,
  53571. const Colour& overlayColour,
  53572. float imageOpacity,
  53573. ImageButton& button)
  53574. {
  53575. if (! button.isEnabled())
  53576. imageOpacity *= 0.3f;
  53577. if (! overlayColour.isOpaque())
  53578. {
  53579. g.setOpacity (imageOpacity);
  53580. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53581. 0, 0, image->getWidth(), image->getHeight(), false);
  53582. }
  53583. if (! overlayColour.isTransparent())
  53584. {
  53585. g.setColour (overlayColour);
  53586. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53587. 0, 0, image->getWidth(), image->getHeight(), true);
  53588. }
  53589. }
  53590. void LookAndFeel::drawCornerResizer (Graphics& g,
  53591. int w, int h,
  53592. bool /*isMouseOver*/,
  53593. bool /*isMouseDragging*/)
  53594. {
  53595. const float lineThickness = jmin (w, h) * 0.075f;
  53596. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53597. {
  53598. g.setColour (Colours::lightgrey);
  53599. g.drawLine (w * i,
  53600. h + 1.0f,
  53601. w + 1.0f,
  53602. h * i,
  53603. lineThickness);
  53604. g.setColour (Colours::darkgrey);
  53605. g.drawLine (w * i + lineThickness,
  53606. h + 1.0f,
  53607. w + 1.0f,
  53608. h * i + lineThickness,
  53609. lineThickness);
  53610. }
  53611. }
  53612. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53613. {
  53614. if (! border.isEmpty())
  53615. {
  53616. const Rectangle<int> fullSize (0, 0, w, h);
  53617. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53618. g.saveState();
  53619. g.excludeClipRegion (centreArea);
  53620. g.setColour (Colour (0x50000000));
  53621. g.drawRect (fullSize);
  53622. g.setColour (Colour (0x19000000));
  53623. g.drawRect (centreArea.expanded (1, 1));
  53624. g.restoreState();
  53625. }
  53626. }
  53627. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53628. const BorderSize& /*border*/, ResizableWindow& window)
  53629. {
  53630. g.fillAll (window.getBackgroundColour());
  53631. }
  53632. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53633. const BorderSize& /*border*/, ResizableWindow&)
  53634. {
  53635. }
  53636. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53637. Graphics& g, int w, int h,
  53638. int titleSpaceX, int titleSpaceW,
  53639. const Image* icon,
  53640. bool drawTitleTextOnLeft)
  53641. {
  53642. const bool isActive = window.isActiveWindow();
  53643. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53644. 0.0f, 0.0f,
  53645. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53646. 0.0f, (float) h, false));
  53647. g.fillAll();
  53648. Font font (h * 0.65f, Font::bold);
  53649. g.setFont (font);
  53650. int textW = font.getStringWidth (window.getName());
  53651. int iconW = 0;
  53652. int iconH = 0;
  53653. if (icon != 0)
  53654. {
  53655. iconH = (int) font.getHeight();
  53656. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53657. }
  53658. textW = jmin (titleSpaceW, textW + iconW);
  53659. int textX = drawTitleTextOnLeft ? titleSpaceX
  53660. : jmax (titleSpaceX, (w - textW) / 2);
  53661. if (textX + textW > titleSpaceX + titleSpaceW)
  53662. textX = titleSpaceX + titleSpaceW - textW;
  53663. if (icon != 0)
  53664. {
  53665. g.setOpacity (isActive ? 1.0f : 0.6f);
  53666. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53667. RectanglePlacement::centred, false);
  53668. textX += iconW;
  53669. textW -= iconW;
  53670. }
  53671. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53672. g.setColour (findColour (DocumentWindow::textColourId));
  53673. else
  53674. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53675. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53676. }
  53677. class GlassWindowButton : public Button
  53678. {
  53679. public:
  53680. GlassWindowButton (const String& name, const Colour& col,
  53681. const Path& normalShape_,
  53682. const Path& toggledShape_) throw()
  53683. : Button (name),
  53684. colour (col),
  53685. normalShape (normalShape_),
  53686. toggledShape (toggledShape_)
  53687. {
  53688. }
  53689. ~GlassWindowButton()
  53690. {
  53691. }
  53692. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53693. {
  53694. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53695. if (! isEnabled())
  53696. alpha *= 0.5f;
  53697. float x = 0, y = 0, diam;
  53698. if (getWidth() < getHeight())
  53699. {
  53700. diam = (float) getWidth();
  53701. y = (getHeight() - getWidth()) * 0.5f;
  53702. }
  53703. else
  53704. {
  53705. diam = (float) getHeight();
  53706. y = (getWidth() - getHeight()) * 0.5f;
  53707. }
  53708. x += diam * 0.05f;
  53709. y += diam * 0.05f;
  53710. diam *= 0.9f;
  53711. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53712. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53713. g.fillEllipse (x, y, diam, diam);
  53714. x += 2.0f;
  53715. y += 2.0f;
  53716. diam -= 4.0f;
  53717. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53718. Path& p = getToggleState() ? toggledShape : normalShape;
  53719. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53720. diam * 0.4f, diam * 0.4f, true));
  53721. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53722. g.fillPath (p, t);
  53723. }
  53724. private:
  53725. Colour colour;
  53726. Path normalShape, toggledShape;
  53727. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53728. };
  53729. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53730. {
  53731. Path shape;
  53732. const float crossThickness = 0.25f;
  53733. if (buttonType == DocumentWindow::closeButton)
  53734. {
  53735. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53736. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53737. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53738. }
  53739. else if (buttonType == DocumentWindow::minimiseButton)
  53740. {
  53741. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53742. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53743. }
  53744. else if (buttonType == DocumentWindow::maximiseButton)
  53745. {
  53746. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53747. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53748. Path fullscreenShape;
  53749. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53750. fullscreenShape.lineTo (0.0f, 100.0f);
  53751. fullscreenShape.lineTo (0.0f, 0.0f);
  53752. fullscreenShape.lineTo (100.0f, 0.0f);
  53753. fullscreenShape.lineTo (100.0f, 45.0f);
  53754. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53755. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53756. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53757. }
  53758. jassertfalse;
  53759. return 0;
  53760. }
  53761. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53762. int titleBarX,
  53763. int titleBarY,
  53764. int titleBarW,
  53765. int titleBarH,
  53766. Button* minimiseButton,
  53767. Button* maximiseButton,
  53768. Button* closeButton,
  53769. bool positionTitleBarButtonsOnLeft)
  53770. {
  53771. const int buttonW = titleBarH - titleBarH / 8;
  53772. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53773. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53774. if (closeButton != 0)
  53775. {
  53776. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53777. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53778. }
  53779. if (positionTitleBarButtonsOnLeft)
  53780. swapVariables (minimiseButton, maximiseButton);
  53781. if (maximiseButton != 0)
  53782. {
  53783. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53784. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53785. }
  53786. if (minimiseButton != 0)
  53787. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53788. }
  53789. int LookAndFeel::getDefaultMenuBarHeight()
  53790. {
  53791. return 24;
  53792. }
  53793. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53794. {
  53795. return new DropShadower (0.4f, 1, 5, 10);
  53796. }
  53797. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53798. int w, int h,
  53799. bool /*isVerticalBar*/,
  53800. bool isMouseOver,
  53801. bool isMouseDragging)
  53802. {
  53803. float alpha = 0.5f;
  53804. if (isMouseOver || isMouseDragging)
  53805. {
  53806. g.fillAll (Colour (0x190000ff));
  53807. alpha = 1.0f;
  53808. }
  53809. const float cx = w * 0.5f;
  53810. const float cy = h * 0.5f;
  53811. const float cr = jmin (w, h) * 0.4f;
  53812. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53813. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53814. true));
  53815. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53816. }
  53817. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53818. const String& text,
  53819. const Justification& position,
  53820. GroupComponent& group)
  53821. {
  53822. const float textH = 15.0f;
  53823. const float indent = 3.0f;
  53824. const float textEdgeGap = 4.0f;
  53825. float cs = 5.0f;
  53826. Font f (textH);
  53827. Path p;
  53828. float x = indent;
  53829. float y = f.getAscent() - 3.0f;
  53830. float w = jmax (0.0f, width - x * 2.0f);
  53831. float h = jmax (0.0f, height - y - indent);
  53832. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53833. const float cs2 = 2.0f * cs;
  53834. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53835. float textX = cs + textEdgeGap;
  53836. if (position.testFlags (Justification::horizontallyCentred))
  53837. textX = cs + (w - cs2 - textW) * 0.5f;
  53838. else if (position.testFlags (Justification::right))
  53839. textX = w - cs - textW - textEdgeGap;
  53840. p.startNewSubPath (x + textX + textW, y);
  53841. p.lineTo (x + w - cs, y);
  53842. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53843. p.lineTo (x + w, y + h - cs);
  53844. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53845. p.lineTo (x + cs, y + h);
  53846. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53847. p.lineTo (x, y + cs);
  53848. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53849. p.lineTo (x + textX, y);
  53850. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53851. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53852. .withMultipliedAlpha (alpha));
  53853. g.strokePath (p, PathStrokeType (2.0f));
  53854. g.setColour (group.findColour (GroupComponent::textColourId)
  53855. .withMultipliedAlpha (alpha));
  53856. g.setFont (f);
  53857. g.drawText (text,
  53858. roundToInt (x + textX), 0,
  53859. roundToInt (textW),
  53860. roundToInt (textH),
  53861. Justification::centred, true);
  53862. }
  53863. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53864. {
  53865. return 1 + tabDepth / 3;
  53866. }
  53867. int LookAndFeel::getTabButtonSpaceAroundImage()
  53868. {
  53869. return 4;
  53870. }
  53871. void LookAndFeel::createTabButtonShape (Path& p,
  53872. int width, int height,
  53873. int /*tabIndex*/,
  53874. const String& /*text*/,
  53875. Button& /*button*/,
  53876. TabbedButtonBar::Orientation orientation,
  53877. const bool /*isMouseOver*/,
  53878. const bool /*isMouseDown*/,
  53879. const bool /*isFrontTab*/)
  53880. {
  53881. const float w = (float) width;
  53882. const float h = (float) height;
  53883. float length = w;
  53884. float depth = h;
  53885. if (orientation == TabbedButtonBar::TabsAtLeft
  53886. || orientation == TabbedButtonBar::TabsAtRight)
  53887. {
  53888. swapVariables (length, depth);
  53889. }
  53890. const float indent = (float) getTabButtonOverlap ((int) depth);
  53891. const float overhang = 4.0f;
  53892. if (orientation == TabbedButtonBar::TabsAtLeft)
  53893. {
  53894. p.startNewSubPath (w, 0.0f);
  53895. p.lineTo (0.0f, indent);
  53896. p.lineTo (0.0f, h - indent);
  53897. p.lineTo (w, h);
  53898. p.lineTo (w + overhang, h + overhang);
  53899. p.lineTo (w + overhang, -overhang);
  53900. }
  53901. else if (orientation == TabbedButtonBar::TabsAtRight)
  53902. {
  53903. p.startNewSubPath (0.0f, 0.0f);
  53904. p.lineTo (w, indent);
  53905. p.lineTo (w, h - indent);
  53906. p.lineTo (0.0f, h);
  53907. p.lineTo (-overhang, h + overhang);
  53908. p.lineTo (-overhang, -overhang);
  53909. }
  53910. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53911. {
  53912. p.startNewSubPath (0.0f, 0.0f);
  53913. p.lineTo (indent, h);
  53914. p.lineTo (w - indent, h);
  53915. p.lineTo (w, 0.0f);
  53916. p.lineTo (w + overhang, -overhang);
  53917. p.lineTo (-overhang, -overhang);
  53918. }
  53919. else
  53920. {
  53921. p.startNewSubPath (0.0f, h);
  53922. p.lineTo (indent, 0.0f);
  53923. p.lineTo (w - indent, 0.0f);
  53924. p.lineTo (w, h);
  53925. p.lineTo (w + overhang, h + overhang);
  53926. p.lineTo (-overhang, h + overhang);
  53927. }
  53928. p.closeSubPath();
  53929. p = p.createPathWithRoundedCorners (3.0f);
  53930. }
  53931. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53932. const Path& path,
  53933. const Colour& preferredColour,
  53934. int /*tabIndex*/,
  53935. const String& /*text*/,
  53936. Button& button,
  53937. TabbedButtonBar::Orientation /*orientation*/,
  53938. const bool /*isMouseOver*/,
  53939. const bool /*isMouseDown*/,
  53940. const bool isFrontTab)
  53941. {
  53942. g.setColour (isFrontTab ? preferredColour
  53943. : preferredColour.withMultipliedAlpha (0.9f));
  53944. g.fillPath (path);
  53945. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53946. : TabbedButtonBar::tabOutlineColourId, false)
  53947. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53948. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53949. }
  53950. void LookAndFeel::drawTabButtonText (Graphics& g,
  53951. int x, int y, int w, int h,
  53952. const Colour& preferredBackgroundColour,
  53953. int /*tabIndex*/,
  53954. const String& text,
  53955. Button& button,
  53956. TabbedButtonBar::Orientation orientation,
  53957. const bool isMouseOver,
  53958. const bool isMouseDown,
  53959. const bool isFrontTab)
  53960. {
  53961. int length = w;
  53962. int depth = h;
  53963. if (orientation == TabbedButtonBar::TabsAtLeft
  53964. || orientation == TabbedButtonBar::TabsAtRight)
  53965. {
  53966. swapVariables (length, depth);
  53967. }
  53968. Font font (depth * 0.6f);
  53969. font.setUnderline (button.hasKeyboardFocus (false));
  53970. GlyphArrangement textLayout;
  53971. textLayout.addFittedText (font, text.trim(),
  53972. 0.0f, 0.0f, (float) length, (float) depth,
  53973. Justification::centred,
  53974. jmax (1, depth / 12));
  53975. AffineTransform transform;
  53976. if (orientation == TabbedButtonBar::TabsAtLeft)
  53977. {
  53978. transform = transform.rotated (float_Pi * -0.5f)
  53979. .translated ((float) x, (float) (y + h));
  53980. }
  53981. else if (orientation == TabbedButtonBar::TabsAtRight)
  53982. {
  53983. transform = transform.rotated (float_Pi * 0.5f)
  53984. .translated ((float) (x + w), (float) y);
  53985. }
  53986. else
  53987. {
  53988. transform = transform.translated ((float) x, (float) y);
  53989. }
  53990. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53991. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53992. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53993. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53994. else
  53995. g.setColour (preferredBackgroundColour.contrasting());
  53996. if (! (isMouseOver || isMouseDown))
  53997. g.setOpacity (0.8f);
  53998. if (! button.isEnabled())
  53999. g.setOpacity (0.3f);
  54000. textLayout.draw (g, transform);
  54001. }
  54002. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54003. const String& text,
  54004. int tabDepth,
  54005. Button&)
  54006. {
  54007. Font f (tabDepth * 0.6f);
  54008. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54009. }
  54010. void LookAndFeel::drawTabButton (Graphics& g,
  54011. int w, int h,
  54012. const Colour& preferredColour,
  54013. int tabIndex,
  54014. const String& text,
  54015. Button& button,
  54016. TabbedButtonBar::Orientation orientation,
  54017. const bool isMouseOver,
  54018. const bool isMouseDown,
  54019. const bool isFrontTab)
  54020. {
  54021. int length = w;
  54022. int depth = h;
  54023. if (orientation == TabbedButtonBar::TabsAtLeft
  54024. || orientation == TabbedButtonBar::TabsAtRight)
  54025. {
  54026. swapVariables (length, depth);
  54027. }
  54028. Path tabShape;
  54029. createTabButtonShape (tabShape, w, h,
  54030. tabIndex, text, button, orientation,
  54031. isMouseOver, isMouseDown, isFrontTab);
  54032. fillTabButtonShape (g, tabShape, preferredColour,
  54033. tabIndex, text, button, orientation,
  54034. isMouseOver, isMouseDown, isFrontTab);
  54035. const int indent = getTabButtonOverlap (depth);
  54036. int x = 0, y = 0;
  54037. if (orientation == TabbedButtonBar::TabsAtLeft
  54038. || orientation == TabbedButtonBar::TabsAtRight)
  54039. {
  54040. y += indent;
  54041. h -= indent * 2;
  54042. }
  54043. else
  54044. {
  54045. x += indent;
  54046. w -= indent * 2;
  54047. }
  54048. drawTabButtonText (g, x, y, w, h, preferredColour,
  54049. tabIndex, text, button, orientation,
  54050. isMouseOver, isMouseDown, isFrontTab);
  54051. }
  54052. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54053. int w, int h,
  54054. TabbedButtonBar& tabBar,
  54055. TabbedButtonBar::Orientation orientation)
  54056. {
  54057. const float shadowSize = 0.2f;
  54058. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54059. Rectangle<int> shadowRect;
  54060. if (orientation == TabbedButtonBar::TabsAtLeft)
  54061. {
  54062. x1 = (float) w;
  54063. x2 = w * (1.0f - shadowSize);
  54064. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54065. }
  54066. else if (orientation == TabbedButtonBar::TabsAtRight)
  54067. {
  54068. x2 = w * shadowSize;
  54069. shadowRect.setBounds (0, 0, (int) x2, h);
  54070. }
  54071. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54072. {
  54073. y2 = h * shadowSize;
  54074. shadowRect.setBounds (0, 0, w, (int) y2);
  54075. }
  54076. else
  54077. {
  54078. y1 = (float) h;
  54079. y2 = h * (1.0f - shadowSize);
  54080. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54081. }
  54082. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54083. Colours::transparentBlack, x2, y2, false));
  54084. shadowRect.expand (2, 2);
  54085. g.fillRect (shadowRect);
  54086. g.setColour (Colour (0x80000000));
  54087. if (orientation == TabbedButtonBar::TabsAtLeft)
  54088. {
  54089. g.fillRect (w - 1, 0, 1, h);
  54090. }
  54091. else if (orientation == TabbedButtonBar::TabsAtRight)
  54092. {
  54093. g.fillRect (0, 0, 1, h);
  54094. }
  54095. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54096. {
  54097. g.fillRect (0, 0, w, 1);
  54098. }
  54099. else
  54100. {
  54101. g.fillRect (0, h - 1, w, 1);
  54102. }
  54103. }
  54104. Button* LookAndFeel::createTabBarExtrasButton()
  54105. {
  54106. const float thickness = 7.0f;
  54107. const float indent = 22.0f;
  54108. Path p;
  54109. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54110. DrawablePath ellipse;
  54111. ellipse.setPath (p);
  54112. ellipse.setFill (Colour (0x99ffffff));
  54113. p.clear();
  54114. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54115. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54116. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54117. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54118. p.setUsingNonZeroWinding (false);
  54119. DrawablePath dp;
  54120. dp.setPath (p);
  54121. dp.setFill (Colour (0x59000000));
  54122. DrawableComposite normalImage;
  54123. normalImage.addAndMakeVisible (ellipse.createCopy());
  54124. normalImage.addAndMakeVisible (dp.createCopy());
  54125. dp.setFill (Colour (0xcc000000));
  54126. DrawableComposite overImage;
  54127. overImage.addAndMakeVisible (ellipse.createCopy());
  54128. overImage.addAndMakeVisible (dp.createCopy());
  54129. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54130. db->setImages (&normalImage, &overImage, 0);
  54131. return db;
  54132. }
  54133. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54134. {
  54135. g.fillAll (Colours::white);
  54136. const int w = header.getWidth();
  54137. const int h = header.getHeight();
  54138. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54139. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54140. false));
  54141. g.fillRect (0, h / 2, w, h);
  54142. g.setColour (Colour (0x33000000));
  54143. g.fillRect (0, h - 1, w, 1);
  54144. for (int i = header.getNumColumns (true); --i >= 0;)
  54145. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54146. }
  54147. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54148. int width, int height,
  54149. bool isMouseOver, bool isMouseDown,
  54150. int columnFlags)
  54151. {
  54152. if (isMouseDown)
  54153. g.fillAll (Colour (0x8899aadd));
  54154. else if (isMouseOver)
  54155. g.fillAll (Colour (0x5599aadd));
  54156. int rightOfText = width - 4;
  54157. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54158. {
  54159. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54160. const float bottom = height - top;
  54161. const float w = height * 0.5f;
  54162. const float x = rightOfText - (w * 1.25f);
  54163. rightOfText = (int) x;
  54164. Path sortArrow;
  54165. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54166. g.setColour (Colour (0x99000000));
  54167. g.fillPath (sortArrow);
  54168. }
  54169. g.setColour (Colours::black);
  54170. g.setFont (height * 0.5f, Font::bold);
  54171. const int textX = 4;
  54172. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54173. }
  54174. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54175. {
  54176. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54177. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54178. background.darker (0.1f),
  54179. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54180. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54181. false));
  54182. g.fillAll();
  54183. }
  54184. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54185. {
  54186. return createTabBarExtrasButton();
  54187. }
  54188. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54189. bool isMouseOver, bool isMouseDown,
  54190. ToolbarItemComponent& component)
  54191. {
  54192. if (isMouseDown)
  54193. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54194. else if (isMouseOver)
  54195. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54196. }
  54197. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54198. const String& text, ToolbarItemComponent& component)
  54199. {
  54200. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54201. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54202. const float fontHeight = jmin (14.0f, height * 0.85f);
  54203. g.setFont (fontHeight);
  54204. g.drawFittedText (text,
  54205. x, y, width, height,
  54206. Justification::centred,
  54207. jmax (1, height / (int) fontHeight));
  54208. }
  54209. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54210. bool isOpen, int width, int height)
  54211. {
  54212. const int buttonSize = (height * 3) / 4;
  54213. const int buttonIndent = (height - buttonSize) / 2;
  54214. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54215. const int textX = buttonIndent * 2 + buttonSize + 2;
  54216. g.setColour (Colours::black);
  54217. g.setFont (height * 0.7f, Font::bold);
  54218. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54219. }
  54220. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54221. PropertyComponent&)
  54222. {
  54223. g.setColour (Colour (0x66ffffff));
  54224. g.fillRect (0, 0, width, height - 1);
  54225. }
  54226. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54227. PropertyComponent& component)
  54228. {
  54229. g.setColour (Colours::black);
  54230. if (! component.isEnabled())
  54231. g.setOpacity (0.6f);
  54232. g.setFont (jmin (height, 24) * 0.65f);
  54233. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54234. g.drawFittedText (component.getName(),
  54235. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54236. Justification::centredLeft, 2);
  54237. }
  54238. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54239. {
  54240. return Rectangle<int> (component.getWidth() / 3, 1,
  54241. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54242. }
  54243. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54244. {
  54245. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54246. {
  54247. Graphics g2 (content);
  54248. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54249. g2.fillPath (path);
  54250. g2.setColour (Colours::white.withAlpha (0.8f));
  54251. g2.strokePath (path, PathStrokeType (2.0f));
  54252. }
  54253. DropShadowEffect shadow;
  54254. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54255. shadow.applyEffect (content, g, 1.0f);
  54256. }
  54257. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54258. const String& instructions,
  54259. GlyphArrangement& text,
  54260. int width)
  54261. {
  54262. text.clear();
  54263. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54264. 8.0f, 22.0f, width - 16.0f,
  54265. Justification::centred);
  54266. text.addJustifiedText (Font (14.0f), instructions,
  54267. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54268. Justification::centred);
  54269. }
  54270. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54271. const String& filename, Image* icon,
  54272. const String& fileSizeDescription,
  54273. const String& fileTimeDescription,
  54274. const bool isDirectory,
  54275. const bool isItemSelected,
  54276. const int /*itemIndex*/,
  54277. DirectoryContentsDisplayComponent&)
  54278. {
  54279. if (isItemSelected)
  54280. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54281. const int x = 32;
  54282. g.setColour (Colours::black);
  54283. if (icon != 0 && icon->isValid())
  54284. {
  54285. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54286. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54287. false);
  54288. }
  54289. else
  54290. {
  54291. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54292. : getDefaultDocumentFileImage();
  54293. if (d != 0)
  54294. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54295. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54296. }
  54297. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54298. g.setFont (height * 0.7f);
  54299. if (width > 450 && ! isDirectory)
  54300. {
  54301. const int sizeX = roundToInt (width * 0.7f);
  54302. const int dateX = roundToInt (width * 0.8f);
  54303. g.drawFittedText (filename,
  54304. x, 0, sizeX - x, height,
  54305. Justification::centredLeft, 1);
  54306. g.setFont (height * 0.5f);
  54307. g.setColour (Colours::darkgrey);
  54308. if (! isDirectory)
  54309. {
  54310. g.drawFittedText (fileSizeDescription,
  54311. sizeX, 0, dateX - sizeX - 8, height,
  54312. Justification::centredRight, 1);
  54313. g.drawFittedText (fileTimeDescription,
  54314. dateX, 0, width - 8 - dateX, height,
  54315. Justification::centredRight, 1);
  54316. }
  54317. }
  54318. else
  54319. {
  54320. g.drawFittedText (filename,
  54321. x, 0, width - x, height,
  54322. Justification::centredLeft, 1);
  54323. }
  54324. }
  54325. Button* LookAndFeel::createFileBrowserGoUpButton()
  54326. {
  54327. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54328. Path arrowPath;
  54329. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54330. DrawablePath arrowImage;
  54331. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54332. arrowImage.setPath (arrowPath);
  54333. goUpButton->setImages (&arrowImage);
  54334. return goUpButton;
  54335. }
  54336. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54337. DirectoryContentsDisplayComponent* fileListComponent,
  54338. FilePreviewComponent* previewComp,
  54339. ComboBox* currentPathBox,
  54340. TextEditor* filenameBox,
  54341. Button* goUpButton)
  54342. {
  54343. const int x = 8;
  54344. int w = browserComp.getWidth() - x - x;
  54345. if (previewComp != 0)
  54346. {
  54347. const int previewWidth = w / 3;
  54348. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54349. w -= previewWidth + 4;
  54350. }
  54351. int y = 4;
  54352. const int controlsHeight = 22;
  54353. const int bottomSectionHeight = controlsHeight + 8;
  54354. const int upButtonWidth = 50;
  54355. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54356. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54357. y += controlsHeight + 4;
  54358. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54359. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54360. y = listAsComp->getBottom() + 4;
  54361. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54362. }
  54363. // Pulls a drawable out of compressed valuetree data..
  54364. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54365. {
  54366. MemoryInputStream m (data, numBytes, false);
  54367. GZIPDecompressorInputStream gz (m);
  54368. ValueTree drawable (ValueTree::readFromStream (gz));
  54369. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54370. }
  54371. const Drawable* LookAndFeel::getDefaultFolderImage()
  54372. {
  54373. if (folderImage == 0)
  54374. {
  54375. static const unsigned char drawableData[] =
  54376. { 120,218,197,86,77,111,27,55,16,229,182,161,237,6,61,39,233,77,63,192,38,56,195,225,215,209,105,210,2,141,13,20,201,193,109,111,178,181,178,183,145,181,130,180,110,145,127,159,199,93,73,137,87,53,218,91,109,192,160,151,179,156,55,111,222,188,229,155,247,
  54377. 231,87,231,175,47,222,170,234,155,229,244,190,86,213,115,253,102,61,253,123,122,189,168,85,51,83,213,119,250,238,221,47,231,151,175,223,169,170,250,121,221,62,172,84,245,172,60,63,209,243,118,49,171,215,170,107,87,23,245,188,83,213,145,182,167,19,91,
  54378. 254,127,223,220,222,117,37,68,82,40,143,174,219,174,107,239,135,168,147,18,37,108,85,245,237,46,207,70,33,249,175,211,238,78,85,186,28,253,76,175,73,109,186,117,251,177,190,106,102,229,241,247,58,24,103,203,15,101,245,103,219,44,187,15,221,39,0,172,142,
  54379. 245,125,211,1,196,205,116,181,125,114,164,175,31,186,78,45,219,229,31,245,186,189,106,150,179,102,121,139,100,154,240,231,167,102,177,64,72,247,105,213,23,122,187,158,206,154,122,217,169,85,57,18,1,47,53,101,107,18,135,204,167,147,192,201,216,20,114,
  54380. 244,195,62,171,234,7,125,198,100,136,216,145,149,211,9,57,103,40,249,72,219,8,167,170,87,250,140,162,199,123,226,3,34,82,202,134,131,13,172,74,170,233,162,0,177,234,166,93,180,15,235,141,170,206,180,157,204,231,150,156,159,207,39,195,50,214,88,18,150,
  54381. 245,205,124,250,104,169,212,135,158,19,144,53,20,112,172,55,237,2,132,13,199,149,130,230,115,145,112,147,147,82,61,157,32,238,178,253,11,145,213,138,10,52,138,38,103,111,99,164,211,137,139,198,35,177,35,167,212,143,15,215,205,13,160,109,163,172,225,152,
  54382. 16,232,17,149,140,103,144,158,146,90,113,217,12,6,197,167,236,3,54,5,181,101,73,54,138,90,245,165,227,120,18,252,150,77,15,242,188,228,204,81,169,139,102,249,5,68,192,145,14,244,112,1,145,29,94,137,96,235,49,136,151,58,246,32,88,192,161,88,176,76,226,
  54383. 36,247,24,176,7,232,62,16,83,42,155,201,160,30,222,65,72,98,82,76,33,198,254,197,96,124,10,150,243,8,130,48,228,36,94,124,6,4,43,38,0,142,205,99,30,4,221,13,33,230,220,71,177,65,49,142,243,150,7,1,51,20,2,5,96,96,84,225,56,217,188,3,33,46,24,228,112,
  54384. 69,69,12,68,228,108,242,99,16,165,118,208,28,51,200,98,87,42,74,62,209,24,4,206,48,22,153,125,132,220,196,56,15,234,99,216,130,0,141,38,74,162,130,48,35,163,141,94,196,245,32,94,104,7,154,132,209,40,108,162,165,232,153,165,17,4,138,201,176,135,58,49,
  54385. 165,130,122,108,114,54,28,240,64,17,89,188,79,177,116,149,10,4,246,91,30,94,104,112,96,226,144,131,144,142,98,78,177,7,128,81,242,224,140,36,249,80,208,145,196,12,202,15,16,60,161,200,69,187,169,213,86,198,123,87,224,255,199,21,94,105,134,72,40,177,245,
  54386. 14,182,32,232,54,196,231,100,111,11,189,168,201,39,177,84,102,38,139,177,168,74,210,87,174,64,20,138,160,67,111,10,4,98,196,97,60,158,118,133,25,111,173,224,171,37,97,185,119,133,221,242,63,184,194,140,71,174,240,252,145,43,72,32,147,146,147,4,104,104,
  54387. 117,134,10,18,12,107,212,40,72,148,57,6,71,69,135,222,248,16,160,168,3,169,144,55,201,69,41,147,137,134,99,50,97,8,178,85,43,217,140,201,151,192,152,10,242,190,24,11,59,183,29,25,42,115,236,98,14,229,252,32,80,66,0,162,17,136,72,6,67,5,45,242,224,10,
  54388. 193,102,71,50,6,17,129,212,18,115,105,150,80,169,45,123,222,141,76,178,70,32,55,24,90,217,132,71,73,200,57,238,204,3,136,49,144,185,55,183,190,20,137,52,246,47,113,232,158,69,35,49,145,208,129,193,56,178,77,135,230,145,113,22,140,69,74,20,146,2,120,218,
  54389. 155,135,48,32,10,89,30,156,165,204,254,222,193,160,12,19,49,6,210,59,11,70,62,4,31,15,64,196,2,157,98,33,58,1,104,32,152,50,31,128,64,148,183,197,108,209,89,107,240,41,75,36,123,16,208,108,180,44,236,250,182,227,27,20,137,118,76,60,165,137,221,92,94,
  54390. 78,215,31,235,245,230,183,242,229,30,214,251,251,195,145,94,148,15,253,170,221,52,93,211,46,7,109,171,81,208,177,94,247,119,132,47,81,186,92,22,246,7,255,254,15,7,107,141,171,197,191,156,123,162,135,187,198,227,131,113,219,80,159,1,4,239,223,231,0,0 };
  54391. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54392. }
  54393. return folderImage;
  54394. }
  54395. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54396. {
  54397. if (documentImage == 0)
  54398. {
  54399. static const unsigned char drawableData[] =
  54400. { 120,218,213,88,77,115,219,54,16,37,147,208,246,228,214,75,155,246,164,123,29,12,176,216,197,199,49,105,218,94,156,153,78,114,72,219,155,108,75,137,26,89,212,200,116,59,233,175,239,3,105,201,164,68,50,158,166,233,76,196,11,69,60,173,128,197,123,139,183,
  54401. 124,241,234,217,155,103,207,207,126,204,242,7,171,233,213,44,203,31,23,47,54,211,191,166,231,203,89,182,184,204,242,147,226,195,165,219,252,125,150,229,249,207,155,242,102,157,229,143,210,227,199,197,101,121,113,115,53,91,85,89,85,174,207,102,243,42,
  54402. 203,143,10,125,58,209,233,251,171,197,219,119,85,250,173,97,151,30,157,151,85,85,94,53,168,147,132,50,226,179,252,225,246,143,174,179,44,63,254,101,90,189,203,242,34,5,127,84,172,77,118,93,109,202,247,179,55,139,203,244,248,97,161,179,63,202,197,170,
  54403. 122,93,125,192,196,242,227,226,106,81,205,54,217,197,116,125,251,228,168,56,191,169,170,108,85,174,126,159,109,202,55,139,213,229,98,245,182,249,97,254,240,167,197,114,137,5,86,31,214,245,111,175,203,37,254,230,162,92,150,55,155,180,148,249,237,39,203,
  54404. 94,215,127,58,10,213,245,39,203,234,249,102,249,87,47,203,63,129,204,49,227,252,73,225,149,145,104,131,245,254,116,34,202,82,164,16,153,179,236,108,177,234,7,49,41,237,130,144,167,17,144,15,42,104,239,93,12,35,32,99,68,9,187,24,125,7,244,77,23,36,164,
  54405. 40,56,226,61,12,107,229,130,215,100,105,24,227,89,17,246,211,105,55,140,49,218,43,207,100,245,72,28,195,70,17,230,201,118,8,243,164,139,233,95,88,23,52,152,162,54,104,48,217,237,105,15,111,91,107,253,131,160,118,34,239,69,128,54,232,135,101,121,61,203,
  54406. 110,169,181,147,2,253,159,82,48,180,229,247,167,74,193,41,141,188,35,93,241,116,18,148,113,214,120,207,113,47,19,109,16,51,182,153,193,5,59,2,10,90,69,114,218,135,48,2,50,198,43,171,189,152,81,144,88,108,85,136,78,246,64,54,42,163,35,69,30,3,121,82,38,
  54407. 98,81,98,70,64,70,139,34,111,163,167,49,144,13,202,138,179,58,220,23,52,180,186,54,104,48,79,109,208,96,198,219,19,31,220,187,118,10,6,65,237,100,222,139,5,109,80,191,30,236,151,162,135,147,142,30,68,105,182,58,6,22,84,43,229,124,148,116,97,145,55,231,
  54408. 139,11,76,228,16,37,14,48,205,145,77,134,34,176,55,152,182,200,57,99,93,204,144,145,253,65,97,229,132,72,104,63,62,71,21,140,54,186,41,226,59,84,19,63,130,15,222,235,224,185,59,104,27,226,68,101,153,241,227,177,248,29,20,136,26,8,252,178,183,241,219,
  54409. 131,137,160,209,107,109,92,79,124,16,211,184,104,93,77,130,110,124,2,65,172,67,201,60,157,88,163,2,91,99,92,216,198,55,78,69,75,190,150,119,84,98,200,71,150,109,124,36,204,227,52,8,33,229,223,68,167,173,167,131,248,137,212,226,141,19,233,160,154,248,
  54410. 144,142,195,140,137,185,59,104,15,247,119,40,126,23,69,81,200,242,110,254,123,20,49,94,112,110,245,199,111,241,167,87,36,252,101,138,132,149,22,22,38,65,134,29,182,139,24,230,192,31,144,184,133,130,72,44,131,210,142,111,147,216,30,76,123,30,113,206,242,
  54411. 150,196,157,65,129,130,76,180,194,61,34,225,160,5,228,233,160,118,34,137,26,202,115,212,29,108,72,134,243,223,90,114,226,199,226,119,80,6,245,152,197,122,217,146,184,53,24,140,210,30,21,59,80,79,124,182,202,71,207,218,112,159,72,80,53,140,109,68,2,191,
  54412. 227,217,210,78,36,94,137,88,231,82,157,8,176,61,0,122,191,19,137,3,255,13,39,183,228,20,193,151,144,119,166,79,36,40,253,156,138,72,11,181,19,137,14,46,176,217,27,180,135,251,219,31,255,235,61,148,165,96,72,122,118,23,229,81,52,135,24,250,163,183,216,
  54413. 211,43,17,217,151,136,253,116,137,28,53,188,127,92,188,221,76,47,23,169,59,90,167,144,141,239,197,86,104,141,189,60,157,80,84,142,140,4,31,154,241,122,105,132,41,107,13,201,39,86,120,24,82,114,206,198,6,96,27,227,172,36,232,168,201,36,219,24,113,62,163,
  54414. 154,101,233,143,166,203,102,26,141,206,174,179,252,89,161,39,243,249,197,121,186,38,233,246,146,211,53,1,123,56,194,231,122,143,103,179,217,60,204,167,19,147,110,41,93,173,219,123,72,89,248,35,173,16,220,50,179,111,60,181,24,88,103,156,235,7,78,248,14,
  54415. 4,119,78,162,93,60,112,35,109,16,124,126,12,17,71,67,24,1,165,142,1,181,215,248,56,6,66,235,193,137,167,61,22,30,5,3,27,101,71,64,169,25,112,216,2,63,22,169,110,43,18,200,140,129,208,160,88,44,220,208,125,65,67,171,107,131,6,243,212,6,13,102,188,61,241,
  54416. 225,189,107,165,96,16,212,78,230,189,88,208,6,245,235,214,237,235,150,62,167,110,155,106,170,53,133,192,117,193,20,84,78,74,174,98,39,92,156,8,112,21,46,80,106,12,209,207,225,228,16,113,59,225,126,87,60,133,25,209,34,36,2,99,242,52,197,48,30,75,244,247,
  54417. 212,238,246,182,173,221,185,78,215,127,167,221,162,163,221,250,152,217,146,196,222,145,100,223,235,105,108,28,250,149,212,74,224,86,2,213,118,110,119,204,224,144,208,38,214,131,200,14,214,223,120,189,230,53,1,193,70,133,154,131,56,223,16,229,48,188,14,
  54418. 201,205,213,121,71,233,68,89,15,124,103,37,53,26,11,118,176,127,169,88,166,158,219,178,117,173,83,108,75,95,55,68,186,193,53,246,146,206,127,6,63,53,78,58,228,204,155,224,113,74,91,232,221,195,240,105,215,34,29,138,64,128,183,8,130,233,71,173,56,54,101,
  54419. 99,75,186,111,65,58,28,229,145,82,19,152,12,99,180,81,130,131,75,234,229,220,247,53,231,154,79,205,185,185,155,199,249,172,38,85,253,204,76,68,95,92,204,207,255,221,75,178,227,14,187,224,224,97,202,172,173,219,12,167,130,133,9,54,135,245,92,176,29,134,
  54420. 165,110,139,141,18,16,223,29,188,183,65,207,144,106,144,151,143,128,224,176,168,110,140,32,62,56,110,219,195,54,235,20,68,209,216,34,232,21,6,41,234,157,39,211,201,107,160,230,66,225,56,153,9,101,21,37,237,150,204,14,115,208,22,221,54,216,230,33,116,
  54421. 14,65,14,44,19,8,236,73,71,246,182,110,125,224,75,132,195,214,247,163,36,51,252,84,76,124,37,212,100,88,62,183,179,76,67,217,218,242,244,229,116,243,126,182,185,254,21,105,126,208,220,239,94,229,30,21,203,244,202,117,93,94,47,170,69,185,106,246,60,219,
  54422. 3,29,23,155,250,109,237,29,170,72,175,109,119,129,127,235,9,92,20,85,185,254,72,220,147,162,121,235,219,13,44,144,225,63,241,244,165,51,0,0 };
  54423. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54424. }
  54425. return documentImage;
  54426. }
  54427. void LookAndFeel::playAlertSound()
  54428. {
  54429. PlatformUtilities::beep();
  54430. }
  54431. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54432. {
  54433. g.setColour (Colours::white.withAlpha (0.7f));
  54434. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54435. g.setColour (Colours::black.withAlpha (0.2f));
  54436. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54437. const int totalBlocks = 7;
  54438. const int numBlocks = roundToInt (totalBlocks * level);
  54439. const float w = (width - 6.0f) / (float) totalBlocks;
  54440. for (int i = 0; i < totalBlocks; ++i)
  54441. {
  54442. if (i >= numBlocks)
  54443. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54444. else
  54445. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54446. : Colours::red);
  54447. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54448. }
  54449. }
  54450. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54451. {
  54452. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54453. if (keyDescription.isNotEmpty())
  54454. {
  54455. if (button.isEnabled())
  54456. {
  54457. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54458. g.fillAll (textColour.withAlpha (alpha));
  54459. g.setOpacity (0.3f);
  54460. g.drawBevel (0, 0, width, height, 2);
  54461. }
  54462. g.setColour (textColour);
  54463. g.setFont (height * 0.6f);
  54464. g.drawFittedText (keyDescription,
  54465. 3, 0, width - 6, height,
  54466. Justification::centred, 1);
  54467. }
  54468. else
  54469. {
  54470. const float thickness = 7.0f;
  54471. const float indent = 22.0f;
  54472. Path p;
  54473. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54474. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54475. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54476. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54477. p.setUsingNonZeroWinding (false);
  54478. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54479. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54480. }
  54481. if (button.hasKeyboardFocus (false))
  54482. {
  54483. g.setColour (textColour.withAlpha (0.4f));
  54484. g.drawRect (0, 0, width, height);
  54485. }
  54486. }
  54487. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54488. float x, float y, float w, float h,
  54489. float maxCornerSize,
  54490. const Colour& baseColour,
  54491. const float strokeWidth,
  54492. const bool flatOnLeft,
  54493. const bool flatOnRight,
  54494. const bool flatOnTop,
  54495. const bool flatOnBottom) throw()
  54496. {
  54497. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54498. return;
  54499. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54500. Path outline;
  54501. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54502. ! (flatOnLeft || flatOnTop),
  54503. ! (flatOnRight || flatOnTop),
  54504. ! (flatOnLeft || flatOnBottom),
  54505. ! (flatOnRight || flatOnBottom));
  54506. ColourGradient cg (baseColour, 0.0f, y,
  54507. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54508. false);
  54509. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54510. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54511. g.setGradientFill (cg);
  54512. g.fillPath (outline);
  54513. g.setColour (Colour (0x80000000));
  54514. g.strokePath (outline, PathStrokeType (strokeWidth));
  54515. }
  54516. void LookAndFeel::drawGlassSphere (Graphics& g,
  54517. const float x, const float y,
  54518. const float diameter,
  54519. const Colour& colour,
  54520. const float outlineThickness) throw()
  54521. {
  54522. if (diameter <= outlineThickness)
  54523. return;
  54524. Path p;
  54525. p.addEllipse (x, y, diameter, diameter);
  54526. {
  54527. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54528. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54529. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54530. g.setGradientFill (cg);
  54531. g.fillPath (p);
  54532. }
  54533. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54534. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54535. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54536. ColourGradient cg (Colours::transparentBlack,
  54537. x + diameter * 0.5f, y + diameter * 0.5f,
  54538. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54539. x, y + diameter * 0.5f, true);
  54540. cg.addColour (0.7, Colours::transparentBlack);
  54541. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54542. g.setGradientFill (cg);
  54543. g.fillPath (p);
  54544. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54545. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54546. }
  54547. void LookAndFeel::drawGlassPointer (Graphics& g,
  54548. const float x, const float y,
  54549. const float diameter,
  54550. const Colour& colour, const float outlineThickness,
  54551. const int direction) throw()
  54552. {
  54553. if (diameter <= outlineThickness)
  54554. return;
  54555. Path p;
  54556. p.startNewSubPath (x + diameter * 0.5f, y);
  54557. p.lineTo (x + diameter, y + diameter * 0.6f);
  54558. p.lineTo (x + diameter, y + diameter);
  54559. p.lineTo (x, y + diameter);
  54560. p.lineTo (x, y + diameter * 0.6f);
  54561. p.closeSubPath();
  54562. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54563. {
  54564. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54565. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54566. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54567. g.setGradientFill (cg);
  54568. g.fillPath (p);
  54569. }
  54570. ColourGradient cg (Colours::transparentBlack,
  54571. x + diameter * 0.5f, y + diameter * 0.5f,
  54572. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54573. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54574. cg.addColour (0.5, Colours::transparentBlack);
  54575. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54576. g.setGradientFill (cg);
  54577. g.fillPath (p);
  54578. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54579. g.strokePath (p, PathStrokeType (outlineThickness));
  54580. }
  54581. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54582. const float x, const float y,
  54583. const float width, const float height,
  54584. const Colour& colour,
  54585. const float outlineThickness,
  54586. const float cornerSize,
  54587. const bool flatOnLeft,
  54588. const bool flatOnRight,
  54589. const bool flatOnTop,
  54590. const bool flatOnBottom) throw()
  54591. {
  54592. if (width <= outlineThickness || height <= outlineThickness)
  54593. return;
  54594. const int intX = (int) x;
  54595. const int intY = (int) y;
  54596. const int intW = (int) width;
  54597. const int intH = (int) height;
  54598. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54599. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54600. const int intEdge = (int) edgeBlurRadius;
  54601. Path outline;
  54602. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54603. ! (flatOnLeft || flatOnTop),
  54604. ! (flatOnRight || flatOnTop),
  54605. ! (flatOnLeft || flatOnBottom),
  54606. ! (flatOnRight || flatOnBottom));
  54607. {
  54608. ColourGradient cg (colour.darker (0.2f), 0, y,
  54609. colour.darker (0.2f), 0, y + height, false);
  54610. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54611. cg.addColour (0.4, colour);
  54612. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54613. g.setGradientFill (cg);
  54614. g.fillPath (outline);
  54615. }
  54616. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54617. colour.darker (0.2f), x, y + height * 0.5f, true);
  54618. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54619. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54620. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54621. {
  54622. g.saveState();
  54623. g.setGradientFill (cg);
  54624. g.reduceClipRegion (intX, intY, intEdge, intH);
  54625. g.fillPath (outline);
  54626. g.restoreState();
  54627. }
  54628. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54629. {
  54630. cg.point1.setX (x + width - edgeBlurRadius);
  54631. cg.point2.setX (x + width);
  54632. g.saveState();
  54633. g.setGradientFill (cg);
  54634. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54635. g.fillPath (outline);
  54636. g.restoreState();
  54637. }
  54638. {
  54639. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54640. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54641. Path highlight;
  54642. LookAndFeelHelpers::createRoundedPath (highlight,
  54643. x + leftIndent,
  54644. y + cs * 0.1f,
  54645. width - (leftIndent + rightIndent),
  54646. height * 0.4f, cs * 0.4f,
  54647. ! (flatOnLeft || flatOnTop),
  54648. ! (flatOnRight || flatOnTop),
  54649. ! (flatOnLeft || flatOnBottom),
  54650. ! (flatOnRight || flatOnBottom));
  54651. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54652. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54653. g.fillPath (highlight);
  54654. }
  54655. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54656. g.strokePath (outline, PathStrokeType (outlineThickness));
  54657. }
  54658. END_JUCE_NAMESPACE
  54659. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54660. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54661. BEGIN_JUCE_NAMESPACE
  54662. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54663. {
  54664. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54665. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54666. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54667. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54668. setColour (Slider::thumbColourId, Colours::white);
  54669. setColour (Slider::trackColourId, Colour (0x7f000000));
  54670. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54671. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54672. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54673. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54674. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54675. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54676. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54677. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54678. }
  54679. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54680. {
  54681. }
  54682. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54683. Button& button,
  54684. const Colour& backgroundColour,
  54685. bool isMouseOverButton,
  54686. bool isButtonDown)
  54687. {
  54688. const int width = button.getWidth();
  54689. const int height = button.getHeight();
  54690. const float indent = 2.0f;
  54691. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54692. roundToInt (height * 0.4f));
  54693. Path p;
  54694. p.addRoundedRectangle (indent, indent,
  54695. width - indent * 2.0f,
  54696. height - indent * 2.0f,
  54697. (float) cornerSize);
  54698. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54699. if (isMouseOverButton)
  54700. {
  54701. if (isButtonDown)
  54702. bc = bc.brighter();
  54703. else if (bc.getBrightness() > 0.5f)
  54704. bc = bc.darker (0.1f);
  54705. else
  54706. bc = bc.brighter (0.1f);
  54707. }
  54708. g.setColour (bc);
  54709. g.fillPath (p);
  54710. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54711. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54712. }
  54713. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54714. Component& /*component*/,
  54715. float x, float y, float w, float h,
  54716. const bool ticked,
  54717. const bool isEnabled,
  54718. const bool /*isMouseOverButton*/,
  54719. const bool isButtonDown)
  54720. {
  54721. Path box;
  54722. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54723. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54724. : Colours::lightgrey.withAlpha (0.1f));
  54725. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54726. g.fillPath (box, trans);
  54727. g.setColour (Colours::black.withAlpha (0.6f));
  54728. g.strokePath (box, PathStrokeType (0.9f), trans);
  54729. if (ticked)
  54730. {
  54731. Path tick;
  54732. tick.startNewSubPath (1.5f, 3.0f);
  54733. tick.lineTo (3.0f, 6.0f);
  54734. tick.lineTo (6.0f, 0.0f);
  54735. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54736. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54737. }
  54738. }
  54739. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54740. ToggleButton& button,
  54741. bool isMouseOverButton,
  54742. bool isButtonDown)
  54743. {
  54744. if (button.hasKeyboardFocus (true))
  54745. {
  54746. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54747. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54748. }
  54749. const int tickWidth = jmin (20, button.getHeight() - 4);
  54750. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54751. (float) tickWidth, (float) tickWidth,
  54752. button.getToggleState(),
  54753. button.isEnabled(),
  54754. isMouseOverButton,
  54755. isButtonDown);
  54756. g.setColour (button.findColour (ToggleButton::textColourId));
  54757. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54758. if (! button.isEnabled())
  54759. g.setOpacity (0.5f);
  54760. const int textX = tickWidth + 5;
  54761. g.drawFittedText (button.getButtonText(),
  54762. textX, 4,
  54763. button.getWidth() - textX - 2, button.getHeight() - 8,
  54764. Justification::centredLeft, 10);
  54765. }
  54766. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54767. int width, int height,
  54768. double progress, const String& textToShow)
  54769. {
  54770. if (progress < 0 || progress >= 1.0)
  54771. {
  54772. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54773. }
  54774. else
  54775. {
  54776. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54777. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54778. g.fillAll (background);
  54779. g.setColour (foreground);
  54780. g.fillRect (1, 1,
  54781. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54782. height - 2);
  54783. if (textToShow.isNotEmpty())
  54784. {
  54785. g.setColour (Colour::contrasting (background, foreground));
  54786. g.setFont (height * 0.6f);
  54787. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54788. }
  54789. }
  54790. }
  54791. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54792. ScrollBar& bar,
  54793. int width, int height,
  54794. int buttonDirection,
  54795. bool isScrollbarVertical,
  54796. bool isMouseOverButton,
  54797. bool isButtonDown)
  54798. {
  54799. if (isScrollbarVertical)
  54800. width -= 2;
  54801. else
  54802. height -= 2;
  54803. Path p;
  54804. if (buttonDirection == 0)
  54805. p.addTriangle (width * 0.5f, height * 0.2f,
  54806. width * 0.1f, height * 0.7f,
  54807. width * 0.9f, height * 0.7f);
  54808. else if (buttonDirection == 1)
  54809. p.addTriangle (width * 0.8f, height * 0.5f,
  54810. width * 0.3f, height * 0.1f,
  54811. width * 0.3f, height * 0.9f);
  54812. else if (buttonDirection == 2)
  54813. p.addTriangle (width * 0.5f, height * 0.8f,
  54814. width * 0.1f, height * 0.3f,
  54815. width * 0.9f, height * 0.3f);
  54816. else if (buttonDirection == 3)
  54817. p.addTriangle (width * 0.2f, height * 0.5f,
  54818. width * 0.7f, height * 0.1f,
  54819. width * 0.7f, height * 0.9f);
  54820. if (isButtonDown)
  54821. g.setColour (Colours::white);
  54822. else if (isMouseOverButton)
  54823. g.setColour (Colours::white.withAlpha (0.7f));
  54824. else
  54825. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54826. g.fillPath (p);
  54827. g.setColour (Colours::black.withAlpha (0.5f));
  54828. g.strokePath (p, PathStrokeType (0.5f));
  54829. }
  54830. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54831. ScrollBar& bar,
  54832. int x, int y,
  54833. int width, int height,
  54834. bool isScrollbarVertical,
  54835. int thumbStartPosition,
  54836. int thumbSize,
  54837. bool isMouseOver,
  54838. bool isMouseDown)
  54839. {
  54840. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54841. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54842. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54843. if (thumbSize > 0.0f)
  54844. {
  54845. Rectangle<int> thumb;
  54846. if (isScrollbarVertical)
  54847. {
  54848. width -= 2;
  54849. g.fillRect (x + roundToInt (width * 0.35f), y,
  54850. roundToInt (width * 0.3f), height);
  54851. thumb.setBounds (x + 1, thumbStartPosition,
  54852. width - 2, thumbSize);
  54853. }
  54854. else
  54855. {
  54856. height -= 2;
  54857. g.fillRect (x, y + roundToInt (height * 0.35f),
  54858. width, roundToInt (height * 0.3f));
  54859. thumb.setBounds (thumbStartPosition, y + 1,
  54860. thumbSize, height - 2);
  54861. }
  54862. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54863. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54864. g.fillRect (thumb);
  54865. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54866. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54867. if (thumbSize > 16)
  54868. {
  54869. for (int i = 3; --i >= 0;)
  54870. {
  54871. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54872. g.setColour (Colours::black.withAlpha (0.15f));
  54873. if (isScrollbarVertical)
  54874. {
  54875. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54876. g.setColour (Colours::white.withAlpha (0.15f));
  54877. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54878. }
  54879. else
  54880. {
  54881. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54882. g.setColour (Colours::white.withAlpha (0.15f));
  54883. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54884. }
  54885. }
  54886. }
  54887. }
  54888. }
  54889. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54890. {
  54891. return &scrollbarShadow;
  54892. }
  54893. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54894. {
  54895. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54896. g.setColour (Colours::black.withAlpha (0.6f));
  54897. g.drawRect (0, 0, width, height);
  54898. }
  54899. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54900. bool, MenuBarComponent& menuBar)
  54901. {
  54902. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54903. }
  54904. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54905. {
  54906. if (textEditor.isEnabled())
  54907. {
  54908. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54909. g.drawRect (0, 0, width, height);
  54910. }
  54911. }
  54912. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54913. const bool isButtonDown,
  54914. int buttonX, int buttonY,
  54915. int buttonW, int buttonH,
  54916. ComboBox& box)
  54917. {
  54918. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54919. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54920. : ComboBox::backgroundColourId));
  54921. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54922. g.setColour (box.findColour (ComboBox::outlineColourId));
  54923. g.drawRect (0, 0, width, height);
  54924. const float arrowX = 0.2f;
  54925. const float arrowH = 0.3f;
  54926. if (box.isEnabled())
  54927. {
  54928. Path p;
  54929. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54930. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54931. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54932. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54933. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54934. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54935. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54936. : ComboBox::buttonColourId));
  54937. g.fillPath (p);
  54938. }
  54939. }
  54940. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54941. {
  54942. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54943. f.setHorizontalScale (0.9f);
  54944. return f;
  54945. }
  54946. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54947. {
  54948. Path p;
  54949. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54950. g.setColour (fill);
  54951. g.fillPath (p);
  54952. g.setColour (outline);
  54953. g.strokePath (p, PathStrokeType (0.3f));
  54954. }
  54955. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54956. int x, int y,
  54957. int w, int h,
  54958. float sliderPos,
  54959. float minSliderPos,
  54960. float maxSliderPos,
  54961. const Slider::SliderStyle style,
  54962. Slider& slider)
  54963. {
  54964. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54965. if (style == Slider::LinearBar)
  54966. {
  54967. g.setColour (slider.findColour (Slider::thumbColourId));
  54968. g.fillRect (x, y, (int) sliderPos - x, h);
  54969. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54970. g.drawRect (x, y, (int) sliderPos - x, h);
  54971. }
  54972. else
  54973. {
  54974. g.setColour (slider.findColour (Slider::trackColourId)
  54975. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54976. if (slider.isHorizontal())
  54977. {
  54978. g.fillRect (x, y + roundToInt (h * 0.6f),
  54979. w, roundToInt (h * 0.2f));
  54980. }
  54981. else
  54982. {
  54983. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54984. jmin (4, roundToInt (w * 0.2f)), h);
  54985. }
  54986. float alpha = 0.35f;
  54987. if (slider.isEnabled())
  54988. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54989. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54990. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54991. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54992. {
  54993. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54994. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54995. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54996. fill, outline);
  54997. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54998. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54999. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55000. fill, outline);
  55001. }
  55002. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55003. {
  55004. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55005. minSliderPos - 7.0f, y + h * 0.9f ,
  55006. minSliderPos, y + h * 0.9f,
  55007. fill, outline);
  55008. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55009. maxSliderPos, y + h * 0.9f,
  55010. maxSliderPos + 7.0f, y + h * 0.9f,
  55011. fill, outline);
  55012. }
  55013. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55014. {
  55015. drawTriangle (g, sliderPos, y + h * 0.9f,
  55016. sliderPos - 7.0f, y + h * 0.2f,
  55017. sliderPos + 7.0f, y + h * 0.2f,
  55018. fill, outline);
  55019. }
  55020. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55021. {
  55022. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55023. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55024. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55025. fill, outline);
  55026. }
  55027. }
  55028. }
  55029. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55030. {
  55031. if (isIncrement)
  55032. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55033. else
  55034. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55035. }
  55036. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55037. {
  55038. return &scrollbarShadow;
  55039. }
  55040. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55041. {
  55042. return 8;
  55043. }
  55044. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55045. int w, int h,
  55046. bool isMouseOver,
  55047. bool isMouseDragging)
  55048. {
  55049. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55050. : Colours::darkgrey);
  55051. const float lineThickness = jmin (w, h) * 0.1f;
  55052. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55053. {
  55054. g.drawLine (w * i,
  55055. h + 1.0f,
  55056. w + 1.0f,
  55057. h * i,
  55058. lineThickness);
  55059. }
  55060. }
  55061. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55062. {
  55063. Path shape;
  55064. if (buttonType == DocumentWindow::closeButton)
  55065. {
  55066. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55067. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55068. ShapeButton* const b = new ShapeButton ("close",
  55069. Colour (0x7fff3333),
  55070. Colour (0xd7ff3333),
  55071. Colour (0xf7ff3333));
  55072. b->setShape (shape, true, true, true);
  55073. return b;
  55074. }
  55075. else if (buttonType == DocumentWindow::minimiseButton)
  55076. {
  55077. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55078. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55079. DrawablePath dp;
  55080. dp.setPath (shape);
  55081. dp.setFill (Colours::black.withAlpha (0.3f));
  55082. b->setImages (&dp);
  55083. return b;
  55084. }
  55085. else if (buttonType == DocumentWindow::maximiseButton)
  55086. {
  55087. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55088. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55089. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55090. DrawablePath dp;
  55091. dp.setPath (shape);
  55092. dp.setFill (Colours::black.withAlpha (0.3f));
  55093. b->setImages (&dp);
  55094. return b;
  55095. }
  55096. jassertfalse;
  55097. return 0;
  55098. }
  55099. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55100. int titleBarX,
  55101. int titleBarY,
  55102. int titleBarW,
  55103. int titleBarH,
  55104. Button* minimiseButton,
  55105. Button* maximiseButton,
  55106. Button* closeButton,
  55107. bool positionTitleBarButtonsOnLeft)
  55108. {
  55109. titleBarY += titleBarH / 8;
  55110. titleBarH -= titleBarH / 4;
  55111. const int buttonW = titleBarH;
  55112. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55113. : titleBarX + titleBarW - buttonW - 4;
  55114. if (closeButton != 0)
  55115. {
  55116. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55117. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55118. : -(buttonW + buttonW / 5);
  55119. }
  55120. if (positionTitleBarButtonsOnLeft)
  55121. swapVariables (minimiseButton, maximiseButton);
  55122. if (maximiseButton != 0)
  55123. {
  55124. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55125. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55126. }
  55127. if (minimiseButton != 0)
  55128. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55129. }
  55130. END_JUCE_NAMESPACE
  55131. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55132. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55133. BEGIN_JUCE_NAMESPACE
  55134. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55135. : model (0),
  55136. itemUnderMouse (-1),
  55137. currentPopupIndex (-1),
  55138. topLevelIndexClicked (0),
  55139. lastMouseX (0),
  55140. lastMouseY (0)
  55141. {
  55142. setRepaintsOnMouseActivity (true);
  55143. setWantsKeyboardFocus (false);
  55144. setMouseClickGrabsKeyboardFocus (false);
  55145. setModel (model_);
  55146. }
  55147. MenuBarComponent::~MenuBarComponent()
  55148. {
  55149. setModel (0);
  55150. Desktop::getInstance().removeGlobalMouseListener (this);
  55151. }
  55152. MenuBarModel* MenuBarComponent::getModel() const throw()
  55153. {
  55154. return model;
  55155. }
  55156. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55157. {
  55158. if (model != newModel)
  55159. {
  55160. if (model != 0)
  55161. model->removeListener (this);
  55162. model = newModel;
  55163. if (model != 0)
  55164. model->addListener (this);
  55165. repaint();
  55166. menuBarItemsChanged (0);
  55167. }
  55168. }
  55169. void MenuBarComponent::paint (Graphics& g)
  55170. {
  55171. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55172. getLookAndFeel().drawMenuBarBackground (g,
  55173. getWidth(),
  55174. getHeight(),
  55175. isMouseOverBar,
  55176. *this);
  55177. if (model != 0)
  55178. {
  55179. for (int i = 0; i < menuNames.size(); ++i)
  55180. {
  55181. Graphics::ScopedSaveState ss (g);
  55182. g.setOrigin (xPositions [i], 0);
  55183. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55184. getLookAndFeel().drawMenuBarItem (g,
  55185. xPositions[i + 1] - xPositions[i],
  55186. getHeight(),
  55187. i,
  55188. menuNames[i],
  55189. i == itemUnderMouse,
  55190. i == currentPopupIndex,
  55191. isMouseOverBar,
  55192. *this);
  55193. }
  55194. }
  55195. }
  55196. void MenuBarComponent::resized()
  55197. {
  55198. xPositions.clear();
  55199. int x = 0;
  55200. xPositions.add (x);
  55201. for (int i = 0; i < menuNames.size(); ++i)
  55202. {
  55203. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55204. xPositions.add (x);
  55205. }
  55206. }
  55207. int MenuBarComponent::getItemAt (const int x, const int y)
  55208. {
  55209. for (int i = 0; i < xPositions.size(); ++i)
  55210. if (x >= xPositions[i] && x < xPositions[i + 1])
  55211. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55212. return -1;
  55213. }
  55214. void MenuBarComponent::repaintMenuItem (int index)
  55215. {
  55216. if (isPositiveAndBelow (index, xPositions.size()))
  55217. {
  55218. const int x1 = xPositions [index];
  55219. const int x2 = xPositions [index + 1];
  55220. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55221. }
  55222. }
  55223. void MenuBarComponent::setItemUnderMouse (const int index)
  55224. {
  55225. if (itemUnderMouse != index)
  55226. {
  55227. repaintMenuItem (itemUnderMouse);
  55228. itemUnderMouse = index;
  55229. repaintMenuItem (itemUnderMouse);
  55230. }
  55231. }
  55232. void MenuBarComponent::setOpenItem (int index)
  55233. {
  55234. if (currentPopupIndex != index)
  55235. {
  55236. repaintMenuItem (currentPopupIndex);
  55237. currentPopupIndex = index;
  55238. repaintMenuItem (currentPopupIndex);
  55239. if (index >= 0)
  55240. Desktop::getInstance().addGlobalMouseListener (this);
  55241. else
  55242. Desktop::getInstance().removeGlobalMouseListener (this);
  55243. }
  55244. }
  55245. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55246. {
  55247. setItemUnderMouse (getItemAt (x, y));
  55248. }
  55249. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55250. {
  55251. public:
  55252. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55253. : bar (bar_), topLevelIndex (topLevelIndex_)
  55254. {
  55255. }
  55256. void modalStateFinished (int returnValue)
  55257. {
  55258. if (bar != 0)
  55259. bar->menuDismissed (topLevelIndex, returnValue);
  55260. }
  55261. private:
  55262. Component::SafePointer<MenuBarComponent> bar;
  55263. const int topLevelIndex;
  55264. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55265. };
  55266. void MenuBarComponent::showMenu (int index)
  55267. {
  55268. if (index != currentPopupIndex)
  55269. {
  55270. PopupMenu::dismissAllActiveMenus();
  55271. menuBarItemsChanged (0);
  55272. setOpenItem (index);
  55273. setItemUnderMouse (index);
  55274. if (index >= 0)
  55275. {
  55276. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55277. menuNames [itemUnderMouse]));
  55278. if (m.lookAndFeel == 0)
  55279. m.setLookAndFeel (&getLookAndFeel());
  55280. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55281. m.showMenu (localAreaToGlobal (itemPos),
  55282. 0, itemPos.getWidth(), 0, 0, this,
  55283. new AsyncCallback (this, index));
  55284. }
  55285. }
  55286. }
  55287. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55288. {
  55289. topLevelIndexClicked = topLevelIndex;
  55290. postCommandMessage (itemId);
  55291. }
  55292. void MenuBarComponent::handleCommandMessage (int commandId)
  55293. {
  55294. const Point<int> mousePos (getMouseXYRelative());
  55295. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55296. if (currentPopupIndex == topLevelIndexClicked)
  55297. setOpenItem (-1);
  55298. if (commandId != 0 && model != 0)
  55299. model->menuItemSelected (commandId, topLevelIndexClicked);
  55300. }
  55301. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55302. {
  55303. if (e.eventComponent == this)
  55304. updateItemUnderMouse (e.x, e.y);
  55305. }
  55306. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55307. {
  55308. if (e.eventComponent == this)
  55309. updateItemUnderMouse (e.x, e.y);
  55310. }
  55311. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55312. {
  55313. if (currentPopupIndex < 0)
  55314. {
  55315. const MouseEvent e2 (e.getEventRelativeTo (this));
  55316. updateItemUnderMouse (e2.x, e2.y);
  55317. currentPopupIndex = -2;
  55318. showMenu (itemUnderMouse);
  55319. }
  55320. }
  55321. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55322. {
  55323. const MouseEvent e2 (e.getEventRelativeTo (this));
  55324. const int item = getItemAt (e2.x, e2.y);
  55325. if (item >= 0)
  55326. showMenu (item);
  55327. }
  55328. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55329. {
  55330. const MouseEvent e2 (e.getEventRelativeTo (this));
  55331. updateItemUnderMouse (e2.x, e2.y);
  55332. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55333. {
  55334. setOpenItem (-1);
  55335. PopupMenu::dismissAllActiveMenus();
  55336. }
  55337. }
  55338. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55339. {
  55340. const MouseEvent e2 (e.getEventRelativeTo (this));
  55341. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55342. {
  55343. if (currentPopupIndex >= 0)
  55344. {
  55345. const int item = getItemAt (e2.x, e2.y);
  55346. if (item >= 0)
  55347. showMenu (item);
  55348. }
  55349. else
  55350. {
  55351. updateItemUnderMouse (e2.x, e2.y);
  55352. }
  55353. lastMouseX = e2.x;
  55354. lastMouseY = e2.y;
  55355. }
  55356. }
  55357. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55358. {
  55359. bool used = false;
  55360. const int numMenus = menuNames.size();
  55361. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55362. if (key.isKeyCode (KeyPress::leftKey))
  55363. {
  55364. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55365. used = true;
  55366. }
  55367. else if (key.isKeyCode (KeyPress::rightKey))
  55368. {
  55369. showMenu ((currentIndex + 1) % numMenus);
  55370. used = true;
  55371. }
  55372. return used;
  55373. }
  55374. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55375. {
  55376. StringArray newNames;
  55377. if (model != 0)
  55378. newNames = model->getMenuBarNames();
  55379. if (newNames != menuNames)
  55380. {
  55381. menuNames = newNames;
  55382. repaint();
  55383. resized();
  55384. }
  55385. }
  55386. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55387. const ApplicationCommandTarget::InvocationInfo& info)
  55388. {
  55389. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55390. return;
  55391. for (int i = 0; i < menuNames.size(); ++i)
  55392. {
  55393. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55394. if (menu.containsCommandItem (info.commandID))
  55395. {
  55396. setItemUnderMouse (i);
  55397. startTimer (200);
  55398. break;
  55399. }
  55400. }
  55401. }
  55402. void MenuBarComponent::timerCallback()
  55403. {
  55404. stopTimer();
  55405. const Point<int> mousePos (getMouseXYRelative());
  55406. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55407. }
  55408. END_JUCE_NAMESPACE
  55409. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55410. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55411. BEGIN_JUCE_NAMESPACE
  55412. MenuBarModel::MenuBarModel() throw()
  55413. : manager (0)
  55414. {
  55415. }
  55416. MenuBarModel::~MenuBarModel()
  55417. {
  55418. setApplicationCommandManagerToWatch (0);
  55419. }
  55420. void MenuBarModel::menuItemsChanged()
  55421. {
  55422. triggerAsyncUpdate();
  55423. }
  55424. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55425. {
  55426. if (manager != newManager)
  55427. {
  55428. if (manager != 0)
  55429. manager->removeListener (this);
  55430. manager = newManager;
  55431. if (manager != 0)
  55432. manager->addListener (this);
  55433. }
  55434. }
  55435. void MenuBarModel::addListener (Listener* const newListener) throw()
  55436. {
  55437. listeners.add (newListener);
  55438. }
  55439. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55440. {
  55441. // Trying to remove a listener that isn't on the list!
  55442. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55443. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55444. jassert (listeners.contains (listenerToRemove));
  55445. listeners.remove (listenerToRemove);
  55446. }
  55447. void MenuBarModel::handleAsyncUpdate()
  55448. {
  55449. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55450. }
  55451. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55452. {
  55453. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55454. }
  55455. void MenuBarModel::applicationCommandListChanged()
  55456. {
  55457. menuItemsChanged();
  55458. }
  55459. END_JUCE_NAMESPACE
  55460. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55461. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55462. BEGIN_JUCE_NAMESPACE
  55463. class PopupMenu::Item
  55464. {
  55465. public:
  55466. Item()
  55467. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55468. usesColour (false), customComp (0), commandManager (0)
  55469. {
  55470. }
  55471. Item (const int itemId_,
  55472. const String& text_,
  55473. const bool active_,
  55474. const bool isTicked_,
  55475. const Image& im,
  55476. const Colour& textColour_,
  55477. const bool usesColour_,
  55478. CustomComponent* const customComp_,
  55479. const PopupMenu* const subMenu_,
  55480. ApplicationCommandManager* const commandManager_)
  55481. : itemId (itemId_), text (text_), textColour (textColour_),
  55482. active (active_), isSeparator (false), isTicked (isTicked_),
  55483. usesColour (usesColour_), image (im), customComp (customComp_),
  55484. commandManager (commandManager_)
  55485. {
  55486. if (subMenu_ != 0)
  55487. subMenu = new PopupMenu (*subMenu_);
  55488. if (commandManager_ != 0 && itemId_ != 0)
  55489. {
  55490. String shortcutKey;
  55491. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55492. ->getKeyPressesAssignedToCommand (itemId_));
  55493. for (int i = 0; i < keyPresses.size(); ++i)
  55494. {
  55495. const String key (keyPresses.getReference(i).getTextDescription());
  55496. if (shortcutKey.isNotEmpty())
  55497. shortcutKey << ", ";
  55498. if (key.length() == 1)
  55499. shortcutKey << "shortcut: '" << key << '\'';
  55500. else
  55501. shortcutKey << key;
  55502. }
  55503. shortcutKey = shortcutKey.trim();
  55504. if (shortcutKey.isNotEmpty())
  55505. text << "<end>" << shortcutKey;
  55506. }
  55507. }
  55508. Item (const Item& other)
  55509. : itemId (other.itemId),
  55510. text (other.text),
  55511. textColour (other.textColour),
  55512. active (other.active),
  55513. isSeparator (other.isSeparator),
  55514. isTicked (other.isTicked),
  55515. usesColour (other.usesColour),
  55516. image (other.image),
  55517. customComp (other.customComp),
  55518. commandManager (other.commandManager)
  55519. {
  55520. if (other.subMenu != 0)
  55521. subMenu = new PopupMenu (*(other.subMenu));
  55522. }
  55523. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55524. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55525. const int itemId;
  55526. String text;
  55527. const Colour textColour;
  55528. const bool active, isSeparator, isTicked, usesColour;
  55529. Image image;
  55530. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55531. ScopedPointer <PopupMenu> subMenu;
  55532. ApplicationCommandManager* const commandManager;
  55533. private:
  55534. Item& operator= (const Item&);
  55535. JUCE_LEAK_DETECTOR (Item);
  55536. };
  55537. class PopupMenu::ItemComponent : public Component
  55538. {
  55539. public:
  55540. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight)
  55541. : itemInfo (itemInfo_),
  55542. isHighlighted (false)
  55543. {
  55544. if (itemInfo.customComp != 0)
  55545. addAndMakeVisible (itemInfo.customComp);
  55546. int itemW = 80;
  55547. int itemH = 16;
  55548. getIdealSize (itemW, itemH, standardItemHeight);
  55549. setSize (itemW, jlimit (2, 600, itemH));
  55550. }
  55551. ~ItemComponent()
  55552. {
  55553. if (itemInfo.customComp != 0)
  55554. removeChildComponent (itemInfo.customComp);
  55555. }
  55556. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55557. {
  55558. if (itemInfo.customComp != 0)
  55559. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55560. else
  55561. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55562. itemInfo.isSeparator,
  55563. standardItemHeight,
  55564. idealWidth, idealHeight);
  55565. }
  55566. void paint (Graphics& g)
  55567. {
  55568. if (itemInfo.customComp == 0)
  55569. {
  55570. String mainText (itemInfo.text);
  55571. String endText;
  55572. const int endIndex = mainText.indexOf ("<end>");
  55573. if (endIndex >= 0)
  55574. {
  55575. endText = mainText.substring (endIndex + 5).trim();
  55576. mainText = mainText.substring (0, endIndex);
  55577. }
  55578. getLookAndFeel()
  55579. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55580. itemInfo.isSeparator,
  55581. itemInfo.active,
  55582. isHighlighted,
  55583. itemInfo.isTicked,
  55584. itemInfo.subMenu != 0,
  55585. mainText, endText,
  55586. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55587. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55588. }
  55589. }
  55590. void resized()
  55591. {
  55592. if (getNumChildComponents() > 0)
  55593. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55594. }
  55595. void setHighlighted (bool shouldBeHighlighted)
  55596. {
  55597. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55598. if (isHighlighted != shouldBeHighlighted)
  55599. {
  55600. isHighlighted = shouldBeHighlighted;
  55601. if (itemInfo.customComp != 0)
  55602. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55603. repaint();
  55604. }
  55605. }
  55606. PopupMenu::Item itemInfo;
  55607. private:
  55608. bool isHighlighted;
  55609. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55610. };
  55611. namespace PopupMenuSettings
  55612. {
  55613. const int scrollZone = 24;
  55614. const int borderSize = 2;
  55615. const int timerInterval = 50;
  55616. const int dismissCommandId = 0x6287345f;
  55617. }
  55618. class PopupMenu::Window : public Component,
  55619. private Timer
  55620. {
  55621. public:
  55622. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55623. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55624. const int minimumWidth_, const int maximumNumColumns_,
  55625. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55626. ApplicationCommandManager** const managerOfChosenCommand_,
  55627. Component* const componentAttachedTo_)
  55628. : Component ("menu"),
  55629. owner (owner_),
  55630. activeSubMenu (0),
  55631. managerOfChosenCommand (managerOfChosenCommand_),
  55632. componentAttachedTo (componentAttachedTo_),
  55633. componentAttachedToOriginal (componentAttachedTo_),
  55634. minimumWidth (minimumWidth_),
  55635. maximumNumColumns (maximumNumColumns_),
  55636. standardItemHeight (standardItemHeight_),
  55637. isOver (false),
  55638. hasBeenOver (false),
  55639. isDown (false),
  55640. needsToScroll (false),
  55641. dismissOnMouseUp (dismissOnMouseUp_),
  55642. hideOnExit (false),
  55643. disableMouseMoves (false),
  55644. hasAnyJuceCompHadFocus (false),
  55645. numColumns (0),
  55646. contentHeight (0),
  55647. childYOffset (0),
  55648. menuCreationTime (Time::getMillisecondCounter()),
  55649. lastMouseMoveTime (0),
  55650. timeEnteredCurrentChildComp (0),
  55651. scrollAcceleration (1.0)
  55652. {
  55653. lastFocused = lastScroll = menuCreationTime;
  55654. setWantsKeyboardFocus (false);
  55655. setMouseClickGrabsKeyboardFocus (false);
  55656. setAlwaysOnTop (true);
  55657. setLookAndFeel (menu.lookAndFeel);
  55658. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55659. for (int i = 0; i < menu.items.size(); ++i)
  55660. {
  55661. PopupMenu::ItemComponent* const itemComp = new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight);
  55662. items.add (itemComp);
  55663. addAndMakeVisible (itemComp);
  55664. itemComp->addMouseListener (this, false);
  55665. }
  55666. calculateWindowPos (target, alignToRectangle);
  55667. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55668. updateYPositions();
  55669. if (itemIdThatMustBeVisible != 0)
  55670. {
  55671. const int y = target.getY() - windowPos.getY();
  55672. ensureItemIsVisible (itemIdThatMustBeVisible,
  55673. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55674. }
  55675. resizeToBestWindowPos();
  55676. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55677. getActiveWindows().add (this);
  55678. Desktop::getInstance().addGlobalMouseListener (this);
  55679. }
  55680. ~Window()
  55681. {
  55682. getActiveWindows().removeValue (this);
  55683. Desktop::getInstance().removeGlobalMouseListener (this);
  55684. activeSubMenu = 0;
  55685. items.clear();
  55686. }
  55687. static Window* create (const PopupMenu& menu,
  55688. bool dismissOnMouseUp,
  55689. Window* const owner_,
  55690. const Rectangle<int>& target,
  55691. int minimumWidth,
  55692. int maximumNumColumns,
  55693. int standardItemHeight,
  55694. bool alignToRectangle,
  55695. int itemIdThatMustBeVisible,
  55696. ApplicationCommandManager** managerOfChosenCommand,
  55697. Component* componentAttachedTo)
  55698. {
  55699. if (menu.items.size() > 0)
  55700. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55701. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55702. managerOfChosenCommand, componentAttachedTo);
  55703. return 0;
  55704. }
  55705. void paint (Graphics& g)
  55706. {
  55707. if (isOpaque())
  55708. g.fillAll (Colours::white);
  55709. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55710. }
  55711. void paintOverChildren (Graphics& g)
  55712. {
  55713. if (isScrolling())
  55714. {
  55715. LookAndFeel& lf = getLookAndFeel();
  55716. if (isScrollZoneActive (false))
  55717. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55718. if (isScrollZoneActive (true))
  55719. {
  55720. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55721. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55722. }
  55723. }
  55724. }
  55725. bool isScrollZoneActive (bool bottomOne) const
  55726. {
  55727. return isScrolling()
  55728. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55729. : childYOffset > 0);
  55730. }
  55731. // hide this and all sub-comps
  55732. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55733. {
  55734. if (isVisible())
  55735. {
  55736. activeSubMenu = 0;
  55737. currentChild = 0;
  55738. exitModalState (item != 0 ? item->itemId : 0);
  55739. if (makeInvisible)
  55740. setVisible (false);
  55741. if (item != 0
  55742. && item->commandManager != 0
  55743. && item->itemId != 0)
  55744. {
  55745. *managerOfChosenCommand = item->commandManager;
  55746. }
  55747. }
  55748. }
  55749. void dismissMenu (const PopupMenu::Item* const item)
  55750. {
  55751. if (owner != 0)
  55752. {
  55753. owner->dismissMenu (item);
  55754. }
  55755. else
  55756. {
  55757. if (item != 0)
  55758. {
  55759. // need a copy of this on the stack as the one passed in will get deleted during this call
  55760. const PopupMenu::Item mi (*item);
  55761. hide (&mi, false);
  55762. }
  55763. else
  55764. {
  55765. hide (0, false);
  55766. }
  55767. }
  55768. }
  55769. void mouseMove (const MouseEvent&) { timerCallback(); }
  55770. void mouseDown (const MouseEvent&) { timerCallback(); }
  55771. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55772. void mouseUp (const MouseEvent&) { timerCallback(); }
  55773. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55774. {
  55775. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55776. lastMouse = Point<int> (-1, -1);
  55777. }
  55778. bool keyPressed (const KeyPress& key)
  55779. {
  55780. if (key.isKeyCode (KeyPress::downKey))
  55781. {
  55782. selectNextItem (1);
  55783. }
  55784. else if (key.isKeyCode (KeyPress::upKey))
  55785. {
  55786. selectNextItem (-1);
  55787. }
  55788. else if (key.isKeyCode (KeyPress::leftKey))
  55789. {
  55790. if (owner != 0)
  55791. {
  55792. Component::SafePointer<Window> parentWindow (owner);
  55793. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55794. hide (0, true);
  55795. if (parentWindow != 0)
  55796. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55797. disableTimerUntilMouseMoves();
  55798. }
  55799. else if (componentAttachedTo != 0)
  55800. {
  55801. componentAttachedTo->keyPressed (key);
  55802. }
  55803. }
  55804. else if (key.isKeyCode (KeyPress::rightKey))
  55805. {
  55806. disableTimerUntilMouseMoves();
  55807. if (showSubMenuFor (currentChild))
  55808. {
  55809. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55810. activeSubMenu->selectNextItem (1);
  55811. }
  55812. else if (componentAttachedTo != 0)
  55813. {
  55814. componentAttachedTo->keyPressed (key);
  55815. }
  55816. }
  55817. else if (key.isKeyCode (KeyPress::returnKey))
  55818. {
  55819. triggerCurrentlyHighlightedItem();
  55820. }
  55821. else if (key.isKeyCode (KeyPress::escapeKey))
  55822. {
  55823. dismissMenu (0);
  55824. }
  55825. else
  55826. {
  55827. return false;
  55828. }
  55829. return true;
  55830. }
  55831. void inputAttemptWhenModal()
  55832. {
  55833. WeakReference<Component> deletionChecker (this);
  55834. timerCallback();
  55835. if (deletionChecker != 0 && ! isOverAnyMenu())
  55836. {
  55837. if (componentAttachedTo != 0)
  55838. {
  55839. // we want to dismiss the menu, but if we do it synchronously, then
  55840. // the mouse-click will be allowed to pass through. That's good, except
  55841. // when the user clicks on the button that orginally popped the menu up,
  55842. // as they'll expect the menu to go away, and in fact it'll just
  55843. // come back. So only dismiss synchronously if they're not on the original
  55844. // comp that we're attached to.
  55845. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55846. if (componentAttachedTo->reallyContains (mousePos, true))
  55847. {
  55848. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55849. return;
  55850. }
  55851. }
  55852. dismissMenu (0);
  55853. }
  55854. }
  55855. void handleCommandMessage (int commandId)
  55856. {
  55857. Component::handleCommandMessage (commandId);
  55858. if (commandId == PopupMenuSettings::dismissCommandId)
  55859. dismissMenu (0);
  55860. }
  55861. void timerCallback()
  55862. {
  55863. if (! isVisible())
  55864. return;
  55865. if (componentAttachedTo != componentAttachedToOriginal)
  55866. {
  55867. dismissMenu (0);
  55868. return;
  55869. }
  55870. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55871. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55872. return;
  55873. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55874. // move rather than a real timer callback
  55875. const Point<int> globalMousePos (Desktop::getMousePosition());
  55876. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55877. const uint32 now = Time::getMillisecondCounter();
  55878. if (now > timeEnteredCurrentChildComp + 100
  55879. && reallyContains (localMousePos, true)
  55880. && currentChild != 0
  55881. && (! disableMouseMoves)
  55882. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55883. {
  55884. showSubMenuFor (currentChild);
  55885. }
  55886. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55887. {
  55888. highlightItemUnderMouse (globalMousePos, localMousePos);
  55889. }
  55890. bool overScrollArea = false;
  55891. if (isScrolling()
  55892. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55893. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55894. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55895. {
  55896. if (now > lastScroll + 20)
  55897. {
  55898. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55899. int amount = 0;
  55900. for (int i = 0; i < items.size() && amount == 0; ++i)
  55901. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55902. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55903. lastScroll = now;
  55904. }
  55905. overScrollArea = true;
  55906. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55907. }
  55908. else
  55909. {
  55910. scrollAcceleration = 1.0;
  55911. }
  55912. const bool wasDown = isDown;
  55913. bool isOverAny = isOverAnyMenu();
  55914. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55915. {
  55916. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55917. isOverAny = isOverAnyMenu();
  55918. }
  55919. if (hideOnExit && hasBeenOver && ! isOverAny)
  55920. {
  55921. hide (0, true);
  55922. }
  55923. else
  55924. {
  55925. isDown = hasBeenOver
  55926. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55927. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55928. bool anyFocused = Process::isForegroundProcess();
  55929. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55930. {
  55931. // because no component at all may have focus, our test here will
  55932. // only be triggered when something has focus and then loses it.
  55933. anyFocused = ! hasAnyJuceCompHadFocus;
  55934. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55935. {
  55936. if (ComponentPeer::getPeer (i)->isFocused())
  55937. {
  55938. anyFocused = true;
  55939. hasAnyJuceCompHadFocus = true;
  55940. break;
  55941. }
  55942. }
  55943. }
  55944. if (! anyFocused)
  55945. {
  55946. if (now > lastFocused + 10)
  55947. {
  55948. wasHiddenBecauseOfAppChange() = true;
  55949. dismissMenu (0);
  55950. return; // may have been deleted by the previous call..
  55951. }
  55952. }
  55953. else if (wasDown && now > menuCreationTime + 250
  55954. && ! (isDown || overScrollArea))
  55955. {
  55956. isOver = reallyContains (localMousePos, true);
  55957. if (isOver)
  55958. {
  55959. triggerCurrentlyHighlightedItem();
  55960. }
  55961. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55962. {
  55963. dismissMenu (0);
  55964. }
  55965. return; // may have been deleted by the previous calls..
  55966. }
  55967. else
  55968. {
  55969. lastFocused = now;
  55970. }
  55971. }
  55972. }
  55973. static Array<Window*>& getActiveWindows()
  55974. {
  55975. static Array<Window*> activeMenuWindows;
  55976. return activeMenuWindows;
  55977. }
  55978. static bool& wasHiddenBecauseOfAppChange() throw()
  55979. {
  55980. static bool b = false;
  55981. return b;
  55982. }
  55983. private:
  55984. Window* owner;
  55985. OwnedArray <PopupMenu::ItemComponent> items;
  55986. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55987. ScopedPointer <Window> activeSubMenu;
  55988. ApplicationCommandManager** managerOfChosenCommand;
  55989. WeakReference<Component> componentAttachedTo;
  55990. Component* componentAttachedToOriginal;
  55991. Rectangle<int> windowPos;
  55992. Point<int> lastMouse;
  55993. int minimumWidth, maximumNumColumns, standardItemHeight;
  55994. bool isOver, hasBeenOver, isDown, needsToScroll;
  55995. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55996. int numColumns, contentHeight, childYOffset;
  55997. Array <int> columnWidths;
  55998. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55999. double scrollAcceleration;
  56000. bool overlaps (const Rectangle<int>& r) const
  56001. {
  56002. return r.intersects (getBounds())
  56003. || (owner != 0 && owner->overlaps (r));
  56004. }
  56005. bool isOverAnyMenu() const
  56006. {
  56007. return (owner != 0) ? owner->isOverAnyMenu()
  56008. : isOverChildren();
  56009. }
  56010. bool isOverChildren() const
  56011. {
  56012. return isVisible()
  56013. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56014. }
  56015. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56016. {
  56017. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  56018. isOver = reallyContains (relPos, true);
  56019. if (activeSubMenu != 0)
  56020. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56021. }
  56022. bool treeContains (const Window* const window) const throw()
  56023. {
  56024. const Window* mw = this;
  56025. while (mw->owner != 0)
  56026. mw = mw->owner;
  56027. while (mw != 0)
  56028. {
  56029. if (mw == window)
  56030. return true;
  56031. mw = mw->activeSubMenu;
  56032. }
  56033. return false;
  56034. }
  56035. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56036. {
  56037. const Rectangle<int> mon (Desktop::getInstance()
  56038. .getMonitorAreaContaining (target.getCentre(),
  56039. #if JUCE_MAC
  56040. true));
  56041. #else
  56042. false)); // on windows, don't stop the menu overlapping the taskbar
  56043. #endif
  56044. int x, y, widthToUse, heightToUse;
  56045. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56046. if (alignToRectangle)
  56047. {
  56048. x = target.getX();
  56049. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56050. const int spaceOver = target.getY() - mon.getY();
  56051. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56052. y = target.getBottom();
  56053. else
  56054. y = target.getY() - heightToUse;
  56055. }
  56056. else
  56057. {
  56058. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56059. if (owner != 0)
  56060. {
  56061. if (owner->owner != 0)
  56062. {
  56063. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56064. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56065. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56066. tendTowardsRight = true;
  56067. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56068. tendTowardsRight = false;
  56069. }
  56070. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56071. {
  56072. tendTowardsRight = true;
  56073. }
  56074. }
  56075. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56076. target.getX() - mon.getX()) - 32;
  56077. if (biggestSpace < widthToUse)
  56078. {
  56079. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56080. if (numColumns > 1)
  56081. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56082. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56083. }
  56084. if (tendTowardsRight)
  56085. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56086. else
  56087. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56088. y = target.getY();
  56089. if (target.getCentreY() > mon.getCentreY())
  56090. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56091. }
  56092. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56093. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56094. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56095. // sets this flag if it's big enough to obscure any of its parent menus
  56096. hideOnExit = (owner != 0)
  56097. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56098. }
  56099. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56100. {
  56101. numColumns = 0;
  56102. contentHeight = 0;
  56103. const int maxMenuH = getParentHeight() - 24;
  56104. int totalW;
  56105. do
  56106. {
  56107. ++numColumns;
  56108. totalW = workOutBestSize (maxMenuW);
  56109. if (totalW > maxMenuW)
  56110. {
  56111. numColumns = jmax (1, numColumns - 1);
  56112. totalW = workOutBestSize (maxMenuW); // to update col widths
  56113. break;
  56114. }
  56115. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56116. {
  56117. break;
  56118. }
  56119. } while (numColumns < maximumNumColumns);
  56120. const int actualH = jmin (contentHeight, maxMenuH);
  56121. needsToScroll = contentHeight > actualH;
  56122. width = updateYPositions();
  56123. height = actualH + PopupMenuSettings::borderSize * 2;
  56124. }
  56125. int workOutBestSize (const int maxMenuW)
  56126. {
  56127. int totalW = 0;
  56128. contentHeight = 0;
  56129. int childNum = 0;
  56130. for (int col = 0; col < numColumns; ++col)
  56131. {
  56132. int i, colW = 50, colH = 0;
  56133. const int numChildren = jmin (items.size() - childNum,
  56134. (items.size() + numColumns - 1) / numColumns);
  56135. for (i = numChildren; --i >= 0;)
  56136. {
  56137. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56138. colH += items.getUnchecked (childNum + i)->getHeight();
  56139. }
  56140. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56141. columnWidths.set (col, colW);
  56142. totalW += colW;
  56143. contentHeight = jmax (contentHeight, colH);
  56144. childNum += numChildren;
  56145. }
  56146. if (totalW < minimumWidth)
  56147. {
  56148. totalW = minimumWidth;
  56149. for (int col = 0; col < numColumns; ++col)
  56150. columnWidths.set (0, totalW / numColumns);
  56151. }
  56152. return totalW;
  56153. }
  56154. void ensureItemIsVisible (const int itemId, int wantedY)
  56155. {
  56156. jassert (itemId != 0)
  56157. for (int i = items.size(); --i >= 0;)
  56158. {
  56159. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56160. if (m != 0
  56161. && m->itemInfo.itemId == itemId
  56162. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56163. {
  56164. const int currentY = m->getY();
  56165. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56166. {
  56167. if (wantedY < 0)
  56168. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56169. jmax (PopupMenuSettings::scrollZone,
  56170. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56171. currentY);
  56172. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56173. int deltaY = wantedY - currentY;
  56174. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56175. jmin (windowPos.getHeight(), mon.getHeight()));
  56176. const int newY = jlimit (mon.getY(),
  56177. mon.getBottom() - windowPos.getHeight(),
  56178. windowPos.getY() + deltaY);
  56179. deltaY -= newY - windowPos.getY();
  56180. childYOffset -= deltaY;
  56181. windowPos.setPosition (windowPos.getX(), newY);
  56182. updateYPositions();
  56183. }
  56184. break;
  56185. }
  56186. }
  56187. }
  56188. void resizeToBestWindowPos()
  56189. {
  56190. Rectangle<int> r (windowPos);
  56191. if (childYOffset < 0)
  56192. {
  56193. r.setBounds (r.getX(), r.getY() - childYOffset,
  56194. r.getWidth(), r.getHeight() + childYOffset);
  56195. }
  56196. else if (childYOffset > 0)
  56197. {
  56198. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56199. if (spaceAtBottom > 0)
  56200. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56201. }
  56202. setBounds (r);
  56203. updateYPositions();
  56204. }
  56205. void alterChildYPos (const int delta)
  56206. {
  56207. if (isScrolling())
  56208. {
  56209. childYOffset += delta;
  56210. if (delta < 0)
  56211. {
  56212. childYOffset = jmax (childYOffset, 0);
  56213. }
  56214. else if (delta > 0)
  56215. {
  56216. childYOffset = jmin (childYOffset,
  56217. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56218. }
  56219. updateYPositions();
  56220. }
  56221. else
  56222. {
  56223. childYOffset = 0;
  56224. }
  56225. resizeToBestWindowPos();
  56226. repaint();
  56227. }
  56228. int updateYPositions()
  56229. {
  56230. int x = 0;
  56231. int childNum = 0;
  56232. for (int col = 0; col < numColumns; ++col)
  56233. {
  56234. const int numChildren = jmin (items.size() - childNum,
  56235. (items.size() + numColumns - 1) / numColumns);
  56236. const int colW = columnWidths [col];
  56237. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56238. for (int i = 0; i < numChildren; ++i)
  56239. {
  56240. Component* const c = items.getUnchecked (childNum + i);
  56241. c->setBounds (x, y, colW, c->getHeight());
  56242. y += c->getHeight();
  56243. }
  56244. x += colW;
  56245. childNum += numChildren;
  56246. }
  56247. return x;
  56248. }
  56249. bool isScrolling() const throw()
  56250. {
  56251. return childYOffset != 0 || needsToScroll;
  56252. }
  56253. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56254. {
  56255. if (currentChild != 0)
  56256. currentChild->setHighlighted (false);
  56257. currentChild = child;
  56258. if (currentChild != 0)
  56259. {
  56260. currentChild->setHighlighted (true);
  56261. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56262. }
  56263. }
  56264. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56265. {
  56266. activeSubMenu = 0;
  56267. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56268. {
  56269. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56270. dismissOnMouseUp,
  56271. this,
  56272. childComp->getScreenBounds(),
  56273. 0, maximumNumColumns,
  56274. standardItemHeight,
  56275. false, 0, managerOfChosenCommand,
  56276. componentAttachedTo);
  56277. if (activeSubMenu != 0)
  56278. {
  56279. activeSubMenu->setVisible (true);
  56280. activeSubMenu->enterModalState (false);
  56281. activeSubMenu->toFront (false);
  56282. return true;
  56283. }
  56284. }
  56285. return false;
  56286. }
  56287. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56288. {
  56289. isOver = reallyContains (localMousePos, true);
  56290. if (isOver)
  56291. hasBeenOver = true;
  56292. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56293. {
  56294. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56295. if (disableMouseMoves && isOver)
  56296. disableMouseMoves = false;
  56297. }
  56298. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56299. return;
  56300. bool isMovingTowardsMenu = false;
  56301. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56302. {
  56303. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56304. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56305. // extends from the last mouse pos to the submenu's rectangle..
  56306. float subX = (float) activeSubMenu->getScreenX();
  56307. if (activeSubMenu->getX() > getX())
  56308. {
  56309. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56310. }
  56311. else
  56312. {
  56313. lastMouse += Point<int> (2, 0);
  56314. subX += activeSubMenu->getWidth();
  56315. }
  56316. Path areaTowardsSubMenu;
  56317. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56318. subX, (float) activeSubMenu->getScreenY(),
  56319. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56320. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56321. }
  56322. lastMouse = globalMousePos;
  56323. if (! isMovingTowardsMenu)
  56324. {
  56325. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56326. if (c == this)
  56327. c = 0;
  56328. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56329. if (mic == 0 && c != 0)
  56330. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56331. if (mic != currentChild
  56332. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56333. {
  56334. if (isOver && (c != 0) && (activeSubMenu != 0))
  56335. activeSubMenu->hide (0, true);
  56336. if (! isOver)
  56337. mic = 0;
  56338. setCurrentlyHighlightedChild (mic);
  56339. }
  56340. }
  56341. }
  56342. void triggerCurrentlyHighlightedItem()
  56343. {
  56344. if (currentChild != 0
  56345. && currentChild->itemInfo.canBeTriggered()
  56346. && (currentChild->itemInfo.customComp == 0
  56347. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56348. {
  56349. dismissMenu (&currentChild->itemInfo);
  56350. }
  56351. }
  56352. void selectNextItem (const int delta)
  56353. {
  56354. disableTimerUntilMouseMoves();
  56355. PopupMenu::ItemComponent* mic = 0;
  56356. bool wasLastOne = (currentChild == 0);
  56357. const int numItems = items.size();
  56358. for (int i = 0; i < numItems + 1; ++i)
  56359. {
  56360. int index = (delta > 0) ? i : (numItems - 1 - i);
  56361. index = (index + numItems) % numItems;
  56362. mic = items.getUnchecked (index);
  56363. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56364. && wasLastOne)
  56365. break;
  56366. if (mic == currentChild)
  56367. wasLastOne = true;
  56368. }
  56369. setCurrentlyHighlightedChild (mic);
  56370. }
  56371. void disableTimerUntilMouseMoves()
  56372. {
  56373. disableMouseMoves = true;
  56374. if (owner != 0)
  56375. owner->disableTimerUntilMouseMoves();
  56376. }
  56377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56378. };
  56379. PopupMenu::PopupMenu()
  56380. : lookAndFeel (0),
  56381. separatorPending (false)
  56382. {
  56383. }
  56384. PopupMenu::PopupMenu (const PopupMenu& other)
  56385. : lookAndFeel (other.lookAndFeel),
  56386. separatorPending (false)
  56387. {
  56388. items.addCopiesOf (other.items);
  56389. }
  56390. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56391. {
  56392. if (this != &other)
  56393. {
  56394. lookAndFeel = other.lookAndFeel;
  56395. clear();
  56396. items.addCopiesOf (other.items);
  56397. }
  56398. return *this;
  56399. }
  56400. PopupMenu::~PopupMenu()
  56401. {
  56402. clear();
  56403. }
  56404. void PopupMenu::clear()
  56405. {
  56406. items.clear();
  56407. separatorPending = false;
  56408. }
  56409. void PopupMenu::addSeparatorIfPending()
  56410. {
  56411. if (separatorPending)
  56412. {
  56413. separatorPending = false;
  56414. if (items.size() > 0)
  56415. items.add (new Item());
  56416. }
  56417. }
  56418. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56419. const bool isActive, const bool isTicked, const Image& iconToUse)
  56420. {
  56421. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56422. // didn't pick anything, so you shouldn't use it as the id
  56423. // for an item..
  56424. addSeparatorIfPending();
  56425. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56426. Colours::black, false, 0, 0, 0));
  56427. }
  56428. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56429. const int commandID,
  56430. const String& displayName)
  56431. {
  56432. jassert (commandManager != 0 && commandID != 0);
  56433. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56434. if (registeredInfo != 0)
  56435. {
  56436. ApplicationCommandInfo info (*registeredInfo);
  56437. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56438. addSeparatorIfPending();
  56439. items.add (new Item (commandID,
  56440. displayName.isNotEmpty() ? displayName
  56441. : info.shortName,
  56442. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56443. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56444. Image::null,
  56445. Colours::black,
  56446. false,
  56447. 0, 0,
  56448. commandManager));
  56449. }
  56450. }
  56451. void PopupMenu::addColouredItem (const int itemResultId,
  56452. const String& itemText,
  56453. const Colour& itemTextColour,
  56454. const bool isActive,
  56455. const bool isTicked,
  56456. const Image& iconToUse)
  56457. {
  56458. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56459. // didn't pick anything, so you shouldn't use it as the id
  56460. // for an item..
  56461. addSeparatorIfPending();
  56462. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56463. itemTextColour, true, 0, 0, 0));
  56464. }
  56465. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56466. {
  56467. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56468. // didn't pick anything, so you shouldn't use it as the id
  56469. // for an item..
  56470. addSeparatorIfPending();
  56471. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56472. Colours::black, false, customComponent, 0, 0));
  56473. }
  56474. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56475. {
  56476. public:
  56477. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56478. const bool triggerMenuItemAutomaticallyWhenClicked)
  56479. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56480. width (w), height (h)
  56481. {
  56482. addAndMakeVisible (comp);
  56483. }
  56484. void getIdealSize (int& idealWidth, int& idealHeight)
  56485. {
  56486. idealWidth = width;
  56487. idealHeight = height;
  56488. }
  56489. void resized()
  56490. {
  56491. if (getChildComponent(0) != 0)
  56492. getChildComponent(0)->setBounds (getLocalBounds());
  56493. }
  56494. private:
  56495. const int width, height;
  56496. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56497. };
  56498. void PopupMenu::addCustomItem (const int itemResultId,
  56499. Component* customComponent,
  56500. int idealWidth, int idealHeight,
  56501. const bool triggerMenuItemAutomaticallyWhenClicked)
  56502. {
  56503. addCustomItem (itemResultId,
  56504. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56505. triggerMenuItemAutomaticallyWhenClicked));
  56506. }
  56507. void PopupMenu::addSubMenu (const String& subMenuName,
  56508. const PopupMenu& subMenu,
  56509. const bool isActive,
  56510. const Image& iconToUse,
  56511. const bool isTicked)
  56512. {
  56513. addSeparatorIfPending();
  56514. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56515. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56516. }
  56517. void PopupMenu::addSeparator()
  56518. {
  56519. separatorPending = true;
  56520. }
  56521. class HeaderItemComponent : public PopupMenu::CustomComponent
  56522. {
  56523. public:
  56524. HeaderItemComponent (const String& name)
  56525. : PopupMenu::CustomComponent (false)
  56526. {
  56527. setName (name);
  56528. }
  56529. void paint (Graphics& g)
  56530. {
  56531. Font f (getLookAndFeel().getPopupMenuFont());
  56532. f.setBold (true);
  56533. g.setFont (f);
  56534. g.setColour (findColour (PopupMenu::headerTextColourId));
  56535. g.drawFittedText (getName(),
  56536. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56537. Justification::bottomLeft, 1);
  56538. }
  56539. void getIdealSize (int& idealWidth, int& idealHeight)
  56540. {
  56541. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56542. idealHeight += idealHeight / 2;
  56543. idealWidth += idealWidth / 4;
  56544. }
  56545. private:
  56546. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56547. };
  56548. void PopupMenu::addSectionHeader (const String& title)
  56549. {
  56550. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56551. }
  56552. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56553. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56554. {
  56555. public:
  56556. PopupMenuCompletionCallback()
  56557. : managerOfChosenCommand (0)
  56558. {
  56559. }
  56560. void modalStateFinished (int result)
  56561. {
  56562. if (managerOfChosenCommand != 0 && result != 0)
  56563. {
  56564. ApplicationCommandTarget::InvocationInfo info (result);
  56565. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56566. managerOfChosenCommand->invoke (info, true);
  56567. }
  56568. // (this would be the place to fade out the component, if that's what's required)
  56569. component = 0;
  56570. }
  56571. ApplicationCommandManager* managerOfChosenCommand;
  56572. ScopedPointer<Component> component;
  56573. private:
  56574. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56575. };
  56576. int PopupMenu::showMenu (const Rectangle<int>& target,
  56577. const int itemIdThatMustBeVisible,
  56578. const int minimumWidth,
  56579. const int maximumNumColumns,
  56580. const int standardItemHeight,
  56581. Component* const componentAttachedTo,
  56582. ModalComponentManager::Callback* userCallback)
  56583. {
  56584. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56585. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56586. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56587. Window::wasHiddenBecauseOfAppChange() = false;
  56588. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56589. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56590. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56591. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56592. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56593. &callback->managerOfChosenCommand, componentAttachedTo);
  56594. if (callback->component == 0)
  56595. return 0;
  56596. callback->component->enterModalState (false, userCallbackDeleter.release());
  56597. callback->component->toFront (false); // need to do this after making it modal, or it could
  56598. // be stuck behind other comps that are already modal..
  56599. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56600. callbackDeleter.release();
  56601. if (userCallback != 0)
  56602. return 0;
  56603. const int result = callback->component->runModalLoop();
  56604. if (! Window::wasHiddenBecauseOfAppChange())
  56605. {
  56606. if (prevTopLevel != 0)
  56607. prevTopLevel->toFront (true);
  56608. if (prevFocused != 0)
  56609. prevFocused->grabKeyboardFocus();
  56610. }
  56611. return result;
  56612. }
  56613. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56614. const int minimumWidth, const int maximumNumColumns,
  56615. const int standardItemHeight,
  56616. ModalComponentManager::Callback* callback)
  56617. {
  56618. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56619. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56620. standardItemHeight, 0, callback);
  56621. }
  56622. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56623. const int itemIdThatMustBeVisible,
  56624. const int minimumWidth, const int maximumNumColumns,
  56625. const int standardItemHeight,
  56626. ModalComponentManager::Callback* callback)
  56627. {
  56628. return showMenu (screenAreaToAttachTo,
  56629. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56630. standardItemHeight, 0, callback);
  56631. }
  56632. int PopupMenu::showAt (Component* componentToAttachTo,
  56633. const int itemIdThatMustBeVisible,
  56634. const int minimumWidth, const int maximumNumColumns,
  56635. const int standardItemHeight,
  56636. ModalComponentManager::Callback* callback)
  56637. {
  56638. if (componentToAttachTo != 0)
  56639. {
  56640. return showMenu (componentToAttachTo->getScreenBounds(),
  56641. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56642. standardItemHeight, componentToAttachTo, callback);
  56643. }
  56644. else
  56645. {
  56646. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56647. standardItemHeight, callback);
  56648. }
  56649. }
  56650. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56651. {
  56652. const int numWindows = Window::getActiveWindows().size();
  56653. for (int i = numWindows; --i >= 0;)
  56654. {
  56655. Window* const pmw = Window::getActiveWindows()[i];
  56656. if (pmw != 0)
  56657. pmw->dismissMenu (0);
  56658. }
  56659. return numWindows > 0;
  56660. }
  56661. int PopupMenu::getNumItems() const throw()
  56662. {
  56663. int num = 0;
  56664. for (int i = items.size(); --i >= 0;)
  56665. if (! (items.getUnchecked(i))->isSeparator)
  56666. ++num;
  56667. return num;
  56668. }
  56669. bool PopupMenu::containsCommandItem (const int commandID) const
  56670. {
  56671. for (int i = items.size(); --i >= 0;)
  56672. {
  56673. const Item* mi = items.getUnchecked (i);
  56674. if ((mi->itemId == commandID && mi->commandManager != 0)
  56675. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56676. {
  56677. return true;
  56678. }
  56679. }
  56680. return false;
  56681. }
  56682. bool PopupMenu::containsAnyActiveItems() const throw()
  56683. {
  56684. for (int i = items.size(); --i >= 0;)
  56685. {
  56686. const Item* const mi = items.getUnchecked (i);
  56687. if (mi->subMenu != 0)
  56688. {
  56689. if (mi->subMenu->containsAnyActiveItems())
  56690. return true;
  56691. }
  56692. else if (mi->active)
  56693. {
  56694. return true;
  56695. }
  56696. }
  56697. return false;
  56698. }
  56699. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56700. {
  56701. lookAndFeel = newLookAndFeel;
  56702. }
  56703. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56704. : isHighlighted (false),
  56705. triggeredAutomatically (isTriggeredAutomatically_)
  56706. {
  56707. }
  56708. PopupMenu::CustomComponent::~CustomComponent()
  56709. {
  56710. }
  56711. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56712. {
  56713. isHighlighted = shouldBeHighlighted;
  56714. repaint();
  56715. }
  56716. void PopupMenu::CustomComponent::triggerMenuItem()
  56717. {
  56718. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56719. if (mic != 0)
  56720. {
  56721. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56722. if (pmw != 0)
  56723. {
  56724. pmw->dismissMenu (&mic->itemInfo);
  56725. }
  56726. else
  56727. {
  56728. // something must have gone wrong with the component hierarchy if this happens..
  56729. jassertfalse;
  56730. }
  56731. }
  56732. else
  56733. {
  56734. // why isn't this component inside a menu? Not much point triggering the item if
  56735. // there's no menu.
  56736. jassertfalse;
  56737. }
  56738. }
  56739. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56740. : subMenu (0),
  56741. itemId (0),
  56742. isSeparator (false),
  56743. isTicked (false),
  56744. isEnabled (false),
  56745. isCustomComponent (false),
  56746. isSectionHeader (false),
  56747. customColour (0),
  56748. customImage (0),
  56749. menu (menu_),
  56750. index (0)
  56751. {
  56752. }
  56753. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56754. {
  56755. }
  56756. bool PopupMenu::MenuItemIterator::next()
  56757. {
  56758. if (index >= menu.items.size())
  56759. return false;
  56760. const Item* const item = menu.items.getUnchecked (index);
  56761. ++index;
  56762. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56763. subMenu = item->subMenu;
  56764. itemId = item->itemId;
  56765. isSeparator = item->isSeparator;
  56766. isTicked = item->isTicked;
  56767. isEnabled = item->active;
  56768. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56769. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56770. customColour = item->usesColour ? &(item->textColour) : 0;
  56771. customImage = item->image;
  56772. commandManager = item->commandManager;
  56773. return true;
  56774. }
  56775. END_JUCE_NAMESPACE
  56776. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56777. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56778. BEGIN_JUCE_NAMESPACE
  56779. ComponentDragger::ComponentDragger()
  56780. {
  56781. }
  56782. ComponentDragger::~ComponentDragger()
  56783. {
  56784. }
  56785. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56786. {
  56787. jassert (componentToDrag != 0);
  56788. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56789. if (componentToDrag != 0)
  56790. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56791. }
  56792. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56793. ComponentBoundsConstrainer* const constrainer)
  56794. {
  56795. jassert (componentToDrag != 0);
  56796. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56797. if (componentToDrag != 0)
  56798. {
  56799. Rectangle<int> bounds (componentToDrag->getBounds());
  56800. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56801. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56802. // the current mouse position instead of the one that the event contains...
  56803. if (componentToDrag->isOnDesktop())
  56804. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56805. else
  56806. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56807. if (constrainer != 0)
  56808. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56809. else
  56810. componentToDrag->setBounds (bounds);
  56811. }
  56812. }
  56813. END_JUCE_NAMESPACE
  56814. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56815. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56816. BEGIN_JUCE_NAMESPACE
  56817. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56818. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56819. class DragImageComponent : public Component,
  56820. public Timer
  56821. {
  56822. public:
  56823. DragImageComponent (const Image& im,
  56824. const String& desc,
  56825. Component* const sourceComponent,
  56826. Component* const mouseDragSource_,
  56827. DragAndDropContainer* const o,
  56828. const Point<int>& imageOffset_)
  56829. : image (im),
  56830. source (sourceComponent),
  56831. mouseDragSource (mouseDragSource_),
  56832. owner (o),
  56833. dragDesc (desc),
  56834. imageOffset (imageOffset_),
  56835. hasCheckedForExternalDrag (false),
  56836. drawImage (true)
  56837. {
  56838. setSize (im.getWidth(), im.getHeight());
  56839. if (mouseDragSource == 0)
  56840. mouseDragSource = source;
  56841. mouseDragSource->addMouseListener (this, false);
  56842. startTimer (200);
  56843. setInterceptsMouseClicks (false, false);
  56844. setAlwaysOnTop (true);
  56845. }
  56846. ~DragImageComponent()
  56847. {
  56848. if (owner->dragImageComponent == this)
  56849. owner->dragImageComponent.release();
  56850. if (mouseDragSource != 0)
  56851. {
  56852. mouseDragSource->removeMouseListener (this);
  56853. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56854. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56855. }
  56856. }
  56857. void paint (Graphics& g)
  56858. {
  56859. if (isOpaque())
  56860. g.fillAll (Colours::white);
  56861. if (drawImage)
  56862. {
  56863. g.setOpacity (1.0f);
  56864. g.drawImageAt (image, 0, 0);
  56865. }
  56866. }
  56867. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56868. {
  56869. Component* hit = getParentComponent();
  56870. if (hit == 0)
  56871. {
  56872. hit = Desktop::getInstance().findComponentAt (screenPos);
  56873. }
  56874. else
  56875. {
  56876. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56877. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56878. }
  56879. // (note: use a local copy of the dragDesc member in case the callback runs
  56880. // a modal loop and deletes this object before the method completes)
  56881. const String dragDescLocal (dragDesc);
  56882. while (hit != 0)
  56883. {
  56884. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56885. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56886. {
  56887. relativePos = hit->getLocalPoint (0, screenPos);
  56888. return ddt;
  56889. }
  56890. hit = hit->getParentComponent();
  56891. }
  56892. return 0;
  56893. }
  56894. void mouseUp (const MouseEvent& e)
  56895. {
  56896. if (e.originalComponent != this)
  56897. {
  56898. if (mouseDragSource != 0)
  56899. mouseDragSource->removeMouseListener (this);
  56900. bool dropAccepted = false;
  56901. DragAndDropTarget* ddt = 0;
  56902. Point<int> relPos;
  56903. if (isVisible())
  56904. {
  56905. setVisible (false);
  56906. ddt = findTarget (e.getScreenPosition(), relPos);
  56907. // fade this component and remove it - it'll be deleted later by the timer callback
  56908. dropAccepted = ddt != 0;
  56909. setVisible (true);
  56910. if (dropAccepted || source == 0)
  56911. {
  56912. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56913. }
  56914. else
  56915. {
  56916. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56917. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56918. Desktop::getInstance().getAnimator().animateComponent (this,
  56919. getBounds() + (target - ourCentre),
  56920. 0.0f, 120,
  56921. true, 1.0, 1.0);
  56922. }
  56923. }
  56924. if (getParentComponent() != 0)
  56925. getParentComponent()->removeChildComponent (this);
  56926. if (dropAccepted && ddt != 0)
  56927. {
  56928. // (note: use a local copy of the dragDesc member in case the callback runs
  56929. // a modal loop and deletes this object before the method completes)
  56930. const String dragDescLocal (dragDesc);
  56931. currentlyOverComp = 0;
  56932. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56933. }
  56934. // careful - this object could now be deleted..
  56935. }
  56936. }
  56937. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56938. {
  56939. // (note: use a local copy of the dragDesc member in case the callback runs
  56940. // a modal loop and deletes this object before it returns)
  56941. const String dragDescLocal (dragDesc);
  56942. Point<int> newPos (screenPos + imageOffset);
  56943. if (getParentComponent() != 0)
  56944. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56945. //if (newX != getX() || newY != getY())
  56946. {
  56947. setTopLeftPosition (newPos.getX(), newPos.getY());
  56948. Point<int> relPos;
  56949. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56950. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56951. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56952. if (ddtComp != currentlyOverComp)
  56953. {
  56954. if (currentlyOverComp != 0 && source != 0
  56955. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56956. {
  56957. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56958. }
  56959. currentlyOverComp = ddtComp;
  56960. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56961. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56962. }
  56963. DragAndDropTarget* target = getCurrentlyOver();
  56964. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56965. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56966. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56967. {
  56968. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56969. {
  56970. hasCheckedForExternalDrag = true;
  56971. StringArray files;
  56972. bool canMoveFiles = false;
  56973. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56974. && files.size() > 0)
  56975. {
  56976. WeakReference<Component> cdw (this);
  56977. setVisible (false);
  56978. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56979. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56980. if (cdw != 0)
  56981. delete this;
  56982. return;
  56983. }
  56984. }
  56985. }
  56986. }
  56987. }
  56988. void mouseDrag (const MouseEvent& e)
  56989. {
  56990. if (e.originalComponent != this)
  56991. updateLocation (true, e.getScreenPosition());
  56992. }
  56993. void timerCallback()
  56994. {
  56995. if (source == 0)
  56996. {
  56997. delete this;
  56998. }
  56999. else if (! isMouseButtonDownAnywhere())
  57000. {
  57001. if (mouseDragSource != 0)
  57002. mouseDragSource->removeMouseListener (this);
  57003. delete this;
  57004. }
  57005. }
  57006. private:
  57007. Image image;
  57008. WeakReference<Component> source;
  57009. WeakReference<Component> mouseDragSource;
  57010. DragAndDropContainer* const owner;
  57011. WeakReference<Component> currentlyOverComp;
  57012. DragAndDropTarget* getCurrentlyOver()
  57013. {
  57014. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  57015. }
  57016. String dragDesc;
  57017. const Point<int> imageOffset;
  57018. bool hasCheckedForExternalDrag, drawImage;
  57019. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  57020. };
  57021. DragAndDropContainer::DragAndDropContainer()
  57022. {
  57023. }
  57024. DragAndDropContainer::~DragAndDropContainer()
  57025. {
  57026. dragImageComponent = 0;
  57027. }
  57028. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57029. Component* sourceComponent,
  57030. const Image& dragImage_,
  57031. const bool allowDraggingToExternalWindows,
  57032. const Point<int>* imageOffsetFromMouse)
  57033. {
  57034. Image dragImage (dragImage_);
  57035. if (dragImageComponent == 0)
  57036. {
  57037. Component* const thisComp = dynamic_cast <Component*> (this);
  57038. if (thisComp == 0)
  57039. {
  57040. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57041. return;
  57042. }
  57043. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57044. if (draggingSource == 0 || ! draggingSource->isDragging())
  57045. {
  57046. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57047. return;
  57048. }
  57049. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57050. Point<int> imageOffset;
  57051. if (dragImage.isNull())
  57052. {
  57053. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57054. .convertedToFormat (Image::ARGB);
  57055. dragImage.multiplyAllAlphas (0.6f);
  57056. const int lo = 150;
  57057. const int hi = 400;
  57058. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  57059. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57060. for (int y = dragImage.getHeight(); --y >= 0;)
  57061. {
  57062. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57063. for (int x = dragImage.getWidth(); --x >= 0;)
  57064. {
  57065. const int dx = x - clipped.getX();
  57066. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57067. if (distance > lo)
  57068. {
  57069. const float alpha = (distance > hi) ? 0
  57070. : (hi - distance) / (float) (hi - lo)
  57071. + Random::getSystemRandom().nextFloat() * 0.008f;
  57072. dragImage.multiplyAlphaAt (x, y, alpha);
  57073. }
  57074. }
  57075. }
  57076. imageOffset = -clipped;
  57077. }
  57078. else
  57079. {
  57080. if (imageOffsetFromMouse == 0)
  57081. imageOffset = -dragImage.getBounds().getCentre();
  57082. else
  57083. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57084. }
  57085. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57086. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57087. currentDragDesc = sourceDescription;
  57088. if (allowDraggingToExternalWindows)
  57089. {
  57090. if (! Desktop::canUseSemiTransparentWindows())
  57091. dragImageComponent->setOpaque (true);
  57092. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57093. | ComponentPeer::windowIsTemporary
  57094. | ComponentPeer::windowIgnoresKeyPresses);
  57095. }
  57096. else
  57097. thisComp->addChildComponent (dragImageComponent);
  57098. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57099. dragImageComponent->setVisible (true);
  57100. }
  57101. }
  57102. bool DragAndDropContainer::isDragAndDropActive() const
  57103. {
  57104. return dragImageComponent != 0;
  57105. }
  57106. const String DragAndDropContainer::getCurrentDragDescription() const
  57107. {
  57108. return (dragImageComponent != 0) ? currentDragDesc
  57109. : String::empty;
  57110. }
  57111. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57112. {
  57113. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57114. }
  57115. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57116. {
  57117. return false;
  57118. }
  57119. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57120. {
  57121. }
  57122. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57123. {
  57124. }
  57125. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57126. {
  57127. }
  57128. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57129. {
  57130. return true;
  57131. }
  57132. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57133. {
  57134. }
  57135. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57136. {
  57137. }
  57138. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57139. {
  57140. }
  57141. END_JUCE_NAMESPACE
  57142. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57143. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57144. BEGIN_JUCE_NAMESPACE
  57145. class MouseCursor::SharedCursorHandle
  57146. {
  57147. public:
  57148. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57149. : handle (createStandardMouseCursor (type)),
  57150. refCount (1),
  57151. standardType (type),
  57152. isStandard (true)
  57153. {
  57154. }
  57155. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57156. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57157. refCount (1),
  57158. standardType (MouseCursor::NormalCursor),
  57159. isStandard (false)
  57160. {
  57161. }
  57162. ~SharedCursorHandle()
  57163. {
  57164. deleteMouseCursor (handle, isStandard);
  57165. }
  57166. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57167. {
  57168. const ScopedLock sl (getLock());
  57169. for (int i = 0; i < getCursors().size(); ++i)
  57170. {
  57171. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57172. if (sc->standardType == type)
  57173. return sc->retain();
  57174. }
  57175. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57176. getCursors().add (sc);
  57177. return sc;
  57178. }
  57179. SharedCursorHandle* retain() throw()
  57180. {
  57181. ++refCount;
  57182. return this;
  57183. }
  57184. void release()
  57185. {
  57186. if (--refCount == 0)
  57187. {
  57188. if (isStandard)
  57189. {
  57190. const ScopedLock sl (getLock());
  57191. getCursors().removeValue (this);
  57192. }
  57193. delete this;
  57194. }
  57195. }
  57196. void* getHandle() const throw() { return handle; }
  57197. private:
  57198. void* const handle;
  57199. Atomic <int> refCount;
  57200. const MouseCursor::StandardCursorType standardType;
  57201. const bool isStandard;
  57202. static CriticalSection& getLock()
  57203. {
  57204. static CriticalSection lock;
  57205. return lock;
  57206. }
  57207. static Array <SharedCursorHandle*>& getCursors()
  57208. {
  57209. static Array <SharedCursorHandle*> cursors;
  57210. return cursors;
  57211. }
  57212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57213. };
  57214. MouseCursor::MouseCursor()
  57215. : cursorHandle (0)
  57216. {
  57217. }
  57218. MouseCursor::MouseCursor (const StandardCursorType type)
  57219. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57220. {
  57221. }
  57222. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57223. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57224. {
  57225. }
  57226. MouseCursor::MouseCursor (const MouseCursor& other)
  57227. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57228. {
  57229. }
  57230. MouseCursor::~MouseCursor()
  57231. {
  57232. if (cursorHandle != 0)
  57233. cursorHandle->release();
  57234. }
  57235. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57236. {
  57237. if (other.cursorHandle != 0)
  57238. other.cursorHandle->retain();
  57239. if (cursorHandle != 0)
  57240. cursorHandle->release();
  57241. cursorHandle = other.cursorHandle;
  57242. return *this;
  57243. }
  57244. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57245. {
  57246. return getHandle() == other.getHandle();
  57247. }
  57248. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57249. {
  57250. return getHandle() != other.getHandle();
  57251. }
  57252. void* MouseCursor::getHandle() const throw()
  57253. {
  57254. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57255. }
  57256. void MouseCursor::showWaitCursor()
  57257. {
  57258. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57259. }
  57260. void MouseCursor::hideWaitCursor()
  57261. {
  57262. Desktop::getInstance().getMainMouseSource().revealCursor();
  57263. }
  57264. END_JUCE_NAMESPACE
  57265. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57266. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57267. BEGIN_JUCE_NAMESPACE
  57268. MouseEvent::MouseEvent (MouseInputSource& source_,
  57269. const Point<int>& position,
  57270. const ModifierKeys& mods_,
  57271. Component* const eventComponent_,
  57272. Component* const originator,
  57273. const Time& eventTime_,
  57274. const Point<int> mouseDownPos_,
  57275. const Time& mouseDownTime_,
  57276. const int numberOfClicks_,
  57277. const bool mouseWasDragged) throw()
  57278. : x (position.getX()),
  57279. y (position.getY()),
  57280. mods (mods_),
  57281. eventComponent (eventComponent_),
  57282. originalComponent (originator),
  57283. eventTime (eventTime_),
  57284. source (source_),
  57285. mouseDownPos (mouseDownPos_),
  57286. mouseDownTime (mouseDownTime_),
  57287. numberOfClicks (numberOfClicks_),
  57288. wasMovedSinceMouseDown (mouseWasDragged)
  57289. {
  57290. }
  57291. MouseEvent::~MouseEvent() throw()
  57292. {
  57293. }
  57294. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57295. {
  57296. if (otherComponent == 0)
  57297. {
  57298. jassertfalse;
  57299. return *this;
  57300. }
  57301. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57302. mods, otherComponent, originalComponent, eventTime,
  57303. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57304. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57305. }
  57306. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57307. {
  57308. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57309. eventTime, mouseDownPos, mouseDownTime,
  57310. numberOfClicks, wasMovedSinceMouseDown);
  57311. }
  57312. bool MouseEvent::mouseWasClicked() const throw()
  57313. {
  57314. return ! wasMovedSinceMouseDown;
  57315. }
  57316. int MouseEvent::getMouseDownX() const throw()
  57317. {
  57318. return mouseDownPos.getX();
  57319. }
  57320. int MouseEvent::getMouseDownY() const throw()
  57321. {
  57322. return mouseDownPos.getY();
  57323. }
  57324. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57325. {
  57326. return mouseDownPos;
  57327. }
  57328. int MouseEvent::getDistanceFromDragStartX() const throw()
  57329. {
  57330. return x - mouseDownPos.getX();
  57331. }
  57332. int MouseEvent::getDistanceFromDragStartY() const throw()
  57333. {
  57334. return y - mouseDownPos.getY();
  57335. }
  57336. int MouseEvent::getDistanceFromDragStart() const throw()
  57337. {
  57338. return mouseDownPos.getDistanceFrom (getPosition());
  57339. }
  57340. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57341. {
  57342. return getPosition() - mouseDownPos;
  57343. }
  57344. int MouseEvent::getLengthOfMousePress() const throw()
  57345. {
  57346. if (mouseDownTime.toMilliseconds() > 0)
  57347. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57348. return 0;
  57349. }
  57350. const Point<int> MouseEvent::getPosition() const throw()
  57351. {
  57352. return Point<int> (x, y);
  57353. }
  57354. int MouseEvent::getScreenX() const
  57355. {
  57356. return getScreenPosition().getX();
  57357. }
  57358. int MouseEvent::getScreenY() const
  57359. {
  57360. return getScreenPosition().getY();
  57361. }
  57362. const Point<int> MouseEvent::getScreenPosition() const
  57363. {
  57364. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57365. }
  57366. int MouseEvent::getMouseDownScreenX() const
  57367. {
  57368. return getMouseDownScreenPosition().getX();
  57369. }
  57370. int MouseEvent::getMouseDownScreenY() const
  57371. {
  57372. return getMouseDownScreenPosition().getY();
  57373. }
  57374. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57375. {
  57376. return eventComponent->localPointToGlobal (mouseDownPos);
  57377. }
  57378. int MouseEvent::doubleClickTimeOutMs = 400;
  57379. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57380. {
  57381. doubleClickTimeOutMs = newTime;
  57382. }
  57383. int MouseEvent::getDoubleClickTimeout() throw()
  57384. {
  57385. return doubleClickTimeOutMs;
  57386. }
  57387. END_JUCE_NAMESPACE
  57388. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57389. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57390. BEGIN_JUCE_NAMESPACE
  57391. class MouseInputSourceInternal : public AsyncUpdater
  57392. {
  57393. public:
  57394. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57395. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57396. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57397. mouseEventCounter (0)
  57398. {
  57399. }
  57400. bool isDragging() const throw()
  57401. {
  57402. return buttonState.isAnyMouseButtonDown();
  57403. }
  57404. Component* getComponentUnderMouse() const
  57405. {
  57406. return static_cast <Component*> (componentUnderMouse);
  57407. }
  57408. const ModifierKeys getCurrentModifiers() const
  57409. {
  57410. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57411. }
  57412. ComponentPeer* getPeer()
  57413. {
  57414. if (! ComponentPeer::isValidPeer (lastPeer))
  57415. lastPeer = 0;
  57416. return lastPeer;
  57417. }
  57418. Component* findComponentAt (const Point<int>& screenPos)
  57419. {
  57420. ComponentPeer* const peer = getPeer();
  57421. if (peer != 0)
  57422. {
  57423. Component* const comp = peer->getComponent();
  57424. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57425. // (the contains() call is needed to test for overlapping desktop windows)
  57426. if (comp->contains (relativePos))
  57427. return comp->getComponentAt (relativePos);
  57428. }
  57429. return 0;
  57430. }
  57431. const Point<int> getScreenPosition() const
  57432. {
  57433. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57434. // value, because that can cause continuity problems.
  57435. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57436. : lastScreenPos);
  57437. }
  57438. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57439. {
  57440. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57441. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57442. }
  57443. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57444. {
  57445. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57446. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57447. }
  57448. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57449. {
  57450. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57451. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57452. }
  57453. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57454. {
  57455. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57456. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57457. }
  57458. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57459. {
  57460. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57461. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57462. }
  57463. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57464. {
  57465. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57466. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57467. }
  57468. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57469. {
  57470. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57471. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57472. }
  57473. // (returns true if the button change caused a modal event loop)
  57474. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57475. {
  57476. if (buttonState == newButtonState)
  57477. return false;
  57478. setScreenPos (screenPos, time, false);
  57479. // (ignore secondary clicks when there's already a button down)
  57480. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57481. {
  57482. buttonState = newButtonState;
  57483. return false;
  57484. }
  57485. const int lastCounter = mouseEventCounter;
  57486. if (buttonState.isAnyMouseButtonDown())
  57487. {
  57488. Component* const current = getComponentUnderMouse();
  57489. if (current != 0)
  57490. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57491. enableUnboundedMouseMovement (false, false);
  57492. }
  57493. buttonState = newButtonState;
  57494. if (buttonState.isAnyMouseButtonDown())
  57495. {
  57496. Desktop::getInstance().incrementMouseClickCounter();
  57497. Component* const current = getComponentUnderMouse();
  57498. if (current != 0)
  57499. {
  57500. registerMouseDown (screenPos, time, current, buttonState);
  57501. sendMouseDown (current, screenPos, time);
  57502. }
  57503. }
  57504. return lastCounter != mouseEventCounter;
  57505. }
  57506. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57507. {
  57508. Component* current = getComponentUnderMouse();
  57509. if (newComponent != current)
  57510. {
  57511. WeakReference<Component> safeNewComp (newComponent);
  57512. const ModifierKeys originalButtonState (buttonState);
  57513. if (current != 0)
  57514. {
  57515. setButtons (screenPos, time, ModifierKeys());
  57516. sendMouseExit (current, screenPos, time);
  57517. buttonState = originalButtonState;
  57518. }
  57519. componentUnderMouse = safeNewComp;
  57520. current = getComponentUnderMouse();
  57521. if (current != 0)
  57522. sendMouseEnter (current, screenPos, time);
  57523. revealCursor (false);
  57524. setButtons (screenPos, time, originalButtonState);
  57525. }
  57526. }
  57527. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57528. {
  57529. ModifierKeys::updateCurrentModifiers();
  57530. if (newPeer != lastPeer)
  57531. {
  57532. setComponentUnderMouse (0, screenPos, time);
  57533. lastPeer = newPeer;
  57534. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57535. }
  57536. }
  57537. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57538. {
  57539. if (! isDragging())
  57540. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57541. if (newScreenPos != lastScreenPos || forceUpdate)
  57542. {
  57543. cancelPendingUpdate();
  57544. lastScreenPos = newScreenPos;
  57545. Component* const current = getComponentUnderMouse();
  57546. if (current != 0)
  57547. {
  57548. if (isDragging())
  57549. {
  57550. registerMouseDrag (newScreenPos);
  57551. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57552. if (isUnboundedMouseModeOn)
  57553. handleUnboundedDrag (current);
  57554. }
  57555. else
  57556. {
  57557. sendMouseMove (current, newScreenPos, time);
  57558. }
  57559. }
  57560. revealCursor (false);
  57561. }
  57562. }
  57563. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57564. {
  57565. jassert (newPeer != 0);
  57566. lastTime = time;
  57567. ++mouseEventCounter;
  57568. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57569. if (isDragging() && newMods.isAnyMouseButtonDown())
  57570. {
  57571. setScreenPos (screenPos, time, false);
  57572. }
  57573. else
  57574. {
  57575. setPeer (newPeer, screenPos, time);
  57576. ComponentPeer* peer = getPeer();
  57577. if (peer != 0)
  57578. {
  57579. if (setButtons (screenPos, time, newMods))
  57580. return; // some modal events have been dispatched, so the current event is now out-of-date
  57581. peer = getPeer();
  57582. if (peer != 0)
  57583. setScreenPos (screenPos, time, false);
  57584. }
  57585. }
  57586. }
  57587. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57588. {
  57589. jassert (peer != 0);
  57590. lastTime = time;
  57591. ++mouseEventCounter;
  57592. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57593. setPeer (peer, screenPos, time);
  57594. setScreenPos (screenPos, time, false);
  57595. triggerFakeMove();
  57596. if (! isDragging())
  57597. {
  57598. Component* current = getComponentUnderMouse();
  57599. if (current != 0)
  57600. sendMouseWheel (current, screenPos, time, x, y);
  57601. }
  57602. }
  57603. const Time getLastMouseDownTime() const throw()
  57604. {
  57605. return Time (mouseDowns[0].time);
  57606. }
  57607. const Point<int> getLastMouseDownPosition() const throw()
  57608. {
  57609. return mouseDowns[0].position;
  57610. }
  57611. int getNumberOfMultipleClicks() const throw()
  57612. {
  57613. int numClicks = 0;
  57614. if (mouseDowns[0].time != Time())
  57615. {
  57616. if (! mouseMovedSignificantlySincePressed)
  57617. ++numClicks;
  57618. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57619. {
  57620. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57621. ++numClicks;
  57622. else
  57623. break;
  57624. }
  57625. }
  57626. return numClicks;
  57627. }
  57628. bool hasMouseMovedSignificantlySincePressed() const throw()
  57629. {
  57630. return mouseMovedSignificantlySincePressed
  57631. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57632. }
  57633. void triggerFakeMove()
  57634. {
  57635. triggerAsyncUpdate();
  57636. }
  57637. void handleAsyncUpdate()
  57638. {
  57639. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57640. }
  57641. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57642. {
  57643. enable = enable && isDragging();
  57644. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57645. if (enable != isUnboundedMouseModeOn)
  57646. {
  57647. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57648. {
  57649. // when released, return the mouse to within the component's bounds
  57650. Component* current = getComponentUnderMouse();
  57651. if (current != 0)
  57652. Desktop::setMousePosition (current->getScreenBounds()
  57653. .getConstrainedPoint (lastScreenPos));
  57654. }
  57655. isUnboundedMouseModeOn = enable;
  57656. unboundedMouseOffset = Point<int>();
  57657. revealCursor (true);
  57658. }
  57659. }
  57660. void handleUnboundedDrag (Component* current)
  57661. {
  57662. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57663. if (! screenArea.contains (lastScreenPos))
  57664. {
  57665. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57666. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57667. Desktop::setMousePosition (componentCentre);
  57668. }
  57669. else if (isCursorVisibleUntilOffscreen
  57670. && (! unboundedMouseOffset.isOrigin())
  57671. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57672. {
  57673. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57674. unboundedMouseOffset = Point<int>();
  57675. }
  57676. }
  57677. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57678. {
  57679. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57680. {
  57681. cursor = MouseCursor::NoCursor;
  57682. forcedUpdate = true;
  57683. }
  57684. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57685. {
  57686. currentCursorHandle = cursor.getHandle();
  57687. cursor.showInWindow (getPeer());
  57688. }
  57689. }
  57690. void hideCursor()
  57691. {
  57692. showMouseCursor (MouseCursor::NoCursor, true);
  57693. }
  57694. void revealCursor (bool forcedUpdate)
  57695. {
  57696. MouseCursor mc (MouseCursor::NormalCursor);
  57697. Component* current = getComponentUnderMouse();
  57698. if (current != 0)
  57699. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57700. showMouseCursor (mc, forcedUpdate);
  57701. }
  57702. const int index;
  57703. const bool isMouseDevice;
  57704. Point<int> lastScreenPos;
  57705. ModifierKeys buttonState;
  57706. private:
  57707. MouseInputSource& source;
  57708. WeakReference<Component> componentUnderMouse;
  57709. ComponentPeer* lastPeer;
  57710. Point<int> unboundedMouseOffset;
  57711. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57712. void* currentCursorHandle;
  57713. int mouseEventCounter;
  57714. struct RecentMouseDown
  57715. {
  57716. RecentMouseDown() : component (0)
  57717. {
  57718. }
  57719. Point<int> position;
  57720. Time time;
  57721. Component* component;
  57722. ModifierKeys buttons;
  57723. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57724. {
  57725. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57726. && abs (position.getX() - other.position.getX()) < 8
  57727. && abs (position.getY() - other.position.getY()) < 8
  57728. && buttons == other.buttons;;
  57729. }
  57730. };
  57731. RecentMouseDown mouseDowns[4];
  57732. bool mouseMovedSignificantlySincePressed;
  57733. Time lastTime;
  57734. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57735. Component* const component, const ModifierKeys& modifiers) throw()
  57736. {
  57737. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57738. mouseDowns[i] = mouseDowns[i - 1];
  57739. mouseDowns[0].position = screenPos;
  57740. mouseDowns[0].time = time;
  57741. mouseDowns[0].component = component;
  57742. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57743. mouseMovedSignificantlySincePressed = false;
  57744. }
  57745. void registerMouseDrag (const Point<int>& screenPos) throw()
  57746. {
  57747. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57748. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57749. }
  57750. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57751. };
  57752. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57753. {
  57754. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57755. }
  57756. MouseInputSource::~MouseInputSource()
  57757. {
  57758. }
  57759. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57760. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57761. bool MouseInputSource::canHover() const { return isMouse(); }
  57762. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57763. int MouseInputSource::getIndex() const { return pimpl->index; }
  57764. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57765. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57766. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57767. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57768. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57769. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57770. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57771. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57772. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57773. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57774. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57775. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57776. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57777. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57778. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57779. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57780. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57781. {
  57782. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57783. }
  57784. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57785. {
  57786. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57787. }
  57788. END_JUCE_NAMESPACE
  57789. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57790. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57791. BEGIN_JUCE_NAMESPACE
  57792. void MouseListener::mouseEnter (const MouseEvent&)
  57793. {
  57794. }
  57795. void MouseListener::mouseExit (const MouseEvent&)
  57796. {
  57797. }
  57798. void MouseListener::mouseDown (const MouseEvent&)
  57799. {
  57800. }
  57801. void MouseListener::mouseUp (const MouseEvent&)
  57802. {
  57803. }
  57804. void MouseListener::mouseDrag (const MouseEvent&)
  57805. {
  57806. }
  57807. void MouseListener::mouseMove (const MouseEvent&)
  57808. {
  57809. }
  57810. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57811. {
  57812. }
  57813. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57814. {
  57815. }
  57816. END_JUCE_NAMESPACE
  57817. /*** End of inlined file: juce_MouseListener.cpp ***/
  57818. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57819. BEGIN_JUCE_NAMESPACE
  57820. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57821. const String& buttonTextWhenTrue,
  57822. const String& buttonTextWhenFalse)
  57823. : PropertyComponent (name),
  57824. onText (buttonTextWhenTrue),
  57825. offText (buttonTextWhenFalse)
  57826. {
  57827. addAndMakeVisible (&button);
  57828. button.setClickingTogglesState (false);
  57829. button.addListener (this);
  57830. }
  57831. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57832. const String& name,
  57833. const String& buttonText)
  57834. : PropertyComponent (name),
  57835. onText (buttonText),
  57836. offText (buttonText)
  57837. {
  57838. addAndMakeVisible (&button);
  57839. button.setClickingTogglesState (false);
  57840. button.setButtonText (buttonText);
  57841. button.getToggleStateValue().referTo (valueToControl);
  57842. button.setClickingTogglesState (true);
  57843. }
  57844. BooleanPropertyComponent::~BooleanPropertyComponent()
  57845. {
  57846. }
  57847. void BooleanPropertyComponent::setState (const bool newState)
  57848. {
  57849. button.setToggleState (newState, true);
  57850. }
  57851. bool BooleanPropertyComponent::getState() const
  57852. {
  57853. return button.getToggleState();
  57854. }
  57855. void BooleanPropertyComponent::paint (Graphics& g)
  57856. {
  57857. PropertyComponent::paint (g);
  57858. g.setColour (Colours::white);
  57859. g.fillRect (button.getBounds());
  57860. g.setColour (findColour (ComboBox::outlineColourId));
  57861. g.drawRect (button.getBounds());
  57862. }
  57863. void BooleanPropertyComponent::refresh()
  57864. {
  57865. button.setToggleState (getState(), false);
  57866. button.setButtonText (button.getToggleState() ? onText : offText);
  57867. }
  57868. void BooleanPropertyComponent::buttonClicked (Button*)
  57869. {
  57870. setState (! getState());
  57871. }
  57872. END_JUCE_NAMESPACE
  57873. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57874. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57875. BEGIN_JUCE_NAMESPACE
  57876. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57877. const bool triggerOnMouseDown)
  57878. : PropertyComponent (name)
  57879. {
  57880. addAndMakeVisible (&button);
  57881. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57882. button.addListener (this);
  57883. }
  57884. ButtonPropertyComponent::~ButtonPropertyComponent()
  57885. {
  57886. }
  57887. void ButtonPropertyComponent::refresh()
  57888. {
  57889. button.setButtonText (getButtonText());
  57890. }
  57891. void ButtonPropertyComponent::buttonClicked (Button*)
  57892. {
  57893. buttonClicked();
  57894. }
  57895. END_JUCE_NAMESPACE
  57896. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57897. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57898. BEGIN_JUCE_NAMESPACE
  57899. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57900. public ValueListener
  57901. {
  57902. public:
  57903. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57904. : sourceValue (sourceValue_),
  57905. mappings (mappings_)
  57906. {
  57907. sourceValue.addListener (this);
  57908. }
  57909. ~RemapperValueSource() {}
  57910. const var getValue() const
  57911. {
  57912. return mappings.indexOf (sourceValue.getValue()) + 1;
  57913. }
  57914. void setValue (const var& newValue)
  57915. {
  57916. const var remappedVal (mappings [(int) newValue - 1]);
  57917. if (remappedVal != sourceValue)
  57918. sourceValue = remappedVal;
  57919. }
  57920. void valueChanged (Value&)
  57921. {
  57922. sendChangeMessage (true);
  57923. }
  57924. protected:
  57925. Value sourceValue;
  57926. Array<var> mappings;
  57927. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57928. };
  57929. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57930. : PropertyComponent (name),
  57931. isCustomClass (true)
  57932. {
  57933. }
  57934. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57935. const String& name,
  57936. const StringArray& choices_,
  57937. const Array <var>& correspondingValues)
  57938. : PropertyComponent (name),
  57939. choices (choices_),
  57940. isCustomClass (false)
  57941. {
  57942. // The array of corresponding values must contain one value for each of the items in
  57943. // the choices array!
  57944. jassert (correspondingValues.size() == choices.size());
  57945. createComboBox();
  57946. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57947. }
  57948. ChoicePropertyComponent::~ChoicePropertyComponent()
  57949. {
  57950. }
  57951. void ChoicePropertyComponent::createComboBox()
  57952. {
  57953. addAndMakeVisible (&comboBox);
  57954. for (int i = 0; i < choices.size(); ++i)
  57955. {
  57956. if (choices[i].isNotEmpty())
  57957. comboBox.addItem (choices[i], i + 1);
  57958. else
  57959. comboBox.addSeparator();
  57960. }
  57961. comboBox.setEditableText (false);
  57962. }
  57963. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57964. {
  57965. jassertfalse; // you need to override this method in your subclass!
  57966. }
  57967. int ChoicePropertyComponent::getIndex() const
  57968. {
  57969. jassertfalse; // you need to override this method in your subclass!
  57970. return -1;
  57971. }
  57972. const StringArray& ChoicePropertyComponent::getChoices() const
  57973. {
  57974. return choices;
  57975. }
  57976. void ChoicePropertyComponent::refresh()
  57977. {
  57978. if (isCustomClass)
  57979. {
  57980. if (! comboBox.isVisible())
  57981. {
  57982. createComboBox();
  57983. comboBox.addListener (this);
  57984. }
  57985. comboBox.setSelectedId (getIndex() + 1, true);
  57986. }
  57987. }
  57988. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57989. {
  57990. if (isCustomClass)
  57991. {
  57992. const int newIndex = comboBox.getSelectedId() - 1;
  57993. if (newIndex != getIndex())
  57994. setIndex (newIndex);
  57995. }
  57996. }
  57997. END_JUCE_NAMESPACE
  57998. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57999. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58000. BEGIN_JUCE_NAMESPACE
  58001. PropertyComponent::PropertyComponent (const String& name,
  58002. const int preferredHeight_)
  58003. : Component (name),
  58004. preferredHeight (preferredHeight_)
  58005. {
  58006. jassert (name.isNotEmpty());
  58007. }
  58008. PropertyComponent::~PropertyComponent()
  58009. {
  58010. }
  58011. void PropertyComponent::paint (Graphics& g)
  58012. {
  58013. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58014. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58015. }
  58016. void PropertyComponent::resized()
  58017. {
  58018. if (getNumChildComponents() > 0)
  58019. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58020. }
  58021. void PropertyComponent::enablementChanged()
  58022. {
  58023. repaint();
  58024. }
  58025. END_JUCE_NAMESPACE
  58026. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58027. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58028. BEGIN_JUCE_NAMESPACE
  58029. class PropertySectionComponent : public Component
  58030. {
  58031. public:
  58032. PropertySectionComponent (const String& sectionTitle,
  58033. const Array <PropertyComponent*>& newProperties,
  58034. const bool sectionIsOpen_)
  58035. : Component (sectionTitle),
  58036. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58037. sectionIsOpen (sectionIsOpen_)
  58038. {
  58039. propertyComps.addArray (newProperties);
  58040. for (int i = propertyComps.size(); --i >= 0;)
  58041. {
  58042. addAndMakeVisible (propertyComps.getUnchecked(i));
  58043. propertyComps.getUnchecked(i)->refresh();
  58044. }
  58045. }
  58046. ~PropertySectionComponent()
  58047. {
  58048. propertyComps.clear();
  58049. }
  58050. void paint (Graphics& g)
  58051. {
  58052. if (titleHeight > 0)
  58053. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58054. }
  58055. void resized()
  58056. {
  58057. int y = titleHeight;
  58058. for (int i = 0; i < propertyComps.size(); ++i)
  58059. {
  58060. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  58061. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  58062. y = pec->getBottom();
  58063. }
  58064. }
  58065. int getPreferredHeight() const
  58066. {
  58067. int y = titleHeight;
  58068. if (isOpen())
  58069. {
  58070. for (int i = propertyComps.size(); --i >= 0;)
  58071. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  58072. }
  58073. return y;
  58074. }
  58075. void setOpen (const bool open)
  58076. {
  58077. if (sectionIsOpen != open)
  58078. {
  58079. sectionIsOpen = open;
  58080. for (int i = propertyComps.size(); --i >= 0;)
  58081. propertyComps.getUnchecked(i)->setVisible (open);
  58082. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58083. if (pp != 0)
  58084. pp->resized();
  58085. }
  58086. }
  58087. bool isOpen() const
  58088. {
  58089. return sectionIsOpen;
  58090. }
  58091. void refreshAll() const
  58092. {
  58093. for (int i = propertyComps.size(); --i >= 0;)
  58094. propertyComps.getUnchecked (i)->refresh();
  58095. }
  58096. void mouseUp (const MouseEvent& e)
  58097. {
  58098. if (e.getMouseDownX() < titleHeight
  58099. && e.x < titleHeight
  58100. && e.y < titleHeight
  58101. && e.getNumberOfClicks() != 2)
  58102. {
  58103. setOpen (! isOpen());
  58104. }
  58105. }
  58106. void mouseDoubleClick (const MouseEvent& e)
  58107. {
  58108. if (e.y < titleHeight)
  58109. setOpen (! isOpen());
  58110. }
  58111. private:
  58112. OwnedArray <PropertyComponent> propertyComps;
  58113. int titleHeight;
  58114. bool sectionIsOpen;
  58115. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58116. };
  58117. class PropertyPanel::PropertyHolderComponent : public Component
  58118. {
  58119. public:
  58120. PropertyHolderComponent() {}
  58121. void paint (Graphics&) {}
  58122. void updateLayout (int width)
  58123. {
  58124. int y = 0;
  58125. for (int i = 0; i < sections.size(); ++i)
  58126. {
  58127. PropertySectionComponent* const section = sections.getUnchecked(i);
  58128. section->setBounds (0, y, width, section->getPreferredHeight());
  58129. y = section->getBottom();
  58130. }
  58131. setSize (width, y);
  58132. repaint();
  58133. }
  58134. void refreshAll() const
  58135. {
  58136. for (int i = 0; i < sections.size(); ++i)
  58137. sections.getUnchecked(i)->refreshAll();
  58138. }
  58139. void clear()
  58140. {
  58141. sections.clear();
  58142. }
  58143. void addSection (PropertySectionComponent* newSection)
  58144. {
  58145. sections.add (newSection);
  58146. addAndMakeVisible (newSection, 0);
  58147. }
  58148. int getNumSections() const throw() { return sections.size(); }
  58149. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58150. private:
  58151. OwnedArray<PropertySectionComponent> sections;
  58152. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58153. };
  58154. PropertyPanel::PropertyPanel()
  58155. {
  58156. messageWhenEmpty = TRANS("(nothing selected)");
  58157. addAndMakeVisible (&viewport);
  58158. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58159. viewport.setFocusContainer (true);
  58160. }
  58161. PropertyPanel::~PropertyPanel()
  58162. {
  58163. clear();
  58164. }
  58165. void PropertyPanel::paint (Graphics& g)
  58166. {
  58167. if (propertyHolderComponent->getNumSections() == 0)
  58168. {
  58169. g.setColour (Colours::black.withAlpha (0.5f));
  58170. g.setFont (14.0f);
  58171. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58172. Justification::centred, true);
  58173. }
  58174. }
  58175. void PropertyPanel::resized()
  58176. {
  58177. viewport.setBounds (getLocalBounds());
  58178. updatePropHolderLayout();
  58179. }
  58180. void PropertyPanel::clear()
  58181. {
  58182. if (propertyHolderComponent->getNumSections() > 0)
  58183. {
  58184. propertyHolderComponent->clear();
  58185. repaint();
  58186. }
  58187. }
  58188. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58189. {
  58190. if (propertyHolderComponent->getNumSections() == 0)
  58191. repaint();
  58192. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58193. updatePropHolderLayout();
  58194. }
  58195. void PropertyPanel::addSection (const String& sectionTitle,
  58196. const Array <PropertyComponent*>& newProperties,
  58197. const bool shouldBeOpen)
  58198. {
  58199. jassert (sectionTitle.isNotEmpty());
  58200. if (propertyHolderComponent->getNumSections() == 0)
  58201. repaint();
  58202. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58203. updatePropHolderLayout();
  58204. }
  58205. void PropertyPanel::updatePropHolderLayout() const
  58206. {
  58207. const int maxWidth = viewport.getMaximumVisibleWidth();
  58208. propertyHolderComponent->updateLayout (maxWidth);
  58209. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58210. if (maxWidth != newMaxWidth)
  58211. {
  58212. // need to do this twice because of scrollbars changing the size, etc.
  58213. propertyHolderComponent->updateLayout (newMaxWidth);
  58214. }
  58215. }
  58216. void PropertyPanel::refreshAll() const
  58217. {
  58218. propertyHolderComponent->refreshAll();
  58219. }
  58220. const StringArray PropertyPanel::getSectionNames() const
  58221. {
  58222. StringArray s;
  58223. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58224. {
  58225. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58226. if (section->getName().isNotEmpty())
  58227. s.add (section->getName());
  58228. }
  58229. return s;
  58230. }
  58231. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58232. {
  58233. int index = 0;
  58234. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58235. {
  58236. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58237. if (section->getName().isNotEmpty())
  58238. {
  58239. if (index == sectionIndex)
  58240. return section->isOpen();
  58241. ++index;
  58242. }
  58243. }
  58244. return false;
  58245. }
  58246. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58247. {
  58248. int index = 0;
  58249. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58250. {
  58251. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58252. if (section->getName().isNotEmpty())
  58253. {
  58254. if (index == sectionIndex)
  58255. {
  58256. section->setOpen (shouldBeOpen);
  58257. break;
  58258. }
  58259. ++index;
  58260. }
  58261. }
  58262. }
  58263. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58264. {
  58265. int index = 0;
  58266. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58267. {
  58268. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58269. if (section->getName().isNotEmpty())
  58270. {
  58271. if (index == sectionIndex)
  58272. {
  58273. section->setEnabled (shouldBeEnabled);
  58274. break;
  58275. }
  58276. ++index;
  58277. }
  58278. }
  58279. }
  58280. XmlElement* PropertyPanel::getOpennessState() const
  58281. {
  58282. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58283. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58284. const StringArray sections (getSectionNames());
  58285. for (int i = 0; i < sections.size(); ++i)
  58286. {
  58287. if (sections[i].isNotEmpty())
  58288. {
  58289. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58290. e->setAttribute ("name", sections[i]);
  58291. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58292. }
  58293. }
  58294. return xml;
  58295. }
  58296. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58297. {
  58298. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58299. {
  58300. const StringArray sections (getSectionNames());
  58301. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58302. {
  58303. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58304. e->getBoolAttribute ("open"));
  58305. }
  58306. viewport.setViewPosition (viewport.getViewPositionX(),
  58307. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58308. }
  58309. }
  58310. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58311. {
  58312. if (messageWhenEmpty != newMessage)
  58313. {
  58314. messageWhenEmpty = newMessage;
  58315. repaint();
  58316. }
  58317. }
  58318. const String& PropertyPanel::getMessageWhenEmpty() const
  58319. {
  58320. return messageWhenEmpty;
  58321. }
  58322. END_JUCE_NAMESPACE
  58323. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58324. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58325. BEGIN_JUCE_NAMESPACE
  58326. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58327. const double rangeMin,
  58328. const double rangeMax,
  58329. const double interval,
  58330. const double skewFactor)
  58331. : PropertyComponent (name)
  58332. {
  58333. addAndMakeVisible (&slider);
  58334. slider.setRange (rangeMin, rangeMax, interval);
  58335. slider.setSkewFactor (skewFactor);
  58336. slider.setSliderStyle (Slider::LinearBar);
  58337. slider.addListener (this);
  58338. }
  58339. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58340. const String& name,
  58341. const double rangeMin,
  58342. const double rangeMax,
  58343. const double interval,
  58344. const double skewFactor)
  58345. : PropertyComponent (name)
  58346. {
  58347. addAndMakeVisible (&slider);
  58348. slider.setRange (rangeMin, rangeMax, interval);
  58349. slider.setSkewFactor (skewFactor);
  58350. slider.setSliderStyle (Slider::LinearBar);
  58351. slider.getValueObject().referTo (valueToControl);
  58352. }
  58353. SliderPropertyComponent::~SliderPropertyComponent()
  58354. {
  58355. }
  58356. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58357. {
  58358. }
  58359. double SliderPropertyComponent::getValue() const
  58360. {
  58361. return slider.getValue();
  58362. }
  58363. void SliderPropertyComponent::refresh()
  58364. {
  58365. slider.setValue (getValue(), false);
  58366. }
  58367. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58368. {
  58369. if (getValue() != slider.getValue())
  58370. setValue (slider.getValue());
  58371. }
  58372. END_JUCE_NAMESPACE
  58373. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58374. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58375. BEGIN_JUCE_NAMESPACE
  58376. class TextPropLabel : public Label
  58377. {
  58378. public:
  58379. TextPropLabel (TextPropertyComponent& owner_,
  58380. const int maxChars_, const bool isMultiline_)
  58381. : Label (String::empty, String::empty),
  58382. owner (owner_),
  58383. maxChars (maxChars_),
  58384. isMultiline (isMultiline_)
  58385. {
  58386. setEditable (true, true, false);
  58387. setColour (backgroundColourId, Colours::white);
  58388. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58389. }
  58390. TextEditor* createEditorComponent()
  58391. {
  58392. TextEditor* const textEditor = Label::createEditorComponent();
  58393. textEditor->setInputRestrictions (maxChars);
  58394. if (isMultiline)
  58395. {
  58396. textEditor->setMultiLine (true, true);
  58397. textEditor->setReturnKeyStartsNewLine (true);
  58398. }
  58399. return textEditor;
  58400. }
  58401. void textWasEdited()
  58402. {
  58403. owner.textWasEdited();
  58404. }
  58405. private:
  58406. TextPropertyComponent& owner;
  58407. int maxChars;
  58408. bool isMultiline;
  58409. };
  58410. TextPropertyComponent::TextPropertyComponent (const String& name,
  58411. const int maxNumChars,
  58412. const bool isMultiLine)
  58413. : PropertyComponent (name)
  58414. {
  58415. createEditor (maxNumChars, isMultiLine);
  58416. }
  58417. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58418. const String& name,
  58419. const int maxNumChars,
  58420. const bool isMultiLine)
  58421. : PropertyComponent (name)
  58422. {
  58423. createEditor (maxNumChars, isMultiLine);
  58424. textEditor->getTextValue().referTo (valueToControl);
  58425. }
  58426. TextPropertyComponent::~TextPropertyComponent()
  58427. {
  58428. }
  58429. void TextPropertyComponent::setText (const String& newText)
  58430. {
  58431. textEditor->setText (newText, true);
  58432. }
  58433. const String TextPropertyComponent::getText() const
  58434. {
  58435. return textEditor->getText();
  58436. }
  58437. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58438. {
  58439. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58440. if (isMultiLine)
  58441. {
  58442. textEditor->setJustificationType (Justification::topLeft);
  58443. preferredHeight = 120;
  58444. }
  58445. }
  58446. void TextPropertyComponent::refresh()
  58447. {
  58448. textEditor->setText (getText(), false);
  58449. }
  58450. void TextPropertyComponent::textWasEdited()
  58451. {
  58452. const String newText (textEditor->getText());
  58453. if (getText() != newText)
  58454. setText (newText);
  58455. }
  58456. END_JUCE_NAMESPACE
  58457. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58458. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58459. BEGIN_JUCE_NAMESPACE
  58460. class SimpleDeviceManagerInputLevelMeter : public Component,
  58461. public Timer
  58462. {
  58463. public:
  58464. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58465. : manager (manager_),
  58466. level (0)
  58467. {
  58468. startTimer (50);
  58469. manager->enableInputLevelMeasurement (true);
  58470. }
  58471. ~SimpleDeviceManagerInputLevelMeter()
  58472. {
  58473. manager->enableInputLevelMeasurement (false);
  58474. }
  58475. void timerCallback()
  58476. {
  58477. const float newLevel = (float) manager->getCurrentInputLevel();
  58478. if (std::abs (level - newLevel) > 0.005f)
  58479. {
  58480. level = newLevel;
  58481. repaint();
  58482. }
  58483. }
  58484. void paint (Graphics& g)
  58485. {
  58486. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58487. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58488. }
  58489. private:
  58490. AudioDeviceManager* const manager;
  58491. float level;
  58492. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58493. };
  58494. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58495. public ListBoxModel
  58496. {
  58497. public:
  58498. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58499. const String& noItemsMessage_,
  58500. const int minNumber_,
  58501. const int maxNumber_)
  58502. : ListBox (String::empty, 0),
  58503. deviceManager (deviceManager_),
  58504. noItemsMessage (noItemsMessage_),
  58505. minNumber (minNumber_),
  58506. maxNumber (maxNumber_)
  58507. {
  58508. items = MidiInput::getDevices();
  58509. setModel (this);
  58510. setOutlineThickness (1);
  58511. }
  58512. ~MidiInputSelectorComponentListBox()
  58513. {
  58514. }
  58515. int getNumRows()
  58516. {
  58517. return items.size();
  58518. }
  58519. void paintListBoxItem (int row,
  58520. Graphics& g,
  58521. int width, int height,
  58522. bool rowIsSelected)
  58523. {
  58524. if (isPositiveAndBelow (row, items.size()))
  58525. {
  58526. if (rowIsSelected)
  58527. g.fillAll (findColour (TextEditor::highlightColourId)
  58528. .withMultipliedAlpha (0.3f));
  58529. const String item (items [row]);
  58530. bool enabled = deviceManager.isMidiInputEnabled (item);
  58531. const int x = getTickX();
  58532. const float tickW = height * 0.75f;
  58533. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58534. enabled, true, true, false);
  58535. g.setFont (height * 0.6f);
  58536. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58537. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58538. }
  58539. }
  58540. void listBoxItemClicked (int row, const MouseEvent& e)
  58541. {
  58542. selectRow (row);
  58543. if (e.x < getTickX())
  58544. flipEnablement (row);
  58545. }
  58546. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58547. {
  58548. flipEnablement (row);
  58549. }
  58550. void returnKeyPressed (int row)
  58551. {
  58552. flipEnablement (row);
  58553. }
  58554. void paint (Graphics& g)
  58555. {
  58556. ListBox::paint (g);
  58557. if (items.size() == 0)
  58558. {
  58559. g.setColour (Colours::grey);
  58560. g.setFont (13.0f);
  58561. g.drawText (noItemsMessage,
  58562. 0, 0, getWidth(), getHeight() / 2,
  58563. Justification::centred, true);
  58564. }
  58565. }
  58566. int getBestHeight (const int preferredHeight)
  58567. {
  58568. const int extra = getOutlineThickness() * 2;
  58569. return jmax (getRowHeight() * 2 + extra,
  58570. jmin (getRowHeight() * getNumRows() + extra,
  58571. preferredHeight));
  58572. }
  58573. private:
  58574. AudioDeviceManager& deviceManager;
  58575. const String noItemsMessage;
  58576. StringArray items;
  58577. int minNumber, maxNumber;
  58578. void flipEnablement (const int row)
  58579. {
  58580. if (isPositiveAndBelow (row, items.size()))
  58581. {
  58582. const String item (items [row]);
  58583. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58584. }
  58585. }
  58586. int getTickX() const
  58587. {
  58588. return getRowHeight() + 5;
  58589. }
  58590. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58591. };
  58592. class AudioDeviceSettingsPanel : public Component,
  58593. public ChangeListener,
  58594. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58595. public ButtonListener
  58596. {
  58597. public:
  58598. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58599. AudioIODeviceType::DeviceSetupDetails& setup_,
  58600. const bool hideAdvancedOptionsWithButton)
  58601. : type (type_),
  58602. setup (setup_)
  58603. {
  58604. if (hideAdvancedOptionsWithButton)
  58605. {
  58606. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58607. showAdvancedSettingsButton->addListener (this);
  58608. }
  58609. type->scanForDevices();
  58610. setup.manager->addChangeListener (this);
  58611. changeListenerCallback (0);
  58612. }
  58613. ~AudioDeviceSettingsPanel()
  58614. {
  58615. setup.manager->removeChangeListener (this);
  58616. }
  58617. void resized()
  58618. {
  58619. const int lx = proportionOfWidth (0.35f);
  58620. const int w = proportionOfWidth (0.4f);
  58621. const int h = 24;
  58622. const int space = 6;
  58623. const int dh = h + space;
  58624. int y = 0;
  58625. if (outputDeviceDropDown != 0)
  58626. {
  58627. outputDeviceDropDown->setBounds (lx, y, w, h);
  58628. if (testButton != 0)
  58629. testButton->setBounds (proportionOfWidth (0.77f),
  58630. outputDeviceDropDown->getY(),
  58631. proportionOfWidth (0.18f),
  58632. h);
  58633. y += dh;
  58634. }
  58635. if (inputDeviceDropDown != 0)
  58636. {
  58637. inputDeviceDropDown->setBounds (lx, y, w, h);
  58638. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58639. inputDeviceDropDown->getY(),
  58640. proportionOfWidth (0.18f),
  58641. h);
  58642. y += dh;
  58643. }
  58644. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58645. if (outputChanList != 0)
  58646. {
  58647. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58648. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58649. y += bh + space;
  58650. }
  58651. if (inputChanList != 0)
  58652. {
  58653. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58654. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58655. y += bh + space;
  58656. }
  58657. y += space * 2;
  58658. if (showAdvancedSettingsButton != 0)
  58659. {
  58660. showAdvancedSettingsButton->changeWidthToFitText (h);
  58661. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58662. }
  58663. if (sampleRateDropDown != 0)
  58664. {
  58665. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58666. || ! showAdvancedSettingsButton->isVisible());
  58667. sampleRateDropDown->setBounds (lx, y, w, h);
  58668. y += dh;
  58669. }
  58670. if (bufferSizeDropDown != 0)
  58671. {
  58672. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58673. || ! showAdvancedSettingsButton->isVisible());
  58674. bufferSizeDropDown->setBounds (lx, y, w, h);
  58675. y += dh;
  58676. }
  58677. if (showUIButton != 0)
  58678. {
  58679. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58680. || ! showAdvancedSettingsButton->isVisible());
  58681. showUIButton->changeWidthToFitText (h);
  58682. showUIButton->setTopLeftPosition (lx, y);
  58683. }
  58684. }
  58685. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58686. {
  58687. if (comboBoxThatHasChanged == 0)
  58688. return;
  58689. AudioDeviceManager::AudioDeviceSetup config;
  58690. setup.manager->getAudioDeviceSetup (config);
  58691. String error;
  58692. if (comboBoxThatHasChanged == outputDeviceDropDown
  58693. || comboBoxThatHasChanged == inputDeviceDropDown)
  58694. {
  58695. if (outputDeviceDropDown != 0)
  58696. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58697. : outputDeviceDropDown->getText();
  58698. if (inputDeviceDropDown != 0)
  58699. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58700. : inputDeviceDropDown->getText();
  58701. if (! type->hasSeparateInputsAndOutputs())
  58702. config.inputDeviceName = config.outputDeviceName;
  58703. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58704. config.useDefaultInputChannels = true;
  58705. else
  58706. config.useDefaultOutputChannels = true;
  58707. error = setup.manager->setAudioDeviceSetup (config, true);
  58708. showCorrectDeviceName (inputDeviceDropDown, true);
  58709. showCorrectDeviceName (outputDeviceDropDown, false);
  58710. updateControlPanelButton();
  58711. resized();
  58712. }
  58713. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58714. {
  58715. if (sampleRateDropDown->getSelectedId() > 0)
  58716. {
  58717. config.sampleRate = sampleRateDropDown->getSelectedId();
  58718. error = setup.manager->setAudioDeviceSetup (config, true);
  58719. }
  58720. }
  58721. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58722. {
  58723. if (bufferSizeDropDown->getSelectedId() > 0)
  58724. {
  58725. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58726. error = setup.manager->setAudioDeviceSetup (config, true);
  58727. }
  58728. }
  58729. if (error.isNotEmpty())
  58730. {
  58731. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58732. "Error when trying to open audio device!",
  58733. error);
  58734. }
  58735. }
  58736. void buttonClicked (Button* button)
  58737. {
  58738. if (button == showAdvancedSettingsButton)
  58739. {
  58740. showAdvancedSettingsButton->setVisible (false);
  58741. resized();
  58742. }
  58743. else if (button == showUIButton)
  58744. {
  58745. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58746. if (device != 0 && device->showControlPanel())
  58747. {
  58748. setup.manager->closeAudioDevice();
  58749. setup.manager->restartLastAudioDevice();
  58750. getTopLevelComponent()->toFront (true);
  58751. }
  58752. }
  58753. else if (button == testButton && testButton != 0)
  58754. {
  58755. setup.manager->playTestSound();
  58756. }
  58757. }
  58758. void updateControlPanelButton()
  58759. {
  58760. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58761. showUIButton = 0;
  58762. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58763. {
  58764. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58765. TRANS ("opens the device's own control panel")));
  58766. showUIButton->addListener (this);
  58767. }
  58768. resized();
  58769. }
  58770. void changeListenerCallback (ChangeBroadcaster*)
  58771. {
  58772. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58773. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58774. {
  58775. if (outputDeviceDropDown == 0)
  58776. {
  58777. outputDeviceDropDown = new ComboBox (String::empty);
  58778. outputDeviceDropDown->addListener (this);
  58779. addAndMakeVisible (outputDeviceDropDown);
  58780. outputDeviceLabel = new Label (String::empty,
  58781. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58782. : TRANS ("device:"));
  58783. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58784. if (setup.maxNumOutputChannels > 0)
  58785. {
  58786. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58787. testButton->addListener (this);
  58788. }
  58789. }
  58790. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58791. }
  58792. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58793. {
  58794. if (inputDeviceDropDown == 0)
  58795. {
  58796. inputDeviceDropDown = new ComboBox (String::empty);
  58797. inputDeviceDropDown->addListener (this);
  58798. addAndMakeVisible (inputDeviceDropDown);
  58799. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58800. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58801. addAndMakeVisible (inputLevelMeter
  58802. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58803. }
  58804. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58805. }
  58806. updateControlPanelButton();
  58807. showCorrectDeviceName (inputDeviceDropDown, true);
  58808. showCorrectDeviceName (outputDeviceDropDown, false);
  58809. if (currentDevice != 0)
  58810. {
  58811. if (setup.maxNumOutputChannels > 0
  58812. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58813. {
  58814. if (outputChanList == 0)
  58815. {
  58816. addAndMakeVisible (outputChanList
  58817. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58818. TRANS ("(no audio output channels found)")));
  58819. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58820. outputChanLabel->attachToComponent (outputChanList, true);
  58821. }
  58822. outputChanList->refresh();
  58823. }
  58824. else
  58825. {
  58826. outputChanLabel = 0;
  58827. outputChanList = 0;
  58828. }
  58829. if (setup.maxNumInputChannels > 0
  58830. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58831. {
  58832. if (inputChanList == 0)
  58833. {
  58834. addAndMakeVisible (inputChanList
  58835. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58836. TRANS ("(no audio input channels found)")));
  58837. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58838. inputChanLabel->attachToComponent (inputChanList, true);
  58839. }
  58840. inputChanList->refresh();
  58841. }
  58842. else
  58843. {
  58844. inputChanLabel = 0;
  58845. inputChanList = 0;
  58846. }
  58847. // sample rate..
  58848. {
  58849. if (sampleRateDropDown == 0)
  58850. {
  58851. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58852. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58853. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58854. }
  58855. else
  58856. {
  58857. sampleRateDropDown->clear();
  58858. sampleRateDropDown->removeListener (this);
  58859. }
  58860. const int numRates = currentDevice->getNumSampleRates();
  58861. for (int i = 0; i < numRates; ++i)
  58862. {
  58863. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58864. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58865. }
  58866. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58867. sampleRateDropDown->addListener (this);
  58868. }
  58869. // buffer size
  58870. {
  58871. if (bufferSizeDropDown == 0)
  58872. {
  58873. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58874. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58875. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58876. }
  58877. else
  58878. {
  58879. bufferSizeDropDown->clear();
  58880. bufferSizeDropDown->removeListener (this);
  58881. }
  58882. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58883. double currentRate = currentDevice->getCurrentSampleRate();
  58884. if (currentRate == 0)
  58885. currentRate = 48000.0;
  58886. for (int i = 0; i < numBufferSizes; ++i)
  58887. {
  58888. const int bs = currentDevice->getBufferSizeSamples (i);
  58889. bufferSizeDropDown->addItem (String (bs)
  58890. + " samples ("
  58891. + String (bs * 1000.0 / currentRate, 1)
  58892. + " ms)",
  58893. bs);
  58894. }
  58895. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58896. bufferSizeDropDown->addListener (this);
  58897. }
  58898. }
  58899. else
  58900. {
  58901. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58902. sampleRateLabel = 0;
  58903. bufferSizeLabel = 0;
  58904. sampleRateDropDown = 0;
  58905. bufferSizeDropDown = 0;
  58906. if (outputDeviceDropDown != 0)
  58907. outputDeviceDropDown->setSelectedId (-1, true);
  58908. if (inputDeviceDropDown != 0)
  58909. inputDeviceDropDown->setSelectedId (-1, true);
  58910. }
  58911. resized();
  58912. setSize (getWidth(), getLowestY() + 4);
  58913. }
  58914. private:
  58915. AudioIODeviceType* const type;
  58916. const AudioIODeviceType::DeviceSetupDetails setup;
  58917. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58918. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58919. ScopedPointer<TextButton> testButton;
  58920. ScopedPointer<Component> inputLevelMeter;
  58921. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58922. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58923. {
  58924. if (box != 0)
  58925. {
  58926. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58927. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58928. box->setSelectedId (index + 1, true);
  58929. if (testButton != 0 && ! isInput)
  58930. testButton->setEnabled (index >= 0);
  58931. }
  58932. }
  58933. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58934. {
  58935. const StringArray devs (type->getDeviceNames (isInputs));
  58936. combo.clear (true);
  58937. for (int i = 0; i < devs.size(); ++i)
  58938. combo.addItem (devs[i], i + 1);
  58939. combo.addItem (TRANS("<< none >>"), -1);
  58940. combo.setSelectedId (-1, true);
  58941. }
  58942. int getLowestY() const
  58943. {
  58944. int y = 0;
  58945. for (int i = getNumChildComponents(); --i >= 0;)
  58946. y = jmax (y, getChildComponent (i)->getBottom());
  58947. return y;
  58948. }
  58949. public:
  58950. class ChannelSelectorListBox : public ListBox,
  58951. public ListBoxModel
  58952. {
  58953. public:
  58954. enum BoxType
  58955. {
  58956. audioInputType,
  58957. audioOutputType
  58958. };
  58959. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58960. const BoxType type_,
  58961. const String& noItemsMessage_)
  58962. : ListBox (String::empty, 0),
  58963. setup (setup_),
  58964. type (type_),
  58965. noItemsMessage (noItemsMessage_)
  58966. {
  58967. refresh();
  58968. setModel (this);
  58969. setOutlineThickness (1);
  58970. }
  58971. ~ChannelSelectorListBox()
  58972. {
  58973. }
  58974. void refresh()
  58975. {
  58976. items.clear();
  58977. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58978. if (currentDevice != 0)
  58979. {
  58980. if (type == audioInputType)
  58981. items = currentDevice->getInputChannelNames();
  58982. else if (type == audioOutputType)
  58983. items = currentDevice->getOutputChannelNames();
  58984. if (setup.useStereoPairs)
  58985. {
  58986. StringArray pairs;
  58987. for (int i = 0; i < items.size(); i += 2)
  58988. {
  58989. const String name (items[i]);
  58990. const String name2 (items[i + 1]);
  58991. String commonBit;
  58992. for (int j = 0; j < name.length(); ++j)
  58993. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58994. commonBit = name.substring (0, j);
  58995. // Make sure we only split the name at a space, because otherwise, things
  58996. // like "input 11" + "input 12" would become "input 11 + 2"
  58997. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58998. commonBit = commonBit.dropLastCharacters (1);
  58999. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59000. }
  59001. items = pairs;
  59002. }
  59003. }
  59004. updateContent();
  59005. repaint();
  59006. }
  59007. int getNumRows()
  59008. {
  59009. return items.size();
  59010. }
  59011. void paintListBoxItem (int row,
  59012. Graphics& g,
  59013. int width, int height,
  59014. bool rowIsSelected)
  59015. {
  59016. if (isPositiveAndBelow (row, items.size()))
  59017. {
  59018. if (rowIsSelected)
  59019. g.fillAll (findColour (TextEditor::highlightColourId)
  59020. .withMultipliedAlpha (0.3f));
  59021. const String item (items [row]);
  59022. bool enabled = false;
  59023. AudioDeviceManager::AudioDeviceSetup config;
  59024. setup.manager->getAudioDeviceSetup (config);
  59025. if (setup.useStereoPairs)
  59026. {
  59027. if (type == audioInputType)
  59028. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59029. else if (type == audioOutputType)
  59030. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59031. }
  59032. else
  59033. {
  59034. if (type == audioInputType)
  59035. enabled = config.inputChannels [row];
  59036. else if (type == audioOutputType)
  59037. enabled = config.outputChannels [row];
  59038. }
  59039. const int x = getTickX();
  59040. const float tickW = height * 0.75f;
  59041. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59042. enabled, true, true, false);
  59043. g.setFont (height * 0.6f);
  59044. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59045. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59046. }
  59047. }
  59048. void listBoxItemClicked (int row, const MouseEvent& e)
  59049. {
  59050. selectRow (row);
  59051. if (e.x < getTickX())
  59052. flipEnablement (row);
  59053. }
  59054. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59055. {
  59056. flipEnablement (row);
  59057. }
  59058. void returnKeyPressed (int row)
  59059. {
  59060. flipEnablement (row);
  59061. }
  59062. void paint (Graphics& g)
  59063. {
  59064. ListBox::paint (g);
  59065. if (items.size() == 0)
  59066. {
  59067. g.setColour (Colours::grey);
  59068. g.setFont (13.0f);
  59069. g.drawText (noItemsMessage,
  59070. 0, 0, getWidth(), getHeight() / 2,
  59071. Justification::centred, true);
  59072. }
  59073. }
  59074. int getBestHeight (int maxHeight)
  59075. {
  59076. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59077. getNumRows())
  59078. + getOutlineThickness() * 2;
  59079. }
  59080. private:
  59081. const AudioIODeviceType::DeviceSetupDetails setup;
  59082. const BoxType type;
  59083. const String noItemsMessage;
  59084. StringArray items;
  59085. void flipEnablement (const int row)
  59086. {
  59087. jassert (type == audioInputType || type == audioOutputType);
  59088. if (isPositiveAndBelow (row, items.size()))
  59089. {
  59090. AudioDeviceManager::AudioDeviceSetup config;
  59091. setup.manager->getAudioDeviceSetup (config);
  59092. if (setup.useStereoPairs)
  59093. {
  59094. BigInteger bits;
  59095. BigInteger& original = (type == audioInputType ? config.inputChannels
  59096. : config.outputChannels);
  59097. int i;
  59098. for (i = 0; i < 256; i += 2)
  59099. bits.setBit (i / 2, original [i] || original [i + 1]);
  59100. if (type == audioInputType)
  59101. {
  59102. config.useDefaultInputChannels = false;
  59103. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59104. }
  59105. else
  59106. {
  59107. config.useDefaultOutputChannels = false;
  59108. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59109. }
  59110. for (i = 0; i < 256; ++i)
  59111. original.setBit (i, bits [i / 2]);
  59112. }
  59113. else
  59114. {
  59115. if (type == audioInputType)
  59116. {
  59117. config.useDefaultInputChannels = false;
  59118. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59119. }
  59120. else
  59121. {
  59122. config.useDefaultOutputChannels = false;
  59123. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59124. }
  59125. }
  59126. String error (setup.manager->setAudioDeviceSetup (config, true));
  59127. if (! error.isEmpty())
  59128. {
  59129. //xxx
  59130. }
  59131. }
  59132. }
  59133. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59134. {
  59135. const int numActive = chans.countNumberOfSetBits();
  59136. if (chans [index])
  59137. {
  59138. if (numActive > minNumber)
  59139. chans.setBit (index, false);
  59140. }
  59141. else
  59142. {
  59143. if (numActive >= maxNumber)
  59144. {
  59145. const int firstActiveChan = chans.findNextSetBit();
  59146. chans.setBit (index > firstActiveChan
  59147. ? firstActiveChan : chans.getHighestBit(),
  59148. false);
  59149. }
  59150. chans.setBit (index, true);
  59151. }
  59152. }
  59153. int getTickX() const
  59154. {
  59155. return getRowHeight() + 5;
  59156. }
  59157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59158. };
  59159. private:
  59160. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59161. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59162. };
  59163. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59164. const int minInputChannels_,
  59165. const int maxInputChannels_,
  59166. const int minOutputChannels_,
  59167. const int maxOutputChannels_,
  59168. const bool showMidiInputOptions,
  59169. const bool showMidiOutputSelector,
  59170. const bool showChannelsAsStereoPairs_,
  59171. const bool hideAdvancedOptionsWithButton_)
  59172. : deviceManager (deviceManager_),
  59173. deviceTypeDropDown (0),
  59174. deviceTypeDropDownLabel (0),
  59175. minOutputChannels (minOutputChannels_),
  59176. maxOutputChannels (maxOutputChannels_),
  59177. minInputChannels (minInputChannels_),
  59178. maxInputChannels (maxInputChannels_),
  59179. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59180. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59181. {
  59182. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59183. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59184. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59185. {
  59186. deviceTypeDropDown = new ComboBox (String::empty);
  59187. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59188. {
  59189. deviceTypeDropDown
  59190. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59191. i + 1);
  59192. }
  59193. addAndMakeVisible (deviceTypeDropDown);
  59194. deviceTypeDropDown->addListener (this);
  59195. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59196. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59197. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59198. }
  59199. if (showMidiInputOptions)
  59200. {
  59201. addAndMakeVisible (midiInputsList
  59202. = new MidiInputSelectorComponentListBox (deviceManager,
  59203. TRANS("(no midi inputs available)"),
  59204. 0, 0));
  59205. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59206. midiInputsLabel->setJustificationType (Justification::topRight);
  59207. midiInputsLabel->attachToComponent (midiInputsList, true);
  59208. }
  59209. else
  59210. {
  59211. midiInputsList = 0;
  59212. midiInputsLabel = 0;
  59213. }
  59214. if (showMidiOutputSelector)
  59215. {
  59216. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59217. midiOutputSelector->addListener (this);
  59218. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59219. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59220. }
  59221. else
  59222. {
  59223. midiOutputSelector = 0;
  59224. midiOutputLabel = 0;
  59225. }
  59226. deviceManager_.addChangeListener (this);
  59227. changeListenerCallback (0);
  59228. }
  59229. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59230. {
  59231. deviceManager.removeChangeListener (this);
  59232. }
  59233. void AudioDeviceSelectorComponent::resized()
  59234. {
  59235. const int lx = proportionOfWidth (0.35f);
  59236. const int w = proportionOfWidth (0.4f);
  59237. const int h = 24;
  59238. const int space = 6;
  59239. const int dh = h + space;
  59240. int y = 15;
  59241. if (deviceTypeDropDown != 0)
  59242. {
  59243. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59244. y += dh + space * 2;
  59245. }
  59246. if (audioDeviceSettingsComp != 0)
  59247. {
  59248. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59249. y += audioDeviceSettingsComp->getHeight() + space;
  59250. }
  59251. if (midiInputsList != 0)
  59252. {
  59253. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59254. midiInputsList->setBounds (lx, y, w, bh);
  59255. y += bh + space;
  59256. }
  59257. if (midiOutputSelector != 0)
  59258. midiOutputSelector->setBounds (lx, y, w, h);
  59259. }
  59260. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59261. {
  59262. if (child == audioDeviceSettingsComp)
  59263. resized();
  59264. }
  59265. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59266. {
  59267. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59268. if (device != 0 && device->hasControlPanel())
  59269. {
  59270. if (device->showControlPanel())
  59271. deviceManager.restartLastAudioDevice();
  59272. getTopLevelComponent()->toFront (true);
  59273. }
  59274. }
  59275. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59276. {
  59277. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59278. {
  59279. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59280. if (type != 0)
  59281. {
  59282. audioDeviceSettingsComp = 0;
  59283. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59284. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59285. }
  59286. }
  59287. else if (comboBoxThatHasChanged == midiOutputSelector)
  59288. {
  59289. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59290. }
  59291. }
  59292. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59293. {
  59294. if (deviceTypeDropDown != 0)
  59295. {
  59296. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59297. }
  59298. if (audioDeviceSettingsComp == 0
  59299. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59300. {
  59301. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59302. audioDeviceSettingsComp = 0;
  59303. AudioIODeviceType* const type
  59304. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59305. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59306. if (type != 0)
  59307. {
  59308. AudioIODeviceType::DeviceSetupDetails details;
  59309. details.manager = &deviceManager;
  59310. details.minNumInputChannels = minInputChannels;
  59311. details.maxNumInputChannels = maxInputChannels;
  59312. details.minNumOutputChannels = minOutputChannels;
  59313. details.maxNumOutputChannels = maxOutputChannels;
  59314. details.useStereoPairs = showChannelsAsStereoPairs;
  59315. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59316. if (audioDeviceSettingsComp != 0)
  59317. {
  59318. addAndMakeVisible (audioDeviceSettingsComp);
  59319. audioDeviceSettingsComp->resized();
  59320. }
  59321. }
  59322. }
  59323. if (midiInputsList != 0)
  59324. {
  59325. midiInputsList->updateContent();
  59326. midiInputsList->repaint();
  59327. }
  59328. if (midiOutputSelector != 0)
  59329. {
  59330. midiOutputSelector->clear();
  59331. const StringArray midiOuts (MidiOutput::getDevices());
  59332. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59333. midiOutputSelector->addSeparator();
  59334. for (int i = 0; i < midiOuts.size(); ++i)
  59335. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59336. int current = -1;
  59337. if (deviceManager.getDefaultMidiOutput() != 0)
  59338. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59339. midiOutputSelector->setSelectedId (current, true);
  59340. }
  59341. resized();
  59342. }
  59343. END_JUCE_NAMESPACE
  59344. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59345. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59346. BEGIN_JUCE_NAMESPACE
  59347. BubbleComponent::BubbleComponent()
  59348. : side (0),
  59349. allowablePlacements (above | below | left | right),
  59350. arrowTipX (0.0f),
  59351. arrowTipY (0.0f)
  59352. {
  59353. setInterceptsMouseClicks (false, false);
  59354. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59355. setComponentEffect (&shadow);
  59356. }
  59357. BubbleComponent::~BubbleComponent()
  59358. {
  59359. }
  59360. void BubbleComponent::paint (Graphics& g)
  59361. {
  59362. int x = content.getX();
  59363. int y = content.getY();
  59364. int w = content.getWidth();
  59365. int h = content.getHeight();
  59366. int cw, ch;
  59367. getContentSize (cw, ch);
  59368. if (side == 3)
  59369. x += w - cw;
  59370. else if (side != 1)
  59371. x += (w - cw) / 2;
  59372. w = cw;
  59373. if (side == 2)
  59374. y += h - ch;
  59375. else if (side != 0)
  59376. y += (h - ch) / 2;
  59377. h = ch;
  59378. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59379. (float) x, (float) y,
  59380. (float) w, (float) h);
  59381. const int cx = x + (w - cw) / 2;
  59382. const int cy = y + (h - ch) / 2;
  59383. const int indent = 3;
  59384. g.setOrigin (cx + indent, cy + indent);
  59385. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59386. paintContent (g, cw - indent * 2, ch - indent * 2);
  59387. }
  59388. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59389. {
  59390. allowablePlacements = newPlacement;
  59391. }
  59392. void BubbleComponent::setPosition (Component* componentToPointTo)
  59393. {
  59394. jassert (componentToPointTo != 0);
  59395. Point<int> pos;
  59396. if (getParentComponent() != 0)
  59397. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59398. else
  59399. pos = componentToPointTo->localPointToGlobal (pos);
  59400. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59401. }
  59402. void BubbleComponent::setPosition (const int arrowTipX_,
  59403. const int arrowTipY_)
  59404. {
  59405. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59406. }
  59407. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59408. {
  59409. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59410. : getParentMonitorArea());
  59411. int x = 0;
  59412. int y = 0;
  59413. int w = 150;
  59414. int h = 30;
  59415. getContentSize (w, h);
  59416. w += 30;
  59417. h += 30;
  59418. const float edgeIndent = 2.0f;
  59419. const int arrowLength = jmin (10, h / 3, w / 3);
  59420. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59421. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59422. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59423. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59424. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59425. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59426. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59427. {
  59428. spaceLeft = spaceRight = 0;
  59429. }
  59430. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59431. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59432. {
  59433. spaceAbove = spaceBelow = 0;
  59434. }
  59435. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59436. {
  59437. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59438. arrowTipX = w * 0.5f;
  59439. content.setSize (w, h - arrowLength);
  59440. if (spaceAbove >= spaceBelow)
  59441. {
  59442. // above
  59443. y = rectangleToPointTo.getY() - h;
  59444. content.setPosition (0, 0);
  59445. arrowTipY = h - edgeIndent;
  59446. side = 2;
  59447. }
  59448. else
  59449. {
  59450. // below
  59451. y = rectangleToPointTo.getBottom();
  59452. content.setPosition (0, arrowLength);
  59453. arrowTipY = edgeIndent;
  59454. side = 0;
  59455. }
  59456. }
  59457. else
  59458. {
  59459. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59460. arrowTipY = h * 0.5f;
  59461. content.setSize (w - arrowLength, h);
  59462. if (spaceLeft > spaceRight)
  59463. {
  59464. // on the left
  59465. x = rectangleToPointTo.getX() - w;
  59466. content.setPosition (0, 0);
  59467. arrowTipX = w - edgeIndent;
  59468. side = 3;
  59469. }
  59470. else
  59471. {
  59472. // on the right
  59473. x = rectangleToPointTo.getRight();
  59474. content.setPosition (arrowLength, 0);
  59475. arrowTipX = edgeIndent;
  59476. side = 1;
  59477. }
  59478. }
  59479. setBounds (x, y, w, h);
  59480. }
  59481. END_JUCE_NAMESPACE
  59482. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59483. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59484. BEGIN_JUCE_NAMESPACE
  59485. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59486. : fadeOutLength (fadeOutLengthMs),
  59487. deleteAfterUse (false)
  59488. {
  59489. }
  59490. BubbleMessageComponent::~BubbleMessageComponent()
  59491. {
  59492. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59493. }
  59494. void BubbleMessageComponent::showAt (int x, int y,
  59495. const String& text,
  59496. const int numMillisecondsBeforeRemoving,
  59497. const bool removeWhenMouseClicked,
  59498. const bool deleteSelfAfterUse)
  59499. {
  59500. textLayout.clear();
  59501. textLayout.setText (text, Font (14.0f));
  59502. textLayout.layout (256, Justification::centredLeft, true);
  59503. setPosition (x, y);
  59504. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59505. }
  59506. void BubbleMessageComponent::showAt (Component* const component,
  59507. const String& text,
  59508. const int numMillisecondsBeforeRemoving,
  59509. const bool removeWhenMouseClicked,
  59510. const bool deleteSelfAfterUse)
  59511. {
  59512. textLayout.clear();
  59513. textLayout.setText (text, Font (14.0f));
  59514. textLayout.layout (256, Justification::centredLeft, true);
  59515. setPosition (component);
  59516. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59517. }
  59518. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59519. const bool removeWhenMouseClicked,
  59520. const bool deleteSelfAfterUse)
  59521. {
  59522. setVisible (true);
  59523. deleteAfterUse = deleteSelfAfterUse;
  59524. if (numMillisecondsBeforeRemoving > 0)
  59525. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59526. else
  59527. expiryTime = 0;
  59528. startTimer (77);
  59529. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59530. if (! (removeWhenMouseClicked && isShowing()))
  59531. mouseClickCounter += 0xfffff;
  59532. repaint();
  59533. }
  59534. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59535. {
  59536. w = textLayout.getWidth() + 16;
  59537. h = textLayout.getHeight() + 16;
  59538. }
  59539. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59540. {
  59541. g.setColour (findColour (TooltipWindow::textColourId));
  59542. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59543. }
  59544. void BubbleMessageComponent::timerCallback()
  59545. {
  59546. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59547. {
  59548. stopTimer();
  59549. setVisible (false);
  59550. if (deleteAfterUse)
  59551. delete this;
  59552. }
  59553. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59554. {
  59555. stopTimer();
  59556. if (deleteAfterUse)
  59557. delete this;
  59558. else
  59559. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59560. }
  59561. }
  59562. END_JUCE_NAMESPACE
  59563. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59564. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59565. BEGIN_JUCE_NAMESPACE
  59566. class ColourComponentSlider : public Slider
  59567. {
  59568. public:
  59569. ColourComponentSlider (const String& name)
  59570. : Slider (name)
  59571. {
  59572. setRange (0.0, 255.0, 1.0);
  59573. }
  59574. const String getTextFromValue (double value)
  59575. {
  59576. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59577. }
  59578. double getValueFromText (const String& text)
  59579. {
  59580. return (double) text.getHexValue32();
  59581. }
  59582. private:
  59583. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59584. };
  59585. class ColourSpaceMarker : public Component
  59586. {
  59587. public:
  59588. ColourSpaceMarker()
  59589. {
  59590. setInterceptsMouseClicks (false, false);
  59591. }
  59592. void paint (Graphics& g)
  59593. {
  59594. g.setColour (Colour::greyLevel (0.1f));
  59595. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59596. g.setColour (Colour::greyLevel (0.9f));
  59597. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59598. }
  59599. private:
  59600. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59601. };
  59602. class ColourSelector::ColourSpaceView : public Component
  59603. {
  59604. public:
  59605. ColourSpaceView (ColourSelector& owner_,
  59606. float& h_, float& s_, float& v_,
  59607. const int edgeSize)
  59608. : owner (owner_),
  59609. h (h_), s (s_), v (v_),
  59610. lastHue (0.0f),
  59611. edge (edgeSize)
  59612. {
  59613. addAndMakeVisible (&marker);
  59614. setMouseCursor (MouseCursor::CrosshairCursor);
  59615. }
  59616. void paint (Graphics& g)
  59617. {
  59618. if (colours.isNull())
  59619. {
  59620. const int width = getWidth() / 2;
  59621. const int height = getHeight() / 2;
  59622. colours = Image (Image::RGB, width, height, false);
  59623. Image::BitmapData pixels (colours, true);
  59624. for (int y = 0; y < height; ++y)
  59625. {
  59626. const float val = 1.0f - y / (float) height;
  59627. for (int x = 0; x < width; ++x)
  59628. {
  59629. const float sat = x / (float) width;
  59630. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59631. }
  59632. }
  59633. }
  59634. g.setOpacity (1.0f);
  59635. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59636. 0, 0, colours.getWidth(), colours.getHeight());
  59637. }
  59638. void mouseDown (const MouseEvent& e)
  59639. {
  59640. mouseDrag (e);
  59641. }
  59642. void mouseDrag (const MouseEvent& e)
  59643. {
  59644. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59645. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59646. owner.setSV (sat, val);
  59647. }
  59648. void updateIfNeeded()
  59649. {
  59650. if (lastHue != h)
  59651. {
  59652. lastHue = h;
  59653. colours = Image::null;
  59654. repaint();
  59655. }
  59656. updateMarker();
  59657. }
  59658. void resized()
  59659. {
  59660. colours = Image::null;
  59661. updateMarker();
  59662. }
  59663. private:
  59664. ColourSelector& owner;
  59665. float& h;
  59666. float& s;
  59667. float& v;
  59668. float lastHue;
  59669. ColourSpaceMarker marker;
  59670. const int edge;
  59671. Image colours;
  59672. void updateMarker()
  59673. {
  59674. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59675. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59676. edge * 2, edge * 2);
  59677. }
  59678. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59679. };
  59680. class HueSelectorMarker : public Component
  59681. {
  59682. public:
  59683. HueSelectorMarker()
  59684. {
  59685. setInterceptsMouseClicks (false, false);
  59686. }
  59687. void paint (Graphics& g)
  59688. {
  59689. Path p;
  59690. p.addTriangle (1.0f, 1.0f,
  59691. getWidth() * 0.3f, getHeight() * 0.5f,
  59692. 1.0f, getHeight() - 1.0f);
  59693. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59694. getWidth() * 0.7f, getHeight() * 0.5f,
  59695. getWidth() - 1.0f, getHeight() - 1.0f);
  59696. g.setColour (Colours::white.withAlpha (0.75f));
  59697. g.fillPath (p);
  59698. g.setColour (Colours::black.withAlpha (0.75f));
  59699. g.strokePath (p, PathStrokeType (1.2f));
  59700. }
  59701. private:
  59702. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59703. };
  59704. class ColourSelector::HueSelectorComp : public Component
  59705. {
  59706. public:
  59707. HueSelectorComp (ColourSelector& owner_,
  59708. float& h_, float& s_, float& v_,
  59709. const int edgeSize)
  59710. : owner (owner_),
  59711. h (h_), s (s_), v (v_),
  59712. lastHue (0.0f),
  59713. edge (edgeSize)
  59714. {
  59715. addAndMakeVisible (&marker);
  59716. }
  59717. void paint (Graphics& g)
  59718. {
  59719. const float yScale = 1.0f / (getHeight() - edge * 2);
  59720. const Rectangle<int> clip (g.getClipBounds());
  59721. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59722. {
  59723. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59724. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59725. }
  59726. }
  59727. void resized()
  59728. {
  59729. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59730. getWidth(), edge * 2);
  59731. }
  59732. void mouseDown (const MouseEvent& e)
  59733. {
  59734. mouseDrag (e);
  59735. }
  59736. void mouseDrag (const MouseEvent& e)
  59737. {
  59738. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59739. }
  59740. void updateIfNeeded()
  59741. {
  59742. resized();
  59743. }
  59744. private:
  59745. ColourSelector& owner;
  59746. float& h;
  59747. float& s;
  59748. float& v;
  59749. float lastHue;
  59750. HueSelectorMarker marker;
  59751. const int edge;
  59752. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59753. };
  59754. class ColourSelector::SwatchComponent : public Component
  59755. {
  59756. public:
  59757. SwatchComponent (ColourSelector& owner_, int index_)
  59758. : owner (owner_), index (index_)
  59759. {
  59760. }
  59761. void paint (Graphics& g)
  59762. {
  59763. const Colour colour (owner.getSwatchColour (index));
  59764. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59765. Colour (0xffdddddd).overlaidWith (colour),
  59766. Colour (0xffffffff).overlaidWith (colour));
  59767. }
  59768. void mouseDown (const MouseEvent&)
  59769. {
  59770. PopupMenu m;
  59771. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59772. m.addSeparator();
  59773. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59774. const int r = m.showAt (this);
  59775. if (r == 1)
  59776. {
  59777. owner.setCurrentColour (owner.getSwatchColour (index));
  59778. }
  59779. else if (r == 2)
  59780. {
  59781. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59782. {
  59783. owner.setSwatchColour (index, owner.getCurrentColour());
  59784. repaint();
  59785. }
  59786. }
  59787. }
  59788. private:
  59789. ColourSelector& owner;
  59790. const int index;
  59791. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59792. };
  59793. ColourSelector::ColourSelector (const int flags_,
  59794. const int edgeGap_,
  59795. const int gapAroundColourSpaceComponent)
  59796. : colour (Colours::white),
  59797. flags (flags_),
  59798. edgeGap (edgeGap_)
  59799. {
  59800. // not much point having a selector with no components in it!
  59801. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59802. updateHSV();
  59803. if ((flags & showSliders) != 0)
  59804. {
  59805. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59806. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59807. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59808. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59809. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59810. for (int i = 4; --i >= 0;)
  59811. sliders[i]->addListener (this);
  59812. }
  59813. if ((flags & showColourspace) != 0)
  59814. {
  59815. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59816. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59817. }
  59818. update();
  59819. }
  59820. ColourSelector::~ColourSelector()
  59821. {
  59822. dispatchPendingMessages();
  59823. swatchComponents.clear();
  59824. }
  59825. const Colour ColourSelector::getCurrentColour() const
  59826. {
  59827. return ((flags & showAlphaChannel) != 0) ? colour
  59828. : colour.withAlpha ((uint8) 0xff);
  59829. }
  59830. void ColourSelector::setCurrentColour (const Colour& c)
  59831. {
  59832. if (c != colour)
  59833. {
  59834. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59835. updateHSV();
  59836. update();
  59837. }
  59838. }
  59839. void ColourSelector::setHue (float newH)
  59840. {
  59841. newH = jlimit (0.0f, 1.0f, newH);
  59842. if (h != newH)
  59843. {
  59844. h = newH;
  59845. colour = Colour (h, s, v, colour.getFloatAlpha());
  59846. update();
  59847. }
  59848. }
  59849. void ColourSelector::setSV (float newS, float newV)
  59850. {
  59851. newS = jlimit (0.0f, 1.0f, newS);
  59852. newV = jlimit (0.0f, 1.0f, newV);
  59853. if (s != newS || v != newV)
  59854. {
  59855. s = newS;
  59856. v = newV;
  59857. colour = Colour (h, s, v, colour.getFloatAlpha());
  59858. update();
  59859. }
  59860. }
  59861. void ColourSelector::updateHSV()
  59862. {
  59863. colour.getHSB (h, s, v);
  59864. }
  59865. void ColourSelector::update()
  59866. {
  59867. if (sliders[0] != 0)
  59868. {
  59869. sliders[0]->setValue ((int) colour.getRed());
  59870. sliders[1]->setValue ((int) colour.getGreen());
  59871. sliders[2]->setValue ((int) colour.getBlue());
  59872. sliders[3]->setValue ((int) colour.getAlpha());
  59873. }
  59874. if (colourSpace != 0)
  59875. {
  59876. colourSpace->updateIfNeeded();
  59877. hueSelector->updateIfNeeded();
  59878. }
  59879. if ((flags & showColourAtTop) != 0)
  59880. repaint (previewArea);
  59881. sendChangeMessage();
  59882. }
  59883. void ColourSelector::paint (Graphics& g)
  59884. {
  59885. g.fillAll (findColour (backgroundColourId));
  59886. if ((flags & showColourAtTop) != 0)
  59887. {
  59888. const Colour currentColour (getCurrentColour());
  59889. g.fillCheckerBoard (previewArea, 10, 10,
  59890. Colour (0xffdddddd).overlaidWith (currentColour),
  59891. Colour (0xffffffff).overlaidWith (currentColour));
  59892. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59893. g.setFont (14.0f, true);
  59894. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59895. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59896. Justification::centred, false);
  59897. }
  59898. if ((flags & showSliders) != 0)
  59899. {
  59900. g.setColour (findColour (labelTextColourId));
  59901. g.setFont (11.0f);
  59902. for (int i = 4; --i >= 0;)
  59903. {
  59904. if (sliders[i]->isVisible())
  59905. g.drawText (sliders[i]->getName() + ":",
  59906. 0, sliders[i]->getY(),
  59907. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59908. Justification::centredRight, false);
  59909. }
  59910. }
  59911. }
  59912. void ColourSelector::resized()
  59913. {
  59914. const int swatchesPerRow = 8;
  59915. const int swatchHeight = 22;
  59916. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59917. const int numSwatches = getNumSwatches();
  59918. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59919. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59920. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59921. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59922. int y = topSpace;
  59923. if ((flags & showColourspace) != 0)
  59924. {
  59925. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59926. colourSpace->setBounds (edgeGap, y,
  59927. getWidth() - hueWidth - edgeGap - 4,
  59928. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59929. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59930. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59931. colourSpace->getHeight());
  59932. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59933. }
  59934. if ((flags & showSliders) != 0)
  59935. {
  59936. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59937. for (int i = 0; i < numSliders; ++i)
  59938. {
  59939. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59940. proportionOfWidth (0.72f), sliderHeight - 2);
  59941. y += sliderHeight;
  59942. }
  59943. }
  59944. if (numSwatches > 0)
  59945. {
  59946. const int startX = 8;
  59947. const int xGap = 4;
  59948. const int yGap = 4;
  59949. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59950. y += edgeGap;
  59951. if (swatchComponents.size() != numSwatches)
  59952. {
  59953. swatchComponents.clear();
  59954. for (int i = 0; i < numSwatches; ++i)
  59955. {
  59956. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59957. swatchComponents.add (sc);
  59958. addAndMakeVisible (sc);
  59959. }
  59960. }
  59961. int x = startX;
  59962. for (int i = 0; i < swatchComponents.size(); ++i)
  59963. {
  59964. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59965. sc->setBounds (x + xGap / 2,
  59966. y + yGap / 2,
  59967. swatchWidth - xGap,
  59968. swatchHeight - yGap);
  59969. if (((i + 1) % swatchesPerRow) == 0)
  59970. {
  59971. x = startX;
  59972. y += swatchHeight;
  59973. }
  59974. else
  59975. {
  59976. x += swatchWidth;
  59977. }
  59978. }
  59979. }
  59980. }
  59981. void ColourSelector::sliderValueChanged (Slider*)
  59982. {
  59983. if (sliders[0] != 0)
  59984. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59985. (uint8) sliders[1]->getValue(),
  59986. (uint8) sliders[2]->getValue(),
  59987. (uint8) sliders[3]->getValue()));
  59988. }
  59989. int ColourSelector::getNumSwatches() const
  59990. {
  59991. return 0;
  59992. }
  59993. const Colour ColourSelector::getSwatchColour (const int) const
  59994. {
  59995. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59996. return Colours::black;
  59997. }
  59998. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59999. {
  60000. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60001. }
  60002. END_JUCE_NAMESPACE
  60003. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60004. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60005. BEGIN_JUCE_NAMESPACE
  60006. class ShadowWindow : public Component
  60007. {
  60008. public:
  60009. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  60010. : topLeft (shadowImageSections [type_ * 3]),
  60011. bottomRight (shadowImageSections [type_ * 3 + 1]),
  60012. filler (shadowImageSections [type_ * 3 + 2]),
  60013. type (type_)
  60014. {
  60015. setInterceptsMouseClicks (false, false);
  60016. if (owner.isOnDesktop())
  60017. {
  60018. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60019. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60020. | ComponentPeer::windowIsTemporary
  60021. | ComponentPeer::windowIgnoresKeyPresses);
  60022. }
  60023. else if (owner.getParentComponent() != 0)
  60024. {
  60025. owner.getParentComponent()->addChildComponent (this);
  60026. }
  60027. }
  60028. void paint (Graphics& g)
  60029. {
  60030. g.setOpacity (1.0f);
  60031. if (type < 2)
  60032. {
  60033. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60034. g.drawImage (topLeft,
  60035. 0, 0, topLeft.getWidth(), imH,
  60036. 0, 0, topLeft.getWidth(), imH);
  60037. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60038. g.drawImage (bottomRight,
  60039. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60040. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60041. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60042. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60043. }
  60044. else
  60045. {
  60046. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60047. g.drawImage (topLeft,
  60048. 0, 0, imW, topLeft.getHeight(),
  60049. 0, 0, imW, topLeft.getHeight());
  60050. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60051. g.drawImage (bottomRight,
  60052. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60053. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60054. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60055. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60056. }
  60057. }
  60058. void resized()
  60059. {
  60060. repaint(); // (needed for correct repainting)
  60061. }
  60062. private:
  60063. const Image topLeft, bottomRight, filler;
  60064. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60065. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  60066. };
  60067. DropShadower::DropShadower (const float alpha_,
  60068. const int xOffset_,
  60069. const int yOffset_,
  60070. const float blurRadius_)
  60071. : owner (0),
  60072. xOffset (xOffset_),
  60073. yOffset (yOffset_),
  60074. alpha (alpha_),
  60075. blurRadius (blurRadius_),
  60076. reentrant (false)
  60077. {
  60078. }
  60079. DropShadower::~DropShadower()
  60080. {
  60081. if (owner != 0)
  60082. owner->removeComponentListener (this);
  60083. reentrant = true;
  60084. shadowWindows.clear();
  60085. }
  60086. void DropShadower::setOwner (Component* componentToFollow)
  60087. {
  60088. if (componentToFollow != owner)
  60089. {
  60090. if (owner != 0)
  60091. owner->removeComponentListener (this);
  60092. // (the component can't be null)
  60093. jassert (componentToFollow != 0);
  60094. owner = componentToFollow;
  60095. jassert (owner != 0);
  60096. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60097. owner->addComponentListener (this);
  60098. updateShadows();
  60099. }
  60100. }
  60101. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60102. {
  60103. updateShadows();
  60104. }
  60105. void DropShadower::componentBroughtToFront (Component&)
  60106. {
  60107. bringShadowWindowsToFront();
  60108. }
  60109. void DropShadower::componentParentHierarchyChanged (Component&)
  60110. {
  60111. shadowWindows.clear();
  60112. updateShadows();
  60113. }
  60114. void DropShadower::componentVisibilityChanged (Component&)
  60115. {
  60116. updateShadows();
  60117. }
  60118. void DropShadower::updateShadows()
  60119. {
  60120. if (reentrant || owner == 0)
  60121. return;
  60122. reentrant = true;
  60123. ComponentPeer* const peer = owner->getPeer();
  60124. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60125. const bool createShadowWindows = shadowWindows.size() == 0
  60126. && owner->getWidth() > 0
  60127. && owner->getHeight() > 0
  60128. && isOwnerVisible
  60129. && (Desktop::canUseSemiTransparentWindows()
  60130. || owner->getParentComponent() != 0);
  60131. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60132. if (createShadowWindows)
  60133. {
  60134. // keep a cached version of the image to save doing the gaussian too often
  60135. String imageId;
  60136. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60137. const int hash = imageId.hashCode();
  60138. Image bigIm (ImageCache::getFromHashCode (hash));
  60139. if (bigIm.isNull())
  60140. {
  60141. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60142. Graphics bigG (bigIm);
  60143. bigG.setColour (Colours::black.withAlpha (alpha));
  60144. bigG.fillRect (shadowEdge + xOffset,
  60145. shadowEdge + yOffset,
  60146. bigIm.getWidth() - (shadowEdge * 2),
  60147. bigIm.getHeight() - (shadowEdge * 2));
  60148. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60149. blurKernel.createGaussianBlur (blurRadius);
  60150. blurKernel.applyToImage (bigIm, bigIm,
  60151. Rectangle<int> (xOffset, yOffset,
  60152. bigIm.getWidth(), bigIm.getHeight()));
  60153. ImageCache::addImageToCache (bigIm, hash);
  60154. }
  60155. const int iw = bigIm.getWidth();
  60156. const int ih = bigIm.getHeight();
  60157. const int shadowEdge2 = shadowEdge * 2;
  60158. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60159. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60160. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60161. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60162. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60163. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60164. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60165. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60166. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60167. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60168. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60169. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60170. for (int i = 0; i < 4; ++i)
  60171. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60172. }
  60173. if (shadowWindows.size() >= 4)
  60174. {
  60175. for (int i = shadowWindows.size(); --i >= 0;)
  60176. {
  60177. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60178. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60179. }
  60180. const int x = owner->getX();
  60181. const int y = owner->getY() - shadowEdge;
  60182. const int w = owner->getWidth();
  60183. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60184. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60185. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60186. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60187. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60188. }
  60189. reentrant = false;
  60190. if (createShadowWindows)
  60191. bringShadowWindowsToFront();
  60192. }
  60193. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60194. const int sx, const int sy)
  60195. {
  60196. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60197. Graphics g (shadowImageSections[num]);
  60198. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60199. }
  60200. void DropShadower::bringShadowWindowsToFront()
  60201. {
  60202. if (! reentrant)
  60203. {
  60204. updateShadows();
  60205. reentrant = true;
  60206. for (int i = shadowWindows.size(); --i >= 0;)
  60207. shadowWindows.getUnchecked(i)->toBehind (owner);
  60208. reentrant = false;
  60209. }
  60210. }
  60211. END_JUCE_NAMESPACE
  60212. /*** End of inlined file: juce_DropShadower.cpp ***/
  60213. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60214. BEGIN_JUCE_NAMESPACE
  60215. class MidiKeyboardUpDownButton : public Button
  60216. {
  60217. public:
  60218. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60219. : Button (String::empty),
  60220. owner (owner_),
  60221. delta (delta_)
  60222. {
  60223. setOpaque (true);
  60224. }
  60225. void clicked()
  60226. {
  60227. int note = owner.getLowestVisibleKey();
  60228. if (delta < 0)
  60229. note = (note - 1) / 12;
  60230. else
  60231. note = note / 12 + 1;
  60232. owner.setLowestVisibleKey (note * 12);
  60233. }
  60234. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60235. {
  60236. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60237. isMouseOverButton, isButtonDown,
  60238. delta > 0);
  60239. }
  60240. private:
  60241. MidiKeyboardComponent& owner;
  60242. const int delta;
  60243. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60244. };
  60245. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60246. const Orientation orientation_)
  60247. : state (state_),
  60248. xOffset (0),
  60249. blackNoteLength (1),
  60250. keyWidth (16.0f),
  60251. orientation (orientation_),
  60252. midiChannel (1),
  60253. midiInChannelMask (0xffff),
  60254. velocity (1.0f),
  60255. noteUnderMouse (-1),
  60256. mouseDownNote (-1),
  60257. rangeStart (0),
  60258. rangeEnd (127),
  60259. firstKey (12 * 4),
  60260. canScroll (true),
  60261. mouseDragging (false),
  60262. useMousePositionForVelocity (true),
  60263. keyMappingOctave (6),
  60264. octaveNumForMiddleC (3)
  60265. {
  60266. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60267. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60268. // initialise with a default set of querty key-mappings..
  60269. const char* const keymap = "awsedftgyhujkolp;";
  60270. for (int i = String (keymap).length(); --i >= 0;)
  60271. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60272. setOpaque (true);
  60273. setWantsKeyboardFocus (true);
  60274. state.addListener (this);
  60275. }
  60276. MidiKeyboardComponent::~MidiKeyboardComponent()
  60277. {
  60278. state.removeListener (this);
  60279. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60280. }
  60281. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60282. {
  60283. keyWidth = widthInPixels;
  60284. resized();
  60285. }
  60286. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60287. {
  60288. if (orientation != newOrientation)
  60289. {
  60290. orientation = newOrientation;
  60291. resized();
  60292. }
  60293. }
  60294. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60295. const int highestNote)
  60296. {
  60297. jassert (lowestNote >= 0 && lowestNote <= 127);
  60298. jassert (highestNote >= 0 && highestNote <= 127);
  60299. jassert (lowestNote <= highestNote);
  60300. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60301. {
  60302. rangeStart = jlimit (0, 127, lowestNote);
  60303. rangeEnd = jlimit (0, 127, highestNote);
  60304. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60305. resized();
  60306. }
  60307. }
  60308. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60309. {
  60310. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60311. if (noteNumber != firstKey)
  60312. {
  60313. firstKey = noteNumber;
  60314. sendChangeMessage();
  60315. resized();
  60316. }
  60317. }
  60318. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60319. {
  60320. if (canScroll != canScroll_)
  60321. {
  60322. canScroll = canScroll_;
  60323. resized();
  60324. }
  60325. }
  60326. void MidiKeyboardComponent::colourChanged()
  60327. {
  60328. repaint();
  60329. }
  60330. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60331. {
  60332. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60333. if (midiChannel != midiChannelNumber)
  60334. {
  60335. resetAnyKeysInUse();
  60336. midiChannel = jlimit (1, 16, midiChannelNumber);
  60337. }
  60338. }
  60339. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60340. {
  60341. midiInChannelMask = midiChannelMask;
  60342. triggerAsyncUpdate();
  60343. }
  60344. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60345. {
  60346. velocity = jlimit (0.0f, 1.0f, velocity_);
  60347. useMousePositionForVelocity = useMousePositionForVelocity_;
  60348. }
  60349. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60350. {
  60351. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60352. static const float blackNoteWidth = 0.7f;
  60353. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60354. 1.0f, 2 - blackNoteWidth * 0.4f,
  60355. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60356. 4.0f, 5 - blackNoteWidth * 0.5f,
  60357. 5.0f, 6 - blackNoteWidth * 0.3f,
  60358. 6.0f };
  60359. static const float widths[] = { 1.0f, blackNoteWidth,
  60360. 1.0f, blackNoteWidth,
  60361. 1.0f, 1.0f, blackNoteWidth,
  60362. 1.0f, blackNoteWidth,
  60363. 1.0f, blackNoteWidth,
  60364. 1.0f };
  60365. const int octave = midiNoteNumber / 12;
  60366. const int note = midiNoteNumber % 12;
  60367. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60368. w = roundToInt (widths [note] * keyWidth_);
  60369. }
  60370. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60371. {
  60372. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60373. int rx, rw;
  60374. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60375. x -= xOffset + rx;
  60376. }
  60377. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60378. {
  60379. int x, y;
  60380. getKeyPos (midiNoteNumber, x, y);
  60381. return x;
  60382. }
  60383. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60384. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60385. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60386. {
  60387. if (! reallyContains (pos, false))
  60388. return -1;
  60389. Point<int> p (pos);
  60390. if (orientation != horizontalKeyboard)
  60391. {
  60392. p = Point<int> (p.getY(), p.getX());
  60393. if (orientation == verticalKeyboardFacingLeft)
  60394. p = Point<int> (p.getX(), getWidth() - p.getY());
  60395. else
  60396. p = Point<int> (getHeight() - p.getX(), p.getY());
  60397. }
  60398. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60399. }
  60400. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60401. {
  60402. if (pos.getY() < blackNoteLength)
  60403. {
  60404. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60405. {
  60406. for (int i = 0; i < 5; ++i)
  60407. {
  60408. const int note = octaveStart + blackNotes [i];
  60409. if (note >= rangeStart && note <= rangeEnd)
  60410. {
  60411. int kx, kw;
  60412. getKeyPos (note, kx, kw);
  60413. kx += xOffset;
  60414. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60415. {
  60416. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60417. return note;
  60418. }
  60419. }
  60420. }
  60421. }
  60422. }
  60423. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60424. {
  60425. for (int i = 0; i < 7; ++i)
  60426. {
  60427. const int note = octaveStart + whiteNotes [i];
  60428. if (note >= rangeStart && note <= rangeEnd)
  60429. {
  60430. int kx, kw;
  60431. getKeyPos (note, kx, kw);
  60432. kx += xOffset;
  60433. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60434. {
  60435. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60436. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60437. return note;
  60438. }
  60439. }
  60440. }
  60441. }
  60442. mousePositionVelocity = 0;
  60443. return -1;
  60444. }
  60445. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60446. {
  60447. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60448. {
  60449. int x, w;
  60450. getKeyPos (noteNum, x, w);
  60451. if (orientation == horizontalKeyboard)
  60452. repaint (x, 0, w, getHeight());
  60453. else if (orientation == verticalKeyboardFacingLeft)
  60454. repaint (0, x, getWidth(), w);
  60455. else if (orientation == verticalKeyboardFacingRight)
  60456. repaint (0, getHeight() - x - w, getWidth(), w);
  60457. }
  60458. }
  60459. void MidiKeyboardComponent::paint (Graphics& g)
  60460. {
  60461. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60462. const Colour lineColour (findColour (keySeparatorLineColourId));
  60463. const Colour textColour (findColour (textLabelColourId));
  60464. int x, w, octave;
  60465. for (octave = 0; octave < 128; octave += 12)
  60466. {
  60467. for (int white = 0; white < 7; ++white)
  60468. {
  60469. const int noteNum = octave + whiteNotes [white];
  60470. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60471. {
  60472. getKeyPos (noteNum, x, w);
  60473. if (orientation == horizontalKeyboard)
  60474. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60475. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60476. noteUnderMouse == noteNum,
  60477. lineColour, textColour);
  60478. else if (orientation == verticalKeyboardFacingLeft)
  60479. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60480. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60481. noteUnderMouse == noteNum,
  60482. lineColour, textColour);
  60483. else if (orientation == verticalKeyboardFacingRight)
  60484. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60485. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60486. noteUnderMouse == noteNum,
  60487. lineColour, textColour);
  60488. }
  60489. }
  60490. }
  60491. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60492. if (orientation == verticalKeyboardFacingLeft)
  60493. {
  60494. x1 = getWidth() - 1.0f;
  60495. x2 = getWidth() - 5.0f;
  60496. }
  60497. else if (orientation == verticalKeyboardFacingRight)
  60498. x2 = 5.0f;
  60499. else
  60500. y2 = 5.0f;
  60501. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60502. Colours::transparentBlack, x2, y2, false));
  60503. getKeyPos (rangeEnd, x, w);
  60504. x += w;
  60505. if (orientation == verticalKeyboardFacingLeft)
  60506. g.fillRect (getWidth() - 5, 0, 5, x);
  60507. else if (orientation == verticalKeyboardFacingRight)
  60508. g.fillRect (0, 0, 5, x);
  60509. else
  60510. g.fillRect (0, 0, x, 5);
  60511. g.setColour (lineColour);
  60512. if (orientation == verticalKeyboardFacingLeft)
  60513. g.fillRect (0, 0, 1, x);
  60514. else if (orientation == verticalKeyboardFacingRight)
  60515. g.fillRect (getWidth() - 1, 0, 1, x);
  60516. else
  60517. g.fillRect (0, getHeight() - 1, x, 1);
  60518. const Colour blackNoteColour (findColour (blackNoteColourId));
  60519. for (octave = 0; octave < 128; octave += 12)
  60520. {
  60521. for (int black = 0; black < 5; ++black)
  60522. {
  60523. const int noteNum = octave + blackNotes [black];
  60524. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60525. {
  60526. getKeyPos (noteNum, x, w);
  60527. if (orientation == horizontalKeyboard)
  60528. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60529. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60530. noteUnderMouse == noteNum,
  60531. blackNoteColour);
  60532. else if (orientation == verticalKeyboardFacingLeft)
  60533. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60534. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60535. noteUnderMouse == noteNum,
  60536. blackNoteColour);
  60537. else if (orientation == verticalKeyboardFacingRight)
  60538. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60539. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60540. noteUnderMouse == noteNum,
  60541. blackNoteColour);
  60542. }
  60543. }
  60544. }
  60545. }
  60546. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60547. Graphics& g, int x, int y, int w, int h,
  60548. bool isDown, bool isOver,
  60549. const Colour& lineColour,
  60550. const Colour& textColour)
  60551. {
  60552. Colour c (Colours::transparentWhite);
  60553. if (isDown)
  60554. c = findColour (keyDownOverlayColourId);
  60555. if (isOver)
  60556. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60557. g.setColour (c);
  60558. g.fillRect (x, y, w, h);
  60559. const String text (getWhiteNoteText (midiNoteNumber));
  60560. if (! text.isEmpty())
  60561. {
  60562. g.setColour (textColour);
  60563. Font f (jmin (12.0f, keyWidth * 0.9f));
  60564. f.setHorizontalScale (0.8f);
  60565. g.setFont (f);
  60566. Justification justification (Justification::centredBottom);
  60567. if (orientation == verticalKeyboardFacingLeft)
  60568. justification = Justification::centredLeft;
  60569. else if (orientation == verticalKeyboardFacingRight)
  60570. justification = Justification::centredRight;
  60571. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60572. }
  60573. g.setColour (lineColour);
  60574. if (orientation == horizontalKeyboard)
  60575. g.fillRect (x, y, 1, h);
  60576. else if (orientation == verticalKeyboardFacingLeft)
  60577. g.fillRect (x, y, w, 1);
  60578. else if (orientation == verticalKeyboardFacingRight)
  60579. g.fillRect (x, y + h - 1, w, 1);
  60580. if (midiNoteNumber == rangeEnd)
  60581. {
  60582. if (orientation == horizontalKeyboard)
  60583. g.fillRect (x + w, y, 1, h);
  60584. else if (orientation == verticalKeyboardFacingLeft)
  60585. g.fillRect (x, y + h, w, 1);
  60586. else if (orientation == verticalKeyboardFacingRight)
  60587. g.fillRect (x, y - 1, w, 1);
  60588. }
  60589. }
  60590. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60591. Graphics& g, int x, int y, int w, int h,
  60592. bool isDown, bool isOver,
  60593. const Colour& noteFillColour)
  60594. {
  60595. Colour c (noteFillColour);
  60596. if (isDown)
  60597. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60598. if (isOver)
  60599. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60600. g.setColour (c);
  60601. g.fillRect (x, y, w, h);
  60602. if (isDown)
  60603. {
  60604. g.setColour (noteFillColour);
  60605. g.drawRect (x, y, w, h);
  60606. }
  60607. else
  60608. {
  60609. const int xIndent = jmax (1, jmin (w, h) / 8);
  60610. g.setColour (c.brighter());
  60611. if (orientation == horizontalKeyboard)
  60612. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60613. else if (orientation == verticalKeyboardFacingLeft)
  60614. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60615. else if (orientation == verticalKeyboardFacingRight)
  60616. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60617. }
  60618. }
  60619. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60620. {
  60621. octaveNumForMiddleC = octaveNumForMiddleC_;
  60622. repaint();
  60623. }
  60624. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60625. {
  60626. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60627. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60628. return String::empty;
  60629. }
  60630. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60631. const bool isMouseOver_,
  60632. const bool isButtonDown,
  60633. const bool movesOctavesUp)
  60634. {
  60635. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60636. float angle;
  60637. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60638. angle = movesOctavesUp ? 0.0f : 0.5f;
  60639. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60640. angle = movesOctavesUp ? 0.25f : 0.75f;
  60641. else
  60642. angle = movesOctavesUp ? 0.75f : 0.25f;
  60643. Path path;
  60644. path.lineTo (0.0f, 1.0f);
  60645. path.lineTo (1.0f, 0.5f);
  60646. path.closeSubPath();
  60647. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60648. g.setColour (findColour (upDownButtonArrowColourId)
  60649. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60650. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60651. w - 2.0f,
  60652. h - 2.0f,
  60653. true));
  60654. }
  60655. void MidiKeyboardComponent::resized()
  60656. {
  60657. int w = getWidth();
  60658. int h = getHeight();
  60659. if (w > 0 && h > 0)
  60660. {
  60661. if (orientation != horizontalKeyboard)
  60662. swapVariables (w, h);
  60663. blackNoteLength = roundToInt (h * 0.7f);
  60664. int kx2, kw2;
  60665. getKeyPos (rangeEnd, kx2, kw2);
  60666. kx2 += kw2;
  60667. if (firstKey != rangeStart)
  60668. {
  60669. int kx1, kw1;
  60670. getKeyPos (rangeStart, kx1, kw1);
  60671. if (kx2 - kx1 <= w)
  60672. {
  60673. firstKey = rangeStart;
  60674. sendChangeMessage();
  60675. repaint();
  60676. }
  60677. }
  60678. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60679. scrollDown->setVisible (showScrollButtons);
  60680. scrollUp->setVisible (showScrollButtons);
  60681. xOffset = 0;
  60682. if (showScrollButtons)
  60683. {
  60684. const int scrollButtonW = jmin (12, w / 2);
  60685. if (orientation == horizontalKeyboard)
  60686. {
  60687. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60688. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60689. }
  60690. else if (orientation == verticalKeyboardFacingLeft)
  60691. {
  60692. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60693. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60694. }
  60695. else if (orientation == verticalKeyboardFacingRight)
  60696. {
  60697. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60698. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60699. }
  60700. int endOfLastKey, kw;
  60701. getKeyPos (rangeEnd, endOfLastKey, kw);
  60702. endOfLastKey += kw;
  60703. float mousePositionVelocity;
  60704. const int spaceAvailable = w - scrollButtonW * 2;
  60705. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60706. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60707. {
  60708. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60709. sendChangeMessage();
  60710. }
  60711. int newOffset = 0;
  60712. getKeyPos (firstKey, newOffset, kw);
  60713. xOffset = newOffset - scrollButtonW;
  60714. }
  60715. else
  60716. {
  60717. firstKey = rangeStart;
  60718. }
  60719. timerCallback();
  60720. repaint();
  60721. }
  60722. }
  60723. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60724. {
  60725. triggerAsyncUpdate();
  60726. }
  60727. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60728. {
  60729. triggerAsyncUpdate();
  60730. }
  60731. void MidiKeyboardComponent::handleAsyncUpdate()
  60732. {
  60733. for (int i = rangeStart; i <= rangeEnd; ++i)
  60734. {
  60735. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60736. {
  60737. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60738. repaintNote (i);
  60739. }
  60740. }
  60741. }
  60742. void MidiKeyboardComponent::resetAnyKeysInUse()
  60743. {
  60744. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60745. {
  60746. state.allNotesOff (midiChannel);
  60747. keysPressed.clear();
  60748. mouseDownNote = -1;
  60749. }
  60750. }
  60751. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60752. {
  60753. float mousePositionVelocity = 0.0f;
  60754. const int newNote = (mouseDragging || isMouseOver())
  60755. ? xyToNote (pos, mousePositionVelocity) : -1;
  60756. if (noteUnderMouse != newNote)
  60757. {
  60758. if (mouseDownNote >= 0)
  60759. {
  60760. state.noteOff (midiChannel, mouseDownNote);
  60761. mouseDownNote = -1;
  60762. }
  60763. if (mouseDragging && newNote >= 0)
  60764. {
  60765. if (! useMousePositionForVelocity)
  60766. mousePositionVelocity = 1.0f;
  60767. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60768. mouseDownNote = newNote;
  60769. }
  60770. repaintNote (noteUnderMouse);
  60771. noteUnderMouse = newNote;
  60772. repaintNote (noteUnderMouse);
  60773. }
  60774. else if (mouseDownNote >= 0 && ! mouseDragging)
  60775. {
  60776. state.noteOff (midiChannel, mouseDownNote);
  60777. mouseDownNote = -1;
  60778. }
  60779. }
  60780. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60781. {
  60782. updateNoteUnderMouse (e.getPosition());
  60783. stopTimer();
  60784. }
  60785. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60786. {
  60787. float mousePositionVelocity;
  60788. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60789. if (newNote >= 0)
  60790. mouseDraggedToKey (newNote, e);
  60791. updateNoteUnderMouse (e.getPosition());
  60792. }
  60793. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60794. {
  60795. return true;
  60796. }
  60797. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60798. {
  60799. }
  60800. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60801. {
  60802. float mousePositionVelocity;
  60803. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60804. mouseDragging = false;
  60805. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60806. {
  60807. repaintNote (noteUnderMouse);
  60808. noteUnderMouse = -1;
  60809. mouseDragging = true;
  60810. updateNoteUnderMouse (e.getPosition());
  60811. startTimer (500);
  60812. }
  60813. }
  60814. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60815. {
  60816. mouseDragging = false;
  60817. updateNoteUnderMouse (e.getPosition());
  60818. stopTimer();
  60819. }
  60820. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60821. {
  60822. updateNoteUnderMouse (e.getPosition());
  60823. }
  60824. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60825. {
  60826. updateNoteUnderMouse (e.getPosition());
  60827. }
  60828. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60829. {
  60830. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60831. }
  60832. void MidiKeyboardComponent::timerCallback()
  60833. {
  60834. updateNoteUnderMouse (getMouseXYRelative());
  60835. }
  60836. void MidiKeyboardComponent::clearKeyMappings()
  60837. {
  60838. resetAnyKeysInUse();
  60839. keyPressNotes.clear();
  60840. keyPresses.clear();
  60841. }
  60842. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60843. const int midiNoteOffsetFromC)
  60844. {
  60845. removeKeyPressForNote (midiNoteOffsetFromC);
  60846. keyPressNotes.add (midiNoteOffsetFromC);
  60847. keyPresses.add (key);
  60848. }
  60849. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60850. {
  60851. for (int i = keyPressNotes.size(); --i >= 0;)
  60852. {
  60853. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60854. {
  60855. keyPressNotes.remove (i);
  60856. keyPresses.remove (i);
  60857. }
  60858. }
  60859. }
  60860. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60861. {
  60862. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60863. keyMappingOctave = newOctaveNumber;
  60864. }
  60865. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60866. {
  60867. bool keyPressUsed = false;
  60868. for (int i = keyPresses.size(); --i >= 0;)
  60869. {
  60870. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60871. if (keyPresses.getReference(i).isCurrentlyDown())
  60872. {
  60873. if (! keysPressed [note])
  60874. {
  60875. keysPressed.setBit (note);
  60876. state.noteOn (midiChannel, note, velocity);
  60877. keyPressUsed = true;
  60878. }
  60879. }
  60880. else
  60881. {
  60882. if (keysPressed [note])
  60883. {
  60884. keysPressed.clearBit (note);
  60885. state.noteOff (midiChannel, note);
  60886. keyPressUsed = true;
  60887. }
  60888. }
  60889. }
  60890. return keyPressUsed;
  60891. }
  60892. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60893. {
  60894. resetAnyKeysInUse();
  60895. }
  60896. END_JUCE_NAMESPACE
  60897. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60898. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60899. #if JUCE_OPENGL
  60900. BEGIN_JUCE_NAMESPACE
  60901. extern void juce_glViewport (const int w, const int h);
  60902. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60903. const int alphaBits_,
  60904. const int depthBufferBits_,
  60905. const int stencilBufferBits_)
  60906. : redBits (bitsPerRGBComponent),
  60907. greenBits (bitsPerRGBComponent),
  60908. blueBits (bitsPerRGBComponent),
  60909. alphaBits (alphaBits_),
  60910. depthBufferBits (depthBufferBits_),
  60911. stencilBufferBits (stencilBufferBits_),
  60912. accumulationBufferRedBits (0),
  60913. accumulationBufferGreenBits (0),
  60914. accumulationBufferBlueBits (0),
  60915. accumulationBufferAlphaBits (0),
  60916. fullSceneAntiAliasingNumSamples (0)
  60917. {
  60918. }
  60919. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60920. : redBits (other.redBits),
  60921. greenBits (other.greenBits),
  60922. blueBits (other.blueBits),
  60923. alphaBits (other.alphaBits),
  60924. depthBufferBits (other.depthBufferBits),
  60925. stencilBufferBits (other.stencilBufferBits),
  60926. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60927. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60928. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60929. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60930. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60931. {
  60932. }
  60933. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60934. {
  60935. redBits = other.redBits;
  60936. greenBits = other.greenBits;
  60937. blueBits = other.blueBits;
  60938. alphaBits = other.alphaBits;
  60939. depthBufferBits = other.depthBufferBits;
  60940. stencilBufferBits = other.stencilBufferBits;
  60941. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60942. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60943. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60944. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60945. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60946. return *this;
  60947. }
  60948. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60949. {
  60950. return redBits == other.redBits
  60951. && greenBits == other.greenBits
  60952. && blueBits == other.blueBits
  60953. && alphaBits == other.alphaBits
  60954. && depthBufferBits == other.depthBufferBits
  60955. && stencilBufferBits == other.stencilBufferBits
  60956. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60957. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60958. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60959. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60960. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60961. }
  60962. static Array<OpenGLContext*> knownContexts;
  60963. OpenGLContext::OpenGLContext() throw()
  60964. {
  60965. knownContexts.add (this);
  60966. }
  60967. OpenGLContext::~OpenGLContext()
  60968. {
  60969. knownContexts.removeValue (this);
  60970. }
  60971. OpenGLContext* OpenGLContext::getCurrentContext()
  60972. {
  60973. for (int i = knownContexts.size(); --i >= 0;)
  60974. {
  60975. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60976. if (oglc->isActive())
  60977. return oglc;
  60978. }
  60979. return 0;
  60980. }
  60981. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60982. {
  60983. public:
  60984. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60985. : ComponentMovementWatcher (owner_),
  60986. owner (owner_),
  60987. wasShowing (false)
  60988. {
  60989. }
  60990. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60991. {
  60992. owner->updateContextPosition();
  60993. }
  60994. void componentPeerChanged()
  60995. {
  60996. const ScopedLock sl (owner->getContextLock());
  60997. owner->deleteContext();
  60998. }
  60999. void componentVisibilityChanged (Component&)
  61000. {
  61001. const bool isShowingNow = owner->isShowing();
  61002. if (wasShowing != isShowingNow)
  61003. {
  61004. wasShowing = isShowingNow;
  61005. if (! isShowingNow)
  61006. {
  61007. const ScopedLock sl (owner->getContextLock());
  61008. owner->deleteContext();
  61009. }
  61010. }
  61011. }
  61012. private:
  61013. OpenGLComponent* const owner;
  61014. bool wasShowing;
  61015. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  61016. };
  61017. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61018. : type (type_),
  61019. contextToShareListsWith (0),
  61020. needToUpdateViewport (true)
  61021. {
  61022. setOpaque (true);
  61023. componentWatcher = new OpenGLComponentWatcher (this);
  61024. }
  61025. OpenGLComponent::~OpenGLComponent()
  61026. {
  61027. deleteContext();
  61028. componentWatcher = 0;
  61029. }
  61030. void OpenGLComponent::deleteContext()
  61031. {
  61032. const ScopedLock sl (contextLock);
  61033. context = 0;
  61034. }
  61035. void OpenGLComponent::updateContextPosition()
  61036. {
  61037. needToUpdateViewport = true;
  61038. if (getWidth() > 0 && getHeight() > 0)
  61039. {
  61040. Component* const topComp = getTopLevelComponent();
  61041. if (topComp->getPeer() != 0)
  61042. {
  61043. const ScopedLock sl (contextLock);
  61044. if (context != 0)
  61045. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61046. getScreenY() - topComp->getScreenY(),
  61047. getWidth(),
  61048. getHeight(),
  61049. topComp->getHeight());
  61050. }
  61051. }
  61052. }
  61053. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61054. {
  61055. OpenGLPixelFormat pf;
  61056. const ScopedLock sl (contextLock);
  61057. if (context != 0)
  61058. pf = context->getPixelFormat();
  61059. return pf;
  61060. }
  61061. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61062. {
  61063. if (! (preferredPixelFormat == formatToUse))
  61064. {
  61065. const ScopedLock sl (contextLock);
  61066. deleteContext();
  61067. preferredPixelFormat = formatToUse;
  61068. }
  61069. }
  61070. void OpenGLComponent::shareWith (OpenGLContext* c)
  61071. {
  61072. if (contextToShareListsWith != c)
  61073. {
  61074. const ScopedLock sl (contextLock);
  61075. deleteContext();
  61076. contextToShareListsWith = c;
  61077. }
  61078. }
  61079. bool OpenGLComponent::makeCurrentContextActive()
  61080. {
  61081. if (context == 0)
  61082. {
  61083. const ScopedLock sl (contextLock);
  61084. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61085. {
  61086. context = createContext();
  61087. if (context != 0)
  61088. {
  61089. updateContextPosition();
  61090. if (context->makeActive())
  61091. newOpenGLContextCreated();
  61092. }
  61093. }
  61094. }
  61095. return context != 0 && context->makeActive();
  61096. }
  61097. void OpenGLComponent::makeCurrentContextInactive()
  61098. {
  61099. if (context != 0)
  61100. context->makeInactive();
  61101. }
  61102. bool OpenGLComponent::isActiveContext() const throw()
  61103. {
  61104. return context != 0 && context->isActive();
  61105. }
  61106. void OpenGLComponent::swapBuffers()
  61107. {
  61108. if (context != 0)
  61109. context->swapBuffers();
  61110. }
  61111. void OpenGLComponent::paint (Graphics&)
  61112. {
  61113. if (renderAndSwapBuffers())
  61114. {
  61115. ComponentPeer* const peer = getPeer();
  61116. if (peer != 0)
  61117. {
  61118. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61119. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61120. }
  61121. }
  61122. }
  61123. bool OpenGLComponent::renderAndSwapBuffers()
  61124. {
  61125. const ScopedLock sl (contextLock);
  61126. if (! makeCurrentContextActive())
  61127. return false;
  61128. if (needToUpdateViewport)
  61129. {
  61130. needToUpdateViewport = false;
  61131. juce_glViewport (getWidth(), getHeight());
  61132. }
  61133. renderOpenGL();
  61134. swapBuffers();
  61135. return true;
  61136. }
  61137. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61138. {
  61139. Component::internalRepaint (x, y, w, h);
  61140. if (context != 0)
  61141. context->repaint();
  61142. }
  61143. END_JUCE_NAMESPACE
  61144. #endif
  61145. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61146. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61147. BEGIN_JUCE_NAMESPACE
  61148. PreferencesPanel::PreferencesPanel()
  61149. : buttonSize (70)
  61150. {
  61151. }
  61152. PreferencesPanel::~PreferencesPanel()
  61153. {
  61154. }
  61155. void PreferencesPanel::addSettingsPage (const String& title,
  61156. const Drawable* icon,
  61157. const Drawable* overIcon,
  61158. const Drawable* downIcon)
  61159. {
  61160. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61161. buttons.add (button);
  61162. button->setImages (icon, overIcon, downIcon);
  61163. button->setRadioGroupId (1);
  61164. button->addListener (this);
  61165. button->setClickingTogglesState (true);
  61166. button->setWantsKeyboardFocus (false);
  61167. addAndMakeVisible (button);
  61168. resized();
  61169. if (currentPage == 0)
  61170. setCurrentPage (title);
  61171. }
  61172. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61173. {
  61174. DrawableImage icon, iconOver, iconDown;
  61175. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61176. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61177. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61178. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61179. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61180. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61181. }
  61182. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61183. {
  61184. setSize (dialogWidth, dialogHeight);
  61185. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61186. }
  61187. void PreferencesPanel::resized()
  61188. {
  61189. for (int i = 0; i < buttons.size(); ++i)
  61190. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61191. if (currentPage != 0)
  61192. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61193. }
  61194. void PreferencesPanel::paint (Graphics& g)
  61195. {
  61196. g.setColour (Colours::grey);
  61197. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61198. }
  61199. void PreferencesPanel::setCurrentPage (const String& pageName)
  61200. {
  61201. if (currentPageName != pageName)
  61202. {
  61203. currentPageName = pageName;
  61204. currentPage = 0;
  61205. currentPage = createComponentForPage (pageName);
  61206. if (currentPage != 0)
  61207. {
  61208. addAndMakeVisible (currentPage);
  61209. currentPage->toBack();
  61210. resized();
  61211. }
  61212. for (int i = 0; i < buttons.size(); ++i)
  61213. {
  61214. if (buttons.getUnchecked(i)->getName() == pageName)
  61215. {
  61216. buttons.getUnchecked(i)->setToggleState (true, false);
  61217. break;
  61218. }
  61219. }
  61220. }
  61221. }
  61222. void PreferencesPanel::buttonClicked (Button*)
  61223. {
  61224. for (int i = 0; i < buttons.size(); ++i)
  61225. {
  61226. if (buttons.getUnchecked(i)->getToggleState())
  61227. {
  61228. setCurrentPage (buttons.getUnchecked(i)->getName());
  61229. break;
  61230. }
  61231. }
  61232. }
  61233. END_JUCE_NAMESPACE
  61234. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61235. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61236. #if JUCE_WINDOWS || JUCE_LINUX
  61237. BEGIN_JUCE_NAMESPACE
  61238. SystemTrayIconComponent::SystemTrayIconComponent()
  61239. {
  61240. addToDesktop (0);
  61241. }
  61242. SystemTrayIconComponent::~SystemTrayIconComponent()
  61243. {
  61244. }
  61245. END_JUCE_NAMESPACE
  61246. #endif
  61247. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61248. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61249. BEGIN_JUCE_NAMESPACE
  61250. class AlertWindowTextEditor : public TextEditor
  61251. {
  61252. public:
  61253. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61254. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61255. {
  61256. setSelectAllWhenFocused (true);
  61257. }
  61258. void returnPressed()
  61259. {
  61260. // pass these up the component hierarchy to be trigger the buttons
  61261. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61262. }
  61263. void escapePressed()
  61264. {
  61265. // pass these up the component hierarchy to be trigger the buttons
  61266. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61267. }
  61268. private:
  61269. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61270. static juce_wchar getDefaultPasswordChar() throw()
  61271. {
  61272. #if JUCE_LINUX
  61273. return 0x2022;
  61274. #else
  61275. return 0x25cf;
  61276. #endif
  61277. }
  61278. };
  61279. AlertWindow::AlertWindow (const String& title,
  61280. const String& message,
  61281. AlertIconType iconType,
  61282. Component* associatedComponent_)
  61283. : TopLevelWindow (title, true),
  61284. alertIconType (iconType),
  61285. associatedComponent (associatedComponent_)
  61286. {
  61287. if (message.isEmpty())
  61288. text = " "; // to force an update if the message is empty
  61289. setMessage (message);
  61290. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61291. {
  61292. Component* const c = Desktop::getInstance().getComponent (i);
  61293. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61294. {
  61295. setAlwaysOnTop (true);
  61296. break;
  61297. }
  61298. }
  61299. if (! JUCEApplication::isStandaloneApp())
  61300. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61301. lookAndFeelChanged();
  61302. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61303. }
  61304. AlertWindow::~AlertWindow()
  61305. {
  61306. removeAllChildren();
  61307. }
  61308. void AlertWindow::userTriedToCloseWindow()
  61309. {
  61310. exitModalState (0);
  61311. }
  61312. void AlertWindow::setMessage (const String& message)
  61313. {
  61314. const String newMessage (message.substring (0, 2048));
  61315. if (text != newMessage)
  61316. {
  61317. text = newMessage;
  61318. font = getLookAndFeel().getAlertWindowMessageFont();
  61319. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61320. textLayout.setText (getName() + "\n\n", titleFont);
  61321. textLayout.appendText (text, font);
  61322. updateLayout (true);
  61323. repaint();
  61324. }
  61325. }
  61326. void AlertWindow::buttonClicked (Button* button)
  61327. {
  61328. if (button->getParentComponent() != 0)
  61329. button->getParentComponent()->exitModalState (button->getCommandID());
  61330. }
  61331. void AlertWindow::addButton (const String& name,
  61332. const int returnValue,
  61333. const KeyPress& shortcutKey1,
  61334. const KeyPress& shortcutKey2)
  61335. {
  61336. TextButton* const b = new TextButton (name, String::empty);
  61337. buttons.add (b);
  61338. b->setWantsKeyboardFocus (true);
  61339. b->setMouseClickGrabsKeyboardFocus (false);
  61340. b->setCommandToTrigger (0, returnValue, false);
  61341. b->addShortcut (shortcutKey1);
  61342. b->addShortcut (shortcutKey2);
  61343. b->addListener (this);
  61344. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61345. addAndMakeVisible (b, 0);
  61346. updateLayout (false);
  61347. }
  61348. int AlertWindow::getNumButtons() const
  61349. {
  61350. return buttons.size();
  61351. }
  61352. void AlertWindow::triggerButtonClick (const String& buttonName)
  61353. {
  61354. for (int i = buttons.size(); --i >= 0;)
  61355. {
  61356. TextButton* const b = buttons.getUnchecked(i);
  61357. if (buttonName == b->getName())
  61358. {
  61359. b->triggerClick();
  61360. break;
  61361. }
  61362. }
  61363. }
  61364. void AlertWindow::addTextEditor (const String& name,
  61365. const String& initialContents,
  61366. const String& onScreenLabel,
  61367. const bool isPasswordBox)
  61368. {
  61369. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61370. textBoxes.add (tc);
  61371. allComps.add (tc);
  61372. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61373. tc->setFont (font);
  61374. tc->setText (initialContents);
  61375. tc->setCaretPosition (initialContents.length());
  61376. addAndMakeVisible (tc);
  61377. textboxNames.add (onScreenLabel);
  61378. updateLayout (false);
  61379. }
  61380. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61381. {
  61382. for (int i = textBoxes.size(); --i >= 0;)
  61383. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61384. return textBoxes.getUnchecked(i);
  61385. return 0;
  61386. }
  61387. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61388. {
  61389. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61390. return t != 0 ? t->getText() : String::empty;
  61391. }
  61392. void AlertWindow::addComboBox (const String& name,
  61393. const StringArray& items,
  61394. const String& onScreenLabel)
  61395. {
  61396. ComboBox* const cb = new ComboBox (name);
  61397. comboBoxes.add (cb);
  61398. allComps.add (cb);
  61399. for (int i = 0; i < items.size(); ++i)
  61400. cb->addItem (items[i], i + 1);
  61401. addAndMakeVisible (cb);
  61402. cb->setSelectedItemIndex (0);
  61403. comboBoxNames.add (onScreenLabel);
  61404. updateLayout (false);
  61405. }
  61406. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61407. {
  61408. for (int i = comboBoxes.size(); --i >= 0;)
  61409. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61410. return comboBoxes.getUnchecked(i);
  61411. return 0;
  61412. }
  61413. class AlertTextComp : public TextEditor
  61414. {
  61415. public:
  61416. AlertTextComp (const String& message,
  61417. const Font& font)
  61418. {
  61419. setReadOnly (true);
  61420. setMultiLine (true, true);
  61421. setCaretVisible (false);
  61422. setScrollbarsShown (true);
  61423. lookAndFeelChanged();
  61424. setWantsKeyboardFocus (false);
  61425. setFont (font);
  61426. setText (message, false);
  61427. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61428. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61429. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61430. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61431. }
  61432. ~AlertTextComp()
  61433. {
  61434. }
  61435. int getPreferredWidth() const throw() { return bestWidth; }
  61436. void updateLayout (const int width)
  61437. {
  61438. TextLayout text;
  61439. text.appendText (getText(), getFont());
  61440. text.layout (width - 8, Justification::topLeft, true);
  61441. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61442. }
  61443. private:
  61444. int bestWidth;
  61445. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61446. };
  61447. void AlertWindow::addTextBlock (const String& textBlock)
  61448. {
  61449. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61450. textBlocks.add (c);
  61451. allComps.add (c);
  61452. addAndMakeVisible (c);
  61453. updateLayout (false);
  61454. }
  61455. void AlertWindow::addProgressBarComponent (double& progressValue)
  61456. {
  61457. ProgressBar* const pb = new ProgressBar (progressValue);
  61458. progressBars.add (pb);
  61459. allComps.add (pb);
  61460. addAndMakeVisible (pb);
  61461. updateLayout (false);
  61462. }
  61463. void AlertWindow::addCustomComponent (Component* const component)
  61464. {
  61465. customComps.add (component);
  61466. allComps.add (component);
  61467. addAndMakeVisible (component);
  61468. updateLayout (false);
  61469. }
  61470. int AlertWindow::getNumCustomComponents() const
  61471. {
  61472. return customComps.size();
  61473. }
  61474. Component* AlertWindow::getCustomComponent (const int index) const
  61475. {
  61476. return customComps [index];
  61477. }
  61478. Component* AlertWindow::removeCustomComponent (const int index)
  61479. {
  61480. Component* const c = getCustomComponent (index);
  61481. if (c != 0)
  61482. {
  61483. customComps.removeValue (c);
  61484. allComps.removeValue (c);
  61485. removeChildComponent (c);
  61486. updateLayout (false);
  61487. }
  61488. return c;
  61489. }
  61490. void AlertWindow::paint (Graphics& g)
  61491. {
  61492. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61493. g.setColour (findColour (textColourId));
  61494. g.setFont (getLookAndFeel().getAlertWindowFont());
  61495. int i;
  61496. for (i = textBoxes.size(); --i >= 0;)
  61497. {
  61498. const TextEditor* const te = textBoxes.getUnchecked(i);
  61499. g.drawFittedText (textboxNames[i],
  61500. te->getX(), te->getY() - 14,
  61501. te->getWidth(), 14,
  61502. Justification::centredLeft, 1);
  61503. }
  61504. for (i = comboBoxNames.size(); --i >= 0;)
  61505. {
  61506. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61507. g.drawFittedText (comboBoxNames[i],
  61508. cb->getX(), cb->getY() - 14,
  61509. cb->getWidth(), 14,
  61510. Justification::centredLeft, 1);
  61511. }
  61512. for (i = customComps.size(); --i >= 0;)
  61513. {
  61514. const Component* const c = customComps.getUnchecked(i);
  61515. g.drawFittedText (c->getName(),
  61516. c->getX(), c->getY() - 14,
  61517. c->getWidth(), 14,
  61518. Justification::centredLeft, 1);
  61519. }
  61520. }
  61521. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61522. {
  61523. const int titleH = 24;
  61524. const int iconWidth = 80;
  61525. const int wid = jmax (font.getStringWidth (text),
  61526. font.getStringWidth (getName()));
  61527. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61528. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61529. const int edgeGap = 10;
  61530. const int labelHeight = 18;
  61531. int iconSpace;
  61532. if (alertIconType == NoIcon)
  61533. {
  61534. textLayout.layout (w, Justification::horizontallyCentred, true);
  61535. iconSpace = 0;
  61536. }
  61537. else
  61538. {
  61539. textLayout.layout (w, Justification::left, true);
  61540. iconSpace = iconWidth;
  61541. }
  61542. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61543. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61544. const int textLayoutH = textLayout.getHeight();
  61545. const int textBottom = 16 + titleH + textLayoutH;
  61546. int h = textBottom;
  61547. int buttonW = 40;
  61548. int i;
  61549. for (i = 0; i < buttons.size(); ++i)
  61550. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61551. w = jmax (buttonW, w);
  61552. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61553. if (buttons.size() > 0)
  61554. h += 20 + buttons.getUnchecked(0)->getHeight();
  61555. for (i = customComps.size(); --i >= 0;)
  61556. {
  61557. Component* c = customComps.getUnchecked(i);
  61558. w = jmax (w, (c->getWidth() * 100) / 80);
  61559. h += 10 + c->getHeight();
  61560. if (c->getName().isNotEmpty())
  61561. h += labelHeight;
  61562. }
  61563. for (i = textBlocks.size(); --i >= 0;)
  61564. {
  61565. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61566. w = jmax (w, ac->getPreferredWidth());
  61567. }
  61568. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61569. for (i = textBlocks.size(); --i >= 0;)
  61570. {
  61571. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61572. ac->updateLayout ((int) (w * 0.8f));
  61573. h += ac->getHeight() + 10;
  61574. }
  61575. h = jmin (getParentHeight() - 50, h);
  61576. if (onlyIncreaseSize)
  61577. {
  61578. w = jmax (w, getWidth());
  61579. h = jmax (h, getHeight());
  61580. }
  61581. if (! isVisible())
  61582. {
  61583. centreAroundComponent (associatedComponent, w, h);
  61584. }
  61585. else
  61586. {
  61587. const int cx = getX() + getWidth() / 2;
  61588. const int cy = getY() + getHeight() / 2;
  61589. setBounds (cx - w / 2,
  61590. cy - h / 2,
  61591. w, h);
  61592. }
  61593. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61594. const int spacer = 16;
  61595. int totalWidth = -spacer;
  61596. for (i = buttons.size(); --i >= 0;)
  61597. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61598. int x = (w - totalWidth) / 2;
  61599. int y = (int) (getHeight() * 0.95f);
  61600. for (i = 0; i < buttons.size(); ++i)
  61601. {
  61602. TextButton* const c = buttons.getUnchecked(i);
  61603. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61604. c->setTopLeftPosition (x, ny);
  61605. if (ny < y)
  61606. y = ny;
  61607. x += c->getWidth() + spacer;
  61608. c->toFront (false);
  61609. }
  61610. y = textBottom;
  61611. for (i = 0; i < allComps.size(); ++i)
  61612. {
  61613. Component* const c = allComps.getUnchecked(i);
  61614. h = 22;
  61615. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61616. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61617. y += labelHeight;
  61618. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61619. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61620. y += labelHeight;
  61621. if (customComps.contains (c))
  61622. {
  61623. if (c->getName().isNotEmpty())
  61624. y += labelHeight;
  61625. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61626. h = c->getHeight();
  61627. }
  61628. else if (textBlocks.contains (c))
  61629. {
  61630. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61631. h = c->getHeight();
  61632. }
  61633. else
  61634. {
  61635. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61636. }
  61637. y += h + 10;
  61638. }
  61639. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61640. }
  61641. bool AlertWindow::containsAnyExtraComponents() const
  61642. {
  61643. return allComps.size() > 0;
  61644. }
  61645. void AlertWindow::mouseDown (const MouseEvent& e)
  61646. {
  61647. dragger.startDraggingComponent (this, e);
  61648. }
  61649. void AlertWindow::mouseDrag (const MouseEvent& e)
  61650. {
  61651. dragger.dragComponent (this, e, &constrainer);
  61652. }
  61653. bool AlertWindow::keyPressed (const KeyPress& key)
  61654. {
  61655. for (int i = buttons.size(); --i >= 0;)
  61656. {
  61657. TextButton* const b = buttons.getUnchecked(i);
  61658. if (b->isRegisteredForShortcut (key))
  61659. {
  61660. b->triggerClick();
  61661. return true;
  61662. }
  61663. }
  61664. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61665. {
  61666. exitModalState (0);
  61667. return true;
  61668. }
  61669. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61670. {
  61671. buttons.getUnchecked(0)->triggerClick();
  61672. return true;
  61673. }
  61674. return false;
  61675. }
  61676. void AlertWindow::lookAndFeelChanged()
  61677. {
  61678. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61679. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61680. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61681. }
  61682. int AlertWindow::getDesktopWindowStyleFlags() const
  61683. {
  61684. return getLookAndFeel().getAlertBoxWindowFlags();
  61685. }
  61686. class AlertWindowInfo
  61687. {
  61688. public:
  61689. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61690. AlertWindow::AlertIconType iconType_, int numButtons_)
  61691. : title (title_), message (message_), iconType (iconType_),
  61692. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61693. {
  61694. }
  61695. String title, message, button1, button2, button3;
  61696. AlertWindow::AlertIconType iconType;
  61697. int numButtons, returnValue;
  61698. WeakReference<Component> associatedComponent;
  61699. int showModal() const
  61700. {
  61701. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61702. return returnValue;
  61703. }
  61704. private:
  61705. void show()
  61706. {
  61707. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61708. : LookAndFeel::getDefaultLookAndFeel();
  61709. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61710. iconType, numButtons, associatedComponent));
  61711. jassert (alertBox != 0); // you have to return one of these!
  61712. returnValue = alertBox->runModalLoop();
  61713. }
  61714. static void* showCallback (void* userData)
  61715. {
  61716. static_cast <AlertWindowInfo*> (userData)->show();
  61717. return 0;
  61718. }
  61719. };
  61720. void AlertWindow::showMessageBox (AlertIconType iconType,
  61721. const String& title,
  61722. const String& message,
  61723. const String& buttonText,
  61724. Component* associatedComponent)
  61725. {
  61726. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61727. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61728. info.showModal();
  61729. }
  61730. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61731. const String& title,
  61732. const String& message,
  61733. const String& button1Text,
  61734. const String& button2Text,
  61735. Component* associatedComponent)
  61736. {
  61737. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61738. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61739. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61740. return info.showModal() != 0;
  61741. }
  61742. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61743. const String& title,
  61744. const String& message,
  61745. const String& button1Text,
  61746. const String& button2Text,
  61747. const String& button3Text,
  61748. Component* associatedComponent)
  61749. {
  61750. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61751. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61752. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61753. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61754. return info.showModal();
  61755. }
  61756. END_JUCE_NAMESPACE
  61757. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61758. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61759. BEGIN_JUCE_NAMESPACE
  61760. CallOutBox::CallOutBox (Component& contentComponent,
  61761. Component& componentToPointTo,
  61762. Component* const parentComponent)
  61763. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61764. {
  61765. addAndMakeVisible (&content);
  61766. if (parentComponent != 0)
  61767. {
  61768. parentComponent->addChildComponent (this);
  61769. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61770. parentComponent->getLocalBounds());
  61771. setVisible (true);
  61772. }
  61773. else
  61774. {
  61775. if (! JUCEApplication::isStandaloneApp())
  61776. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61777. updatePosition (componentToPointTo.getScreenBounds(),
  61778. componentToPointTo.getParentMonitorArea());
  61779. addToDesktop (ComponentPeer::windowIsTemporary);
  61780. }
  61781. }
  61782. CallOutBox::~CallOutBox()
  61783. {
  61784. }
  61785. void CallOutBox::setArrowSize (const float newSize)
  61786. {
  61787. arrowSize = newSize;
  61788. borderSpace = jmax (20, (int) arrowSize);
  61789. refreshPath();
  61790. }
  61791. void CallOutBox::paint (Graphics& g)
  61792. {
  61793. if (background.isNull())
  61794. {
  61795. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61796. Graphics g2 (background);
  61797. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61798. }
  61799. g.setColour (Colours::black);
  61800. g.drawImageAt (background, 0, 0);
  61801. }
  61802. void CallOutBox::resized()
  61803. {
  61804. content.setTopLeftPosition (borderSpace, borderSpace);
  61805. refreshPath();
  61806. }
  61807. void CallOutBox::moved()
  61808. {
  61809. refreshPath();
  61810. }
  61811. void CallOutBox::childBoundsChanged (Component*)
  61812. {
  61813. updatePosition (targetArea, availableArea);
  61814. }
  61815. bool CallOutBox::hitTest (int x, int y)
  61816. {
  61817. return outline.contains ((float) x, (float) y);
  61818. }
  61819. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61820. void CallOutBox::inputAttemptWhenModal()
  61821. {
  61822. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61823. if (targetArea.contains (mousePos))
  61824. {
  61825. // if you click on the area that originally popped-up the callout, you expect it
  61826. // to get rid of the box, but deleting the box here allows the click to pass through and
  61827. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61828. postCommandMessage (callOutBoxDismissCommandId);
  61829. }
  61830. else
  61831. {
  61832. exitModalState (0);
  61833. setVisible (false);
  61834. }
  61835. }
  61836. void CallOutBox::handleCommandMessage (int commandId)
  61837. {
  61838. Component::handleCommandMessage (commandId);
  61839. if (commandId == callOutBoxDismissCommandId)
  61840. {
  61841. exitModalState (0);
  61842. setVisible (false);
  61843. }
  61844. }
  61845. bool CallOutBox::keyPressed (const KeyPress& key)
  61846. {
  61847. if (key.isKeyCode (KeyPress::escapeKey))
  61848. {
  61849. inputAttemptWhenModal();
  61850. return true;
  61851. }
  61852. return false;
  61853. }
  61854. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61855. {
  61856. targetArea = newAreaToPointTo;
  61857. availableArea = newAreaToFitIn;
  61858. Rectangle<int> bounds (0, 0,
  61859. content.getWidth() + borderSpace * 2,
  61860. content.getHeight() + borderSpace * 2);
  61861. const int hw = bounds.getWidth() / 2;
  61862. const int hh = bounds.getHeight() / 2;
  61863. const float hwReduced = (float) (hw - borderSpace * 3);
  61864. const float hhReduced = (float) (hh - borderSpace * 3);
  61865. const float arrowIndent = borderSpace - arrowSize;
  61866. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61867. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61868. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61869. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61870. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61871. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61872. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61873. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61874. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61875. float nearest = 1.0e9f;
  61876. for (int i = 0; i < 4; ++i)
  61877. {
  61878. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61879. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61880. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61881. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61882. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61883. distanceFromCentre *= 2.0f;
  61884. if (distanceFromCentre < nearest)
  61885. {
  61886. nearest = distanceFromCentre;
  61887. targetPoint = targets[i];
  61888. bounds.setPosition ((int) (centre.getX() - hw),
  61889. (int) (centre.getY() - hh));
  61890. }
  61891. }
  61892. setBounds (bounds);
  61893. }
  61894. void CallOutBox::refreshPath()
  61895. {
  61896. repaint();
  61897. background = Image::null;
  61898. outline.clear();
  61899. const float gap = 4.5f;
  61900. const float cornerSize = 9.0f;
  61901. const float cornerSize2 = 2.0f * cornerSize;
  61902. const float arrowBaseWidth = arrowSize * 0.7f;
  61903. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61904. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61905. outline.startNewSubPath (left + cornerSize, top);
  61906. if (targetY <= top)
  61907. {
  61908. outline.lineTo (targetX - arrowBaseWidth, top);
  61909. outline.lineTo (targetX, targetY);
  61910. outline.lineTo (targetX + arrowBaseWidth, top);
  61911. }
  61912. outline.lineTo (right - cornerSize, top);
  61913. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61914. if (targetX >= right)
  61915. {
  61916. outline.lineTo (right, targetY - arrowBaseWidth);
  61917. outline.lineTo (targetX, targetY);
  61918. outline.lineTo (right, targetY + arrowBaseWidth);
  61919. }
  61920. outline.lineTo (right, bottom - cornerSize);
  61921. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61922. if (targetY >= bottom)
  61923. {
  61924. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61925. outline.lineTo (targetX, targetY);
  61926. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61927. }
  61928. outline.lineTo (left + cornerSize, bottom);
  61929. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61930. if (targetX <= left)
  61931. {
  61932. outline.lineTo (left, targetY + arrowBaseWidth);
  61933. outline.lineTo (targetX, targetY);
  61934. outline.lineTo (left, targetY - arrowBaseWidth);
  61935. }
  61936. outline.lineTo (left, top + cornerSize);
  61937. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61938. outline.closeSubPath();
  61939. }
  61940. END_JUCE_NAMESPACE
  61941. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61942. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61943. BEGIN_JUCE_NAMESPACE
  61944. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61945. static Array <ComponentPeer*> heavyweightPeers;
  61946. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61947. : component (component_),
  61948. styleFlags (styleFlags_),
  61949. lastPaintTime (0),
  61950. constrainer (0),
  61951. lastDragAndDropCompUnderMouse (0),
  61952. fakeMouseMessageSent (false),
  61953. isWindowMinimised (false)
  61954. {
  61955. heavyweightPeers.add (this);
  61956. }
  61957. ComponentPeer::~ComponentPeer()
  61958. {
  61959. heavyweightPeers.removeValue (this);
  61960. Desktop::getInstance().triggerFocusCallback();
  61961. }
  61962. int ComponentPeer::getNumPeers() throw()
  61963. {
  61964. return heavyweightPeers.size();
  61965. }
  61966. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61967. {
  61968. return heavyweightPeers [index];
  61969. }
  61970. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61971. {
  61972. for (int i = heavyweightPeers.size(); --i >= 0;)
  61973. {
  61974. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61975. if (peer->getComponent() == component)
  61976. return peer;
  61977. }
  61978. return 0;
  61979. }
  61980. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61981. {
  61982. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61983. }
  61984. void ComponentPeer::updateCurrentModifiers() throw()
  61985. {
  61986. ModifierKeys::updateCurrentModifiers();
  61987. }
  61988. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61989. {
  61990. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61991. jassert (mouse != 0); // not enough sources!
  61992. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61993. }
  61994. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61995. {
  61996. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61997. jassert (mouse != 0); // not enough sources!
  61998. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61999. }
  62000. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62001. {
  62002. Graphics g (&contextToPaintTo);
  62003. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62004. g.saveState();
  62005. #endif
  62006. JUCE_TRY
  62007. {
  62008. component->paintEntireComponent (g, true);
  62009. }
  62010. JUCE_CATCH_EXCEPTION
  62011. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62012. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62013. // clearly when things are being repainted.
  62014. g.restoreState();
  62015. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62016. (uint8) Random::getSystemRandom().nextInt (255),
  62017. (uint8) Random::getSystemRandom().nextInt (255),
  62018. (uint8) 0x50));
  62019. #endif
  62020. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62021. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62022. mess up a lot of the calculations that the library needs to do.
  62023. */
  62024. jassert (roundToInt (10.1f) == 10);
  62025. }
  62026. bool ComponentPeer::handleKeyPress (const int keyCode,
  62027. const juce_wchar textCharacter)
  62028. {
  62029. updateCurrentModifiers();
  62030. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62031. ? Component::getCurrentlyFocusedComponent()
  62032. : component;
  62033. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62034. {
  62035. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62036. if (currentModalComp != 0)
  62037. target = currentModalComp;
  62038. }
  62039. const KeyPress keyInfo (keyCode,
  62040. ModifierKeys::getCurrentModifiers().getRawFlags()
  62041. & ModifierKeys::allKeyboardModifiers,
  62042. textCharacter);
  62043. bool keyWasUsed = false;
  62044. while (target != 0)
  62045. {
  62046. const WeakReference<Component> deletionChecker (target);
  62047. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62048. if (keyListeners != 0)
  62049. {
  62050. for (int i = keyListeners->size(); --i >= 0;)
  62051. {
  62052. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  62053. if (keyWasUsed || deletionChecker == 0)
  62054. return keyWasUsed;
  62055. i = jmin (i, keyListeners->size());
  62056. }
  62057. }
  62058. keyWasUsed = target->keyPressed (keyInfo);
  62059. if (keyWasUsed || deletionChecker == 0)
  62060. break;
  62061. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62062. {
  62063. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62064. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62065. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62066. break;
  62067. }
  62068. target = target->getParentComponent();
  62069. }
  62070. return keyWasUsed;
  62071. }
  62072. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62073. {
  62074. updateCurrentModifiers();
  62075. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62076. ? Component::getCurrentlyFocusedComponent()
  62077. : component;
  62078. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62079. {
  62080. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62081. if (currentModalComp != 0)
  62082. target = currentModalComp;
  62083. }
  62084. bool keyWasUsed = false;
  62085. while (target != 0)
  62086. {
  62087. const WeakReference<Component> deletionChecker (target);
  62088. keyWasUsed = target->keyStateChanged (isKeyDown);
  62089. if (keyWasUsed || deletionChecker == 0)
  62090. break;
  62091. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  62092. if (keyListeners != 0)
  62093. {
  62094. for (int i = keyListeners->size(); --i >= 0;)
  62095. {
  62096. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62097. if (keyWasUsed || deletionChecker == 0)
  62098. return keyWasUsed;
  62099. i = jmin (i, keyListeners->size());
  62100. }
  62101. }
  62102. target = target->getParentComponent();
  62103. }
  62104. return keyWasUsed;
  62105. }
  62106. void ComponentPeer::handleModifierKeysChange()
  62107. {
  62108. updateCurrentModifiers();
  62109. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62110. if (target == 0)
  62111. target = Component::getCurrentlyFocusedComponent();
  62112. if (target == 0)
  62113. target = component;
  62114. if (target != 0)
  62115. target->internalModifierKeysChanged();
  62116. }
  62117. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62118. {
  62119. Component* const c = Component::getCurrentlyFocusedComponent();
  62120. if (component->isParentOf (c))
  62121. {
  62122. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62123. if (ti != 0 && ti->isTextInputActive())
  62124. return ti;
  62125. }
  62126. return 0;
  62127. }
  62128. void ComponentPeer::handleBroughtToFront()
  62129. {
  62130. updateCurrentModifiers();
  62131. if (component != 0)
  62132. component->internalBroughtToFront();
  62133. }
  62134. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62135. {
  62136. constrainer = newConstrainer;
  62137. }
  62138. void ComponentPeer::handleMovedOrResized()
  62139. {
  62140. updateCurrentModifiers();
  62141. const bool nowMinimised = isMinimised();
  62142. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62143. {
  62144. const WeakReference<Component> deletionChecker (component);
  62145. const Rectangle<int> newBounds (getBounds());
  62146. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62147. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62148. if (wasMoved || wasResized)
  62149. {
  62150. component->bounds = newBounds;
  62151. if (wasResized)
  62152. component->repaint();
  62153. component->sendMovedResizedMessages (wasMoved, wasResized);
  62154. if (deletionChecker == 0)
  62155. return;
  62156. }
  62157. }
  62158. if (isWindowMinimised != nowMinimised)
  62159. {
  62160. isWindowMinimised = nowMinimised;
  62161. component->minimisationStateChanged (nowMinimised);
  62162. component->sendVisibilityChangeMessage();
  62163. }
  62164. if (! isFullScreen())
  62165. lastNonFullscreenBounds = component->getBounds();
  62166. }
  62167. void ComponentPeer::handleFocusGain()
  62168. {
  62169. updateCurrentModifiers();
  62170. if (component->isParentOf (lastFocusedComponent))
  62171. {
  62172. Component::currentlyFocusedComponent = lastFocusedComponent;
  62173. Desktop::getInstance().triggerFocusCallback();
  62174. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62175. }
  62176. else
  62177. {
  62178. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62179. component->grabKeyboardFocus();
  62180. else
  62181. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62182. }
  62183. }
  62184. void ComponentPeer::handleFocusLoss()
  62185. {
  62186. updateCurrentModifiers();
  62187. if (component->hasKeyboardFocus (true))
  62188. {
  62189. lastFocusedComponent = Component::currentlyFocusedComponent;
  62190. if (lastFocusedComponent != 0)
  62191. {
  62192. Component::currentlyFocusedComponent = 0;
  62193. Desktop::getInstance().triggerFocusCallback();
  62194. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62195. }
  62196. }
  62197. }
  62198. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62199. {
  62200. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62201. ? static_cast <Component*> (lastFocusedComponent)
  62202. : component;
  62203. }
  62204. void ComponentPeer::handleScreenSizeChange()
  62205. {
  62206. updateCurrentModifiers();
  62207. component->parentSizeChanged();
  62208. handleMovedOrResized();
  62209. }
  62210. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62211. {
  62212. lastNonFullscreenBounds = newBounds;
  62213. }
  62214. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62215. {
  62216. return lastNonFullscreenBounds;
  62217. }
  62218. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62219. {
  62220. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62221. }
  62222. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62223. {
  62224. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62225. }
  62226. namespace ComponentPeerHelpers
  62227. {
  62228. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62229. const StringArray& files,
  62230. FileDragAndDropTarget* const lastOne)
  62231. {
  62232. while (c != 0)
  62233. {
  62234. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62235. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62236. return t;
  62237. c = c->getParentComponent();
  62238. }
  62239. return 0;
  62240. }
  62241. }
  62242. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62243. {
  62244. updateCurrentModifiers();
  62245. FileDragAndDropTarget* lastTarget
  62246. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62247. FileDragAndDropTarget* newTarget = 0;
  62248. Component* const compUnderMouse = component->getComponentAt (position);
  62249. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62250. {
  62251. lastDragAndDropCompUnderMouse = compUnderMouse;
  62252. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62253. if (newTarget != lastTarget)
  62254. {
  62255. if (lastTarget != 0)
  62256. lastTarget->fileDragExit (files);
  62257. dragAndDropTargetComponent = 0;
  62258. if (newTarget != 0)
  62259. {
  62260. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62261. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62262. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62263. }
  62264. }
  62265. }
  62266. else
  62267. {
  62268. newTarget = lastTarget;
  62269. }
  62270. if (newTarget != 0)
  62271. {
  62272. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62273. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62274. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62275. }
  62276. }
  62277. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62278. {
  62279. handleFileDragMove (files, Point<int> (-1, -1));
  62280. jassert (dragAndDropTargetComponent == 0);
  62281. lastDragAndDropCompUnderMouse = 0;
  62282. }
  62283. // We'll use an async message to deliver the drop, because if the target decides
  62284. // to run a modal loop, it can gum-up the operating system..
  62285. class AsyncFileDropMessage : public CallbackMessage
  62286. {
  62287. public:
  62288. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62289. const Point<int>& position_, const StringArray& files_)
  62290. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62291. {
  62292. }
  62293. void messageCallback()
  62294. {
  62295. if (target != 0)
  62296. dropTarget->filesDropped (files, position.getX(), position.getY());
  62297. }
  62298. private:
  62299. WeakReference<Component> target;
  62300. FileDragAndDropTarget* const dropTarget;
  62301. const Point<int> position;
  62302. const StringArray files;
  62303. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62304. };
  62305. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62306. {
  62307. handleFileDragMove (files, position);
  62308. if (dragAndDropTargetComponent != 0)
  62309. {
  62310. FileDragAndDropTarget* const target
  62311. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62312. dragAndDropTargetComponent = 0;
  62313. lastDragAndDropCompUnderMouse = 0;
  62314. if (target != 0)
  62315. {
  62316. Component* const targetComp = dynamic_cast <Component*> (target);
  62317. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62318. {
  62319. targetComp->internalModalInputAttempt();
  62320. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62321. return;
  62322. }
  62323. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62324. }
  62325. }
  62326. }
  62327. void ComponentPeer::handleUserClosingWindow()
  62328. {
  62329. updateCurrentModifiers();
  62330. component->userTriedToCloseWindow();
  62331. }
  62332. void ComponentPeer::clearMaskedRegion()
  62333. {
  62334. maskedRegion.clear();
  62335. }
  62336. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62337. {
  62338. maskedRegion.add (x, y, w, h);
  62339. }
  62340. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62341. {
  62342. StringArray s;
  62343. s.add ("Software Renderer");
  62344. return s;
  62345. }
  62346. int ComponentPeer::getCurrentRenderingEngine() throw()
  62347. {
  62348. return 0;
  62349. }
  62350. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62351. {
  62352. }
  62353. END_JUCE_NAMESPACE
  62354. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62355. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62356. BEGIN_JUCE_NAMESPACE
  62357. DialogWindow::DialogWindow (const String& name,
  62358. const Colour& backgroundColour_,
  62359. const bool escapeKeyTriggersCloseButton_,
  62360. const bool addToDesktop_)
  62361. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62362. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62363. {
  62364. }
  62365. DialogWindow::~DialogWindow()
  62366. {
  62367. }
  62368. void DialogWindow::resized()
  62369. {
  62370. DocumentWindow::resized();
  62371. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62372. if (escapeKeyTriggersCloseButton
  62373. && getCloseButton() != 0
  62374. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62375. {
  62376. getCloseButton()->addShortcut (esc);
  62377. }
  62378. }
  62379. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62380. // VC compiler complains about the undefined copy constructor)
  62381. class TempDialogWindow : public DialogWindow
  62382. {
  62383. public:
  62384. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62385. : DialogWindow (title, colour, escapeCloses, true)
  62386. {
  62387. if (! JUCEApplication::isStandaloneApp())
  62388. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62389. }
  62390. void closeButtonPressed()
  62391. {
  62392. setVisible (false);
  62393. }
  62394. private:
  62395. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62396. };
  62397. int DialogWindow::showModalDialog (const String& dialogTitle,
  62398. Component* contentComponent,
  62399. Component* componentToCentreAround,
  62400. const Colour& colour,
  62401. const bool escapeKeyTriggersCloseButton,
  62402. const bool shouldBeResizable,
  62403. const bool useBottomRightCornerResizer)
  62404. {
  62405. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62406. dw.setContentComponent (contentComponent, true, true);
  62407. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62408. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62409. const int result = dw.runModalLoop();
  62410. dw.setContentComponent (0, false);
  62411. return result;
  62412. }
  62413. END_JUCE_NAMESPACE
  62414. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62415. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62416. BEGIN_JUCE_NAMESPACE
  62417. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62418. {
  62419. public:
  62420. ButtonListenerProxy (DocumentWindow& owner_)
  62421. : owner (owner_)
  62422. {
  62423. }
  62424. void buttonClicked (Button* button)
  62425. {
  62426. if (button == owner.getMinimiseButton())
  62427. owner.minimiseButtonPressed();
  62428. else if (button == owner.getMaximiseButton())
  62429. owner.maximiseButtonPressed();
  62430. else if (button == owner.getCloseButton())
  62431. owner.closeButtonPressed();
  62432. }
  62433. private:
  62434. DocumentWindow& owner;
  62435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62436. };
  62437. DocumentWindow::DocumentWindow (const String& title,
  62438. const Colour& backgroundColour,
  62439. const int requiredButtons_,
  62440. const bool addToDesktop_)
  62441. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62442. titleBarHeight (26),
  62443. menuBarHeight (24),
  62444. requiredButtons (requiredButtons_),
  62445. #if JUCE_MAC
  62446. positionTitleBarButtonsOnLeft (true),
  62447. #else
  62448. positionTitleBarButtonsOnLeft (false),
  62449. #endif
  62450. drawTitleTextCentred (true),
  62451. menuBarModel (0)
  62452. {
  62453. setResizeLimits (128, 128, 32768, 32768);
  62454. lookAndFeelChanged();
  62455. }
  62456. DocumentWindow::~DocumentWindow()
  62457. {
  62458. // Don't delete or remove the resizer components yourself! They're managed by the
  62459. // DocumentWindow, and you should leave them alone! You may have deleted them
  62460. // accidentally by careless use of deleteAllChildren()..?
  62461. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62462. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62463. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62464. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62465. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62466. titleBarButtons[i] = 0;
  62467. menuBar = 0;
  62468. }
  62469. void DocumentWindow::repaintTitleBar()
  62470. {
  62471. repaint (getTitleBarArea());
  62472. }
  62473. void DocumentWindow::setName (const String& newName)
  62474. {
  62475. if (newName != getName())
  62476. {
  62477. Component::setName (newName);
  62478. repaintTitleBar();
  62479. }
  62480. }
  62481. void DocumentWindow::setIcon (const Image& imageToUse)
  62482. {
  62483. titleBarIcon = imageToUse;
  62484. repaintTitleBar();
  62485. }
  62486. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62487. {
  62488. titleBarHeight = newHeight;
  62489. resized();
  62490. repaintTitleBar();
  62491. }
  62492. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62493. const bool positionTitleBarButtonsOnLeft_)
  62494. {
  62495. requiredButtons = requiredButtons_;
  62496. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62497. lookAndFeelChanged();
  62498. }
  62499. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62500. {
  62501. drawTitleTextCentred = textShouldBeCentred;
  62502. repaintTitleBar();
  62503. }
  62504. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62505. {
  62506. if (menuBarModel != newMenuBarModel)
  62507. {
  62508. menuBar = 0;
  62509. menuBarModel = newMenuBarModel;
  62510. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62511. : getLookAndFeel().getDefaultMenuBarHeight();
  62512. if (menuBarModel != 0)
  62513. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62514. resized();
  62515. }
  62516. }
  62517. Component* DocumentWindow::getMenuBarComponent() const throw()
  62518. {
  62519. return menuBar;
  62520. }
  62521. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62522. {
  62523. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62524. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62525. if (menuBar != 0)
  62526. menuBar->setEnabled (isActiveWindow());
  62527. resized();
  62528. }
  62529. void DocumentWindow::closeButtonPressed()
  62530. {
  62531. /* If you've got a close button, you have to override this method to get
  62532. rid of your window!
  62533. If the window is just a pop-up, you should override this method and make
  62534. it delete the window in whatever way is appropriate for your app. E.g. you
  62535. might just want to call "delete this".
  62536. If your app is centred around this window such that the whole app should quit when
  62537. the window is closed, then you will probably want to use this method as an opportunity
  62538. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62539. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62540. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62541. or closing it via the taskbar icon on Windows).
  62542. */
  62543. jassertfalse;
  62544. }
  62545. void DocumentWindow::minimiseButtonPressed()
  62546. {
  62547. setMinimised (true);
  62548. }
  62549. void DocumentWindow::maximiseButtonPressed()
  62550. {
  62551. setFullScreen (! isFullScreen());
  62552. }
  62553. void DocumentWindow::paint (Graphics& g)
  62554. {
  62555. ResizableWindow::paint (g);
  62556. if (resizableBorder == 0)
  62557. {
  62558. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62559. const BorderSize border (getBorderThickness());
  62560. g.fillRect (0, 0, getWidth(), border.getTop());
  62561. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62562. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62563. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62564. }
  62565. const Rectangle<int> titleBarArea (getTitleBarArea());
  62566. g.reduceClipRegion (titleBarArea);
  62567. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62568. int titleSpaceX1 = 6;
  62569. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62570. for (int i = 0; i < 3; ++i)
  62571. {
  62572. if (titleBarButtons[i] != 0)
  62573. {
  62574. if (positionTitleBarButtonsOnLeft)
  62575. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62576. else
  62577. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62578. }
  62579. }
  62580. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62581. titleBarArea.getWidth(),
  62582. titleBarArea.getHeight(),
  62583. titleSpaceX1,
  62584. jmax (1, titleSpaceX2 - titleSpaceX1),
  62585. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62586. ! drawTitleTextCentred);
  62587. }
  62588. void DocumentWindow::resized()
  62589. {
  62590. ResizableWindow::resized();
  62591. if (titleBarButtons[1] != 0)
  62592. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62593. const Rectangle<int> titleBarArea (getTitleBarArea());
  62594. getLookAndFeel()
  62595. .positionDocumentWindowButtons (*this,
  62596. titleBarArea.getX(), titleBarArea.getY(),
  62597. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62598. titleBarButtons[0],
  62599. titleBarButtons[1],
  62600. titleBarButtons[2],
  62601. positionTitleBarButtonsOnLeft);
  62602. if (menuBar != 0)
  62603. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62604. titleBarArea.getWidth(), menuBarHeight);
  62605. }
  62606. const BorderSize DocumentWindow::getBorderThickness()
  62607. {
  62608. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  62609. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62610. }
  62611. const BorderSize DocumentWindow::getContentComponentBorder()
  62612. {
  62613. BorderSize border (getBorderThickness());
  62614. border.setTop (border.getTop()
  62615. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62616. + (menuBar != 0 ? menuBarHeight : 0));
  62617. return border;
  62618. }
  62619. int DocumentWindow::getTitleBarHeight() const
  62620. {
  62621. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62622. }
  62623. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62624. {
  62625. const BorderSize border (getBorderThickness());
  62626. return Rectangle<int> (border.getLeft(), border.getTop(),
  62627. getWidth() - border.getLeftAndRight(),
  62628. getTitleBarHeight());
  62629. }
  62630. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62631. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62632. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62633. int DocumentWindow::getDesktopWindowStyleFlags() const
  62634. {
  62635. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62636. if ((requiredButtons & minimiseButton) != 0)
  62637. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62638. if ((requiredButtons & maximiseButton) != 0)
  62639. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62640. if ((requiredButtons & closeButton) != 0)
  62641. styleFlags |= ComponentPeer::windowHasCloseButton;
  62642. return styleFlags;
  62643. }
  62644. void DocumentWindow::lookAndFeelChanged()
  62645. {
  62646. int i;
  62647. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62648. titleBarButtons[i] = 0;
  62649. if (! isUsingNativeTitleBar())
  62650. {
  62651. LookAndFeel& lf = getLookAndFeel();
  62652. if ((requiredButtons & minimiseButton) != 0)
  62653. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62654. if ((requiredButtons & maximiseButton) != 0)
  62655. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62656. if ((requiredButtons & closeButton) != 0)
  62657. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62658. for (i = 0; i < 3; ++i)
  62659. {
  62660. if (titleBarButtons[i] != 0)
  62661. {
  62662. if (buttonListener == 0)
  62663. buttonListener = new ButtonListenerProxy (*this);
  62664. titleBarButtons[i]->addListener (buttonListener);
  62665. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62666. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62667. Component::addAndMakeVisible (titleBarButtons[i]);
  62668. }
  62669. }
  62670. if (getCloseButton() != 0)
  62671. {
  62672. #if JUCE_MAC
  62673. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62674. #else
  62675. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62676. #endif
  62677. }
  62678. }
  62679. activeWindowStatusChanged();
  62680. ResizableWindow::lookAndFeelChanged();
  62681. }
  62682. void DocumentWindow::parentHierarchyChanged()
  62683. {
  62684. lookAndFeelChanged();
  62685. }
  62686. void DocumentWindow::activeWindowStatusChanged()
  62687. {
  62688. ResizableWindow::activeWindowStatusChanged();
  62689. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62690. if (titleBarButtons[i] != 0)
  62691. titleBarButtons[i]->setEnabled (isActiveWindow());
  62692. if (menuBar != 0)
  62693. menuBar->setEnabled (isActiveWindow());
  62694. }
  62695. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62696. {
  62697. if (getTitleBarArea().contains (e.x, e.y)
  62698. && getMaximiseButton() != 0)
  62699. {
  62700. getMaximiseButton()->triggerClick();
  62701. }
  62702. }
  62703. void DocumentWindow::userTriedToCloseWindow()
  62704. {
  62705. closeButtonPressed();
  62706. }
  62707. END_JUCE_NAMESPACE
  62708. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62709. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62710. BEGIN_JUCE_NAMESPACE
  62711. ResizableWindow::ResizableWindow (const String& name,
  62712. const bool addToDesktop_)
  62713. : TopLevelWindow (name, addToDesktop_),
  62714. resizeToFitContent (false),
  62715. fullscreen (false),
  62716. lastNonFullScreenPos (50, 50, 256, 256),
  62717. constrainer (0)
  62718. #if JUCE_DEBUG
  62719. , hasBeenResized (false)
  62720. #endif
  62721. {
  62722. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62723. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62724. if (addToDesktop_)
  62725. Component::addToDesktop (getDesktopWindowStyleFlags());
  62726. }
  62727. ResizableWindow::ResizableWindow (const String& name,
  62728. const Colour& backgroundColour_,
  62729. const bool addToDesktop_)
  62730. : TopLevelWindow (name, addToDesktop_),
  62731. resizeToFitContent (false),
  62732. fullscreen (false),
  62733. lastNonFullScreenPos (50, 50, 256, 256),
  62734. constrainer (0)
  62735. #if JUCE_DEBUG
  62736. , hasBeenResized (false)
  62737. #endif
  62738. {
  62739. setBackgroundColour (backgroundColour_);
  62740. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62741. if (addToDesktop_)
  62742. Component::addToDesktop (getDesktopWindowStyleFlags());
  62743. }
  62744. ResizableWindow::~ResizableWindow()
  62745. {
  62746. // Don't delete or remove the resizer components yourself! They're managed by the
  62747. // ResizableWindow, and you should leave them alone! You may have deleted them
  62748. // accidentally by careless use of deleteAllChildren()..?
  62749. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62750. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62751. resizableCorner = 0;
  62752. resizableBorder = 0;
  62753. contentComponent.deleteAndZero();
  62754. // have you been adding your own components directly to this window..? tut tut tut.
  62755. // Read the instructions for using a ResizableWindow!
  62756. jassert (getNumChildComponents() == 0);
  62757. }
  62758. int ResizableWindow::getDesktopWindowStyleFlags() const
  62759. {
  62760. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62761. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62762. styleFlags |= ComponentPeer::windowIsResizable;
  62763. return styleFlags;
  62764. }
  62765. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62766. const bool deleteOldOne,
  62767. const bool resizeToFit)
  62768. {
  62769. resizeToFitContent = resizeToFit;
  62770. if (newContentComponent != static_cast <Component*> (contentComponent))
  62771. {
  62772. if (deleteOldOne)
  62773. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62774. // external deletion of the content comp)
  62775. else
  62776. removeChildComponent (contentComponent);
  62777. contentComponent = newContentComponent;
  62778. Component::addAndMakeVisible (contentComponent);
  62779. }
  62780. if (resizeToFit)
  62781. childBoundsChanged (contentComponent);
  62782. resized(); // must always be called to position the new content comp
  62783. }
  62784. void ResizableWindow::setContentComponentSize (int width, int height)
  62785. {
  62786. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62787. const BorderSize border (getContentComponentBorder());
  62788. setSize (width + border.getLeftAndRight(),
  62789. height + border.getTopAndBottom());
  62790. }
  62791. const BorderSize ResizableWindow::getBorderThickness()
  62792. {
  62793. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62794. }
  62795. const BorderSize ResizableWindow::getContentComponentBorder()
  62796. {
  62797. return getBorderThickness();
  62798. }
  62799. void ResizableWindow::moved()
  62800. {
  62801. updateLastPos();
  62802. }
  62803. void ResizableWindow::visibilityChanged()
  62804. {
  62805. TopLevelWindow::visibilityChanged();
  62806. updateLastPos();
  62807. }
  62808. void ResizableWindow::resized()
  62809. {
  62810. if (resizableBorder != 0)
  62811. {
  62812. #if JUCE_WINDOWS || JUCE_LINUX
  62813. // hide the resizable border if the OS already provides one..
  62814. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62815. #else
  62816. resizableBorder->setVisible (! isFullScreen());
  62817. #endif
  62818. resizableBorder->setBorderThickness (getBorderThickness());
  62819. resizableBorder->setSize (getWidth(), getHeight());
  62820. resizableBorder->toBack();
  62821. }
  62822. if (resizableCorner != 0)
  62823. {
  62824. #if JUCE_MAC
  62825. // hide the resizable border if the OS already provides one..
  62826. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62827. #else
  62828. resizableCorner->setVisible (! isFullScreen());
  62829. #endif
  62830. const int resizerSize = 18;
  62831. resizableCorner->setBounds (getWidth() - resizerSize,
  62832. getHeight() - resizerSize,
  62833. resizerSize, resizerSize);
  62834. }
  62835. if (contentComponent != 0)
  62836. contentComponent->setBoundsInset (getContentComponentBorder());
  62837. updateLastPos();
  62838. #if JUCE_DEBUG
  62839. hasBeenResized = true;
  62840. #endif
  62841. }
  62842. void ResizableWindow::childBoundsChanged (Component* child)
  62843. {
  62844. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62845. {
  62846. // not going to look very good if this component has a zero size..
  62847. jassert (child->getWidth() > 0);
  62848. jassert (child->getHeight() > 0);
  62849. const BorderSize borders (getContentComponentBorder());
  62850. setSize (child->getWidth() + borders.getLeftAndRight(),
  62851. child->getHeight() + borders.getTopAndBottom());
  62852. }
  62853. }
  62854. void ResizableWindow::activeWindowStatusChanged()
  62855. {
  62856. const BorderSize border (getContentComponentBorder());
  62857. Rectangle<int> area (getLocalBounds());
  62858. repaint (area.removeFromTop (border.getTop()));
  62859. repaint (area.removeFromLeft (border.getLeft()));
  62860. repaint (area.removeFromRight (border.getRight()));
  62861. repaint (area.removeFromBottom (border.getBottom()));
  62862. }
  62863. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62864. const bool useBottomRightCornerResizer)
  62865. {
  62866. if (shouldBeResizable)
  62867. {
  62868. if (useBottomRightCornerResizer)
  62869. {
  62870. resizableBorder = 0;
  62871. if (resizableCorner == 0)
  62872. {
  62873. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62874. resizableCorner->setAlwaysOnTop (true);
  62875. }
  62876. }
  62877. else
  62878. {
  62879. resizableCorner = 0;
  62880. if (resizableBorder == 0)
  62881. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62882. }
  62883. }
  62884. else
  62885. {
  62886. resizableCorner = 0;
  62887. resizableBorder = 0;
  62888. }
  62889. if (isUsingNativeTitleBar())
  62890. recreateDesktopWindow();
  62891. childBoundsChanged (contentComponent);
  62892. resized();
  62893. }
  62894. bool ResizableWindow::isResizable() const throw()
  62895. {
  62896. return resizableCorner != 0
  62897. || resizableBorder != 0;
  62898. }
  62899. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62900. const int newMinimumHeight,
  62901. const int newMaximumWidth,
  62902. const int newMaximumHeight) throw()
  62903. {
  62904. // if you've set up a custom constrainer then these settings won't have any effect..
  62905. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62906. if (constrainer == 0)
  62907. setConstrainer (&defaultConstrainer);
  62908. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62909. newMaximumWidth, newMaximumHeight);
  62910. setBoundsConstrained (getBounds());
  62911. }
  62912. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62913. {
  62914. if (constrainer != newConstrainer)
  62915. {
  62916. constrainer = newConstrainer;
  62917. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62918. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62919. resizableCorner = 0;
  62920. resizableBorder = 0;
  62921. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62922. ComponentPeer* const peer = getPeer();
  62923. if (peer != 0)
  62924. peer->setConstrainer (newConstrainer);
  62925. }
  62926. }
  62927. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62928. {
  62929. if (constrainer != 0)
  62930. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62931. else
  62932. setBounds (bounds);
  62933. }
  62934. void ResizableWindow::paint (Graphics& g)
  62935. {
  62936. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62937. getBorderThickness(), *this);
  62938. if (! isFullScreen())
  62939. {
  62940. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62941. getBorderThickness(), *this);
  62942. }
  62943. #if JUCE_DEBUG
  62944. /* If this fails, then you've probably written a subclass with a resized()
  62945. callback but forgotten to make it call its parent class's resized() method.
  62946. It's important when you override methods like resized(), moved(),
  62947. etc., that you make sure the base class methods also get called.
  62948. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62949. because your content should all be inside the content component - and it's the
  62950. content component's resized() method that you should be using to do your
  62951. layout.
  62952. */
  62953. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62954. #endif
  62955. }
  62956. void ResizableWindow::lookAndFeelChanged()
  62957. {
  62958. resized();
  62959. if (isOnDesktop())
  62960. {
  62961. Component::addToDesktop (getDesktopWindowStyleFlags());
  62962. ComponentPeer* const peer = getPeer();
  62963. if (peer != 0)
  62964. peer->setConstrainer (constrainer);
  62965. }
  62966. }
  62967. const Colour ResizableWindow::getBackgroundColour() const throw()
  62968. {
  62969. return findColour (backgroundColourId, false);
  62970. }
  62971. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62972. {
  62973. Colour backgroundColour (newColour);
  62974. if (! Desktop::canUseSemiTransparentWindows())
  62975. backgroundColour = newColour.withAlpha (1.0f);
  62976. setColour (backgroundColourId, backgroundColour);
  62977. setOpaque (backgroundColour.isOpaque());
  62978. repaint();
  62979. }
  62980. bool ResizableWindow::isFullScreen() const
  62981. {
  62982. if (isOnDesktop())
  62983. {
  62984. ComponentPeer* const peer = getPeer();
  62985. return peer != 0 && peer->isFullScreen();
  62986. }
  62987. return fullscreen;
  62988. }
  62989. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62990. {
  62991. if (shouldBeFullScreen != isFullScreen())
  62992. {
  62993. updateLastPos();
  62994. fullscreen = shouldBeFullScreen;
  62995. if (isOnDesktop())
  62996. {
  62997. ComponentPeer* const peer = getPeer();
  62998. if (peer != 0)
  62999. {
  63000. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63001. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63002. peer->setFullScreen (shouldBeFullScreen);
  63003. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63004. setBounds (lastPos);
  63005. }
  63006. else
  63007. {
  63008. jassertfalse;
  63009. }
  63010. }
  63011. else
  63012. {
  63013. if (shouldBeFullScreen)
  63014. setBounds (0, 0, getParentWidth(), getParentHeight());
  63015. else
  63016. setBounds (lastNonFullScreenPos);
  63017. }
  63018. resized();
  63019. }
  63020. }
  63021. bool ResizableWindow::isMinimised() const
  63022. {
  63023. ComponentPeer* const peer = getPeer();
  63024. return (peer != 0) && peer->isMinimised();
  63025. }
  63026. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63027. {
  63028. if (shouldMinimise != isMinimised())
  63029. {
  63030. ComponentPeer* const peer = getPeer();
  63031. if (peer != 0)
  63032. {
  63033. updateLastPos();
  63034. peer->setMinimised (shouldMinimise);
  63035. }
  63036. else
  63037. {
  63038. jassertfalse;
  63039. }
  63040. }
  63041. }
  63042. void ResizableWindow::updateLastPos()
  63043. {
  63044. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63045. {
  63046. lastNonFullScreenPos = getBounds();
  63047. }
  63048. }
  63049. void ResizableWindow::parentSizeChanged()
  63050. {
  63051. if (isFullScreen() && getParentComponent() != 0)
  63052. {
  63053. setBounds (0, 0, getParentWidth(), getParentHeight());
  63054. }
  63055. }
  63056. const String ResizableWindow::getWindowStateAsString()
  63057. {
  63058. updateLastPos();
  63059. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63060. }
  63061. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63062. {
  63063. StringArray tokens;
  63064. tokens.addTokens (s, false);
  63065. tokens.removeEmptyStrings();
  63066. tokens.trim();
  63067. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63068. const int firstCoord = fs ? 1 : 0;
  63069. if (tokens.size() != firstCoord + 4)
  63070. return false;
  63071. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63072. tokens[firstCoord + 1].getIntValue(),
  63073. tokens[firstCoord + 2].getIntValue(),
  63074. tokens[firstCoord + 3].getIntValue());
  63075. if (newPos.isEmpty())
  63076. return false;
  63077. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63078. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63079. if (peer != 0)
  63080. peer->getFrameSize().addTo (newPos);
  63081. if (! screen.contains (newPos))
  63082. {
  63083. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63084. jmin (newPos.getHeight(), screen.getHeight()));
  63085. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63086. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63087. }
  63088. if (peer != 0)
  63089. {
  63090. peer->getFrameSize().subtractFrom (newPos);
  63091. peer->setNonFullScreenBounds (newPos);
  63092. }
  63093. lastNonFullScreenPos = newPos;
  63094. setFullScreen (fs);
  63095. if (! fs)
  63096. setBoundsConstrained (newPos);
  63097. return true;
  63098. }
  63099. void ResizableWindow::mouseDown (const MouseEvent& e)
  63100. {
  63101. if (! isFullScreen())
  63102. dragger.startDraggingComponent (this, e);
  63103. }
  63104. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63105. {
  63106. if (! isFullScreen())
  63107. dragger.dragComponent (this, e, constrainer);
  63108. }
  63109. #if JUCE_DEBUG
  63110. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63111. {
  63112. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63113. manages its child components automatically, and if you add your own it'll cause
  63114. trouble. Instead, use setContentComponent() to give it a component which
  63115. will be automatically resized and kept in the right place - then you can add
  63116. subcomponents to the content comp. See the notes for the ResizableWindow class
  63117. for more info.
  63118. If you really know what you're doing and want to avoid this assertion, just call
  63119. Component::addChildComponent directly.
  63120. */
  63121. jassertfalse;
  63122. Component::addChildComponent (child, zOrder);
  63123. }
  63124. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63125. {
  63126. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63127. manages its child components automatically, and if you add your own it'll cause
  63128. trouble. Instead, use setContentComponent() to give it a component which
  63129. will be automatically resized and kept in the right place - then you can add
  63130. subcomponents to the content comp. See the notes for the ResizableWindow class
  63131. for more info.
  63132. If you really know what you're doing and want to avoid this assertion, just call
  63133. Component::addAndMakeVisible directly.
  63134. */
  63135. jassertfalse;
  63136. Component::addAndMakeVisible (child, zOrder);
  63137. }
  63138. #endif
  63139. END_JUCE_NAMESPACE
  63140. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63141. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63142. BEGIN_JUCE_NAMESPACE
  63143. SplashScreen::SplashScreen()
  63144. {
  63145. setOpaque (true);
  63146. }
  63147. SplashScreen::~SplashScreen()
  63148. {
  63149. }
  63150. void SplashScreen::show (const String& title,
  63151. const Image& backgroundImage_,
  63152. const int minimumTimeToDisplayFor,
  63153. const bool useDropShadow,
  63154. const bool removeOnMouseClick)
  63155. {
  63156. backgroundImage = backgroundImage_;
  63157. jassert (backgroundImage_.isValid());
  63158. if (backgroundImage_.isValid())
  63159. {
  63160. setOpaque (! backgroundImage_.hasAlphaChannel());
  63161. show (title,
  63162. backgroundImage_.getWidth(),
  63163. backgroundImage_.getHeight(),
  63164. minimumTimeToDisplayFor,
  63165. useDropShadow,
  63166. removeOnMouseClick);
  63167. }
  63168. }
  63169. void SplashScreen::show (const String& title,
  63170. const int width,
  63171. const int height,
  63172. const int minimumTimeToDisplayFor,
  63173. const bool useDropShadow,
  63174. const bool removeOnMouseClick)
  63175. {
  63176. setName (title);
  63177. setAlwaysOnTop (true);
  63178. setVisible (true);
  63179. centreWithSize (width, height);
  63180. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63181. toFront (false);
  63182. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63183. repaint();
  63184. originalClickCounter = removeOnMouseClick
  63185. ? Desktop::getMouseButtonClickCounter()
  63186. : std::numeric_limits<int>::max();
  63187. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63188. startTimer (50);
  63189. }
  63190. void SplashScreen::paint (Graphics& g)
  63191. {
  63192. g.setOpacity (1.0f);
  63193. g.drawImage (backgroundImage,
  63194. 0, 0, getWidth(), getHeight(),
  63195. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63196. }
  63197. void SplashScreen::timerCallback()
  63198. {
  63199. if (Time::getCurrentTime() > earliestTimeToDelete
  63200. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63201. {
  63202. delete this;
  63203. }
  63204. }
  63205. END_JUCE_NAMESPACE
  63206. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63207. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63208. BEGIN_JUCE_NAMESPACE
  63209. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63210. const bool hasProgressBar,
  63211. const bool hasCancelButton,
  63212. const int timeOutMsWhenCancelling_,
  63213. const String& cancelButtonText)
  63214. : Thread ("Juce Progress Window"),
  63215. progress (0.0),
  63216. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63217. {
  63218. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63219. .createAlertWindow (title, String::empty, cancelButtonText,
  63220. String::empty, String::empty,
  63221. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63222. if (hasProgressBar)
  63223. alertWindow->addProgressBarComponent (progress);
  63224. }
  63225. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63226. {
  63227. stopThread (timeOutMsWhenCancelling);
  63228. }
  63229. bool ThreadWithProgressWindow::runThread (const int priority)
  63230. {
  63231. startThread (priority);
  63232. startTimer (100);
  63233. {
  63234. const ScopedLock sl (messageLock);
  63235. alertWindow->setMessage (message);
  63236. }
  63237. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63238. stopThread (timeOutMsWhenCancelling);
  63239. alertWindow->setVisible (false);
  63240. return finishedNaturally;
  63241. }
  63242. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63243. {
  63244. progress = newProgress;
  63245. }
  63246. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63247. {
  63248. const ScopedLock sl (messageLock);
  63249. message = newStatusMessage;
  63250. }
  63251. void ThreadWithProgressWindow::timerCallback()
  63252. {
  63253. if (! isThreadRunning())
  63254. {
  63255. // thread has finished normally..
  63256. alertWindow->exitModalState (1);
  63257. alertWindow->setVisible (false);
  63258. }
  63259. else
  63260. {
  63261. const ScopedLock sl (messageLock);
  63262. alertWindow->setMessage (message);
  63263. }
  63264. }
  63265. END_JUCE_NAMESPACE
  63266. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63267. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63268. BEGIN_JUCE_NAMESPACE
  63269. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63270. const int millisecondsBeforeTipAppears_)
  63271. : Component ("tooltip"),
  63272. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63273. mouseClicks (0),
  63274. lastHideTime (0),
  63275. lastComponentUnderMouse (0),
  63276. changedCompsSinceShown (true)
  63277. {
  63278. if (Desktop::getInstance().getMainMouseSource().canHover())
  63279. startTimer (123);
  63280. setAlwaysOnTop (true);
  63281. setOpaque (true);
  63282. if (parentComponent != 0)
  63283. parentComponent->addChildComponent (this);
  63284. }
  63285. TooltipWindow::~TooltipWindow()
  63286. {
  63287. hide();
  63288. }
  63289. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63290. {
  63291. millisecondsBeforeTipAppears = newTimeMs;
  63292. }
  63293. void TooltipWindow::paint (Graphics& g)
  63294. {
  63295. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63296. }
  63297. void TooltipWindow::mouseEnter (const MouseEvent&)
  63298. {
  63299. hide();
  63300. }
  63301. void TooltipWindow::showFor (const String& tip)
  63302. {
  63303. jassert (tip.isNotEmpty());
  63304. if (tipShowing != tip)
  63305. repaint();
  63306. tipShowing = tip;
  63307. Point<int> mousePos (Desktop::getMousePosition());
  63308. if (getParentComponent() != 0)
  63309. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63310. int x, y, w, h;
  63311. getLookAndFeel().getTooltipSize (tip, w, h);
  63312. if (mousePos.getX() > getParentWidth() / 2)
  63313. x = mousePos.getX() - (w + 12);
  63314. else
  63315. x = mousePos.getX() + 24;
  63316. if (mousePos.getY() > getParentHeight() / 2)
  63317. y = mousePos.getY() - (h + 6);
  63318. else
  63319. y = mousePos.getY() + 6;
  63320. setBounds (x, y, w, h);
  63321. setVisible (true);
  63322. if (getParentComponent() == 0)
  63323. {
  63324. addToDesktop (ComponentPeer::windowHasDropShadow
  63325. | ComponentPeer::windowIsTemporary
  63326. | ComponentPeer::windowIgnoresKeyPresses);
  63327. }
  63328. toFront (false);
  63329. }
  63330. const String TooltipWindow::getTipFor (Component* const c)
  63331. {
  63332. if (c != 0
  63333. && Process::isForegroundProcess()
  63334. && ! Component::isMouseButtonDownAnywhere())
  63335. {
  63336. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63337. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63338. return ttc->getTooltip();
  63339. }
  63340. return String::empty;
  63341. }
  63342. void TooltipWindow::hide()
  63343. {
  63344. tipShowing = String::empty;
  63345. removeFromDesktop();
  63346. setVisible (false);
  63347. }
  63348. void TooltipWindow::timerCallback()
  63349. {
  63350. const unsigned int now = Time::getApproximateMillisecondCounter();
  63351. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63352. const String newTip (getTipFor (newComp));
  63353. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63354. lastComponentUnderMouse = newComp;
  63355. lastTipUnderMouse = newTip;
  63356. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63357. const bool mouseWasClicked = clickCount > mouseClicks;
  63358. mouseClicks = clickCount;
  63359. const Point<int> mousePos (Desktop::getMousePosition());
  63360. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63361. lastMousePos = mousePos;
  63362. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63363. lastCompChangeTime = now;
  63364. if (isVisible() || now < lastHideTime + 500)
  63365. {
  63366. // if a tip is currently visible (or has just disappeared), update to a new one
  63367. // immediately if needed..
  63368. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63369. {
  63370. if (isVisible())
  63371. {
  63372. lastHideTime = now;
  63373. hide();
  63374. }
  63375. }
  63376. else if (tipChanged)
  63377. {
  63378. showFor (newTip);
  63379. }
  63380. }
  63381. else
  63382. {
  63383. // if there isn't currently a tip, but one is needed, only let it
  63384. // appear after a timeout..
  63385. if (newTip.isNotEmpty()
  63386. && newTip != tipShowing
  63387. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63388. {
  63389. showFor (newTip);
  63390. }
  63391. }
  63392. }
  63393. END_JUCE_NAMESPACE
  63394. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63395. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63396. BEGIN_JUCE_NAMESPACE
  63397. /** Keeps track of the active top level window.
  63398. */
  63399. class TopLevelWindowManager : public Timer,
  63400. public DeletedAtShutdown
  63401. {
  63402. public:
  63403. TopLevelWindowManager()
  63404. : currentActive (0)
  63405. {
  63406. }
  63407. ~TopLevelWindowManager()
  63408. {
  63409. clearSingletonInstance();
  63410. }
  63411. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63412. void timerCallback()
  63413. {
  63414. startTimer (jmin (1731, getTimerInterval() * 2));
  63415. TopLevelWindow* active = 0;
  63416. if (Process::isForegroundProcess())
  63417. {
  63418. active = currentActive;
  63419. Component* const c = Component::getCurrentlyFocusedComponent();
  63420. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63421. if (tlw == 0 && c != 0)
  63422. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63423. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63424. if (tlw != 0)
  63425. active = tlw;
  63426. }
  63427. if (active != currentActive)
  63428. {
  63429. currentActive = active;
  63430. for (int i = windows.size(); --i >= 0;)
  63431. {
  63432. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63433. tlw->setWindowActive (isWindowActive (tlw));
  63434. i = jmin (i, windows.size() - 1);
  63435. }
  63436. Desktop::getInstance().triggerFocusCallback();
  63437. }
  63438. }
  63439. bool addWindow (TopLevelWindow* const w)
  63440. {
  63441. windows.add (w);
  63442. startTimer (10);
  63443. return isWindowActive (w);
  63444. }
  63445. void removeWindow (TopLevelWindow* const w)
  63446. {
  63447. startTimer (10);
  63448. if (currentActive == w)
  63449. currentActive = 0;
  63450. windows.removeValue (w);
  63451. if (windows.size() == 0)
  63452. deleteInstance();
  63453. }
  63454. Array <TopLevelWindow*> windows;
  63455. private:
  63456. TopLevelWindow* currentActive;
  63457. bool isWindowActive (TopLevelWindow* const tlw) const
  63458. {
  63459. return (tlw == currentActive
  63460. || tlw->isParentOf (currentActive)
  63461. || tlw->hasKeyboardFocus (true))
  63462. && tlw->isShowing();
  63463. }
  63464. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63465. };
  63466. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63467. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63468. {
  63469. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63470. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63471. }
  63472. TopLevelWindow::TopLevelWindow (const String& name,
  63473. const bool addToDesktop_)
  63474. : Component (name),
  63475. useDropShadow (true),
  63476. useNativeTitleBar (false),
  63477. windowIsActive_ (false)
  63478. {
  63479. setOpaque (true);
  63480. if (addToDesktop_)
  63481. Component::addToDesktop (getDesktopWindowStyleFlags());
  63482. else
  63483. setDropShadowEnabled (true);
  63484. setWantsKeyboardFocus (true);
  63485. setBroughtToFrontOnMouseClick (true);
  63486. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63487. }
  63488. TopLevelWindow::~TopLevelWindow()
  63489. {
  63490. shadower = 0;
  63491. TopLevelWindowManager::getInstance()->removeWindow (this);
  63492. }
  63493. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63494. {
  63495. if (hasKeyboardFocus (true))
  63496. TopLevelWindowManager::getInstance()->timerCallback();
  63497. else
  63498. TopLevelWindowManager::getInstance()->startTimer (10);
  63499. }
  63500. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63501. {
  63502. if (windowIsActive_ != isNowActive)
  63503. {
  63504. windowIsActive_ = isNowActive;
  63505. activeWindowStatusChanged();
  63506. }
  63507. }
  63508. void TopLevelWindow::activeWindowStatusChanged()
  63509. {
  63510. }
  63511. void TopLevelWindow::parentHierarchyChanged()
  63512. {
  63513. setDropShadowEnabled (useDropShadow);
  63514. }
  63515. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63516. {
  63517. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63518. if (useDropShadow)
  63519. styleFlags |= ComponentPeer::windowHasDropShadow;
  63520. if (useNativeTitleBar)
  63521. styleFlags |= ComponentPeer::windowHasTitleBar;
  63522. return styleFlags;
  63523. }
  63524. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63525. {
  63526. useDropShadow = useShadow;
  63527. if (isOnDesktop())
  63528. {
  63529. shadower = 0;
  63530. Component::addToDesktop (getDesktopWindowStyleFlags());
  63531. }
  63532. else
  63533. {
  63534. if (useShadow && isOpaque())
  63535. {
  63536. if (shadower == 0)
  63537. {
  63538. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63539. if (shadower != 0)
  63540. shadower->setOwner (this);
  63541. }
  63542. }
  63543. else
  63544. {
  63545. shadower = 0;
  63546. }
  63547. }
  63548. }
  63549. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63550. {
  63551. if (useNativeTitleBar != useNativeTitleBar_)
  63552. {
  63553. useNativeTitleBar = useNativeTitleBar_;
  63554. recreateDesktopWindow();
  63555. sendLookAndFeelChange();
  63556. }
  63557. }
  63558. void TopLevelWindow::recreateDesktopWindow()
  63559. {
  63560. if (isOnDesktop())
  63561. {
  63562. Component::addToDesktop (getDesktopWindowStyleFlags());
  63563. toFront (true);
  63564. }
  63565. }
  63566. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63567. {
  63568. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63569. because this class needs to make sure its layout corresponds with settings like whether
  63570. it's got a native title bar or not.
  63571. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63572. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63573. method, then add or remove whatever flags are necessary from this value before returning it.
  63574. */
  63575. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63576. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63577. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63578. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63579. sendLookAndFeelChange();
  63580. }
  63581. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63582. {
  63583. if (c == 0)
  63584. c = TopLevelWindow::getActiveTopLevelWindow();
  63585. if (c == 0)
  63586. {
  63587. centreWithSize (width, height);
  63588. }
  63589. else
  63590. {
  63591. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63592. Rectangle<int> parentArea (c->getParentMonitorArea());
  63593. if (getParentComponent() != 0)
  63594. {
  63595. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63596. parentArea = getParentComponent()->getLocalBounds();
  63597. }
  63598. parentArea.reduce (12, 12);
  63599. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63600. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63601. width, height);
  63602. }
  63603. }
  63604. int TopLevelWindow::getNumTopLevelWindows() throw()
  63605. {
  63606. return TopLevelWindowManager::getInstance()->windows.size();
  63607. }
  63608. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63609. {
  63610. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63611. }
  63612. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63613. {
  63614. TopLevelWindow* best = 0;
  63615. int bestNumTWLParents = -1;
  63616. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63617. {
  63618. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63619. if (tlw->isActiveWindow())
  63620. {
  63621. int numTWLParents = 0;
  63622. const Component* c = tlw->getParentComponent();
  63623. while (c != 0)
  63624. {
  63625. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63626. ++numTWLParents;
  63627. c = c->getParentComponent();
  63628. }
  63629. if (bestNumTWLParents < numTWLParents)
  63630. {
  63631. best = tlw;
  63632. bestNumTWLParents = numTWLParents;
  63633. }
  63634. }
  63635. }
  63636. return best;
  63637. }
  63638. END_JUCE_NAMESPACE
  63639. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63640. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63641. BEGIN_JUCE_NAMESPACE
  63642. MarkerList::MarkerList()
  63643. {
  63644. }
  63645. MarkerList::MarkerList (const MarkerList& other)
  63646. {
  63647. operator= (other);
  63648. }
  63649. MarkerList& MarkerList::operator= (const MarkerList& other)
  63650. {
  63651. if (other != *this)
  63652. {
  63653. markers.clear();
  63654. markers.addCopiesOf (other.markers);
  63655. markersHaveChanged();
  63656. }
  63657. return *this;
  63658. }
  63659. MarkerList::~MarkerList()
  63660. {
  63661. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63662. }
  63663. bool MarkerList::operator== (const MarkerList& other) const throw()
  63664. {
  63665. if (other.markers.size() != markers.size())
  63666. return false;
  63667. for (int i = markers.size(); --i >= 0;)
  63668. {
  63669. const Marker* const m1 = markers.getUnchecked(i);
  63670. jassert (m1 != 0);
  63671. const Marker* const m2 = other.getMarker (m1->name);
  63672. if (m2 == 0 || *m1 != *m2)
  63673. return false;
  63674. }
  63675. return true;
  63676. }
  63677. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63678. {
  63679. return ! operator== (other);
  63680. }
  63681. int MarkerList::getNumMarkers() const throw()
  63682. {
  63683. return markers.size();
  63684. }
  63685. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63686. {
  63687. return markers [index];
  63688. }
  63689. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63690. {
  63691. for (int i = 0; i < markers.size(); ++i)
  63692. {
  63693. const Marker* const m = markers.getUnchecked(i);
  63694. if (m->name == name)
  63695. return m;
  63696. }
  63697. return 0;
  63698. }
  63699. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63700. {
  63701. Marker* const m = const_cast <Marker*> (getMarker (name));
  63702. if (m != 0)
  63703. {
  63704. if (m->position != position)
  63705. {
  63706. m->position = position;
  63707. markersHaveChanged();
  63708. }
  63709. return;
  63710. }
  63711. markers.add (new Marker (name, position));
  63712. markersHaveChanged();
  63713. }
  63714. void MarkerList::removeMarker (const int index)
  63715. {
  63716. if (isPositiveAndBelow (index, markers.size()))
  63717. {
  63718. markers.remove (index);
  63719. markersHaveChanged();
  63720. }
  63721. }
  63722. void MarkerList::removeMarker (const String& name)
  63723. {
  63724. for (int i = 0; i < markers.size(); ++i)
  63725. {
  63726. const Marker* const m = markers.getUnchecked(i);
  63727. if (m->name == name)
  63728. {
  63729. markers.remove (i);
  63730. markersHaveChanged();
  63731. }
  63732. }
  63733. }
  63734. void MarkerList::markersHaveChanged()
  63735. {
  63736. listeners.call (&MarkerList::Listener::markersChanged, this);
  63737. }
  63738. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63739. {
  63740. }
  63741. void MarkerList::addListener (Listener* listener)
  63742. {
  63743. listeners.add (listener);
  63744. }
  63745. void MarkerList::removeListener (Listener* listener)
  63746. {
  63747. listeners.remove (listener);
  63748. }
  63749. MarkerList::Marker::Marker (const Marker& other)
  63750. : name (other.name), position (other.position)
  63751. {
  63752. }
  63753. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63754. : name (name_), position (position_)
  63755. {
  63756. }
  63757. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63758. {
  63759. return name == other.name && position == other.position;
  63760. }
  63761. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63762. {
  63763. return ! operator== (other);
  63764. }
  63765. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63766. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63767. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63768. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63769. : state (state_)
  63770. {
  63771. }
  63772. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63773. {
  63774. return state.getNumChildren();
  63775. }
  63776. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63777. {
  63778. return state.getChild (index);
  63779. }
  63780. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63781. {
  63782. return state.getChildWithProperty (nameProperty, name);
  63783. }
  63784. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63785. {
  63786. return marker.isAChildOf (state);
  63787. }
  63788. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63789. {
  63790. jassert (containsMarker (marker));
  63791. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63792. }
  63793. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63794. {
  63795. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63796. if (marker.isValid())
  63797. {
  63798. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63799. }
  63800. else
  63801. {
  63802. marker = ValueTree (markerTag);
  63803. marker.setProperty (nameProperty, m.name, 0);
  63804. marker.setProperty (posProperty, m.position.toString(), 0);
  63805. state.addChild (marker, -1, undoManager);
  63806. }
  63807. }
  63808. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63809. {
  63810. state.removeChild (marker, undoManager);
  63811. }
  63812. class MarkerListEvaluator : public Expression::EvaluationContext
  63813. {
  63814. public:
  63815. MarkerListEvaluator (const MarkerList& markerList_, Component* const parentComponent_)
  63816. : markerList (markerList_), parentComponent (parentComponent_)
  63817. {
  63818. }
  63819. const Expression getSymbolValue (const String& objectName, const String& member) const
  63820. {
  63821. if (member.isEmpty())
  63822. {
  63823. const MarkerList::Marker* const marker = markerList.getMarker (objectName);
  63824. if (marker != 0)
  63825. return Expression (marker->position.resolve (this));
  63826. }
  63827. else if (parentComponent != 0 && objectName == RelativeCoordinate::Strings::parent)
  63828. {
  63829. if (member == RelativeCoordinate::Strings::right) return Expression ((double) parentComponent->getWidth());
  63830. if (member == RelativeCoordinate::Strings::bottom) return Expression ((double) parentComponent->getHeight());
  63831. }
  63832. return Expression::EvaluationContext::getSymbolValue (objectName, member);
  63833. }
  63834. private:
  63835. const MarkerList& markerList;
  63836. Component* parentComponent;
  63837. JUCE_DECLARE_NON_COPYABLE (MarkerListEvaluator);
  63838. };
  63839. double MarkerList::getMarkerPosition (const Marker& marker, Component* const parentComponent) const
  63840. {
  63841. MarkerListEvaluator context (*this, parentComponent);
  63842. return marker.position.resolve (&context);
  63843. }
  63844. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63845. {
  63846. const int numMarkers = getNumMarkers();
  63847. StringArray updatedMarkers;
  63848. int i;
  63849. for (i = 0; i < numMarkers; ++i)
  63850. {
  63851. const ValueTree marker (state.getChild (i));
  63852. const String name (marker [nameProperty].toString());
  63853. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63854. updatedMarkers.add (name);
  63855. }
  63856. for (i = markerList.getNumMarkers(); --i >= 0;)
  63857. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63858. markerList.removeMarker (i);
  63859. }
  63860. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63861. {
  63862. state.removeAllChildren (undoManager);
  63863. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63864. setMarker (*markerList.getMarker(i), undoManager);
  63865. }
  63866. END_JUCE_NAMESPACE
  63867. /*** End of inlined file: juce_MarkerList.cpp ***/
  63868. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63869. BEGIN_JUCE_NAMESPACE
  63870. const String RelativeCoordinate::Strings::parent ("parent");
  63871. const String RelativeCoordinate::Strings::this_ ("this");
  63872. const String RelativeCoordinate::Strings::left ("left");
  63873. const String RelativeCoordinate::Strings::right ("right");
  63874. const String RelativeCoordinate::Strings::top ("top");
  63875. const String RelativeCoordinate::Strings::bottom ("bottom");
  63876. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  63877. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  63878. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  63879. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  63880. RelativeCoordinate::RelativeCoordinate()
  63881. {
  63882. }
  63883. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63884. : term (term_)
  63885. {
  63886. }
  63887. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63888. : term (other.term)
  63889. {
  63890. }
  63891. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63892. {
  63893. term = other.term;
  63894. return *this;
  63895. }
  63896. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63897. : term (absoluteDistanceFromOrigin)
  63898. {
  63899. }
  63900. RelativeCoordinate::RelativeCoordinate (const String& s)
  63901. {
  63902. try
  63903. {
  63904. term = Expression (s);
  63905. }
  63906. catch (...)
  63907. {}
  63908. }
  63909. RelativeCoordinate::~RelativeCoordinate()
  63910. {
  63911. }
  63912. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63913. {
  63914. return term.toString() == other.term.toString();
  63915. }
  63916. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63917. {
  63918. return ! operator== (other);
  63919. }
  63920. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  63921. {
  63922. try
  63923. {
  63924. if (context != 0)
  63925. return term.evaluate (*context);
  63926. else
  63927. return term.evaluate();
  63928. }
  63929. catch (...)
  63930. {}
  63931. return 0.0;
  63932. }
  63933. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  63934. {
  63935. try
  63936. {
  63937. if (context != 0)
  63938. term.evaluate (*context);
  63939. else
  63940. term.evaluate();
  63941. }
  63942. catch (...)
  63943. {
  63944. return true;
  63945. }
  63946. return false;
  63947. }
  63948. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  63949. {
  63950. try
  63951. {
  63952. if (context != 0)
  63953. {
  63954. term = term.adjustedToGiveNewResult (newPos, *context);
  63955. }
  63956. else
  63957. {
  63958. Expression::EvaluationContext defaultContext;
  63959. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  63960. }
  63961. }
  63962. catch (...)
  63963. {}
  63964. }
  63965. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  63966. {
  63967. try
  63968. {
  63969. return term.referencesSymbol (coordName, context);
  63970. }
  63971. catch (...)
  63972. {}
  63973. return false;
  63974. }
  63975. bool RelativeCoordinate::isDynamic() const
  63976. {
  63977. return term.usesAnySymbols();
  63978. }
  63979. const String RelativeCoordinate::toString() const
  63980. {
  63981. return term.toString();
  63982. }
  63983. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  63984. {
  63985. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  63986. if (term.referencesSymbol (oldName, 0))
  63987. term = term.withRenamedSymbol (oldName, newName);
  63988. }
  63989. END_JUCE_NAMESPACE
  63990. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  63991. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  63992. BEGIN_JUCE_NAMESPACE
  63993. namespace RelativePointHelpers
  63994. {
  63995. void skipComma (const juce_wchar* const s, int& i)
  63996. {
  63997. while (CharacterFunctions::isWhitespace (s[i]))
  63998. ++i;
  63999. if (s[i] == ',')
  64000. ++i;
  64001. }
  64002. }
  64003. RelativePoint::RelativePoint()
  64004. {
  64005. }
  64006. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64007. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64008. {
  64009. }
  64010. RelativePoint::RelativePoint (const float x_, const float y_)
  64011. : x (x_), y (y_)
  64012. {
  64013. }
  64014. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64015. : x (x_), y (y_)
  64016. {
  64017. }
  64018. RelativePoint::RelativePoint (const String& s)
  64019. {
  64020. int i = 0;
  64021. x = RelativeCoordinate (Expression::parse (s, i));
  64022. RelativePointHelpers::skipComma (s, i);
  64023. y = RelativeCoordinate (Expression::parse (s, i));
  64024. }
  64025. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64026. {
  64027. return x == other.x && y == other.y;
  64028. }
  64029. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64030. {
  64031. return ! operator== (other);
  64032. }
  64033. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64034. {
  64035. return Point<float> ((float) x.resolve (context),
  64036. (float) y.resolve (context));
  64037. }
  64038. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64039. {
  64040. x.moveToAbsolute (newPos.getX(), context);
  64041. y.moveToAbsolute (newPos.getY(), context);
  64042. }
  64043. const String RelativePoint::toString() const
  64044. {
  64045. return x.toString() + ", " + y.toString();
  64046. }
  64047. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64048. {
  64049. x.renameSymbolIfUsed (oldName, newName);
  64050. y.renameSymbolIfUsed (oldName, newName);
  64051. }
  64052. bool RelativePoint::isDynamic() const
  64053. {
  64054. return x.isDynamic() || y.isDynamic();
  64055. }
  64056. END_JUCE_NAMESPACE
  64057. /*** End of inlined file: juce_RelativePoint.cpp ***/
  64058. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  64059. BEGIN_JUCE_NAMESPACE
  64060. namespace RelativeRectangleHelpers
  64061. {
  64062. inline void skipComma (const juce_wchar* const s, int& i)
  64063. {
  64064. while (CharacterFunctions::isWhitespace (s[i]))
  64065. ++i;
  64066. if (s[i] == ',')
  64067. ++i;
  64068. }
  64069. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  64070. {
  64071. if (e.getType() == Expression::symbolType)
  64072. {
  64073. String objectName, memberName;
  64074. e.getSymbolParts (objectName, memberName);
  64075. if (objectName != RelativeCoordinate::Strings::this_)
  64076. return true;
  64077. }
  64078. else
  64079. {
  64080. for (int i = e.getNumInputs(); --i >= 0;)
  64081. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  64082. return true;
  64083. }
  64084. return false;
  64085. }
  64086. }
  64087. RelativeRectangle::RelativeRectangle()
  64088. {
  64089. }
  64090. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64091. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64092. : left (left_), right (right_), top (top_), bottom (bottom_)
  64093. {
  64094. }
  64095. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  64096. : left (rect.getX()),
  64097. right (Expression::symbol (RelativeCoordinate::Strings::this_ + "." + RelativeCoordinate::Strings::left)
  64098. + Expression ((double) rect.getWidth())),
  64099. top (rect.getY()),
  64100. bottom (Expression::symbol (RelativeCoordinate::Strings::this_ + "." + RelativeCoordinate::Strings::top)
  64101. + Expression ((double) rect.getHeight()))
  64102. {
  64103. }
  64104. RelativeRectangle::RelativeRectangle (const String& s)
  64105. {
  64106. int i = 0;
  64107. left = RelativeCoordinate (Expression::parse (s, i));
  64108. RelativeRectangleHelpers::skipComma (s, i);
  64109. top = RelativeCoordinate (Expression::parse (s, i));
  64110. RelativeRectangleHelpers::skipComma (s, i);
  64111. right = RelativeCoordinate (Expression::parse (s, i));
  64112. RelativeRectangleHelpers::skipComma (s, i);
  64113. bottom = RelativeCoordinate (Expression::parse (s, i));
  64114. }
  64115. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64116. {
  64117. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64118. }
  64119. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64120. {
  64121. return ! operator== (other);
  64122. }
  64123. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64124. {
  64125. const double l = left.resolve (context);
  64126. const double r = right.resolve (context);
  64127. const double t = top.resolve (context);
  64128. const double b = bottom.resolve (context);
  64129. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64130. }
  64131. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64132. {
  64133. left.moveToAbsolute (newPos.getX(), context);
  64134. right.moveToAbsolute (newPos.getRight(), context);
  64135. top.moveToAbsolute (newPos.getY(), context);
  64136. bottom.moveToAbsolute (newPos.getBottom(), context);
  64137. }
  64138. bool RelativeRectangle::isDynamic() const
  64139. {
  64140. using namespace RelativeRectangleHelpers;
  64141. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64142. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64143. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64144. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64145. }
  64146. const String RelativeRectangle::toString() const
  64147. {
  64148. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64149. }
  64150. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64151. {
  64152. left.renameSymbolIfUsed (oldName, newName);
  64153. right.renameSymbolIfUsed (oldName, newName);
  64154. top.renameSymbolIfUsed (oldName, newName);
  64155. bottom.renameSymbolIfUsed (oldName, newName);
  64156. }
  64157. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64158. {
  64159. public:
  64160. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64161. : RelativeCoordinatePositionerBase (component_),
  64162. rectangle (rectangle_)
  64163. {
  64164. }
  64165. bool registerCoordinates()
  64166. {
  64167. bool ok = addCoordinate (rectangle.left);
  64168. ok = addCoordinate (rectangle.right) && ok;
  64169. ok = addCoordinate (rectangle.top) && ok;
  64170. ok = addCoordinate (rectangle.bottom) && ok;
  64171. return ok;
  64172. }
  64173. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64174. {
  64175. return rectangle == other;
  64176. }
  64177. void applyToComponentBounds()
  64178. {
  64179. for (int i = 4; --i >= 0;)
  64180. {
  64181. const Rectangle<int> newBounds (rectangle.resolve (this).getSmallestIntegerContainer());
  64182. if (newBounds == getComponent().getBounds())
  64183. return;
  64184. getComponent().setBounds (newBounds);
  64185. }
  64186. jassertfalse; // must be a recursive reference!
  64187. }
  64188. private:
  64189. const RelativeRectangle rectangle;
  64190. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64191. };
  64192. // An expression context that can evaluate expressions using "this"
  64193. class TemporaryRectangleContext : public Expression::EvaluationContext
  64194. {
  64195. public:
  64196. TemporaryRectangleContext (const RelativeRectangle& rect_) : rect (rect_) {}
  64197. const Expression getSymbolValue (const String& objectName, const String& edge) const
  64198. {
  64199. if (objectName == RelativeCoordinate::Strings::this_)
  64200. {
  64201. if (edge == RelativeCoordinate::Strings::left) return rect.left.getExpression();
  64202. if (edge == RelativeCoordinate::Strings::right) return rect.right.getExpression();
  64203. if (edge == RelativeCoordinate::Strings::top) return rect.top.getExpression();
  64204. if (edge == RelativeCoordinate::Strings::bottom) return rect.bottom.getExpression();
  64205. }
  64206. return Expression::EvaluationContext::getSymbolValue (objectName, edge);
  64207. }
  64208. private:
  64209. const RelativeRectangle& rect;
  64210. JUCE_DECLARE_NON_COPYABLE (TemporaryRectangleContext);
  64211. };
  64212. void RelativeRectangle::applyToComponent (Component& component) const
  64213. {
  64214. if (isDynamic())
  64215. {
  64216. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64217. if (current == 0 || ! current->isUsingRectangle (*this))
  64218. {
  64219. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64220. component.setPositioner (p);
  64221. p->apply();
  64222. }
  64223. }
  64224. else
  64225. {
  64226. component.setPositioner (0);
  64227. TemporaryRectangleContext context (*this);
  64228. component.setBounds (resolve (&context).getSmallestIntegerContainer());
  64229. }
  64230. }
  64231. END_JUCE_NAMESPACE
  64232. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64233. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64234. BEGIN_JUCE_NAMESPACE
  64235. RelativePointPath::RelativePointPath()
  64236. : usesNonZeroWinding (true),
  64237. containsDynamicPoints (false)
  64238. {
  64239. }
  64240. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64241. : usesNonZeroWinding (true),
  64242. containsDynamicPoints (false)
  64243. {
  64244. for (int i = 0; i < other.elements.size(); ++i)
  64245. elements.add (other.elements.getUnchecked(i)->clone());
  64246. }
  64247. RelativePointPath::RelativePointPath (const Path& path)
  64248. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64249. containsDynamicPoints (false)
  64250. {
  64251. for (Path::Iterator i (path); i.next();)
  64252. {
  64253. switch (i.elementType)
  64254. {
  64255. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64256. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64257. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64258. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64259. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64260. default: jassertfalse; break;
  64261. }
  64262. }
  64263. }
  64264. RelativePointPath::~RelativePointPath()
  64265. {
  64266. }
  64267. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64268. {
  64269. if (elements.size() != other.elements.size()
  64270. || usesNonZeroWinding != other.usesNonZeroWinding
  64271. || containsDynamicPoints != other.containsDynamicPoints)
  64272. return false;
  64273. for (int i = 0; i < elements.size(); ++i)
  64274. {
  64275. ElementBase* const e1 = elements.getUnchecked(i);
  64276. ElementBase* const e2 = other.elements.getUnchecked(i);
  64277. if (e1->type != e2->type)
  64278. return false;
  64279. int numPoints1, numPoints2;
  64280. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64281. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64282. jassert (numPoints1 == numPoints2);
  64283. for (int j = numPoints1; --j >= 0;)
  64284. if (points1[j] != points2[j])
  64285. return false;
  64286. }
  64287. return true;
  64288. }
  64289. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64290. {
  64291. return ! operator== (other);
  64292. }
  64293. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64294. {
  64295. elements.swapWithArray (other.elements);
  64296. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64297. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64298. }
  64299. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64300. {
  64301. for (int i = 0; i < elements.size(); ++i)
  64302. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64303. }
  64304. bool RelativePointPath::containsAnyDynamicPoints() const
  64305. {
  64306. return containsDynamicPoints;
  64307. }
  64308. void RelativePointPath::addElement (ElementBase* newElement)
  64309. {
  64310. if (newElement != 0)
  64311. {
  64312. elements.add (newElement);
  64313. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64314. }
  64315. }
  64316. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64317. {
  64318. }
  64319. bool RelativePointPath::ElementBase::isDynamic()
  64320. {
  64321. int numPoints;
  64322. const RelativePoint* const points = getControlPoints (numPoints);
  64323. for (int i = numPoints; --i >= 0;)
  64324. if (points[i].isDynamic())
  64325. return true;
  64326. return false;
  64327. }
  64328. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64329. : ElementBase (startSubPathElement), startPos (pos)
  64330. {
  64331. }
  64332. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64333. {
  64334. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64335. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64336. return v;
  64337. }
  64338. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64339. {
  64340. path.startNewSubPath (startPos.resolve (coordFinder));
  64341. }
  64342. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64343. {
  64344. numPoints = 1;
  64345. return &startPos;
  64346. }
  64347. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64348. {
  64349. return new StartSubPath (startPos);
  64350. }
  64351. RelativePointPath::CloseSubPath::CloseSubPath()
  64352. : ElementBase (closeSubPathElement)
  64353. {
  64354. }
  64355. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64356. {
  64357. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64358. }
  64359. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64360. {
  64361. path.closeSubPath();
  64362. }
  64363. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64364. {
  64365. numPoints = 0;
  64366. return 0;
  64367. }
  64368. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64369. {
  64370. return new CloseSubPath();
  64371. }
  64372. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64373. : ElementBase (lineToElement), endPoint (endPoint_)
  64374. {
  64375. }
  64376. const ValueTree RelativePointPath::LineTo::createTree() const
  64377. {
  64378. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64379. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64380. return v;
  64381. }
  64382. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64383. {
  64384. path.lineTo (endPoint.resolve (coordFinder));
  64385. }
  64386. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64387. {
  64388. numPoints = 1;
  64389. return &endPoint;
  64390. }
  64391. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64392. {
  64393. return new LineTo (endPoint);
  64394. }
  64395. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64396. : ElementBase (quadraticToElement)
  64397. {
  64398. controlPoints[0] = controlPoint;
  64399. controlPoints[1] = endPoint;
  64400. }
  64401. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64402. {
  64403. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64404. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64405. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64406. return v;
  64407. }
  64408. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64409. {
  64410. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64411. controlPoints[1].resolve (coordFinder));
  64412. }
  64413. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64414. {
  64415. numPoints = 2;
  64416. return controlPoints;
  64417. }
  64418. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64419. {
  64420. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64421. }
  64422. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64423. : ElementBase (cubicToElement)
  64424. {
  64425. controlPoints[0] = controlPoint1;
  64426. controlPoints[1] = controlPoint2;
  64427. controlPoints[2] = endPoint;
  64428. }
  64429. const ValueTree RelativePointPath::CubicTo::createTree() const
  64430. {
  64431. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64432. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64433. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64434. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64435. return v;
  64436. }
  64437. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64438. {
  64439. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64440. controlPoints[1].resolve (coordFinder),
  64441. controlPoints[2].resolve (coordFinder));
  64442. }
  64443. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64444. {
  64445. numPoints = 3;
  64446. return controlPoints;
  64447. }
  64448. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64449. {
  64450. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64451. }
  64452. END_JUCE_NAMESPACE
  64453. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64454. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64455. BEGIN_JUCE_NAMESPACE
  64456. RelativeParallelogram::RelativeParallelogram()
  64457. {
  64458. }
  64459. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64460. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64461. {
  64462. }
  64463. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64464. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64465. {
  64466. }
  64467. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64468. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64469. {
  64470. }
  64471. RelativeParallelogram::~RelativeParallelogram()
  64472. {
  64473. }
  64474. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64475. {
  64476. points[0] = topLeft.resolve (coordFinder);
  64477. points[1] = topRight.resolve (coordFinder);
  64478. points[2] = bottomLeft.resolve (coordFinder);
  64479. }
  64480. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64481. {
  64482. resolveThreePoints (points, coordFinder);
  64483. points[3] = points[1] + (points[2] - points[0]);
  64484. }
  64485. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64486. {
  64487. Point<float> points[4];
  64488. resolveFourCorners (points, coordFinder);
  64489. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64490. }
  64491. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64492. {
  64493. Point<float> points[4];
  64494. resolveFourCorners (points, coordFinder);
  64495. path.startNewSubPath (points[0]);
  64496. path.lineTo (points[1]);
  64497. path.lineTo (points[3]);
  64498. path.lineTo (points[2]);
  64499. path.closeSubPath();
  64500. }
  64501. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64502. {
  64503. Point<float> corners[3];
  64504. resolveThreePoints (corners, coordFinder);
  64505. const Line<float> top (corners[0], corners[1]);
  64506. const Line<float> left (corners[0], corners[2]);
  64507. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64508. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64509. topRight.moveToAbsolute (newTopRight, coordFinder);
  64510. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64511. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64512. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64513. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64514. }
  64515. bool RelativeParallelogram::isDynamic() const
  64516. {
  64517. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64518. }
  64519. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64520. {
  64521. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64522. }
  64523. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64524. {
  64525. return ! operator== (other);
  64526. }
  64527. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64528. {
  64529. const Point<float> tr (corners[1] - corners[0]);
  64530. const Point<float> bl (corners[2] - corners[0]);
  64531. target -= corners[0];
  64532. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64533. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64534. }
  64535. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64536. {
  64537. return corners[0]
  64538. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64539. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64540. }
  64541. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64542. {
  64543. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64544. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64545. }
  64546. END_JUCE_NAMESPACE
  64547. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64548. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64549. BEGIN_JUCE_NAMESPACE
  64550. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64551. : Component::Positioner (component_), registeredOk (false)
  64552. {
  64553. }
  64554. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64555. {
  64556. unregisterListeners();
  64557. }
  64558. const Expression RelativeCoordinatePositionerBase::getSymbolValue (const String& objectName, const String& member) const
  64559. {
  64560. jassert (objectName.isNotEmpty());
  64561. if (member.isNotEmpty())
  64562. {
  64563. const Component* comp = getSourceComponent (objectName);
  64564. if (comp == 0)
  64565. {
  64566. if (objectName == RelativeCoordinate::Strings::parent)
  64567. comp = getComponent().getParentComponent();
  64568. else if (objectName == RelativeCoordinate::Strings::this_ || objectName == getComponent().getComponentID())
  64569. comp = &getComponent();
  64570. }
  64571. if (comp != 0)
  64572. {
  64573. if (member == RelativeCoordinate::Strings::left) return xToExpression (comp, 0);
  64574. if (member == RelativeCoordinate::Strings::right) return xToExpression (comp, comp->getWidth());
  64575. if (member == RelativeCoordinate::Strings::top) return yToExpression (comp, 0);
  64576. if (member == RelativeCoordinate::Strings::bottom) return yToExpression (comp, comp->getHeight());
  64577. }
  64578. }
  64579. for (int i = sourceMarkerLists.size(); --i >= 0;)
  64580. {
  64581. MarkerList* const markerList = sourceMarkerLists.getUnchecked(i);
  64582. const MarkerList::Marker* const marker = markerList->getMarker (objectName);
  64583. if (marker != 0)
  64584. return Expression (markerList->getMarkerPosition (*marker, getComponent().getParentComponent()));
  64585. }
  64586. return Expression::EvaluationContext::getSymbolValue (objectName, member);
  64587. }
  64588. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64589. {
  64590. apply();
  64591. }
  64592. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64593. {
  64594. apply();
  64595. }
  64596. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64597. {
  64598. jassert (sourceComponents.contains (&component));
  64599. sourceComponents.removeValue (&component);
  64600. }
  64601. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64602. {
  64603. apply();
  64604. }
  64605. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64606. {
  64607. jassert (sourceMarkerLists.contains (markerList));
  64608. sourceMarkerLists.removeValue (markerList);
  64609. }
  64610. void RelativeCoordinatePositionerBase::apply()
  64611. {
  64612. if (! registeredOk)
  64613. {
  64614. unregisterListeners();
  64615. registeredOk = registerCoordinates();
  64616. }
  64617. applyToComponentBounds();
  64618. }
  64619. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64620. {
  64621. return registerListeners (coord.getExpression());
  64622. }
  64623. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64624. {
  64625. const bool ok = addCoordinate (point.x);
  64626. return addCoordinate (point.y) && ok;
  64627. }
  64628. bool RelativeCoordinatePositionerBase::registerListeners (const Expression& e)
  64629. {
  64630. bool ok = true;
  64631. if (e.getType() == Expression::symbolType)
  64632. {
  64633. String objectName, memberName;
  64634. e.getSymbolParts (objectName, memberName);
  64635. if (memberName.isNotEmpty())
  64636. ok = registerComponent (objectName) && ok;
  64637. else
  64638. ok = registerMarker (objectName) && ok;
  64639. }
  64640. else
  64641. {
  64642. for (int i = e.getNumInputs(); --i >= 0;)
  64643. ok = registerListeners (e.getInput (i)) && ok;
  64644. }
  64645. return ok;
  64646. }
  64647. bool RelativeCoordinatePositionerBase::registerComponent (const String& componentID)
  64648. {
  64649. Component* comp = findComponent (componentID);
  64650. if (comp == 0)
  64651. {
  64652. if (componentID == RelativeCoordinate::Strings::parent)
  64653. comp = getComponent().getParentComponent();
  64654. else if (componentID == RelativeCoordinate::Strings::this_ || componentID == getComponent().getComponentID())
  64655. comp = &getComponent();
  64656. }
  64657. if (comp != 0)
  64658. {
  64659. if (comp != &getComponent())
  64660. registerComponentListener (comp);
  64661. return true;
  64662. }
  64663. else
  64664. {
  64665. // The component we want doesn't exist, so watch the parent in case the hierarchy changes and it appears later..
  64666. Component* const parent = getComponent().getParentComponent();
  64667. if (parent != 0)
  64668. registerComponentListener (parent);
  64669. else
  64670. registerComponentListener (&getComponent());
  64671. return false;
  64672. }
  64673. }
  64674. bool RelativeCoordinatePositionerBase::registerMarker (const String markerName)
  64675. {
  64676. Component* const parent = getComponent().getParentComponent();
  64677. if (parent != 0)
  64678. {
  64679. MarkerList* list = parent->getMarkers (true);
  64680. if (list == 0 || list->getMarker (markerName) == 0)
  64681. list = parent->getMarkers (false);
  64682. if (list != 0 && list->getMarker (markerName) != 0)
  64683. {
  64684. registerMarkerListListener (list);
  64685. return true;
  64686. }
  64687. else
  64688. {
  64689. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64690. registerMarkerListListener (parent->getMarkers (true));
  64691. registerMarkerListListener (parent->getMarkers (false));
  64692. }
  64693. }
  64694. return false;
  64695. }
  64696. void RelativeCoordinatePositionerBase::registerComponentListener (Component* const comp)
  64697. {
  64698. if (comp != 0 && ! sourceComponents.contains (comp))
  64699. {
  64700. comp->addComponentListener (this);
  64701. sourceComponents.add (comp);
  64702. }
  64703. }
  64704. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64705. {
  64706. if (list != 0 && ! sourceMarkerLists.contains (list))
  64707. {
  64708. list->addListener (this);
  64709. sourceMarkerLists.add (list);
  64710. }
  64711. }
  64712. void RelativeCoordinatePositionerBase::unregisterListeners()
  64713. {
  64714. int i;
  64715. for (i = sourceComponents.size(); --i >= 0;)
  64716. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64717. for (i = sourceMarkerLists.size(); --i >= 0;)
  64718. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64719. sourceComponents.clear();
  64720. sourceMarkerLists.clear();
  64721. }
  64722. Component* RelativeCoordinatePositionerBase::findComponent (const String& componentID) const
  64723. {
  64724. Component* const parent = getComponent().getParentComponent();
  64725. if (parent != 0)
  64726. {
  64727. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64728. {
  64729. Component* const c = parent->getChildComponent(i);
  64730. if (c->getComponentID() == componentID)
  64731. return c;
  64732. }
  64733. }
  64734. return 0;
  64735. }
  64736. Component* RelativeCoordinatePositionerBase::getSourceComponent (const String& objectName) const
  64737. {
  64738. for (int i = sourceComponents.size(); --i >= 0;)
  64739. {
  64740. Component* const comp = sourceComponents.getUnchecked(i);
  64741. if (comp->getComponentID() == objectName)
  64742. return comp;
  64743. }
  64744. return 0;
  64745. }
  64746. const Expression RelativeCoordinatePositionerBase::xToExpression (const Component* const source, const int x) const
  64747. {
  64748. return Expression ((double) (getComponent().getLocalPoint (source, Point<int> (x, 0)).getX() + getComponent().getX()));
  64749. }
  64750. const Expression RelativeCoordinatePositionerBase::yToExpression (const Component* const source, const int y) const
  64751. {
  64752. return Expression ((double) (getComponent().getLocalPoint (source, Point<int> (0, y)).getY() + getComponent().getY()));
  64753. }
  64754. END_JUCE_NAMESPACE
  64755. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64756. #endif
  64757. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64758. /*** Start of inlined file: juce_Colour.cpp ***/
  64759. BEGIN_JUCE_NAMESPACE
  64760. namespace ColourHelpers
  64761. {
  64762. uint8 floatAlphaToInt (const float alpha) throw()
  64763. {
  64764. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64765. }
  64766. void convertHSBtoRGB (float h, float s, float v,
  64767. uint8& r, uint8& g, uint8& b) throw()
  64768. {
  64769. v = jlimit (0.0f, 1.0f, v);
  64770. v *= 255.0f;
  64771. const uint8 intV = (uint8) roundToInt (v);
  64772. if (s <= 0)
  64773. {
  64774. r = intV;
  64775. g = intV;
  64776. b = intV;
  64777. }
  64778. else
  64779. {
  64780. s = jmin (1.0f, s);
  64781. h = jlimit (0.0f, 1.0f, h);
  64782. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64783. const float f = h - std::floor (h);
  64784. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64785. const float y = v * (1.0f - s * f);
  64786. const float z = v * (1.0f - (s * (1.0f - f)));
  64787. if (h < 1.0f)
  64788. {
  64789. r = intV;
  64790. g = (uint8) roundToInt (z);
  64791. b = x;
  64792. }
  64793. else if (h < 2.0f)
  64794. {
  64795. r = (uint8) roundToInt (y);
  64796. g = intV;
  64797. b = x;
  64798. }
  64799. else if (h < 3.0f)
  64800. {
  64801. r = x;
  64802. g = intV;
  64803. b = (uint8) roundToInt (z);
  64804. }
  64805. else if (h < 4.0f)
  64806. {
  64807. r = x;
  64808. g = (uint8) roundToInt (y);
  64809. b = intV;
  64810. }
  64811. else if (h < 5.0f)
  64812. {
  64813. r = (uint8) roundToInt (z);
  64814. g = x;
  64815. b = intV;
  64816. }
  64817. else if (h < 6.0f)
  64818. {
  64819. r = intV;
  64820. g = x;
  64821. b = (uint8) roundToInt (y);
  64822. }
  64823. else
  64824. {
  64825. r = 0;
  64826. g = 0;
  64827. b = 0;
  64828. }
  64829. }
  64830. }
  64831. }
  64832. Colour::Colour() throw()
  64833. : argb (0)
  64834. {
  64835. }
  64836. Colour::Colour (const Colour& other) throw()
  64837. : argb (other.argb)
  64838. {
  64839. }
  64840. Colour& Colour::operator= (const Colour& other) throw()
  64841. {
  64842. argb = other.argb;
  64843. return *this;
  64844. }
  64845. bool Colour::operator== (const Colour& other) const throw()
  64846. {
  64847. return argb.getARGB() == other.argb.getARGB();
  64848. }
  64849. bool Colour::operator!= (const Colour& other) const throw()
  64850. {
  64851. return argb.getARGB() != other.argb.getARGB();
  64852. }
  64853. Colour::Colour (const uint32 argb_) throw()
  64854. : argb (argb_)
  64855. {
  64856. }
  64857. Colour::Colour (const uint8 red,
  64858. const uint8 green,
  64859. const uint8 blue) throw()
  64860. {
  64861. argb.setARGB (0xff, red, green, blue);
  64862. }
  64863. const Colour Colour::fromRGB (const uint8 red,
  64864. const uint8 green,
  64865. const uint8 blue) throw()
  64866. {
  64867. return Colour (red, green, blue);
  64868. }
  64869. Colour::Colour (const uint8 red,
  64870. const uint8 green,
  64871. const uint8 blue,
  64872. const uint8 alpha) throw()
  64873. {
  64874. argb.setARGB (alpha, red, green, blue);
  64875. }
  64876. const Colour Colour::fromRGBA (const uint8 red,
  64877. const uint8 green,
  64878. const uint8 blue,
  64879. const uint8 alpha) throw()
  64880. {
  64881. return Colour (red, green, blue, alpha);
  64882. }
  64883. Colour::Colour (const uint8 red,
  64884. const uint8 green,
  64885. const uint8 blue,
  64886. const float alpha) throw()
  64887. {
  64888. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64889. }
  64890. const Colour Colour::fromRGBAFloat (const uint8 red,
  64891. const uint8 green,
  64892. const uint8 blue,
  64893. const float alpha) throw()
  64894. {
  64895. return Colour (red, green, blue, alpha);
  64896. }
  64897. Colour::Colour (const float hue,
  64898. const float saturation,
  64899. const float brightness,
  64900. const float alpha) throw()
  64901. {
  64902. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64903. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64904. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64905. }
  64906. const Colour Colour::fromHSV (const float hue,
  64907. const float saturation,
  64908. const float brightness,
  64909. const float alpha) throw()
  64910. {
  64911. return Colour (hue, saturation, brightness, alpha);
  64912. }
  64913. Colour::Colour (const float hue,
  64914. const float saturation,
  64915. const float brightness,
  64916. const uint8 alpha) throw()
  64917. {
  64918. uint8 r = getRed(), g = getGreen(), b = getBlue();
  64919. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64920. argb.setARGB (alpha, r, g, b);
  64921. }
  64922. Colour::~Colour() throw()
  64923. {
  64924. }
  64925. const PixelARGB Colour::getPixelARGB() const throw()
  64926. {
  64927. PixelARGB p (argb);
  64928. p.premultiply();
  64929. return p;
  64930. }
  64931. uint32 Colour::getARGB() const throw()
  64932. {
  64933. return argb.getARGB();
  64934. }
  64935. bool Colour::isTransparent() const throw()
  64936. {
  64937. return getAlpha() == 0;
  64938. }
  64939. bool Colour::isOpaque() const throw()
  64940. {
  64941. return getAlpha() == 0xff;
  64942. }
  64943. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64944. {
  64945. PixelARGB newCol (argb);
  64946. newCol.setAlpha (newAlpha);
  64947. return Colour (newCol.getARGB());
  64948. }
  64949. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64950. {
  64951. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64952. PixelARGB newCol (argb);
  64953. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64954. return Colour (newCol.getARGB());
  64955. }
  64956. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64957. {
  64958. jassert (alphaMultiplier >= 0);
  64959. PixelARGB newCol (argb);
  64960. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64961. return Colour (newCol.getARGB());
  64962. }
  64963. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64964. {
  64965. const int destAlpha = getAlpha();
  64966. if (destAlpha > 0)
  64967. {
  64968. const int invA = 0xff - (int) src.getAlpha();
  64969. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64970. if (resA > 0)
  64971. {
  64972. const int da = (invA * destAlpha) / resA;
  64973. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64974. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64975. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64976. (uint8) resA);
  64977. }
  64978. return *this;
  64979. }
  64980. else
  64981. {
  64982. return src;
  64983. }
  64984. }
  64985. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64986. {
  64987. if (proportionOfOther <= 0)
  64988. return *this;
  64989. if (proportionOfOther >= 1.0f)
  64990. return other;
  64991. PixelARGB c1 (getPixelARGB());
  64992. const PixelARGB c2 (other.getPixelARGB());
  64993. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64994. c1.unpremultiply();
  64995. return Colour (c1.getARGB());
  64996. }
  64997. float Colour::getFloatRed() const throw()
  64998. {
  64999. return getRed() / 255.0f;
  65000. }
  65001. float Colour::getFloatGreen() const throw()
  65002. {
  65003. return getGreen() / 255.0f;
  65004. }
  65005. float Colour::getFloatBlue() const throw()
  65006. {
  65007. return getBlue() / 255.0f;
  65008. }
  65009. float Colour::getFloatAlpha() const throw()
  65010. {
  65011. return getAlpha() / 255.0f;
  65012. }
  65013. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65014. {
  65015. const int r = getRed();
  65016. const int g = getGreen();
  65017. const int b = getBlue();
  65018. const int hi = jmax (r, g, b);
  65019. const int lo = jmin (r, g, b);
  65020. if (hi != 0)
  65021. {
  65022. s = (hi - lo) / (float) hi;
  65023. if (s != 0)
  65024. {
  65025. const float invDiff = 1.0f / (hi - lo);
  65026. const float red = (hi - r) * invDiff;
  65027. const float green = (hi - g) * invDiff;
  65028. const float blue = (hi - b) * invDiff;
  65029. if (r == hi)
  65030. h = blue - green;
  65031. else if (g == hi)
  65032. h = 2.0f + red - blue;
  65033. else
  65034. h = 4.0f + green - red;
  65035. h *= 1.0f / 6.0f;
  65036. if (h < 0)
  65037. ++h;
  65038. }
  65039. else
  65040. {
  65041. h = 0;
  65042. }
  65043. }
  65044. else
  65045. {
  65046. s = 0;
  65047. h = 0;
  65048. }
  65049. v = hi / 255.0f;
  65050. }
  65051. float Colour::getHue() const throw()
  65052. {
  65053. float h, s, b;
  65054. getHSB (h, s, b);
  65055. return h;
  65056. }
  65057. const Colour Colour::withHue (const float hue) const throw()
  65058. {
  65059. float h, s, b;
  65060. getHSB (h, s, b);
  65061. return Colour (hue, s, b, getAlpha());
  65062. }
  65063. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65064. {
  65065. float h, s, b;
  65066. getHSB (h, s, b);
  65067. h += amountToRotate;
  65068. h -= std::floor (h);
  65069. return Colour (h, s, b, getAlpha());
  65070. }
  65071. float Colour::getSaturation() const throw()
  65072. {
  65073. float h, s, b;
  65074. getHSB (h, s, b);
  65075. return s;
  65076. }
  65077. const Colour Colour::withSaturation (const float saturation) const throw()
  65078. {
  65079. float h, s, b;
  65080. getHSB (h, s, b);
  65081. return Colour (h, saturation, b, getAlpha());
  65082. }
  65083. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65084. {
  65085. float h, s, b;
  65086. getHSB (h, s, b);
  65087. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65088. }
  65089. float Colour::getBrightness() const throw()
  65090. {
  65091. float h, s, b;
  65092. getHSB (h, s, b);
  65093. return b;
  65094. }
  65095. const Colour Colour::withBrightness (const float brightness) const throw()
  65096. {
  65097. float h, s, b;
  65098. getHSB (h, s, b);
  65099. return Colour (h, s, brightness, getAlpha());
  65100. }
  65101. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65102. {
  65103. float h, s, b;
  65104. getHSB (h, s, b);
  65105. b *= amount;
  65106. if (b > 1.0f)
  65107. b = 1.0f;
  65108. return Colour (h, s, b, getAlpha());
  65109. }
  65110. const Colour Colour::brighter (float amount) const throw()
  65111. {
  65112. amount = 1.0f / (1.0f + amount);
  65113. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65114. (uint8) (255 - (amount * (255 - getGreen()))),
  65115. (uint8) (255 - (amount * (255 - getBlue()))),
  65116. getAlpha());
  65117. }
  65118. const Colour Colour::darker (float amount) const throw()
  65119. {
  65120. amount = 1.0f / (1.0f + amount);
  65121. return Colour ((uint8) (amount * getRed()),
  65122. (uint8) (amount * getGreen()),
  65123. (uint8) (amount * getBlue()),
  65124. getAlpha());
  65125. }
  65126. const Colour Colour::greyLevel (const float brightness) throw()
  65127. {
  65128. const uint8 level
  65129. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65130. return Colour (level, level, level);
  65131. }
  65132. const Colour Colour::contrasting (const float amount) const throw()
  65133. {
  65134. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65135. ? Colours::black
  65136. : Colours::white).withAlpha (amount));
  65137. }
  65138. const Colour Colour::contrasting (const Colour& colour1,
  65139. const Colour& colour2) throw()
  65140. {
  65141. const float b1 = colour1.getBrightness();
  65142. const float b2 = colour2.getBrightness();
  65143. float best = 0.0f;
  65144. float bestDist = 0.0f;
  65145. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65146. {
  65147. const float d1 = std::abs (i - b1);
  65148. const float d2 = std::abs (i - b2);
  65149. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65150. if (dist > bestDist)
  65151. {
  65152. best = i;
  65153. bestDist = dist;
  65154. }
  65155. }
  65156. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65157. .withBrightness (best);
  65158. }
  65159. const String Colour::toString() const
  65160. {
  65161. return String::toHexString ((int) argb.getARGB());
  65162. }
  65163. const Colour Colour::fromString (const String& encodedColourString)
  65164. {
  65165. return Colour ((uint32) encodedColourString.getHexValue32());
  65166. }
  65167. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65168. {
  65169. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65170. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65171. .toUpperCase();
  65172. }
  65173. END_JUCE_NAMESPACE
  65174. /*** End of inlined file: juce_Colour.cpp ***/
  65175. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65176. BEGIN_JUCE_NAMESPACE
  65177. ColourGradient::ColourGradient() throw()
  65178. {
  65179. #if JUCE_DEBUG
  65180. point1.setX (987654.0f);
  65181. #endif
  65182. }
  65183. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65184. const Colour& colour2, const float x2_, const float y2_,
  65185. const bool isRadial_)
  65186. : point1 (x1_, y1_),
  65187. point2 (x2_, y2_),
  65188. isRadial (isRadial_)
  65189. {
  65190. colours.add (ColourPoint (0.0, colour1));
  65191. colours.add (ColourPoint (1.0, colour2));
  65192. }
  65193. ColourGradient::~ColourGradient()
  65194. {
  65195. }
  65196. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65197. {
  65198. return point1 == other.point1 && point2 == other.point2
  65199. && isRadial == other.isRadial
  65200. && colours == other.colours;
  65201. }
  65202. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65203. {
  65204. return ! operator== (other);
  65205. }
  65206. void ColourGradient::clearColours()
  65207. {
  65208. colours.clear();
  65209. }
  65210. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65211. {
  65212. // must be within the two end-points
  65213. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65214. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65215. int i;
  65216. for (i = 0; i < colours.size(); ++i)
  65217. if (colours.getReference(i).position > pos)
  65218. break;
  65219. colours.insert (i, ColourPoint (pos, colour));
  65220. return i;
  65221. }
  65222. void ColourGradient::removeColour (int index)
  65223. {
  65224. jassert (index > 0 && index < colours.size() - 1);
  65225. colours.remove (index);
  65226. }
  65227. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65228. {
  65229. for (int i = 0; i < colours.size(); ++i)
  65230. {
  65231. Colour& c = colours.getReference(i).colour;
  65232. c = c.withMultipliedAlpha (multiplier);
  65233. }
  65234. }
  65235. int ColourGradient::getNumColours() const throw()
  65236. {
  65237. return colours.size();
  65238. }
  65239. double ColourGradient::getColourPosition (const int index) const throw()
  65240. {
  65241. if (isPositiveAndBelow (index, colours.size()))
  65242. return colours.getReference (index).position;
  65243. return 0;
  65244. }
  65245. const Colour ColourGradient::getColour (const int index) const throw()
  65246. {
  65247. if (isPositiveAndBelow (index, colours.size()))
  65248. return colours.getReference (index).colour;
  65249. return Colour();
  65250. }
  65251. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65252. {
  65253. if (isPositiveAndBelow (index, colours.size()))
  65254. colours.getReference (index).colour = newColour;
  65255. }
  65256. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65257. {
  65258. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65259. if (position <= 0 || colours.size() <= 1)
  65260. return colours.getReference(0).colour;
  65261. int i = colours.size() - 1;
  65262. while (position < colours.getReference(i).position)
  65263. --i;
  65264. const ColourPoint& p1 = colours.getReference (i);
  65265. if (i >= colours.size() - 1)
  65266. return p1.colour;
  65267. const ColourPoint& p2 = colours.getReference (i + 1);
  65268. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65269. }
  65270. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65271. {
  65272. #if JUCE_DEBUG
  65273. // trying to use the object without setting its co-ordinates? Have a careful read of
  65274. // the comments for the constructors.
  65275. jassert (point1.getX() != 987654.0f);
  65276. #endif
  65277. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65278. 3 * (int) point1.transformedBy (transform)
  65279. .getDistanceFrom (point2.transformedBy (transform)));
  65280. lookupTable.malloc (numEntries);
  65281. if (colours.size() >= 2)
  65282. {
  65283. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65284. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65285. int index = 0;
  65286. for (int j = 1; j < colours.size(); ++j)
  65287. {
  65288. const ColourPoint& p = colours.getReference (j);
  65289. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65290. const PixelARGB pix2 (p.colour.getPixelARGB());
  65291. for (int i = 0; i < numToDo; ++i)
  65292. {
  65293. jassert (index >= 0 && index < numEntries);
  65294. lookupTable[index] = pix1;
  65295. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65296. ++index;
  65297. }
  65298. pix1 = pix2;
  65299. }
  65300. while (index < numEntries)
  65301. lookupTable [index++] = pix1;
  65302. }
  65303. else
  65304. {
  65305. jassertfalse; // no colours specified!
  65306. }
  65307. return numEntries;
  65308. }
  65309. bool ColourGradient::isOpaque() const throw()
  65310. {
  65311. for (int i = 0; i < colours.size(); ++i)
  65312. if (! colours.getReference(i).colour.isOpaque())
  65313. return false;
  65314. return true;
  65315. }
  65316. bool ColourGradient::isInvisible() const throw()
  65317. {
  65318. for (int i = 0; i < colours.size(); ++i)
  65319. if (! colours.getReference(i).colour.isTransparent())
  65320. return false;
  65321. return true;
  65322. }
  65323. END_JUCE_NAMESPACE
  65324. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65325. /*** Start of inlined file: juce_Colours.cpp ***/
  65326. BEGIN_JUCE_NAMESPACE
  65327. const Colour Colours::transparentBlack (0);
  65328. const Colour Colours::transparentWhite (0x00ffffff);
  65329. const Colour Colours::aliceblue (0xfff0f8ff);
  65330. const Colour Colours::antiquewhite (0xfffaebd7);
  65331. const Colour Colours::aqua (0xff00ffff);
  65332. const Colour Colours::aquamarine (0xff7fffd4);
  65333. const Colour Colours::azure (0xfff0ffff);
  65334. const Colour Colours::beige (0xfff5f5dc);
  65335. const Colour Colours::bisque (0xffffe4c4);
  65336. const Colour Colours::black (0xff000000);
  65337. const Colour Colours::blanchedalmond (0xffffebcd);
  65338. const Colour Colours::blue (0xff0000ff);
  65339. const Colour Colours::blueviolet (0xff8a2be2);
  65340. const Colour Colours::brown (0xffa52a2a);
  65341. const Colour Colours::burlywood (0xffdeb887);
  65342. const Colour Colours::cadetblue (0xff5f9ea0);
  65343. const Colour Colours::chartreuse (0xff7fff00);
  65344. const Colour Colours::chocolate (0xffd2691e);
  65345. const Colour Colours::coral (0xffff7f50);
  65346. const Colour Colours::cornflowerblue (0xff6495ed);
  65347. const Colour Colours::cornsilk (0xfffff8dc);
  65348. const Colour Colours::crimson (0xffdc143c);
  65349. const Colour Colours::cyan (0xff00ffff);
  65350. const Colour Colours::darkblue (0xff00008b);
  65351. const Colour Colours::darkcyan (0xff008b8b);
  65352. const Colour Colours::darkgoldenrod (0xffb8860b);
  65353. const Colour Colours::darkgrey (0xff555555);
  65354. const Colour Colours::darkgreen (0xff006400);
  65355. const Colour Colours::darkkhaki (0xffbdb76b);
  65356. const Colour Colours::darkmagenta (0xff8b008b);
  65357. const Colour Colours::darkolivegreen (0xff556b2f);
  65358. const Colour Colours::darkorange (0xffff8c00);
  65359. const Colour Colours::darkorchid (0xff9932cc);
  65360. const Colour Colours::darkred (0xff8b0000);
  65361. const Colour Colours::darksalmon (0xffe9967a);
  65362. const Colour Colours::darkseagreen (0xff8fbc8f);
  65363. const Colour Colours::darkslateblue (0xff483d8b);
  65364. const Colour Colours::darkslategrey (0xff2f4f4f);
  65365. const Colour Colours::darkturquoise (0xff00ced1);
  65366. const Colour Colours::darkviolet (0xff9400d3);
  65367. const Colour Colours::deeppink (0xffff1493);
  65368. const Colour Colours::deepskyblue (0xff00bfff);
  65369. const Colour Colours::dimgrey (0xff696969);
  65370. const Colour Colours::dodgerblue (0xff1e90ff);
  65371. const Colour Colours::firebrick (0xffb22222);
  65372. const Colour Colours::floralwhite (0xfffffaf0);
  65373. const Colour Colours::forestgreen (0xff228b22);
  65374. const Colour Colours::fuchsia (0xffff00ff);
  65375. const Colour Colours::gainsboro (0xffdcdcdc);
  65376. const Colour Colours::gold (0xffffd700);
  65377. const Colour Colours::goldenrod (0xffdaa520);
  65378. const Colour Colours::grey (0xff808080);
  65379. const Colour Colours::green (0xff008000);
  65380. const Colour Colours::greenyellow (0xffadff2f);
  65381. const Colour Colours::honeydew (0xfff0fff0);
  65382. const Colour Colours::hotpink (0xffff69b4);
  65383. const Colour Colours::indianred (0xffcd5c5c);
  65384. const Colour Colours::indigo (0xff4b0082);
  65385. const Colour Colours::ivory (0xfffffff0);
  65386. const Colour Colours::khaki (0xfff0e68c);
  65387. const Colour Colours::lavender (0xffe6e6fa);
  65388. const Colour Colours::lavenderblush (0xfffff0f5);
  65389. const Colour Colours::lemonchiffon (0xfffffacd);
  65390. const Colour Colours::lightblue (0xffadd8e6);
  65391. const Colour Colours::lightcoral (0xfff08080);
  65392. const Colour Colours::lightcyan (0xffe0ffff);
  65393. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65394. const Colour Colours::lightgreen (0xff90ee90);
  65395. const Colour Colours::lightgrey (0xffd3d3d3);
  65396. const Colour Colours::lightpink (0xffffb6c1);
  65397. const Colour Colours::lightsalmon (0xffffa07a);
  65398. const Colour Colours::lightseagreen (0xff20b2aa);
  65399. const Colour Colours::lightskyblue (0xff87cefa);
  65400. const Colour Colours::lightslategrey (0xff778899);
  65401. const Colour Colours::lightsteelblue (0xffb0c4de);
  65402. const Colour Colours::lightyellow (0xffffffe0);
  65403. const Colour Colours::lime (0xff00ff00);
  65404. const Colour Colours::limegreen (0xff32cd32);
  65405. const Colour Colours::linen (0xfffaf0e6);
  65406. const Colour Colours::magenta (0xffff00ff);
  65407. const Colour Colours::maroon (0xff800000);
  65408. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65409. const Colour Colours::mediumblue (0xff0000cd);
  65410. const Colour Colours::mediumorchid (0xffba55d3);
  65411. const Colour Colours::mediumpurple (0xff9370db);
  65412. const Colour Colours::mediumseagreen (0xff3cb371);
  65413. const Colour Colours::mediumslateblue (0xff7b68ee);
  65414. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65415. const Colour Colours::mediumturquoise (0xff48d1cc);
  65416. const Colour Colours::mediumvioletred (0xffc71585);
  65417. const Colour Colours::midnightblue (0xff191970);
  65418. const Colour Colours::mintcream (0xfff5fffa);
  65419. const Colour Colours::mistyrose (0xffffe4e1);
  65420. const Colour Colours::navajowhite (0xffffdead);
  65421. const Colour Colours::navy (0xff000080);
  65422. const Colour Colours::oldlace (0xfffdf5e6);
  65423. const Colour Colours::olive (0xff808000);
  65424. const Colour Colours::olivedrab (0xff6b8e23);
  65425. const Colour Colours::orange (0xffffa500);
  65426. const Colour Colours::orangered (0xffff4500);
  65427. const Colour Colours::orchid (0xffda70d6);
  65428. const Colour Colours::palegoldenrod (0xffeee8aa);
  65429. const Colour Colours::palegreen (0xff98fb98);
  65430. const Colour Colours::paleturquoise (0xffafeeee);
  65431. const Colour Colours::palevioletred (0xffdb7093);
  65432. const Colour Colours::papayawhip (0xffffefd5);
  65433. const Colour Colours::peachpuff (0xffffdab9);
  65434. const Colour Colours::peru (0xffcd853f);
  65435. const Colour Colours::pink (0xffffc0cb);
  65436. const Colour Colours::plum (0xffdda0dd);
  65437. const Colour Colours::powderblue (0xffb0e0e6);
  65438. const Colour Colours::purple (0xff800080);
  65439. const Colour Colours::red (0xffff0000);
  65440. const Colour Colours::rosybrown (0xffbc8f8f);
  65441. const Colour Colours::royalblue (0xff4169e1);
  65442. const Colour Colours::saddlebrown (0xff8b4513);
  65443. const Colour Colours::salmon (0xfffa8072);
  65444. const Colour Colours::sandybrown (0xfff4a460);
  65445. const Colour Colours::seagreen (0xff2e8b57);
  65446. const Colour Colours::seashell (0xfffff5ee);
  65447. const Colour Colours::sienna (0xffa0522d);
  65448. const Colour Colours::silver (0xffc0c0c0);
  65449. const Colour Colours::skyblue (0xff87ceeb);
  65450. const Colour Colours::slateblue (0xff6a5acd);
  65451. const Colour Colours::slategrey (0xff708090);
  65452. const Colour Colours::snow (0xfffffafa);
  65453. const Colour Colours::springgreen (0xff00ff7f);
  65454. const Colour Colours::steelblue (0xff4682b4);
  65455. const Colour Colours::tan (0xffd2b48c);
  65456. const Colour Colours::teal (0xff008080);
  65457. const Colour Colours::thistle (0xffd8bfd8);
  65458. const Colour Colours::tomato (0xffff6347);
  65459. const Colour Colours::turquoise (0xff40e0d0);
  65460. const Colour Colours::violet (0xffee82ee);
  65461. const Colour Colours::wheat (0xfff5deb3);
  65462. const Colour Colours::white (0xffffffff);
  65463. const Colour Colours::whitesmoke (0xfff5f5f5);
  65464. const Colour Colours::yellow (0xffffff00);
  65465. const Colour Colours::yellowgreen (0xff9acd32);
  65466. const Colour Colours::findColourForName (const String& colourName,
  65467. const Colour& defaultColour)
  65468. {
  65469. static const int presets[] =
  65470. {
  65471. // (first value is the string's hashcode, second is ARGB)
  65472. 0x05978fff, 0xff000000, /* black */
  65473. 0x06bdcc29, 0xffffffff, /* white */
  65474. 0x002e305a, 0xff0000ff, /* blue */
  65475. 0x00308adf, 0xff808080, /* grey */
  65476. 0x05e0cf03, 0xff008000, /* green */
  65477. 0x0001b891, 0xffff0000, /* red */
  65478. 0xd43c6474, 0xffffff00, /* yellow */
  65479. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65480. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65481. 0x002dcebc, 0xff00ffff, /* aqua */
  65482. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65483. 0x0590228f, 0xfff0ffff, /* azure */
  65484. 0x05947fe4, 0xfff5f5dc, /* beige */
  65485. 0xad388e35, 0xffffe4c4, /* bisque */
  65486. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65487. 0x39129959, 0xff8a2be2, /* blueviolet */
  65488. 0x059a8136, 0xffa52a2a, /* brown */
  65489. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65490. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65491. 0x6b748956, 0xff7fff00, /* chartreuse */
  65492. 0x2903623c, 0xffd2691e, /* chocolate */
  65493. 0x05a74431, 0xffff7f50, /* coral */
  65494. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65495. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65496. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65497. 0x002ed323, 0xff00ffff, /* cyan */
  65498. 0x67cc74d0, 0xff00008b, /* darkblue */
  65499. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65500. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65501. 0x67cecf55, 0xff555555, /* darkgrey */
  65502. 0x920b194d, 0xff006400, /* darkgreen */
  65503. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65504. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65505. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65506. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65507. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65508. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65509. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65510. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65511. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65512. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65513. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65514. 0xc8769375, 0xff9400d3, /* darkviolet */
  65515. 0x25832862, 0xffff1493, /* deeppink */
  65516. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65517. 0x634c8b67, 0xff696969, /* dimgrey */
  65518. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65519. 0xef19e3cb, 0xffb22222, /* firebrick */
  65520. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65521. 0xd086fd06, 0xff228b22, /* forestgreen */
  65522. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65523. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65524. 0x00308060, 0xffffd700, /* gold */
  65525. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65526. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65527. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65528. 0x41892743, 0xffff69b4, /* hotpink */
  65529. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65530. 0xb969fed2, 0xff4b0082, /* indigo */
  65531. 0x05fef6a9, 0xfffffff0, /* ivory */
  65532. 0x06149302, 0xfff0e68c, /* khaki */
  65533. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65534. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65535. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65536. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65537. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65538. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65539. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65540. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65541. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65542. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65543. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65544. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65545. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65546. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65547. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65548. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65549. 0x0032afd5, 0xff00ff00, /* lime */
  65550. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65551. 0x06234efa, 0xfffaf0e6, /* linen */
  65552. 0x316858a9, 0xffff00ff, /* magenta */
  65553. 0xbf8ca470, 0xff800000, /* maroon */
  65554. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65555. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65556. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65557. 0x07556b71, 0xff9370db, /* mediumpurple */
  65558. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65559. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65560. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65561. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65562. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65563. 0x168eb32a, 0xff191970, /* midnightblue */
  65564. 0x4306b960, 0xfff5fffa, /* mintcream */
  65565. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65566. 0xe97218a6, 0xffffdead, /* navajowhite */
  65567. 0x00337bb6, 0xff000080, /* navy */
  65568. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65569. 0x064ee1db, 0xff808000, /* olive */
  65570. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65571. 0xc3de262e, 0xffffa500, /* orange */
  65572. 0x58bebba3, 0xffff4500, /* orangered */
  65573. 0xc3def8a3, 0xffda70d6, /* orchid */
  65574. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65575. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65576. 0x74022737, 0xffafeeee, /* paleturquoise */
  65577. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65578. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65579. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65580. 0x003472f8, 0xffcd853f, /* peru */
  65581. 0x00348176, 0xffffc0cb, /* pink */
  65582. 0x00348d94, 0xffdda0dd, /* plum */
  65583. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65584. 0xc5c507bc, 0xff800080, /* purple */
  65585. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65586. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65587. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65588. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65589. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65590. 0x34636c14, 0xff2e8b57, /* seagreen */
  65591. 0x3507fb41, 0xfffff5ee, /* seashell */
  65592. 0xca348772, 0xffa0522d, /* sienna */
  65593. 0xca37d30d, 0xffc0c0c0, /* silver */
  65594. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65595. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65596. 0x44ab37f8, 0xff708090, /* slategrey */
  65597. 0x0035f183, 0xfffffafa, /* snow */
  65598. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65599. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65600. 0x0001bfa1, 0xffd2b48c, /* tan */
  65601. 0x0036425c, 0xff008080, /* teal */
  65602. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65603. 0xcc41600a, 0xffff6347, /* tomato */
  65604. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65605. 0xcf57947f, 0xffee82ee, /* violet */
  65606. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65607. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65608. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65609. };
  65610. const int hash = colourName.trim().toLowerCase().hashCode();
  65611. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65612. if (presets [i] == hash)
  65613. return Colour (presets [i + 1]);
  65614. return defaultColour;
  65615. }
  65616. END_JUCE_NAMESPACE
  65617. /*** End of inlined file: juce_Colours.cpp ***/
  65618. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65619. BEGIN_JUCE_NAMESPACE
  65620. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65621. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65622. const Path& path, const AffineTransform& transform)
  65623. : bounds (bounds_),
  65624. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65625. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65626. needToCheckEmptinesss (true)
  65627. {
  65628. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65629. int* t = table;
  65630. for (int i = bounds.getHeight(); --i >= 0;)
  65631. {
  65632. *t = 0;
  65633. t += lineStrideElements;
  65634. }
  65635. const int topLimit = bounds.getY() << 8;
  65636. const int heightLimit = bounds.getHeight() << 8;
  65637. const int leftLimit = bounds.getX() << 8;
  65638. const int rightLimit = bounds.getRight() << 8;
  65639. PathFlatteningIterator iter (path, transform);
  65640. while (iter.next())
  65641. {
  65642. int y1 = roundToInt (iter.y1 * 256.0f);
  65643. int y2 = roundToInt (iter.y2 * 256.0f);
  65644. if (y1 != y2)
  65645. {
  65646. y1 -= topLimit;
  65647. y2 -= topLimit;
  65648. const int startY = y1;
  65649. int direction = -1;
  65650. if (y1 > y2)
  65651. {
  65652. swapVariables (y1, y2);
  65653. direction = 1;
  65654. }
  65655. if (y1 < 0)
  65656. y1 = 0;
  65657. if (y2 > heightLimit)
  65658. y2 = heightLimit;
  65659. if (y1 < y2)
  65660. {
  65661. const double startX = 256.0f * iter.x1;
  65662. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65663. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65664. do
  65665. {
  65666. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65667. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65668. if (x < leftLimit)
  65669. x = leftLimit;
  65670. else if (x >= rightLimit)
  65671. x = rightLimit - 1;
  65672. addEdgePoint (x, y1 >> 8, direction * step);
  65673. y1 += step;
  65674. }
  65675. while (y1 < y2);
  65676. }
  65677. }
  65678. }
  65679. sanitiseLevels (path.isUsingNonZeroWinding());
  65680. }
  65681. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65682. : bounds (rectangleToAdd),
  65683. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65684. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65685. needToCheckEmptinesss (true)
  65686. {
  65687. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65688. table[0] = 0;
  65689. const int x1 = rectangleToAdd.getX() << 8;
  65690. const int x2 = rectangleToAdd.getRight() << 8;
  65691. int* t = table;
  65692. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65693. {
  65694. t[0] = 2;
  65695. t[1] = x1;
  65696. t[2] = 255;
  65697. t[3] = x2;
  65698. t[4] = 0;
  65699. t += lineStrideElements;
  65700. }
  65701. }
  65702. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65703. : bounds (rectanglesToAdd.getBounds()),
  65704. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65705. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65706. needToCheckEmptinesss (true)
  65707. {
  65708. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65709. int* t = table;
  65710. for (int i = bounds.getHeight(); --i >= 0;)
  65711. {
  65712. *t = 0;
  65713. t += lineStrideElements;
  65714. }
  65715. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65716. {
  65717. const Rectangle<int>* const r = iter.getRectangle();
  65718. const int x1 = r->getX() << 8;
  65719. const int x2 = r->getRight() << 8;
  65720. int y = r->getY() - bounds.getY();
  65721. for (int j = r->getHeight(); --j >= 0;)
  65722. {
  65723. addEdgePoint (x1, y, 255);
  65724. addEdgePoint (x2, y, -255);
  65725. ++y;
  65726. }
  65727. }
  65728. sanitiseLevels (true);
  65729. }
  65730. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65731. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65732. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65733. 2 + (int) rectangleToAdd.getWidth(),
  65734. 2 + (int) rectangleToAdd.getHeight())),
  65735. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65736. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65737. needToCheckEmptinesss (true)
  65738. {
  65739. jassert (! rectangleToAdd.isEmpty());
  65740. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65741. table[0] = 0;
  65742. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65743. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65744. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65745. jassert (y1 < 256);
  65746. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65747. if (x2 <= x1 || y2 <= y1)
  65748. {
  65749. bounds.setHeight (0);
  65750. return;
  65751. }
  65752. int lineY = 0;
  65753. int* t = table;
  65754. if ((y1 >> 8) == (y2 >> 8))
  65755. {
  65756. t[0] = 2;
  65757. t[1] = x1;
  65758. t[2] = y2 - y1;
  65759. t[3] = x2;
  65760. t[4] = 0;
  65761. ++lineY;
  65762. t += lineStrideElements;
  65763. }
  65764. else
  65765. {
  65766. t[0] = 2;
  65767. t[1] = x1;
  65768. t[2] = 255 - (y1 & 255);
  65769. t[3] = x2;
  65770. t[4] = 0;
  65771. ++lineY;
  65772. t += lineStrideElements;
  65773. while (lineY < (y2 >> 8))
  65774. {
  65775. t[0] = 2;
  65776. t[1] = x1;
  65777. t[2] = 255;
  65778. t[3] = x2;
  65779. t[4] = 0;
  65780. ++lineY;
  65781. t += lineStrideElements;
  65782. }
  65783. jassert (lineY < bounds.getHeight());
  65784. t[0] = 2;
  65785. t[1] = x1;
  65786. t[2] = y2 & 255;
  65787. t[3] = x2;
  65788. t[4] = 0;
  65789. ++lineY;
  65790. t += lineStrideElements;
  65791. }
  65792. while (lineY < bounds.getHeight())
  65793. {
  65794. t[0] = 0;
  65795. t += lineStrideElements;
  65796. ++lineY;
  65797. }
  65798. }
  65799. EdgeTable::EdgeTable (const EdgeTable& other)
  65800. {
  65801. operator= (other);
  65802. }
  65803. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65804. {
  65805. bounds = other.bounds;
  65806. maxEdgesPerLine = other.maxEdgesPerLine;
  65807. lineStrideElements = other.lineStrideElements;
  65808. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65809. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65810. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65811. return *this;
  65812. }
  65813. EdgeTable::~EdgeTable()
  65814. {
  65815. }
  65816. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65817. {
  65818. while (--numLines >= 0)
  65819. {
  65820. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65821. src += srcLineStride;
  65822. dest += destLineStride;
  65823. }
  65824. }
  65825. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65826. {
  65827. // Convert the table from relative windings to absolute levels..
  65828. int* lineStart = table;
  65829. for (int i = bounds.getHeight(); --i >= 0;)
  65830. {
  65831. int* line = lineStart;
  65832. lineStart += lineStrideElements;
  65833. int num = *line;
  65834. if (num == 0)
  65835. continue;
  65836. int level = 0;
  65837. if (useNonZeroWinding)
  65838. {
  65839. while (--num > 0)
  65840. {
  65841. line += 2;
  65842. level += *line;
  65843. int corrected = abs (level);
  65844. if (corrected >> 8)
  65845. corrected = 255;
  65846. *line = corrected;
  65847. }
  65848. }
  65849. else
  65850. {
  65851. while (--num > 0)
  65852. {
  65853. line += 2;
  65854. level += *line;
  65855. int corrected = abs (level);
  65856. if (corrected >> 8)
  65857. {
  65858. corrected &= 511;
  65859. if (corrected >> 8)
  65860. corrected = 511 - corrected;
  65861. }
  65862. *line = corrected;
  65863. }
  65864. }
  65865. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65866. }
  65867. }
  65868. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65869. {
  65870. if (newNumEdgesPerLine != maxEdgesPerLine)
  65871. {
  65872. maxEdgesPerLine = newNumEdgesPerLine;
  65873. jassert (bounds.getHeight() > 0);
  65874. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65875. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65876. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65877. table.swapWith (newTable);
  65878. lineStrideElements = newLineStrideElements;
  65879. }
  65880. }
  65881. void EdgeTable::optimiseTable()
  65882. {
  65883. int maxLineElements = 0;
  65884. for (int i = bounds.getHeight(); --i >= 0;)
  65885. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65886. remapTableForNumEdges (maxLineElements);
  65887. }
  65888. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65889. {
  65890. jassert (y >= 0 && y < bounds.getHeight());
  65891. int* line = table + lineStrideElements * y;
  65892. const int numPoints = line[0];
  65893. int n = numPoints << 1;
  65894. if (n > 0)
  65895. {
  65896. while (n > 0)
  65897. {
  65898. const int cx = line [n - 1];
  65899. if (cx <= x)
  65900. {
  65901. if (cx == x)
  65902. {
  65903. line [n] += winding;
  65904. return;
  65905. }
  65906. break;
  65907. }
  65908. n -= 2;
  65909. }
  65910. if (numPoints >= maxEdgesPerLine)
  65911. {
  65912. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65913. jassert (numPoints < maxEdgesPerLine);
  65914. line = table + lineStrideElements * y;
  65915. }
  65916. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65917. }
  65918. line [n + 1] = x;
  65919. line [n + 2] = winding;
  65920. line[0]++;
  65921. }
  65922. void EdgeTable::translate (float dx, const int dy) throw()
  65923. {
  65924. bounds.translate ((int) std::floor (dx), dy);
  65925. int* lineStart = table;
  65926. const int intDx = (int) (dx * 256.0f);
  65927. for (int i = bounds.getHeight(); --i >= 0;)
  65928. {
  65929. int* line = lineStart;
  65930. lineStart += lineStrideElements;
  65931. int num = *line++;
  65932. while (--num >= 0)
  65933. {
  65934. *line += intDx;
  65935. line += 2;
  65936. }
  65937. }
  65938. }
  65939. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65940. {
  65941. jassert (y >= 0 && y < bounds.getHeight());
  65942. int* dest = table + lineStrideElements * y;
  65943. if (dest[0] == 0)
  65944. return;
  65945. int otherNumPoints = *otherLine;
  65946. if (otherNumPoints == 0)
  65947. {
  65948. *dest = 0;
  65949. return;
  65950. }
  65951. const int right = bounds.getRight() << 8;
  65952. // optimise for the common case where our line lies entirely within a
  65953. // single pair of points, as happens when clipping to a simple rect.
  65954. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65955. {
  65956. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65957. return;
  65958. }
  65959. ++otherLine;
  65960. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65961. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65962. memcpy (temp, dest, lineSizeBytes);
  65963. const int* src1 = temp;
  65964. int srcNum1 = *src1++;
  65965. int x1 = *src1++;
  65966. const int* src2 = otherLine;
  65967. int srcNum2 = otherNumPoints;
  65968. int x2 = *src2++;
  65969. int destIndex = 0, destTotal = 0;
  65970. int level1 = 0, level2 = 0;
  65971. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65972. while (srcNum1 > 0 && srcNum2 > 0)
  65973. {
  65974. int nextX;
  65975. if (x1 < x2)
  65976. {
  65977. nextX = x1;
  65978. level1 = *src1++;
  65979. x1 = *src1++;
  65980. --srcNum1;
  65981. }
  65982. else if (x1 == x2)
  65983. {
  65984. nextX = x1;
  65985. level1 = *src1++;
  65986. level2 = *src2++;
  65987. x1 = *src1++;
  65988. x2 = *src2++;
  65989. --srcNum1;
  65990. --srcNum2;
  65991. }
  65992. else
  65993. {
  65994. nextX = x2;
  65995. level2 = *src2++;
  65996. x2 = *src2++;
  65997. --srcNum2;
  65998. }
  65999. if (nextX > lastX)
  66000. {
  66001. if (nextX >= right)
  66002. break;
  66003. lastX = nextX;
  66004. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66005. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  66006. if (nextLevel != lastLevel)
  66007. {
  66008. if (destTotal >= maxEdgesPerLine)
  66009. {
  66010. dest[0] = destTotal;
  66011. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66012. dest = table + lineStrideElements * y;
  66013. }
  66014. ++destTotal;
  66015. lastLevel = nextLevel;
  66016. dest[++destIndex] = nextX;
  66017. dest[++destIndex] = nextLevel;
  66018. }
  66019. }
  66020. }
  66021. if (lastLevel > 0)
  66022. {
  66023. if (destTotal >= maxEdgesPerLine)
  66024. {
  66025. dest[0] = destTotal;
  66026. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66027. dest = table + lineStrideElements * y;
  66028. }
  66029. ++destTotal;
  66030. dest[++destIndex] = right;
  66031. dest[++destIndex] = 0;
  66032. }
  66033. dest[0] = destTotal;
  66034. #if JUCE_DEBUG
  66035. int last = std::numeric_limits<int>::min();
  66036. for (int i = 0; i < dest[0]; ++i)
  66037. {
  66038. jassert (dest[i * 2 + 1] > last);
  66039. last = dest[i * 2 + 1];
  66040. }
  66041. jassert (dest [dest[0] * 2] == 0);
  66042. #endif
  66043. }
  66044. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66045. {
  66046. int* lastItem = dest + (dest[0] * 2 - 1);
  66047. if (x2 < lastItem[0])
  66048. {
  66049. if (x2 <= dest[1])
  66050. {
  66051. dest[0] = 0;
  66052. return;
  66053. }
  66054. while (x2 < lastItem[-2])
  66055. {
  66056. --(dest[0]);
  66057. lastItem -= 2;
  66058. }
  66059. lastItem[0] = x2;
  66060. lastItem[1] = 0;
  66061. }
  66062. if (x1 > dest[1])
  66063. {
  66064. while (lastItem[0] > x1)
  66065. lastItem -= 2;
  66066. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66067. if (itemsRemoved > 0)
  66068. {
  66069. dest[0] -= itemsRemoved;
  66070. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66071. }
  66072. dest[1] = x1;
  66073. }
  66074. }
  66075. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  66076. {
  66077. const Rectangle<int> clipped (r.getIntersection (bounds));
  66078. if (clipped.isEmpty())
  66079. {
  66080. needToCheckEmptinesss = false;
  66081. bounds.setHeight (0);
  66082. }
  66083. else
  66084. {
  66085. const int top = clipped.getY() - bounds.getY();
  66086. const int bottom = clipped.getBottom() - bounds.getY();
  66087. if (bottom < bounds.getHeight())
  66088. bounds.setHeight (bottom);
  66089. if (clipped.getRight() < bounds.getRight())
  66090. bounds.setRight (clipped.getRight());
  66091. for (int i = top; --i >= 0;)
  66092. table [lineStrideElements * i] = 0;
  66093. if (clipped.getX() > bounds.getX())
  66094. {
  66095. const int x1 = clipped.getX() << 8;
  66096. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66097. int* line = table + lineStrideElements * top;
  66098. for (int i = bottom - top; --i >= 0;)
  66099. {
  66100. if (line[0] != 0)
  66101. clipEdgeTableLineToRange (line, x1, x2);
  66102. line += lineStrideElements;
  66103. }
  66104. }
  66105. needToCheckEmptinesss = true;
  66106. }
  66107. }
  66108. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  66109. {
  66110. const Rectangle<int> clipped (r.getIntersection (bounds));
  66111. if (! clipped.isEmpty())
  66112. {
  66113. const int top = clipped.getY() - bounds.getY();
  66114. const int bottom = clipped.getBottom() - bounds.getY();
  66115. //XXX optimise here by shortening the table if it fills top or bottom
  66116. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66117. clipped.getX() << 8, 0,
  66118. clipped.getRight() << 8, 255,
  66119. std::numeric_limits<int>::max(), 0 };
  66120. for (int i = top; i < bottom; ++i)
  66121. intersectWithEdgeTableLine (i, rectLine);
  66122. needToCheckEmptinesss = true;
  66123. }
  66124. }
  66125. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66126. {
  66127. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66128. if (clipped.isEmpty())
  66129. {
  66130. needToCheckEmptinesss = false;
  66131. bounds.setHeight (0);
  66132. }
  66133. else
  66134. {
  66135. const int top = clipped.getY() - bounds.getY();
  66136. const int bottom = clipped.getBottom() - bounds.getY();
  66137. if (bottom < bounds.getHeight())
  66138. bounds.setHeight (bottom);
  66139. if (clipped.getRight() < bounds.getRight())
  66140. bounds.setRight (clipped.getRight());
  66141. int i = 0;
  66142. for (i = top; --i >= 0;)
  66143. table [lineStrideElements * i] = 0;
  66144. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66145. for (i = top; i < bottom; ++i)
  66146. {
  66147. intersectWithEdgeTableLine (i, otherLine);
  66148. otherLine += other.lineStrideElements;
  66149. }
  66150. needToCheckEmptinesss = true;
  66151. }
  66152. }
  66153. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66154. {
  66155. y -= bounds.getY();
  66156. if (y < 0 || y >= bounds.getHeight())
  66157. return;
  66158. needToCheckEmptinesss = true;
  66159. if (numPixels <= 0)
  66160. {
  66161. table [lineStrideElements * y] = 0;
  66162. return;
  66163. }
  66164. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66165. int destIndex = 0, lastLevel = 0;
  66166. while (--numPixels >= 0)
  66167. {
  66168. const int alpha = *mask;
  66169. mask += maskStride;
  66170. if (alpha != lastLevel)
  66171. {
  66172. tempLine[++destIndex] = (x << 8);
  66173. tempLine[++destIndex] = alpha;
  66174. lastLevel = alpha;
  66175. }
  66176. ++x;
  66177. }
  66178. if (lastLevel > 0)
  66179. {
  66180. tempLine[++destIndex] = (x << 8);
  66181. tempLine[++destIndex] = 0;
  66182. }
  66183. tempLine[0] = destIndex >> 1;
  66184. intersectWithEdgeTableLine (y, tempLine);
  66185. }
  66186. bool EdgeTable::isEmpty() throw()
  66187. {
  66188. if (needToCheckEmptinesss)
  66189. {
  66190. needToCheckEmptinesss = false;
  66191. int* t = table;
  66192. for (int i = bounds.getHeight(); --i >= 0;)
  66193. {
  66194. if (t[0] > 1)
  66195. return false;
  66196. t += lineStrideElements;
  66197. }
  66198. bounds.setHeight (0);
  66199. }
  66200. return bounds.getHeight() == 0;
  66201. }
  66202. END_JUCE_NAMESPACE
  66203. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66204. /*** Start of inlined file: juce_FillType.cpp ***/
  66205. BEGIN_JUCE_NAMESPACE
  66206. FillType::FillType() throw()
  66207. : colour (0xff000000), image (0)
  66208. {
  66209. }
  66210. FillType::FillType (const Colour& colour_) throw()
  66211. : colour (colour_), image (0)
  66212. {
  66213. }
  66214. FillType::FillType (const ColourGradient& gradient_)
  66215. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66216. {
  66217. }
  66218. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66219. : colour (0xff000000), image (image_), transform (transform_)
  66220. {
  66221. }
  66222. FillType::FillType (const FillType& other)
  66223. : colour (other.colour),
  66224. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66225. image (other.image), transform (other.transform)
  66226. {
  66227. }
  66228. FillType& FillType::operator= (const FillType& other)
  66229. {
  66230. if (this != &other)
  66231. {
  66232. colour = other.colour;
  66233. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66234. image = other.image;
  66235. transform = other.transform;
  66236. }
  66237. return *this;
  66238. }
  66239. FillType::~FillType() throw()
  66240. {
  66241. }
  66242. bool FillType::operator== (const FillType& other) const
  66243. {
  66244. return colour == other.colour && image == other.image
  66245. && transform == other.transform
  66246. && (gradient == other.gradient
  66247. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66248. }
  66249. bool FillType::operator!= (const FillType& other) const
  66250. {
  66251. return ! operator== (other);
  66252. }
  66253. void FillType::setColour (const Colour& newColour) throw()
  66254. {
  66255. gradient = 0;
  66256. image = Image::null;
  66257. colour = newColour;
  66258. }
  66259. void FillType::setGradient (const ColourGradient& newGradient)
  66260. {
  66261. if (gradient != 0)
  66262. {
  66263. *gradient = newGradient;
  66264. }
  66265. else
  66266. {
  66267. image = Image::null;
  66268. gradient = new ColourGradient (newGradient);
  66269. colour = Colours::black;
  66270. }
  66271. }
  66272. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66273. {
  66274. gradient = 0;
  66275. image = image_;
  66276. transform = transform_;
  66277. colour = Colours::black;
  66278. }
  66279. void FillType::setOpacity (const float newOpacity) throw()
  66280. {
  66281. colour = colour.withAlpha (newOpacity);
  66282. }
  66283. bool FillType::isInvisible() const throw()
  66284. {
  66285. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66286. }
  66287. END_JUCE_NAMESPACE
  66288. /*** End of inlined file: juce_FillType.cpp ***/
  66289. /*** Start of inlined file: juce_Graphics.cpp ***/
  66290. BEGIN_JUCE_NAMESPACE
  66291. namespace
  66292. {
  66293. template <typename Type>
  66294. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66295. {
  66296. const int maxVal = 0x3fffffff;
  66297. return (int) x >= -maxVal && (int) x <= maxVal
  66298. && (int) y >= -maxVal && (int) y <= maxVal
  66299. && (int) w >= -maxVal && (int) w <= maxVal
  66300. && (int) h >= -maxVal && (int) h <= maxVal;
  66301. }
  66302. }
  66303. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66304. {
  66305. }
  66306. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66307. {
  66308. }
  66309. Graphics::Graphics (const Image& imageToDrawOnto)
  66310. : context (imageToDrawOnto.createLowLevelContext()),
  66311. contextToDelete (context),
  66312. saveStatePending (false)
  66313. {
  66314. }
  66315. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66316. : context (internalContext),
  66317. saveStatePending (false)
  66318. {
  66319. }
  66320. Graphics::~Graphics()
  66321. {
  66322. }
  66323. void Graphics::resetToDefaultState()
  66324. {
  66325. saveStateIfPending();
  66326. context->setFill (FillType());
  66327. context->setFont (Font());
  66328. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66329. }
  66330. bool Graphics::isVectorDevice() const
  66331. {
  66332. return context->isVectorDevice();
  66333. }
  66334. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66335. {
  66336. saveStateIfPending();
  66337. return context->clipToRectangle (area);
  66338. }
  66339. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66340. {
  66341. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66342. }
  66343. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66344. {
  66345. saveStateIfPending();
  66346. return context->clipToRectangleList (clipRegion);
  66347. }
  66348. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66349. {
  66350. saveStateIfPending();
  66351. context->clipToPath (path, transform);
  66352. return ! context->isClipEmpty();
  66353. }
  66354. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66355. {
  66356. saveStateIfPending();
  66357. context->clipToImageAlpha (image, transform);
  66358. return ! context->isClipEmpty();
  66359. }
  66360. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66361. {
  66362. saveStateIfPending();
  66363. context->excludeClipRectangle (rectangleToExclude);
  66364. }
  66365. bool Graphics::isClipEmpty() const
  66366. {
  66367. return context->isClipEmpty();
  66368. }
  66369. const Rectangle<int> Graphics::getClipBounds() const
  66370. {
  66371. return context->getClipBounds();
  66372. }
  66373. void Graphics::saveState()
  66374. {
  66375. saveStateIfPending();
  66376. saveStatePending = true;
  66377. }
  66378. void Graphics::restoreState()
  66379. {
  66380. if (saveStatePending)
  66381. saveStatePending = false;
  66382. else
  66383. context->restoreState();
  66384. }
  66385. void Graphics::saveStateIfPending()
  66386. {
  66387. if (saveStatePending)
  66388. {
  66389. saveStatePending = false;
  66390. context->saveState();
  66391. }
  66392. }
  66393. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66394. {
  66395. saveStateIfPending();
  66396. context->setOrigin (newOriginX, newOriginY);
  66397. }
  66398. void Graphics::addTransform (const AffineTransform& transform)
  66399. {
  66400. saveStateIfPending();
  66401. context->addTransform (transform);
  66402. }
  66403. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66404. {
  66405. return context->clipRegionIntersects (area);
  66406. }
  66407. void Graphics::beginTransparencyLayer (float layerOpacity)
  66408. {
  66409. saveStateIfPending();
  66410. context->beginTransparencyLayer (layerOpacity);
  66411. }
  66412. void Graphics::endTransparencyLayer()
  66413. {
  66414. context->endTransparencyLayer();
  66415. }
  66416. void Graphics::setColour (const Colour& newColour)
  66417. {
  66418. saveStateIfPending();
  66419. context->setFill (newColour);
  66420. }
  66421. void Graphics::setOpacity (const float newOpacity)
  66422. {
  66423. saveStateIfPending();
  66424. context->setOpacity (newOpacity);
  66425. }
  66426. void Graphics::setGradientFill (const ColourGradient& gradient)
  66427. {
  66428. setFillType (gradient);
  66429. }
  66430. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66431. {
  66432. saveStateIfPending();
  66433. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66434. context->setOpacity (opacity);
  66435. }
  66436. void Graphics::setFillType (const FillType& newFill)
  66437. {
  66438. saveStateIfPending();
  66439. context->setFill (newFill);
  66440. }
  66441. void Graphics::setFont (const Font& newFont)
  66442. {
  66443. saveStateIfPending();
  66444. context->setFont (newFont);
  66445. }
  66446. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66447. {
  66448. saveStateIfPending();
  66449. Font f (context->getFont());
  66450. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66451. context->setFont (f);
  66452. }
  66453. const Font Graphics::getCurrentFont() const
  66454. {
  66455. return context->getFont();
  66456. }
  66457. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66458. {
  66459. if (text.isNotEmpty()
  66460. && startX < context->getClipBounds().getRight())
  66461. {
  66462. GlyphArrangement arr;
  66463. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66464. arr.draw (*this);
  66465. }
  66466. }
  66467. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66468. {
  66469. if (text.isNotEmpty())
  66470. {
  66471. GlyphArrangement arr;
  66472. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66473. arr.draw (*this, transform);
  66474. }
  66475. }
  66476. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66477. {
  66478. if (text.isNotEmpty()
  66479. && startX < context->getClipBounds().getRight())
  66480. {
  66481. GlyphArrangement arr;
  66482. arr.addJustifiedText (context->getFont(), text,
  66483. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66484. Justification::left);
  66485. arr.draw (*this);
  66486. }
  66487. }
  66488. void Graphics::drawText (const String& text,
  66489. const int x, const int y, const int width, const int height,
  66490. const Justification& justificationType,
  66491. const bool useEllipsesIfTooBig) const
  66492. {
  66493. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66494. {
  66495. GlyphArrangement arr;
  66496. arr.addCurtailedLineOfText (context->getFont(), text,
  66497. 0.0f, 0.0f, (float) width,
  66498. useEllipsesIfTooBig);
  66499. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66500. (float) x, (float) y, (float) width, (float) height,
  66501. justificationType);
  66502. arr.draw (*this);
  66503. }
  66504. }
  66505. void Graphics::drawFittedText (const String& text,
  66506. const int x, const int y, const int width, const int height,
  66507. const Justification& justification,
  66508. const int maximumNumberOfLines,
  66509. const float minimumHorizontalScale) const
  66510. {
  66511. if (text.isNotEmpty()
  66512. && width > 0 && height > 0
  66513. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66514. {
  66515. GlyphArrangement arr;
  66516. arr.addFittedText (context->getFont(), text,
  66517. (float) x, (float) y, (float) width, (float) height,
  66518. justification,
  66519. maximumNumberOfLines,
  66520. minimumHorizontalScale);
  66521. arr.draw (*this);
  66522. }
  66523. }
  66524. void Graphics::fillRect (int x, int y, int width, int height) const
  66525. {
  66526. // passing in a silly number can cause maths problems in rendering!
  66527. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66528. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66529. }
  66530. void Graphics::fillRect (const Rectangle<int>& r) const
  66531. {
  66532. context->fillRect (r, false);
  66533. }
  66534. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66535. {
  66536. // passing in a silly number can cause maths problems in rendering!
  66537. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66538. Path p;
  66539. p.addRectangle (x, y, width, height);
  66540. fillPath (p);
  66541. }
  66542. void Graphics::setPixel (int x, int y) const
  66543. {
  66544. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66545. }
  66546. void Graphics::fillAll() const
  66547. {
  66548. fillRect (context->getClipBounds());
  66549. }
  66550. void Graphics::fillAll (const Colour& colourToUse) const
  66551. {
  66552. if (! colourToUse.isTransparent())
  66553. {
  66554. const Rectangle<int> clip (context->getClipBounds());
  66555. context->saveState();
  66556. context->setFill (colourToUse);
  66557. context->fillRect (clip, false);
  66558. context->restoreState();
  66559. }
  66560. }
  66561. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66562. {
  66563. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66564. context->fillPath (path, transform);
  66565. }
  66566. void Graphics::strokePath (const Path& path,
  66567. const PathStrokeType& strokeType,
  66568. const AffineTransform& transform) const
  66569. {
  66570. Path stroke;
  66571. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66572. fillPath (stroke);
  66573. }
  66574. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66575. const int lineThickness) const
  66576. {
  66577. // passing in a silly number can cause maths problems in rendering!
  66578. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66579. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66580. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66581. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66582. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66583. }
  66584. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66585. {
  66586. // passing in a silly number can cause maths problems in rendering!
  66587. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66588. Path p;
  66589. p.addRectangle (x, y, width, lineThickness);
  66590. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66591. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66592. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66593. fillPath (p);
  66594. }
  66595. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66596. {
  66597. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66598. }
  66599. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66600. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66601. const bool useGradient, const bool sharpEdgeOnOutside) const
  66602. {
  66603. // passing in a silly number can cause maths problems in rendering!
  66604. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66605. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66606. {
  66607. context->saveState();
  66608. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66609. const float ramp = oldOpacity / bevelThickness;
  66610. for (int i = bevelThickness; --i >= 0;)
  66611. {
  66612. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66613. : oldOpacity;
  66614. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66615. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66616. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66617. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66618. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66619. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66620. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66621. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66622. }
  66623. context->restoreState();
  66624. }
  66625. }
  66626. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66627. {
  66628. // passing in a silly number can cause maths problems in rendering!
  66629. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66630. Path p;
  66631. p.addEllipse (x, y, width, height);
  66632. fillPath (p);
  66633. }
  66634. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66635. const float lineThickness) const
  66636. {
  66637. // passing in a silly number can cause maths problems in rendering!
  66638. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66639. Path p;
  66640. p.addEllipse (x, y, width, height);
  66641. strokePath (p, PathStrokeType (lineThickness));
  66642. }
  66643. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66644. {
  66645. // passing in a silly number can cause maths problems in rendering!
  66646. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66647. Path p;
  66648. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66649. fillPath (p);
  66650. }
  66651. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66652. {
  66653. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66654. }
  66655. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66656. const float cornerSize, const float lineThickness) const
  66657. {
  66658. // passing in a silly number can cause maths problems in rendering!
  66659. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66660. Path p;
  66661. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66662. strokePath (p, PathStrokeType (lineThickness));
  66663. }
  66664. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66665. {
  66666. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66667. }
  66668. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66669. {
  66670. Path p;
  66671. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66672. fillPath (p);
  66673. }
  66674. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66675. const int checkWidth, const int checkHeight,
  66676. const Colour& colour1, const Colour& colour2) const
  66677. {
  66678. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66679. if (checkWidth > 0 && checkHeight > 0)
  66680. {
  66681. context->saveState();
  66682. if (colour1 == colour2)
  66683. {
  66684. context->setFill (colour1);
  66685. context->fillRect (area, false);
  66686. }
  66687. else
  66688. {
  66689. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66690. if (! clipped.isEmpty())
  66691. {
  66692. context->clipToRectangle (clipped);
  66693. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66694. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66695. const int startX = area.getX() + checkNumX * checkWidth;
  66696. const int startY = area.getY() + checkNumY * checkHeight;
  66697. const int right = clipped.getRight();
  66698. const int bottom = clipped.getBottom();
  66699. for (int i = 0; i < 2; ++i)
  66700. {
  66701. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66702. int cy = i;
  66703. for (int y = startY; y < bottom; y += checkHeight)
  66704. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66705. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66706. }
  66707. }
  66708. }
  66709. context->restoreState();
  66710. }
  66711. }
  66712. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66713. {
  66714. context->drawVerticalLine (x, top, bottom);
  66715. }
  66716. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66717. {
  66718. context->drawHorizontalLine (y, left, right);
  66719. }
  66720. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66721. {
  66722. context->drawLine (Line<float> (x1, y1, x2, y2));
  66723. }
  66724. void Graphics::drawLine (const float startX, const float startY,
  66725. const float endX, const float endY,
  66726. const float lineThickness) const
  66727. {
  66728. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66729. }
  66730. void Graphics::drawLine (const Line<float>& line) const
  66731. {
  66732. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66733. }
  66734. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66735. {
  66736. Path p;
  66737. p.addLineSegment (line, lineThickness);
  66738. fillPath (p);
  66739. }
  66740. void Graphics::drawDashedLine (const float startX, const float startY,
  66741. const float endX, const float endY,
  66742. const float* const dashLengths,
  66743. const int numDashLengths,
  66744. const float lineThickness) const
  66745. {
  66746. const double dx = endX - startX;
  66747. const double dy = endY - startY;
  66748. const double totalLen = juce_hypot (dx, dy);
  66749. if (totalLen >= 0.5)
  66750. {
  66751. const double onePixAlpha = 1.0 / totalLen;
  66752. double alpha = 0.0;
  66753. float x = startX;
  66754. float y = startY;
  66755. int n = 0;
  66756. while (alpha < 1.0f)
  66757. {
  66758. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66759. n = n % numDashLengths;
  66760. const float oldX = x;
  66761. const float oldY = y;
  66762. x = (float) (startX + dx * alpha);
  66763. y = (float) (startY + dy * alpha);
  66764. if ((n & 1) != 0)
  66765. {
  66766. if (lineThickness != 1.0f)
  66767. drawLine (oldX, oldY, x, y, lineThickness);
  66768. else
  66769. drawLine (oldX, oldY, x, y);
  66770. }
  66771. }
  66772. }
  66773. }
  66774. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66775. {
  66776. saveStateIfPending();
  66777. context->setInterpolationQuality (newQuality);
  66778. }
  66779. void Graphics::drawImageAt (const Image& imageToDraw,
  66780. const int topLeftX, const int topLeftY,
  66781. const bool fillAlphaChannelWithCurrentBrush) const
  66782. {
  66783. const int imageW = imageToDraw.getWidth();
  66784. const int imageH = imageToDraw.getHeight();
  66785. drawImage (imageToDraw,
  66786. topLeftX, topLeftY, imageW, imageH,
  66787. 0, 0, imageW, imageH,
  66788. fillAlphaChannelWithCurrentBrush);
  66789. }
  66790. void Graphics::drawImageWithin (const Image& imageToDraw,
  66791. const int destX, const int destY,
  66792. const int destW, const int destH,
  66793. const RectanglePlacement& placementWithinTarget,
  66794. const bool fillAlphaChannelWithCurrentBrush) const
  66795. {
  66796. // passing in a silly number can cause maths problems in rendering!
  66797. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66798. if (imageToDraw.isValid())
  66799. {
  66800. const int imageW = imageToDraw.getWidth();
  66801. const int imageH = imageToDraw.getHeight();
  66802. if (imageW > 0 && imageH > 0)
  66803. {
  66804. double newX = 0.0, newY = 0.0;
  66805. double newW = imageW;
  66806. double newH = imageH;
  66807. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66808. destX, destY, destW, destH);
  66809. if (newW > 0 && newH > 0)
  66810. {
  66811. drawImage (imageToDraw,
  66812. roundToInt (newX), roundToInt (newY),
  66813. roundToInt (newW), roundToInt (newH),
  66814. 0, 0, imageW, imageH,
  66815. fillAlphaChannelWithCurrentBrush);
  66816. }
  66817. }
  66818. }
  66819. }
  66820. void Graphics::drawImage (const Image& imageToDraw,
  66821. int dx, int dy, int dw, int dh,
  66822. int sx, int sy, int sw, int sh,
  66823. const bool fillAlphaChannelWithCurrentBrush) const
  66824. {
  66825. // passing in a silly number can cause maths problems in rendering!
  66826. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66827. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66828. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66829. {
  66830. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66831. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66832. .translated ((float) dx, (float) dy),
  66833. fillAlphaChannelWithCurrentBrush);
  66834. }
  66835. }
  66836. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66837. const AffineTransform& transform,
  66838. const bool fillAlphaChannelWithCurrentBrush) const
  66839. {
  66840. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66841. {
  66842. if (fillAlphaChannelWithCurrentBrush)
  66843. {
  66844. context->saveState();
  66845. context->clipToImageAlpha (imageToDraw, transform);
  66846. fillAll();
  66847. context->restoreState();
  66848. }
  66849. else
  66850. {
  66851. context->drawImage (imageToDraw, transform, false);
  66852. }
  66853. }
  66854. }
  66855. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66856. : context (g)
  66857. {
  66858. context.saveState();
  66859. }
  66860. Graphics::ScopedSaveState::~ScopedSaveState()
  66861. {
  66862. context.restoreState();
  66863. }
  66864. END_JUCE_NAMESPACE
  66865. /*** End of inlined file: juce_Graphics.cpp ***/
  66866. /*** Start of inlined file: juce_Justification.cpp ***/
  66867. BEGIN_JUCE_NAMESPACE
  66868. Justification::Justification (const Justification& other) throw()
  66869. : flags (other.flags)
  66870. {
  66871. }
  66872. Justification& Justification::operator= (const Justification& other) throw()
  66873. {
  66874. flags = other.flags;
  66875. return *this;
  66876. }
  66877. int Justification::getOnlyVerticalFlags() const throw()
  66878. {
  66879. return flags & (top | bottom | verticallyCentred);
  66880. }
  66881. int Justification::getOnlyHorizontalFlags() const throw()
  66882. {
  66883. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66884. }
  66885. END_JUCE_NAMESPACE
  66886. /*** End of inlined file: juce_Justification.cpp ***/
  66887. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66888. BEGIN_JUCE_NAMESPACE
  66889. // this will throw an assertion if you try to draw something that's not
  66890. // possible in postscript
  66891. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66892. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66893. #define notPossibleInPostscriptAssert jassertfalse
  66894. #else
  66895. #define notPossibleInPostscriptAssert
  66896. #endif
  66897. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66898. const String& documentTitle,
  66899. const int totalWidth_,
  66900. const int totalHeight_)
  66901. : out (resultingPostScript),
  66902. totalWidth (totalWidth_),
  66903. totalHeight (totalHeight_),
  66904. needToClip (true)
  66905. {
  66906. stateStack.add (new SavedState());
  66907. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66908. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66909. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66910. "\n%%BoundingBox: 0 0 600 824"
  66911. "\n%%Pages: 0"
  66912. "\n%%Creator: Raw Material Software JUCE"
  66913. "\n%%Title: " << documentTitle <<
  66914. "\n%%CreationDate: none"
  66915. "\n%%LanguageLevel: 2"
  66916. "\n%%EndComments"
  66917. "\n%%BeginProlog"
  66918. "\n%%BeginResource: JRes"
  66919. "\n/bd {bind def} bind def"
  66920. "\n/c {setrgbcolor} bd"
  66921. "\n/m {moveto} bd"
  66922. "\n/l {lineto} bd"
  66923. "\n/rl {rlineto} bd"
  66924. "\n/ct {curveto} bd"
  66925. "\n/cp {closepath} bd"
  66926. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66927. "\n/doclip {initclip newpath} bd"
  66928. "\n/endclip {clip newpath} bd"
  66929. "\n%%EndResource"
  66930. "\n%%EndProlog"
  66931. "\n%%BeginSetup"
  66932. "\n%%EndSetup"
  66933. "\n%%Page: 1 1"
  66934. "\n%%BeginPageSetup"
  66935. "\n%%EndPageSetup\n\n"
  66936. << "40 800 translate\n"
  66937. << scale << ' ' << scale << " scale\n\n";
  66938. }
  66939. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66940. {
  66941. }
  66942. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66943. {
  66944. return true;
  66945. }
  66946. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66947. {
  66948. if (x != 0 || y != 0)
  66949. {
  66950. stateStack.getLast()->xOffset += x;
  66951. stateStack.getLast()->yOffset += y;
  66952. needToClip = true;
  66953. }
  66954. }
  66955. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66956. {
  66957. //xxx
  66958. jassertfalse;
  66959. }
  66960. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66961. {
  66962. jassertfalse; //xxx
  66963. return 1.0f;
  66964. }
  66965. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66966. {
  66967. needToClip = true;
  66968. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66969. }
  66970. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66971. {
  66972. needToClip = true;
  66973. return stateStack.getLast()->clip.clipTo (clipRegion);
  66974. }
  66975. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66976. {
  66977. needToClip = true;
  66978. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66979. }
  66980. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66981. {
  66982. writeClip();
  66983. Path p (path);
  66984. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66985. writePath (p);
  66986. out << "clip\n";
  66987. }
  66988. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66989. {
  66990. needToClip = true;
  66991. jassertfalse; // xxx
  66992. }
  66993. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66994. {
  66995. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66996. }
  66997. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66998. {
  66999. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67000. -stateStack.getLast()->yOffset);
  67001. }
  67002. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67003. {
  67004. return stateStack.getLast()->clip.isEmpty();
  67005. }
  67006. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67007. : xOffset (0),
  67008. yOffset (0)
  67009. {
  67010. }
  67011. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67012. {
  67013. }
  67014. void LowLevelGraphicsPostScriptRenderer::saveState()
  67015. {
  67016. stateStack.add (new SavedState (*stateStack.getLast()));
  67017. }
  67018. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67019. {
  67020. jassert (stateStack.size() > 0);
  67021. if (stateStack.size() > 0)
  67022. stateStack.removeLast();
  67023. }
  67024. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  67025. {
  67026. }
  67027. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  67028. {
  67029. }
  67030. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67031. {
  67032. if (needToClip)
  67033. {
  67034. needToClip = false;
  67035. out << "doclip ";
  67036. int itemsOnLine = 0;
  67037. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67038. {
  67039. if (++itemsOnLine == 6)
  67040. {
  67041. itemsOnLine = 0;
  67042. out << '\n';
  67043. }
  67044. const Rectangle<int>& r = *i.getRectangle();
  67045. out << r.getX() << ' ' << -r.getY() << ' '
  67046. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67047. }
  67048. out << "endclip\n";
  67049. }
  67050. }
  67051. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67052. {
  67053. Colour c (Colours::white.overlaidWith (colour));
  67054. if (lastColour != c)
  67055. {
  67056. lastColour = c;
  67057. out << String (c.getFloatRed(), 3) << ' '
  67058. << String (c.getFloatGreen(), 3) << ' '
  67059. << String (c.getFloatBlue(), 3) << " c\n";
  67060. }
  67061. }
  67062. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67063. {
  67064. out << String (x, 2) << ' '
  67065. << String (-y, 2) << ' ';
  67066. }
  67067. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67068. {
  67069. out << "newpath ";
  67070. float lastX = 0.0f;
  67071. float lastY = 0.0f;
  67072. int itemsOnLine = 0;
  67073. Path::Iterator i (path);
  67074. while (i.next())
  67075. {
  67076. if (++itemsOnLine == 4)
  67077. {
  67078. itemsOnLine = 0;
  67079. out << '\n';
  67080. }
  67081. switch (i.elementType)
  67082. {
  67083. case Path::Iterator::startNewSubPath:
  67084. writeXY (i.x1, i.y1);
  67085. lastX = i.x1;
  67086. lastY = i.y1;
  67087. out << "m ";
  67088. break;
  67089. case Path::Iterator::lineTo:
  67090. writeXY (i.x1, i.y1);
  67091. lastX = i.x1;
  67092. lastY = i.y1;
  67093. out << "l ";
  67094. break;
  67095. case Path::Iterator::quadraticTo:
  67096. {
  67097. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67098. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67099. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67100. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67101. writeXY (cp1x, cp1y);
  67102. writeXY (cp2x, cp2y);
  67103. writeXY (i.x2, i.y2);
  67104. out << "ct ";
  67105. lastX = i.x2;
  67106. lastY = i.y2;
  67107. }
  67108. break;
  67109. case Path::Iterator::cubicTo:
  67110. writeXY (i.x1, i.y1);
  67111. writeXY (i.x2, i.y2);
  67112. writeXY (i.x3, i.y3);
  67113. out << "ct ";
  67114. lastX = i.x3;
  67115. lastY = i.y3;
  67116. break;
  67117. case Path::Iterator::closePath:
  67118. out << "cp ";
  67119. break;
  67120. default:
  67121. jassertfalse;
  67122. break;
  67123. }
  67124. }
  67125. out << '\n';
  67126. }
  67127. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67128. {
  67129. out << "[ "
  67130. << trans.mat00 << ' '
  67131. << trans.mat10 << ' '
  67132. << trans.mat01 << ' '
  67133. << trans.mat11 << ' '
  67134. << trans.mat02 << ' '
  67135. << trans.mat12 << " ] concat ";
  67136. }
  67137. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67138. {
  67139. stateStack.getLast()->fillType = fillType;
  67140. }
  67141. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67142. {
  67143. }
  67144. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67145. {
  67146. }
  67147. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67148. {
  67149. if (stateStack.getLast()->fillType.isColour())
  67150. {
  67151. writeClip();
  67152. writeColour (stateStack.getLast()->fillType.colour);
  67153. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67154. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67155. }
  67156. else
  67157. {
  67158. Path p;
  67159. p.addRectangle (r);
  67160. fillPath (p, AffineTransform::identity);
  67161. }
  67162. }
  67163. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67164. {
  67165. if (stateStack.getLast()->fillType.isColour())
  67166. {
  67167. writeClip();
  67168. Path p (path);
  67169. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67170. (float) stateStack.getLast()->yOffset));
  67171. writePath (p);
  67172. writeColour (stateStack.getLast()->fillType.colour);
  67173. out << "fill\n";
  67174. }
  67175. else if (stateStack.getLast()->fillType.isGradient())
  67176. {
  67177. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67178. // postscript can't do semi-transparent ones.
  67179. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67180. writeClip();
  67181. out << "gsave ";
  67182. {
  67183. Path p (path);
  67184. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67185. writePath (p);
  67186. out << "clip\n";
  67187. }
  67188. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67189. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67190. // time-being, this just fills it with the average colour..
  67191. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67192. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67193. out << "grestore\n";
  67194. }
  67195. }
  67196. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67197. const int sx, const int sy,
  67198. const int maxW, const int maxH) const
  67199. {
  67200. out << "{<\n";
  67201. const int w = jmin (maxW, im.getWidth());
  67202. const int h = jmin (maxH, im.getHeight());
  67203. int charsOnLine = 0;
  67204. const Image::BitmapData srcData (im, 0, 0, w, h);
  67205. Colour pixel;
  67206. for (int y = h; --y >= 0;)
  67207. {
  67208. for (int x = 0; x < w; ++x)
  67209. {
  67210. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67211. if (x >= sx && y >= sy)
  67212. {
  67213. if (im.isARGB())
  67214. {
  67215. PixelARGB p (*(const PixelARGB*) pixelData);
  67216. p.unpremultiply();
  67217. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67218. }
  67219. else if (im.isRGB())
  67220. {
  67221. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67222. }
  67223. else
  67224. {
  67225. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67226. }
  67227. }
  67228. else
  67229. {
  67230. pixel = Colours::transparentWhite;
  67231. }
  67232. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67233. out << String::toHexString (pixelValues, 3, 0);
  67234. charsOnLine += 3;
  67235. if (charsOnLine > 100)
  67236. {
  67237. out << '\n';
  67238. charsOnLine = 0;
  67239. }
  67240. }
  67241. }
  67242. out << "\n>}\n";
  67243. }
  67244. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67245. {
  67246. const int w = sourceImage.getWidth();
  67247. const int h = sourceImage.getHeight();
  67248. writeClip();
  67249. out << "gsave ";
  67250. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67251. .scaled (1.0f, -1.0f));
  67252. RectangleList imageClip;
  67253. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67254. out << "newpath ";
  67255. int itemsOnLine = 0;
  67256. for (RectangleList::Iterator i (imageClip); i.next();)
  67257. {
  67258. if (++itemsOnLine == 6)
  67259. {
  67260. out << '\n';
  67261. itemsOnLine = 0;
  67262. }
  67263. const Rectangle<int>& r = *i.getRectangle();
  67264. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67265. }
  67266. out << " clip newpath\n";
  67267. out << w << ' ' << h << " scale\n";
  67268. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67269. writeImage (sourceImage, 0, 0, w, h);
  67270. out << "false 3 colorimage grestore\n";
  67271. needToClip = true;
  67272. }
  67273. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67274. {
  67275. Path p;
  67276. p.addLineSegment (line, 1.0f);
  67277. fillPath (p, AffineTransform::identity);
  67278. }
  67279. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67280. {
  67281. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67282. }
  67283. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67284. {
  67285. drawLine (Line<float> (left, (float) y, right, (float) y));
  67286. }
  67287. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67288. {
  67289. stateStack.getLast()->font = newFont;
  67290. }
  67291. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67292. {
  67293. return stateStack.getLast()->font;
  67294. }
  67295. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67296. {
  67297. Path p;
  67298. Font& font = stateStack.getLast()->font;
  67299. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67300. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67301. }
  67302. END_JUCE_NAMESPACE
  67303. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67304. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67305. BEGIN_JUCE_NAMESPACE
  67306. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67307. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67308. #endif
  67309. #if JUCE_MSVC
  67310. #pragma warning (push)
  67311. #pragma warning (disable: 4127) // "expression is constant" warning
  67312. #if JUCE_DEBUG
  67313. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67314. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67315. #endif
  67316. #endif
  67317. namespace SoftwareRendererClasses
  67318. {
  67319. template <class PixelType, bool replaceExisting = false>
  67320. class SolidColourEdgeTableRenderer
  67321. {
  67322. public:
  67323. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67324. : data (data_),
  67325. sourceColour (colour)
  67326. {
  67327. if (sizeof (PixelType) == 3)
  67328. {
  67329. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67330. && sourceColour.getGreen() == sourceColour.getBlue();
  67331. filler[0].set (sourceColour);
  67332. filler[1].set (sourceColour);
  67333. filler[2].set (sourceColour);
  67334. filler[3].set (sourceColour);
  67335. }
  67336. }
  67337. forcedinline void setEdgeTableYPos (const int y) throw()
  67338. {
  67339. linePixels = (PixelType*) data.getLinePointer (y);
  67340. }
  67341. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67342. {
  67343. if (replaceExisting)
  67344. linePixels[x].set (sourceColour);
  67345. else
  67346. linePixels[x].blend (sourceColour, alphaLevel);
  67347. }
  67348. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67349. {
  67350. if (replaceExisting)
  67351. linePixels[x].set (sourceColour);
  67352. else
  67353. linePixels[x].blend (sourceColour);
  67354. }
  67355. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67356. {
  67357. PixelARGB p (sourceColour);
  67358. p.multiplyAlpha (alphaLevel);
  67359. PixelType* dest = linePixels + x;
  67360. if (replaceExisting || p.getAlpha() >= 0xff)
  67361. replaceLine (dest, p, width);
  67362. else
  67363. blendLine (dest, p, width);
  67364. }
  67365. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67366. {
  67367. PixelType* dest = linePixels + x;
  67368. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67369. replaceLine (dest, sourceColour, width);
  67370. else
  67371. blendLine (dest, sourceColour, width);
  67372. }
  67373. private:
  67374. const Image::BitmapData& data;
  67375. PixelType* linePixels;
  67376. PixelARGB sourceColour;
  67377. PixelRGB filler [4];
  67378. bool areRGBComponentsEqual;
  67379. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67380. {
  67381. do
  67382. {
  67383. dest->blend (colour);
  67384. ++dest;
  67385. } while (--width > 0);
  67386. }
  67387. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67388. {
  67389. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67390. {
  67391. memset (dest, colour.getRed(), width * 3);
  67392. }
  67393. else
  67394. {
  67395. if (width >> 5)
  67396. {
  67397. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67398. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67399. {
  67400. dest->set (colour);
  67401. ++dest;
  67402. --width;
  67403. }
  67404. while (width > 4)
  67405. {
  67406. int* d = reinterpret_cast<int*> (dest);
  67407. *d++ = intFiller[0];
  67408. *d++ = intFiller[1];
  67409. *d++ = intFiller[2];
  67410. dest = reinterpret_cast<PixelRGB*> (d);
  67411. width -= 4;
  67412. }
  67413. }
  67414. while (--width >= 0)
  67415. {
  67416. dest->set (colour);
  67417. ++dest;
  67418. }
  67419. }
  67420. }
  67421. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67422. {
  67423. memset (dest, colour.getAlpha(), width);
  67424. }
  67425. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67426. {
  67427. do
  67428. {
  67429. dest->set (colour);
  67430. ++dest;
  67431. } while (--width > 0);
  67432. }
  67433. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67434. };
  67435. class LinearGradientPixelGenerator
  67436. {
  67437. public:
  67438. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67439. : lookupTable (lookupTable_), numEntries (numEntries_)
  67440. {
  67441. jassert (numEntries_ >= 0);
  67442. Point<float> p1 (gradient.point1);
  67443. Point<float> p2 (gradient.point2);
  67444. if (! transform.isIdentity())
  67445. {
  67446. const Line<float> l (p2, p1);
  67447. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67448. p1.applyTransform (transform);
  67449. p2.applyTransform (transform);
  67450. p3.applyTransform (transform);
  67451. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67452. }
  67453. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67454. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67455. if (vertical)
  67456. {
  67457. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67458. start = roundToInt (p1.getY() * scale);
  67459. }
  67460. else if (horizontal)
  67461. {
  67462. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67463. start = roundToInt (p1.getX() * scale);
  67464. }
  67465. else
  67466. {
  67467. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67468. yTerm = p1.getY() - p1.getX() / grad;
  67469. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67470. grad *= scale;
  67471. }
  67472. }
  67473. forcedinline void setY (const int y) throw()
  67474. {
  67475. if (vertical)
  67476. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67477. else if (! horizontal)
  67478. start = roundToInt ((y - yTerm) * grad);
  67479. }
  67480. inline const PixelARGB getPixel (const int x) const throw()
  67481. {
  67482. return vertical ? linePix
  67483. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67484. }
  67485. private:
  67486. const PixelARGB* const lookupTable;
  67487. const int numEntries;
  67488. PixelARGB linePix;
  67489. int start, scale;
  67490. double grad, yTerm;
  67491. bool vertical, horizontal;
  67492. enum { numScaleBits = 12 };
  67493. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67494. };
  67495. class RadialGradientPixelGenerator
  67496. {
  67497. public:
  67498. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67499. const PixelARGB* const lookupTable_, const int numEntries_)
  67500. : lookupTable (lookupTable_),
  67501. numEntries (numEntries_),
  67502. gx1 (gradient.point1.getX()),
  67503. gy1 (gradient.point1.getY())
  67504. {
  67505. jassert (numEntries_ >= 0);
  67506. const Point<float> diff (gradient.point1 - gradient.point2);
  67507. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67508. invScale = numEntries / std::sqrt (maxDist);
  67509. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67510. }
  67511. forcedinline void setY (const int y) throw()
  67512. {
  67513. dy = y - gy1;
  67514. dy *= dy;
  67515. }
  67516. inline const PixelARGB getPixel (const int px) const throw()
  67517. {
  67518. double x = px - gx1;
  67519. x *= x;
  67520. x += dy;
  67521. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67522. }
  67523. protected:
  67524. const PixelARGB* const lookupTable;
  67525. const int numEntries;
  67526. const double gx1, gy1;
  67527. double maxDist, invScale, dy;
  67528. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67529. };
  67530. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67531. {
  67532. public:
  67533. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67534. const PixelARGB* const lookupTable_, const int numEntries_)
  67535. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67536. inverseTransform (transform.inverted())
  67537. {
  67538. tM10 = inverseTransform.mat10;
  67539. tM00 = inverseTransform.mat00;
  67540. }
  67541. forcedinline void setY (const int y) throw()
  67542. {
  67543. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67544. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67545. }
  67546. inline const PixelARGB getPixel (const int px) const throw()
  67547. {
  67548. double x = px;
  67549. const double y = tM10 * x + lineYM11;
  67550. x = tM00 * x + lineYM01;
  67551. x *= x;
  67552. x += y * y;
  67553. if (x >= maxDist)
  67554. return lookupTable [numEntries];
  67555. else
  67556. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67557. }
  67558. private:
  67559. double tM10, tM00, lineYM01, lineYM11;
  67560. const AffineTransform inverseTransform;
  67561. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67562. };
  67563. template <class PixelType, class GradientType>
  67564. class GradientEdgeTableRenderer : public GradientType
  67565. {
  67566. public:
  67567. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67568. const PixelARGB* const lookupTable_, const int numEntries_)
  67569. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67570. destData (destData_)
  67571. {
  67572. }
  67573. forcedinline void setEdgeTableYPos (const int y) throw()
  67574. {
  67575. linePixels = (PixelType*) destData.getLinePointer (y);
  67576. GradientType::setY (y);
  67577. }
  67578. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67579. {
  67580. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67581. }
  67582. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67583. {
  67584. linePixels[x].blend (GradientType::getPixel (x));
  67585. }
  67586. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67587. {
  67588. PixelType* dest = linePixels + x;
  67589. if (alphaLevel < 0xff)
  67590. {
  67591. do
  67592. {
  67593. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67594. } while (--width > 0);
  67595. }
  67596. else
  67597. {
  67598. do
  67599. {
  67600. (dest++)->blend (GradientType::getPixel (x++));
  67601. } while (--width > 0);
  67602. }
  67603. }
  67604. void handleEdgeTableLineFull (int x, int width) const throw()
  67605. {
  67606. PixelType* dest = linePixels + x;
  67607. do
  67608. {
  67609. (dest++)->blend (GradientType::getPixel (x++));
  67610. } while (--width > 0);
  67611. }
  67612. private:
  67613. const Image::BitmapData& destData;
  67614. PixelType* linePixels;
  67615. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67616. };
  67617. namespace RenderingHelpers
  67618. {
  67619. forcedinline int safeModulo (int n, const int divisor) throw()
  67620. {
  67621. jassert (divisor > 0);
  67622. n %= divisor;
  67623. return (n < 0) ? (n + divisor) : n;
  67624. }
  67625. }
  67626. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67627. class ImageFillEdgeTableRenderer
  67628. {
  67629. public:
  67630. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67631. const Image::BitmapData& srcData_,
  67632. const int extraAlpha_,
  67633. const int x, const int y)
  67634. : destData (destData_),
  67635. srcData (srcData_),
  67636. extraAlpha (extraAlpha_ + 1),
  67637. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67638. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67639. {
  67640. }
  67641. forcedinline void setEdgeTableYPos (int y) throw()
  67642. {
  67643. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67644. y -= yOffset;
  67645. if (repeatPattern)
  67646. {
  67647. jassert (y >= 0);
  67648. y %= srcData.height;
  67649. }
  67650. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67651. }
  67652. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67653. {
  67654. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67655. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67656. }
  67657. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67658. {
  67659. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67660. }
  67661. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67662. {
  67663. DestPixelType* dest = linePixels + x;
  67664. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67665. x -= xOffset;
  67666. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67667. if (alphaLevel < 0xfe)
  67668. {
  67669. do
  67670. {
  67671. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67672. } while (--width > 0);
  67673. }
  67674. else
  67675. {
  67676. if (repeatPattern)
  67677. {
  67678. do
  67679. {
  67680. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67681. } while (--width > 0);
  67682. }
  67683. else
  67684. {
  67685. copyRow (dest, sourceLineStart + x, width);
  67686. }
  67687. }
  67688. }
  67689. void handleEdgeTableLineFull (int x, int width) const throw()
  67690. {
  67691. DestPixelType* dest = linePixels + x;
  67692. x -= xOffset;
  67693. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67694. if (extraAlpha < 0xfe)
  67695. {
  67696. do
  67697. {
  67698. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67699. } while (--width > 0);
  67700. }
  67701. else
  67702. {
  67703. if (repeatPattern)
  67704. {
  67705. do
  67706. {
  67707. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67708. } while (--width > 0);
  67709. }
  67710. else
  67711. {
  67712. copyRow (dest, sourceLineStart + x, width);
  67713. }
  67714. }
  67715. }
  67716. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67717. {
  67718. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67719. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67720. uint8* mask = (uint8*) (s + x - xOffset);
  67721. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67722. mask += PixelARGB::indexA;
  67723. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67724. }
  67725. private:
  67726. const Image::BitmapData& destData;
  67727. const Image::BitmapData& srcData;
  67728. const int extraAlpha, xOffset, yOffset;
  67729. DestPixelType* linePixels;
  67730. SrcPixelType* sourceLineStart;
  67731. template <class PixelType1, class PixelType2>
  67732. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67733. {
  67734. do
  67735. {
  67736. dest++ ->blend (*src++);
  67737. } while (--width > 0);
  67738. }
  67739. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67740. {
  67741. memcpy (dest, src, width * sizeof (PixelRGB));
  67742. }
  67743. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67744. };
  67745. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67746. class TransformedImageFillEdgeTableRenderer
  67747. {
  67748. public:
  67749. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67750. const Image::BitmapData& srcData_,
  67751. const AffineTransform& transform,
  67752. const int extraAlpha_,
  67753. const bool betterQuality_)
  67754. : interpolator (transform,
  67755. betterQuality_ ? 0.5f : 0.0f,
  67756. betterQuality_ ? -128 : 0),
  67757. destData (destData_),
  67758. srcData (srcData_),
  67759. extraAlpha (extraAlpha_ + 1),
  67760. betterQuality (betterQuality_),
  67761. maxX (srcData_.width - 1),
  67762. maxY (srcData_.height - 1),
  67763. scratchSize (2048)
  67764. {
  67765. scratchBuffer.malloc (scratchSize);
  67766. }
  67767. forcedinline void setEdgeTableYPos (const int newY) throw()
  67768. {
  67769. y = newY;
  67770. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67771. }
  67772. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67773. {
  67774. SrcPixelType p;
  67775. generate (&p, x, 1);
  67776. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67777. }
  67778. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67779. {
  67780. SrcPixelType p;
  67781. generate (&p, x, 1);
  67782. linePixels[x].blend (p, extraAlpha);
  67783. }
  67784. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67785. {
  67786. if (width > scratchSize)
  67787. {
  67788. scratchSize = width;
  67789. scratchBuffer.malloc (scratchSize);
  67790. }
  67791. SrcPixelType* span = scratchBuffer;
  67792. generate (span, x, width);
  67793. DestPixelType* dest = linePixels + x;
  67794. alphaLevel *= extraAlpha;
  67795. alphaLevel >>= 8;
  67796. if (alphaLevel < 0xfe)
  67797. {
  67798. do
  67799. {
  67800. dest++ ->blend (*span++, alphaLevel);
  67801. } while (--width > 0);
  67802. }
  67803. else
  67804. {
  67805. do
  67806. {
  67807. dest++ ->blend (*span++);
  67808. } while (--width > 0);
  67809. }
  67810. }
  67811. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67812. {
  67813. handleEdgeTableLine (x, width, 255);
  67814. }
  67815. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67816. {
  67817. if (width > scratchSize)
  67818. {
  67819. scratchSize = width;
  67820. scratchBuffer.malloc (scratchSize);
  67821. }
  67822. y = y_;
  67823. generate (scratchBuffer.getData(), x, width);
  67824. et.clipLineToMask (x, y_,
  67825. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67826. sizeof (SrcPixelType), width);
  67827. }
  67828. private:
  67829. template <class PixelType>
  67830. void generate (PixelType* dest, const int x, int numPixels) throw()
  67831. {
  67832. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67833. do
  67834. {
  67835. int hiResX, hiResY;
  67836. this->interpolator.next (hiResX, hiResY);
  67837. int loResX = hiResX >> 8;
  67838. int loResY = hiResY >> 8;
  67839. if (repeatPattern)
  67840. {
  67841. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67842. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67843. }
  67844. if (betterQuality)
  67845. {
  67846. if (isPositiveAndBelow (loResX, maxX))
  67847. {
  67848. if (isPositiveAndBelow (loResY, maxY))
  67849. {
  67850. // In the centre of the image..
  67851. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67852. hiResX & 255, hiResY & 255);
  67853. ++dest;
  67854. continue;
  67855. }
  67856. else
  67857. {
  67858. // At a top or bottom edge..
  67859. if (! repeatPattern)
  67860. {
  67861. if (loResY < 0)
  67862. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67863. else
  67864. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67865. ++dest;
  67866. continue;
  67867. }
  67868. }
  67869. }
  67870. else
  67871. {
  67872. if (isPositiveAndBelow (loResY, maxY))
  67873. {
  67874. // At a left or right hand edge..
  67875. if (! repeatPattern)
  67876. {
  67877. if (loResX < 0)
  67878. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67879. else
  67880. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67881. ++dest;
  67882. continue;
  67883. }
  67884. }
  67885. }
  67886. }
  67887. if (! repeatPattern)
  67888. {
  67889. if (loResX < 0) loResX = 0;
  67890. if (loResY < 0) loResY = 0;
  67891. if (loResX > maxX) loResX = maxX;
  67892. if (loResY > maxY) loResY = maxY;
  67893. }
  67894. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67895. ++dest;
  67896. } while (--numPixels > 0);
  67897. }
  67898. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67899. {
  67900. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67901. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67902. c[0] += weight * src[0];
  67903. c[1] += weight * src[1];
  67904. c[2] += weight * src[2];
  67905. c[3] += weight * src[3];
  67906. weight = subPixelX * (256 - subPixelY);
  67907. c[0] += weight * src[4];
  67908. c[1] += weight * src[5];
  67909. c[2] += weight * src[6];
  67910. c[3] += weight * src[7];
  67911. src += this->srcData.lineStride;
  67912. weight = (256 - subPixelX) * subPixelY;
  67913. c[0] += weight * src[0];
  67914. c[1] += weight * src[1];
  67915. c[2] += weight * src[2];
  67916. c[3] += weight * src[3];
  67917. weight = subPixelX * subPixelY;
  67918. c[0] += weight * src[4];
  67919. c[1] += weight * src[5];
  67920. c[2] += weight * src[6];
  67921. c[3] += weight * src[7];
  67922. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67923. (uint8) (c[PixelARGB::indexR] >> 16),
  67924. (uint8) (c[PixelARGB::indexG] >> 16),
  67925. (uint8) (c[PixelARGB::indexB] >> 16));
  67926. }
  67927. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67928. {
  67929. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67930. uint32 weight = (256 - subPixelX) * alpha;
  67931. c[0] += weight * src[0];
  67932. c[1] += weight * src[1];
  67933. c[2] += weight * src[2];
  67934. c[3] += weight * src[3];
  67935. weight = subPixelX * alpha;
  67936. c[0] += weight * src[4];
  67937. c[1] += weight * src[5];
  67938. c[2] += weight * src[6];
  67939. c[3] += weight * src[7];
  67940. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67941. (uint8) (c[PixelARGB::indexR] >> 16),
  67942. (uint8) (c[PixelARGB::indexG] >> 16),
  67943. (uint8) (c[PixelARGB::indexB] >> 16));
  67944. }
  67945. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67946. {
  67947. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67948. uint32 weight = (256 - subPixelY) * alpha;
  67949. c[0] += weight * src[0];
  67950. c[1] += weight * src[1];
  67951. c[2] += weight * src[2];
  67952. c[3] += weight * src[3];
  67953. src += this->srcData.lineStride;
  67954. weight = subPixelY * alpha;
  67955. c[0] += weight * src[0];
  67956. c[1] += weight * src[1];
  67957. c[2] += weight * src[2];
  67958. c[3] += weight * src[3];
  67959. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67960. (uint8) (c[PixelARGB::indexR] >> 16),
  67961. (uint8) (c[PixelARGB::indexG] >> 16),
  67962. (uint8) (c[PixelARGB::indexB] >> 16));
  67963. }
  67964. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67965. {
  67966. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67967. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67968. c[0] += weight * src[0];
  67969. c[1] += weight * src[1];
  67970. c[2] += weight * src[2];
  67971. weight = subPixelX * (256 - subPixelY);
  67972. c[0] += weight * src[3];
  67973. c[1] += weight * src[4];
  67974. c[2] += weight * src[5];
  67975. src += this->srcData.lineStride;
  67976. weight = (256 - subPixelX) * subPixelY;
  67977. c[0] += weight * src[0];
  67978. c[1] += weight * src[1];
  67979. c[2] += weight * src[2];
  67980. weight = subPixelX * subPixelY;
  67981. c[0] += weight * src[3];
  67982. c[1] += weight * src[4];
  67983. c[2] += weight * src[5];
  67984. dest->setARGB ((uint8) 255,
  67985. (uint8) (c[PixelRGB::indexR] >> 16),
  67986. (uint8) (c[PixelRGB::indexG] >> 16),
  67987. (uint8) (c[PixelRGB::indexB] >> 16));
  67988. }
  67989. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67990. {
  67991. uint32 c[3] = { 128, 128, 128 };
  67992. uint32 weight = (256 - subPixelX);
  67993. c[0] += weight * src[0];
  67994. c[1] += weight * src[1];
  67995. c[2] += weight * src[2];
  67996. c[0] += subPixelX * src[3];
  67997. c[1] += subPixelX * src[4];
  67998. c[2] += subPixelX * src[5];
  67999. dest->setARGB ((uint8) 255,
  68000. (uint8) (c[PixelRGB::indexR] >> 8),
  68001. (uint8) (c[PixelRGB::indexG] >> 8),
  68002. (uint8) (c[PixelRGB::indexB] >> 8));
  68003. }
  68004. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  68005. {
  68006. uint32 c[3] = { 128, 128, 128 };
  68007. uint32 weight = (256 - subPixelY);
  68008. c[0] += weight * src[0];
  68009. c[1] += weight * src[1];
  68010. c[2] += weight * src[2];
  68011. src += this->srcData.lineStride;
  68012. c[0] += subPixelY * src[0];
  68013. c[1] += subPixelY * src[1];
  68014. c[2] += subPixelY * src[2];
  68015. dest->setARGB ((uint8) 255,
  68016. (uint8) (c[PixelRGB::indexR] >> 8),
  68017. (uint8) (c[PixelRGB::indexG] >> 8),
  68018. (uint8) (c[PixelRGB::indexB] >> 8));
  68019. }
  68020. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  68021. {
  68022. uint32 c = 256 * 128;
  68023. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  68024. c += src[1] * (subPixelX * (256 - subPixelY));
  68025. src += this->srcData.lineStride;
  68026. c += src[0] * ((256 - subPixelX) * subPixelY);
  68027. c += src[1] * (subPixelX * subPixelY);
  68028. *((uint8*) dest) = (uint8) (c >> 16);
  68029. }
  68030. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  68031. {
  68032. uint32 c = 256 * 128;
  68033. c += src[0] * (256 - subPixelX) * alpha;
  68034. c += src[1] * subPixelX * alpha;
  68035. *((uint8*) dest) = (uint8) (c >> 16);
  68036. }
  68037. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  68038. {
  68039. uint32 c = 256 * 128;
  68040. c += src[0] * (256 - subPixelY) * alpha;
  68041. src += this->srcData.lineStride;
  68042. c += src[0] * subPixelY * alpha;
  68043. *((uint8*) dest) = (uint8) (c >> 16);
  68044. }
  68045. class TransformedImageSpanInterpolator
  68046. {
  68047. public:
  68048. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  68049. : inverseTransform (transform.inverted()),
  68050. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  68051. {}
  68052. void setStartOfLine (float x, float y, const int numPixels) throw()
  68053. {
  68054. jassert (numPixels > 0);
  68055. x += pixelOffset;
  68056. y += pixelOffset;
  68057. float x1 = x, y1 = y;
  68058. x += numPixels;
  68059. inverseTransform.transformPoints (x1, y1, x, y);
  68060. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  68061. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  68062. }
  68063. void next (int& x, int& y) throw()
  68064. {
  68065. x = xBresenham.n;
  68066. xBresenham.stepToNext();
  68067. y = yBresenham.n;
  68068. yBresenham.stepToNext();
  68069. }
  68070. private:
  68071. class BresenhamInterpolator
  68072. {
  68073. public:
  68074. BresenhamInterpolator() throw() {}
  68075. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  68076. {
  68077. numSteps = numSteps_;
  68078. step = (n2 - n1) / numSteps;
  68079. remainder = modulo = (n2 - n1) % numSteps;
  68080. n = n1 + pixelOffsetInt;
  68081. if (modulo <= 0)
  68082. {
  68083. modulo += numSteps;
  68084. remainder += numSteps;
  68085. --step;
  68086. }
  68087. modulo -= numSteps;
  68088. }
  68089. forcedinline void stepToNext() throw()
  68090. {
  68091. modulo += remainder;
  68092. n += step;
  68093. if (modulo > 0)
  68094. {
  68095. modulo -= numSteps;
  68096. ++n;
  68097. }
  68098. }
  68099. int n;
  68100. private:
  68101. int numSteps, step, modulo, remainder;
  68102. };
  68103. const AffineTransform inverseTransform;
  68104. BresenhamInterpolator xBresenham, yBresenham;
  68105. const float pixelOffset;
  68106. const int pixelOffsetInt;
  68107. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  68108. };
  68109. TransformedImageSpanInterpolator interpolator;
  68110. const Image::BitmapData& destData;
  68111. const Image::BitmapData& srcData;
  68112. const int extraAlpha;
  68113. const bool betterQuality;
  68114. const int maxX, maxY;
  68115. int y;
  68116. DestPixelType* linePixels;
  68117. HeapBlock <SrcPixelType> scratchBuffer;
  68118. int scratchSize;
  68119. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  68120. };
  68121. class ClipRegionBase : public ReferenceCountedObject
  68122. {
  68123. public:
  68124. ClipRegionBase() {}
  68125. virtual ~ClipRegionBase() {}
  68126. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68127. virtual const Ptr clone() const = 0;
  68128. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68129. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68130. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68131. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68132. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68133. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68134. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68135. virtual const Ptr translated (const Point<int>& delta) = 0;
  68136. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68137. virtual const Rectangle<int> getClipBounds() const = 0;
  68138. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68139. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68140. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68141. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68142. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68143. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68144. protected:
  68145. template <class Iterator>
  68146. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68147. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68148. {
  68149. switch (destData.pixelFormat)
  68150. {
  68151. case Image::ARGB:
  68152. switch (srcData.pixelFormat)
  68153. {
  68154. case Image::ARGB:
  68155. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68156. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68157. break;
  68158. case Image::RGB:
  68159. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68160. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68161. break;
  68162. default:
  68163. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68164. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68165. break;
  68166. }
  68167. break;
  68168. case Image::RGB:
  68169. switch (srcData.pixelFormat)
  68170. {
  68171. case Image::ARGB:
  68172. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68173. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68174. break;
  68175. case Image::RGB:
  68176. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68177. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68178. break;
  68179. default:
  68180. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68181. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68182. break;
  68183. }
  68184. break;
  68185. default:
  68186. switch (srcData.pixelFormat)
  68187. {
  68188. case Image::ARGB:
  68189. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68190. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68191. break;
  68192. case Image::RGB:
  68193. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68194. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68195. break;
  68196. default:
  68197. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68198. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68199. break;
  68200. }
  68201. break;
  68202. }
  68203. }
  68204. template <class Iterator>
  68205. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68206. {
  68207. switch (destData.pixelFormat)
  68208. {
  68209. case Image::ARGB:
  68210. switch (srcData.pixelFormat)
  68211. {
  68212. case Image::ARGB:
  68213. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68214. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68215. break;
  68216. case Image::RGB:
  68217. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68218. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68219. break;
  68220. default:
  68221. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68222. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68223. break;
  68224. }
  68225. break;
  68226. case Image::RGB:
  68227. switch (srcData.pixelFormat)
  68228. {
  68229. case Image::ARGB:
  68230. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68231. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68232. break;
  68233. case Image::RGB:
  68234. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68235. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68236. break;
  68237. default:
  68238. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68239. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68240. break;
  68241. }
  68242. break;
  68243. default:
  68244. switch (srcData.pixelFormat)
  68245. {
  68246. case Image::ARGB:
  68247. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68248. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68249. break;
  68250. case Image::RGB:
  68251. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68252. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68253. break;
  68254. default:
  68255. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68256. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68257. break;
  68258. }
  68259. break;
  68260. }
  68261. }
  68262. template <class Iterator, class DestPixelType>
  68263. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68264. {
  68265. jassert (destData.pixelStride == sizeof (DestPixelType));
  68266. if (replaceContents)
  68267. {
  68268. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68269. iter.iterate (r);
  68270. }
  68271. else
  68272. {
  68273. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68274. iter.iterate (r);
  68275. }
  68276. }
  68277. template <class Iterator, class DestPixelType>
  68278. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68279. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68280. {
  68281. jassert (destData.pixelStride == sizeof (DestPixelType));
  68282. if (g.isRadial)
  68283. {
  68284. if (isIdentity)
  68285. {
  68286. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68287. iter.iterate (renderer);
  68288. }
  68289. else
  68290. {
  68291. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68292. iter.iterate (renderer);
  68293. }
  68294. }
  68295. else
  68296. {
  68297. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68298. iter.iterate (renderer);
  68299. }
  68300. }
  68301. };
  68302. class ClipRegion_EdgeTable : public ClipRegionBase
  68303. {
  68304. public:
  68305. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68306. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68307. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68308. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68309. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68310. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68311. ~ClipRegion_EdgeTable() {}
  68312. const Ptr clone() const
  68313. {
  68314. return new ClipRegion_EdgeTable (*this);
  68315. }
  68316. const Ptr applyClipTo (const Ptr& target) const
  68317. {
  68318. return target->clipToEdgeTable (edgeTable);
  68319. }
  68320. const Ptr clipToRectangle (const Rectangle<int>& r)
  68321. {
  68322. edgeTable.clipToRectangle (r);
  68323. return edgeTable.isEmpty() ? 0 : this;
  68324. }
  68325. const Ptr clipToRectangleList (const RectangleList& r)
  68326. {
  68327. RectangleList inverse (edgeTable.getMaximumBounds());
  68328. if (inverse.subtract (r))
  68329. for (RectangleList::Iterator iter (inverse); iter.next();)
  68330. edgeTable.excludeRectangle (*iter.getRectangle());
  68331. return edgeTable.isEmpty() ? 0 : this;
  68332. }
  68333. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68334. {
  68335. edgeTable.excludeRectangle (r);
  68336. return edgeTable.isEmpty() ? 0 : this;
  68337. }
  68338. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68339. {
  68340. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68341. edgeTable.clipToEdgeTable (et);
  68342. return edgeTable.isEmpty() ? 0 : this;
  68343. }
  68344. const Ptr clipToEdgeTable (const EdgeTable& et)
  68345. {
  68346. edgeTable.clipToEdgeTable (et);
  68347. return edgeTable.isEmpty() ? 0 : this;
  68348. }
  68349. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68350. {
  68351. const Image::BitmapData srcData (image, false);
  68352. if (transform.isOnlyTranslation())
  68353. {
  68354. // If our translation doesn't involve any distortion, just use a simple blit..
  68355. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68356. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68357. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68358. {
  68359. const int imageX = ((tx + 128) >> 8);
  68360. const int imageY = ((ty + 128) >> 8);
  68361. if (image.getFormat() == Image::ARGB)
  68362. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68363. else
  68364. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68365. return edgeTable.isEmpty() ? 0 : this;
  68366. }
  68367. }
  68368. if (transform.isSingularity())
  68369. return 0;
  68370. {
  68371. Path p;
  68372. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68373. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68374. edgeTable.clipToEdgeTable (et2);
  68375. }
  68376. if (! edgeTable.isEmpty())
  68377. {
  68378. if (image.getFormat() == Image::ARGB)
  68379. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68380. else
  68381. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68382. }
  68383. return edgeTable.isEmpty() ? 0 : this;
  68384. }
  68385. const Ptr translated (const Point<int>& delta)
  68386. {
  68387. edgeTable.translate ((float) delta.getX(), delta.getY());
  68388. return edgeTable.isEmpty() ? 0 : this;
  68389. }
  68390. bool clipRegionIntersects (const Rectangle<int>& r) const
  68391. {
  68392. return edgeTable.getMaximumBounds().intersects (r);
  68393. }
  68394. const Rectangle<int> getClipBounds() const
  68395. {
  68396. return edgeTable.getMaximumBounds();
  68397. }
  68398. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68399. {
  68400. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68401. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68402. if (! clipped.isEmpty())
  68403. {
  68404. ClipRegion_EdgeTable et (clipped);
  68405. et.edgeTable.clipToEdgeTable (edgeTable);
  68406. et.fillAllWithColour (destData, colour, replaceContents);
  68407. }
  68408. }
  68409. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68410. {
  68411. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68412. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68413. if (! clipped.isEmpty())
  68414. {
  68415. ClipRegion_EdgeTable et (clipped);
  68416. et.edgeTable.clipToEdgeTable (edgeTable);
  68417. et.fillAllWithColour (destData, colour, false);
  68418. }
  68419. }
  68420. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68421. {
  68422. switch (destData.pixelFormat)
  68423. {
  68424. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68425. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68426. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68427. }
  68428. }
  68429. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68430. {
  68431. HeapBlock <PixelARGB> lookupTable;
  68432. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68433. jassert (numLookupEntries > 0);
  68434. switch (destData.pixelFormat)
  68435. {
  68436. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68437. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68438. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68439. }
  68440. }
  68441. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68442. {
  68443. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68444. }
  68445. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68446. {
  68447. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68448. }
  68449. EdgeTable edgeTable;
  68450. private:
  68451. template <class SrcPixelType>
  68452. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68453. {
  68454. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68455. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68456. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68457. edgeTable.getMaximumBounds().getWidth());
  68458. }
  68459. template <class SrcPixelType>
  68460. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68461. {
  68462. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68463. edgeTable.clipToRectangle (r);
  68464. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68465. for (int y = 0; y < r.getHeight(); ++y)
  68466. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68467. }
  68468. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68469. };
  68470. class ClipRegion_RectangleList : public ClipRegionBase
  68471. {
  68472. public:
  68473. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68474. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68475. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68476. ~ClipRegion_RectangleList() {}
  68477. const Ptr clone() const
  68478. {
  68479. return new ClipRegion_RectangleList (*this);
  68480. }
  68481. const Ptr applyClipTo (const Ptr& target) const
  68482. {
  68483. return target->clipToRectangleList (clip);
  68484. }
  68485. const Ptr clipToRectangle (const Rectangle<int>& r)
  68486. {
  68487. clip.clipTo (r);
  68488. return clip.isEmpty() ? 0 : this;
  68489. }
  68490. const Ptr clipToRectangleList (const RectangleList& r)
  68491. {
  68492. clip.clipTo (r);
  68493. return clip.isEmpty() ? 0 : this;
  68494. }
  68495. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68496. {
  68497. clip.subtract (r);
  68498. return clip.isEmpty() ? 0 : this;
  68499. }
  68500. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68501. {
  68502. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68503. }
  68504. const Ptr clipToEdgeTable (const EdgeTable& et)
  68505. {
  68506. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68507. }
  68508. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68509. {
  68510. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68511. }
  68512. const Ptr translated (const Point<int>& delta)
  68513. {
  68514. clip.offsetAll (delta.getX(), delta.getY());
  68515. return clip.isEmpty() ? 0 : this;
  68516. }
  68517. bool clipRegionIntersects (const Rectangle<int>& r) const
  68518. {
  68519. return clip.intersects (r);
  68520. }
  68521. const Rectangle<int> getClipBounds() const
  68522. {
  68523. return clip.getBounds();
  68524. }
  68525. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68526. {
  68527. SubRectangleIterator iter (clip, area);
  68528. switch (destData.pixelFormat)
  68529. {
  68530. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68531. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68532. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68533. }
  68534. }
  68535. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68536. {
  68537. SubRectangleIteratorFloat iter (clip, area);
  68538. switch (destData.pixelFormat)
  68539. {
  68540. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68541. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68542. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68543. }
  68544. }
  68545. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68546. {
  68547. switch (destData.pixelFormat)
  68548. {
  68549. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68550. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68551. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68552. }
  68553. }
  68554. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68555. {
  68556. HeapBlock <PixelARGB> lookupTable;
  68557. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68558. jassert (numLookupEntries > 0);
  68559. switch (destData.pixelFormat)
  68560. {
  68561. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68562. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68563. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68564. }
  68565. }
  68566. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68567. {
  68568. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68569. }
  68570. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68571. {
  68572. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68573. }
  68574. RectangleList clip;
  68575. template <class Renderer>
  68576. void iterate (Renderer& r) const throw()
  68577. {
  68578. RectangleList::Iterator iter (clip);
  68579. while (iter.next())
  68580. {
  68581. const Rectangle<int> rect (*iter.getRectangle());
  68582. const int x = rect.getX();
  68583. const int w = rect.getWidth();
  68584. jassert (w > 0);
  68585. const int bottom = rect.getBottom();
  68586. for (int y = rect.getY(); y < bottom; ++y)
  68587. {
  68588. r.setEdgeTableYPos (y);
  68589. r.handleEdgeTableLineFull (x, w);
  68590. }
  68591. }
  68592. }
  68593. private:
  68594. class SubRectangleIterator
  68595. {
  68596. public:
  68597. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68598. : clip (clip_), area (area_)
  68599. {
  68600. }
  68601. template <class Renderer>
  68602. void iterate (Renderer& r) const throw()
  68603. {
  68604. RectangleList::Iterator iter (clip);
  68605. while (iter.next())
  68606. {
  68607. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68608. if (! rect.isEmpty())
  68609. {
  68610. const int x = rect.getX();
  68611. const int w = rect.getWidth();
  68612. const int bottom = rect.getBottom();
  68613. for (int y = rect.getY(); y < bottom; ++y)
  68614. {
  68615. r.setEdgeTableYPos (y);
  68616. r.handleEdgeTableLineFull (x, w);
  68617. }
  68618. }
  68619. }
  68620. }
  68621. private:
  68622. const RectangleList& clip;
  68623. const Rectangle<int> area;
  68624. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68625. };
  68626. class SubRectangleIteratorFloat
  68627. {
  68628. public:
  68629. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68630. : clip (clip_), area (area_)
  68631. {
  68632. }
  68633. template <class Renderer>
  68634. void iterate (Renderer& r) const throw()
  68635. {
  68636. int left = roundToInt (area.getX() * 256.0f);
  68637. int top = roundToInt (area.getY() * 256.0f);
  68638. int right = roundToInt (area.getRight() * 256.0f);
  68639. int bottom = roundToInt (area.getBottom() * 256.0f);
  68640. int totalTop, totalLeft, totalBottom, totalRight;
  68641. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68642. if ((top >> 8) == (bottom >> 8))
  68643. {
  68644. topAlpha = bottom - top;
  68645. bottomAlpha = 0;
  68646. totalTop = top >> 8;
  68647. totalBottom = bottom = top = totalTop + 1;
  68648. }
  68649. else
  68650. {
  68651. if ((top & 255) == 0)
  68652. {
  68653. topAlpha = 0;
  68654. top = totalTop = (top >> 8);
  68655. }
  68656. else
  68657. {
  68658. topAlpha = 255 - (top & 255);
  68659. totalTop = (top >> 8);
  68660. top = totalTop + 1;
  68661. }
  68662. bottomAlpha = bottom & 255;
  68663. bottom >>= 8;
  68664. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68665. }
  68666. if ((left >> 8) == (right >> 8))
  68667. {
  68668. leftAlpha = right - left;
  68669. rightAlpha = 0;
  68670. totalLeft = (left >> 8);
  68671. totalRight = right = left = totalLeft + 1;
  68672. }
  68673. else
  68674. {
  68675. if ((left & 255) == 0)
  68676. {
  68677. leftAlpha = 0;
  68678. left = totalLeft = (left >> 8);
  68679. }
  68680. else
  68681. {
  68682. leftAlpha = 255 - (left & 255);
  68683. totalLeft = (left >> 8);
  68684. left = totalLeft + 1;
  68685. }
  68686. rightAlpha = right & 255;
  68687. right >>= 8;
  68688. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68689. }
  68690. RectangleList::Iterator iter (clip);
  68691. while (iter.next())
  68692. {
  68693. const int clipLeft = iter.getRectangle()->getX();
  68694. const int clipRight = iter.getRectangle()->getRight();
  68695. const int clipTop = iter.getRectangle()->getY();
  68696. const int clipBottom = iter.getRectangle()->getBottom();
  68697. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68698. {
  68699. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68700. {
  68701. if (topAlpha != 0 && totalTop >= clipTop)
  68702. {
  68703. r.setEdgeTableYPos (totalTop);
  68704. r.handleEdgeTablePixel (left, topAlpha);
  68705. }
  68706. const int endY = jmin (bottom, clipBottom);
  68707. for (int y = jmax (clipTop, top); y < endY; ++y)
  68708. {
  68709. r.setEdgeTableYPos (y);
  68710. r.handleEdgeTablePixelFull (left);
  68711. }
  68712. if (bottomAlpha != 0 && bottom < clipBottom)
  68713. {
  68714. r.setEdgeTableYPos (bottom);
  68715. r.handleEdgeTablePixel (left, bottomAlpha);
  68716. }
  68717. }
  68718. else
  68719. {
  68720. const int clippedLeft = jmax (left, clipLeft);
  68721. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68722. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68723. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68724. if (topAlpha != 0 && totalTop >= clipTop)
  68725. {
  68726. r.setEdgeTableYPos (totalTop);
  68727. if (doLeftAlpha)
  68728. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68729. if (clippedWidth > 0)
  68730. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68731. if (doRightAlpha)
  68732. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68733. }
  68734. const int endY = jmin (bottom, clipBottom);
  68735. for (int y = jmax (clipTop, top); y < endY; ++y)
  68736. {
  68737. r.setEdgeTableYPos (y);
  68738. if (doLeftAlpha)
  68739. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68740. if (clippedWidth > 0)
  68741. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68742. if (doRightAlpha)
  68743. r.handleEdgeTablePixel (right, rightAlpha);
  68744. }
  68745. if (bottomAlpha != 0 && bottom < clipBottom)
  68746. {
  68747. r.setEdgeTableYPos (bottom);
  68748. if (doLeftAlpha)
  68749. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68750. if (clippedWidth > 0)
  68751. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68752. if (doRightAlpha)
  68753. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68754. }
  68755. }
  68756. }
  68757. }
  68758. }
  68759. private:
  68760. const RectangleList& clip;
  68761. const Rectangle<float>& area;
  68762. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68763. };
  68764. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68765. };
  68766. }
  68767. class LowLevelGraphicsSoftwareRenderer::SavedState
  68768. {
  68769. public:
  68770. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68771. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68772. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68773. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68774. {
  68775. }
  68776. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68777. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68778. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68779. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68780. {
  68781. }
  68782. SavedState (const SavedState& other)
  68783. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68784. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68785. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68786. interpolationQuality (other.interpolationQuality)
  68787. {
  68788. }
  68789. void setOrigin (const int x, const int y) throw()
  68790. {
  68791. if (isOnlyTranslated)
  68792. {
  68793. xOffset += x;
  68794. yOffset += y;
  68795. }
  68796. else
  68797. {
  68798. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68799. }
  68800. }
  68801. void addTransform (const AffineTransform& t)
  68802. {
  68803. if ((! isOnlyTranslated)
  68804. || (! t.isOnlyTranslation())
  68805. || (int) (t.getTranslationX() * 256.0f) != 0
  68806. || (int) (t.getTranslationY() * 256.0f) != 0)
  68807. {
  68808. complexTransform = getTransformWith (t);
  68809. isOnlyTranslated = false;
  68810. }
  68811. else
  68812. {
  68813. xOffset += (int) t.getTranslationX();
  68814. yOffset += (int) t.getTranslationY();
  68815. }
  68816. }
  68817. float getScaleFactor() const
  68818. {
  68819. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68820. }
  68821. bool clipToRectangle (const Rectangle<int>& r)
  68822. {
  68823. if (clip != 0)
  68824. {
  68825. if (isOnlyTranslated)
  68826. {
  68827. cloneClipIfMultiplyReferenced();
  68828. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68829. }
  68830. else
  68831. {
  68832. Path p;
  68833. p.addRectangle (r);
  68834. clipToPath (p, AffineTransform::identity);
  68835. }
  68836. }
  68837. return clip != 0;
  68838. }
  68839. bool clipToRectangleList (const RectangleList& r)
  68840. {
  68841. if (clip != 0)
  68842. {
  68843. if (isOnlyTranslated)
  68844. {
  68845. cloneClipIfMultiplyReferenced();
  68846. RectangleList offsetList (r);
  68847. offsetList.offsetAll (xOffset, yOffset);
  68848. clip = clip->clipToRectangleList (offsetList);
  68849. }
  68850. else
  68851. {
  68852. clipToPath (r.toPath(), AffineTransform::identity);
  68853. }
  68854. }
  68855. return clip != 0;
  68856. }
  68857. bool excludeClipRectangle (const Rectangle<int>& r)
  68858. {
  68859. if (clip != 0)
  68860. {
  68861. cloneClipIfMultiplyReferenced();
  68862. if (isOnlyTranslated)
  68863. {
  68864. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68865. }
  68866. else
  68867. {
  68868. Path p;
  68869. p.addRectangle (r.toFloat());
  68870. p.applyTransform (complexTransform);
  68871. p.addRectangle (clip->getClipBounds().toFloat());
  68872. p.setUsingNonZeroWinding (false);
  68873. clip = clip->clipToPath (p, AffineTransform::identity);
  68874. }
  68875. }
  68876. return clip != 0;
  68877. }
  68878. void clipToPath (const Path& p, const AffineTransform& transform)
  68879. {
  68880. if (clip != 0)
  68881. {
  68882. cloneClipIfMultiplyReferenced();
  68883. clip = clip->clipToPath (p, getTransformWith (transform));
  68884. }
  68885. }
  68886. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68887. {
  68888. if (clip != 0)
  68889. {
  68890. if (sourceImage.hasAlphaChannel())
  68891. {
  68892. cloneClipIfMultiplyReferenced();
  68893. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68894. interpolationQuality != Graphics::lowResamplingQuality);
  68895. }
  68896. else
  68897. {
  68898. Path p;
  68899. p.addRectangle (sourceImage.getBounds());
  68900. clipToPath (p, t);
  68901. }
  68902. }
  68903. }
  68904. bool clipRegionIntersects (const Rectangle<int>& r) const
  68905. {
  68906. if (clip != 0)
  68907. {
  68908. if (isOnlyTranslated)
  68909. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68910. else
  68911. return getClipBounds().intersects (r);
  68912. }
  68913. return false;
  68914. }
  68915. const Rectangle<int> getUntransformedClipBounds() const
  68916. {
  68917. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68918. }
  68919. const Rectangle<int> getClipBounds() const
  68920. {
  68921. if (clip != 0)
  68922. {
  68923. if (isOnlyTranslated)
  68924. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68925. else
  68926. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68927. }
  68928. return Rectangle<int>();
  68929. }
  68930. SavedState* beginTransparencyLayer (float opacity)
  68931. {
  68932. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68933. SavedState* s = new SavedState (*this);
  68934. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68935. s->compositionAlpha = opacity;
  68936. if (s->isOnlyTranslated)
  68937. {
  68938. s->xOffset -= layerBounds.getX();
  68939. s->yOffset -= layerBounds.getY();
  68940. }
  68941. else
  68942. {
  68943. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68944. (float) -layerBounds.getY()));
  68945. }
  68946. s->cloneClipIfMultiplyReferenced();
  68947. s->clip = s->clip->translated (-layerBounds.getPosition());
  68948. return s;
  68949. }
  68950. void endTransparencyLayer (SavedState& layerState)
  68951. {
  68952. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68953. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68954. g->setOpacity (layerState.compositionAlpha);
  68955. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68956. (float) layerBounds.getY()), false);
  68957. }
  68958. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68959. {
  68960. if (clip != 0)
  68961. {
  68962. if (isOnlyTranslated)
  68963. {
  68964. if (fillType.isColour())
  68965. {
  68966. Image::BitmapData destData (image, true);
  68967. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68968. }
  68969. else
  68970. {
  68971. const Rectangle<int> totalClip (clip->getClipBounds());
  68972. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68973. if (! clipped.isEmpty())
  68974. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68975. }
  68976. }
  68977. else
  68978. {
  68979. Path p;
  68980. p.addRectangle (r);
  68981. fillPath (p, AffineTransform::identity);
  68982. }
  68983. }
  68984. }
  68985. void fillRect (const Rectangle<float>& r)
  68986. {
  68987. if (clip != 0)
  68988. {
  68989. if (isOnlyTranslated)
  68990. {
  68991. if (fillType.isColour())
  68992. {
  68993. Image::BitmapData destData (image, true);
  68994. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68995. }
  68996. else
  68997. {
  68998. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68999. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69000. if (! clipped.isEmpty())
  69001. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69002. }
  69003. }
  69004. else
  69005. {
  69006. Path p;
  69007. p.addRectangle (r);
  69008. fillPath (p, AffineTransform::identity);
  69009. }
  69010. }
  69011. }
  69012. void fillPath (const Path& path, const AffineTransform& transform)
  69013. {
  69014. if (clip != 0)
  69015. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  69016. }
  69017. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  69018. {
  69019. jassert (isOnlyTranslated);
  69020. if (clip != 0)
  69021. {
  69022. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69023. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69024. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69025. fillShape (shapeToFill, false);
  69026. }
  69027. }
  69028. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69029. {
  69030. jassert (clip != 0);
  69031. shapeToFill = clip->applyClipTo (shapeToFill);
  69032. if (shapeToFill != 0)
  69033. {
  69034. Image::BitmapData destData (image, true);
  69035. if (fillType.isGradient())
  69036. {
  69037. jassert (! replaceContents); // that option is just for solid colours
  69038. ColourGradient g2 (*(fillType.gradient));
  69039. g2.multiplyOpacity (fillType.getOpacity());
  69040. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  69041. const bool isIdentity = transform.isOnlyTranslation();
  69042. if (isIdentity)
  69043. {
  69044. // If our translation doesn't involve any distortion, we can speed it up..
  69045. g2.point1.applyTransform (transform);
  69046. g2.point2.applyTransform (transform);
  69047. transform = AffineTransform::identity;
  69048. }
  69049. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69050. }
  69051. else if (fillType.isTiledImage())
  69052. {
  69053. renderImage (fillType.image, fillType.transform, shapeToFill);
  69054. }
  69055. else
  69056. {
  69057. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69058. }
  69059. }
  69060. }
  69061. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69062. {
  69063. const AffineTransform transform (getTransformWith (t));
  69064. const Image::BitmapData destData (image, true);
  69065. const Image::BitmapData srcData (sourceImage, false);
  69066. const int alpha = fillType.colour.getAlpha();
  69067. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69068. if (transform.isOnlyTranslation())
  69069. {
  69070. // If our translation doesn't involve any distortion, just use a simple blit..
  69071. int tx = (int) (transform.getTranslationX() * 256.0f);
  69072. int ty = (int) (transform.getTranslationY() * 256.0f);
  69073. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69074. {
  69075. tx = ((tx + 128) >> 8);
  69076. ty = ((ty + 128) >> 8);
  69077. if (tiledFillClipRegion != 0)
  69078. {
  69079. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69080. }
  69081. else
  69082. {
  69083. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  69084. c = clip->applyClipTo (c);
  69085. if (c != 0)
  69086. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69087. }
  69088. return;
  69089. }
  69090. }
  69091. if (transform.isSingularity())
  69092. return;
  69093. if (tiledFillClipRegion != 0)
  69094. {
  69095. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69096. }
  69097. else
  69098. {
  69099. Path p;
  69100. p.addRectangle (sourceImage.getBounds());
  69101. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69102. c = c->clipToPath (p, transform);
  69103. if (c != 0)
  69104. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69105. }
  69106. }
  69107. Image image;
  69108. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69109. private:
  69110. AffineTransform complexTransform;
  69111. int xOffset, yOffset;
  69112. float compositionAlpha;
  69113. public:
  69114. bool isOnlyTranslated;
  69115. Font font;
  69116. FillType fillType;
  69117. Graphics::ResamplingQuality interpolationQuality;
  69118. private:
  69119. void cloneClipIfMultiplyReferenced()
  69120. {
  69121. if (clip->getReferenceCount() > 1)
  69122. clip = clip->clone();
  69123. }
  69124. const AffineTransform getTransform() const
  69125. {
  69126. if (isOnlyTranslated)
  69127. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  69128. return complexTransform;
  69129. }
  69130. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  69131. {
  69132. if (isOnlyTranslated)
  69133. return userTransform.translated ((float) xOffset, (float) yOffset);
  69134. return userTransform.followedBy (complexTransform);
  69135. }
  69136. SavedState& operator= (const SavedState&);
  69137. };
  69138. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69139. : image (image_),
  69140. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69141. {
  69142. }
  69143. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69144. const RectangleList& initialClip)
  69145. : image (image_),
  69146. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69147. {
  69148. }
  69149. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69150. {
  69151. }
  69152. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69153. {
  69154. return false;
  69155. }
  69156. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69157. {
  69158. currentState->setOrigin (x, y);
  69159. }
  69160. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69161. {
  69162. currentState->addTransform (transform);
  69163. }
  69164. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69165. {
  69166. return currentState->getScaleFactor();
  69167. }
  69168. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69169. {
  69170. return currentState->clipToRectangle (r);
  69171. }
  69172. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69173. {
  69174. return currentState->clipToRectangleList (clipRegion);
  69175. }
  69176. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69177. {
  69178. currentState->excludeClipRectangle (r);
  69179. }
  69180. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69181. {
  69182. currentState->clipToPath (path, transform);
  69183. }
  69184. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69185. {
  69186. currentState->clipToImageAlpha (sourceImage, transform);
  69187. }
  69188. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69189. {
  69190. return currentState->clipRegionIntersects (r);
  69191. }
  69192. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69193. {
  69194. return currentState->getClipBounds();
  69195. }
  69196. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69197. {
  69198. return currentState->clip == 0;
  69199. }
  69200. void LowLevelGraphicsSoftwareRenderer::saveState()
  69201. {
  69202. stateStack.add (new SavedState (*currentState));
  69203. }
  69204. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69205. {
  69206. SavedState* const top = stateStack.getLast();
  69207. if (top != 0)
  69208. {
  69209. currentState = top;
  69210. stateStack.removeLast (1, false);
  69211. }
  69212. else
  69213. {
  69214. jassertfalse; // trying to pop with an empty stack!
  69215. }
  69216. }
  69217. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69218. {
  69219. saveState();
  69220. currentState = currentState->beginTransparencyLayer (opacity);
  69221. }
  69222. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69223. {
  69224. const ScopedPointer<SavedState> layer (currentState);
  69225. restoreState();
  69226. currentState->endTransparencyLayer (*layer);
  69227. }
  69228. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69229. {
  69230. currentState->fillType = fillType;
  69231. }
  69232. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69233. {
  69234. currentState->fillType.setOpacity (newOpacity);
  69235. }
  69236. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69237. {
  69238. currentState->interpolationQuality = quality;
  69239. }
  69240. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69241. {
  69242. currentState->fillRect (r, replaceExistingContents);
  69243. }
  69244. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69245. {
  69246. currentState->fillPath (path, transform);
  69247. }
  69248. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69249. {
  69250. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69251. }
  69252. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69253. {
  69254. Path p;
  69255. p.addLineSegment (line, 1.0f);
  69256. fillPath (p, AffineTransform::identity);
  69257. }
  69258. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69259. {
  69260. if (bottom > top)
  69261. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69262. }
  69263. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69264. {
  69265. if (right > left)
  69266. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69267. }
  69268. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69269. {
  69270. public:
  69271. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69272. void draw (SavedState& state, float x, const float y) const
  69273. {
  69274. if (snapToIntegerCoordinate)
  69275. x = std::floor (x + 0.5f);
  69276. if (edgeTable != 0)
  69277. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69278. }
  69279. void generate (const Font& newFont, const int glyphNumber)
  69280. {
  69281. font = newFont;
  69282. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69283. glyph = glyphNumber;
  69284. edgeTable = 0;
  69285. Path glyphPath;
  69286. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69287. if (! glyphPath.isEmpty())
  69288. {
  69289. const float fontHeight = font.getHeight();
  69290. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69291. #if JUCE_MAC || JUCE_IOS
  69292. .translated (0.0f, -0.5f)
  69293. #endif
  69294. );
  69295. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69296. glyphPath, transform);
  69297. }
  69298. }
  69299. Font font;
  69300. int glyph, lastAccessCount;
  69301. bool snapToIntegerCoordinate;
  69302. private:
  69303. ScopedPointer <EdgeTable> edgeTable;
  69304. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69305. };
  69306. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69307. {
  69308. public:
  69309. GlyphCache()
  69310. : accessCounter (0), hits (0), misses (0)
  69311. {
  69312. addNewGlyphSlots (120);
  69313. }
  69314. ~GlyphCache()
  69315. {
  69316. clearSingletonInstance();
  69317. }
  69318. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69319. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69320. {
  69321. ++accessCounter;
  69322. int oldestCounter = std::numeric_limits<int>::max();
  69323. CachedGlyph* oldest = 0;
  69324. for (int i = glyphs.size(); --i >= 0;)
  69325. {
  69326. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69327. if (glyph->glyph == glyphNumber && glyph->font == font)
  69328. {
  69329. ++hits;
  69330. glyph->lastAccessCount = accessCounter;
  69331. glyph->draw (state, x, y);
  69332. return;
  69333. }
  69334. if (glyph->lastAccessCount <= oldestCounter)
  69335. {
  69336. oldestCounter = glyph->lastAccessCount;
  69337. oldest = glyph;
  69338. }
  69339. }
  69340. if (hits + ++misses > (glyphs.size() << 4))
  69341. {
  69342. if (misses * 2 > hits)
  69343. addNewGlyphSlots (32);
  69344. hits = misses = 0;
  69345. oldest = glyphs.getLast();
  69346. }
  69347. jassert (oldest != 0);
  69348. oldest->lastAccessCount = accessCounter;
  69349. oldest->generate (font, glyphNumber);
  69350. oldest->draw (state, x, y);
  69351. }
  69352. private:
  69353. friend class OwnedArray <CachedGlyph>;
  69354. OwnedArray <CachedGlyph> glyphs;
  69355. int accessCounter, hits, misses;
  69356. void addNewGlyphSlots (int num)
  69357. {
  69358. while (--num >= 0)
  69359. glyphs.add (new CachedGlyph());
  69360. }
  69361. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69362. };
  69363. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69364. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69365. {
  69366. currentState->font = newFont;
  69367. }
  69368. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69369. {
  69370. return currentState->font;
  69371. }
  69372. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69373. {
  69374. Font& f = currentState->font;
  69375. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69376. {
  69377. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69378. transform.getTranslationX(),
  69379. transform.getTranslationY());
  69380. }
  69381. else
  69382. {
  69383. Path p;
  69384. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69385. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69386. }
  69387. }
  69388. #if JUCE_MSVC
  69389. #pragma warning (pop)
  69390. #if JUCE_DEBUG
  69391. #pragma optimize ("", on) // resets optimisations to the project defaults
  69392. #endif
  69393. #endif
  69394. END_JUCE_NAMESPACE
  69395. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69396. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69397. BEGIN_JUCE_NAMESPACE
  69398. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69399. : flags (other.flags)
  69400. {
  69401. }
  69402. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69403. {
  69404. flags = other.flags;
  69405. return *this;
  69406. }
  69407. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69408. const double dx, const double dy, const double dw, const double dh) const throw()
  69409. {
  69410. if (w == 0 || h == 0)
  69411. return;
  69412. if ((flags & stretchToFit) != 0)
  69413. {
  69414. x = dx;
  69415. y = dy;
  69416. w = dw;
  69417. h = dh;
  69418. }
  69419. else
  69420. {
  69421. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69422. : jmin (dw / w, dh / h);
  69423. if ((flags & onlyReduceInSize) != 0)
  69424. scale = jmin (scale, 1.0);
  69425. if ((flags & onlyIncreaseInSize) != 0)
  69426. scale = jmax (scale, 1.0);
  69427. w *= scale;
  69428. h *= scale;
  69429. if ((flags & xLeft) != 0)
  69430. x = dx;
  69431. else if ((flags & xRight) != 0)
  69432. x = dx + dw - w;
  69433. else
  69434. x = dx + (dw - w) * 0.5;
  69435. if ((flags & yTop) != 0)
  69436. y = dy;
  69437. else if ((flags & yBottom) != 0)
  69438. y = dy + dh - h;
  69439. else
  69440. y = dy + (dh - h) * 0.5;
  69441. }
  69442. }
  69443. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69444. {
  69445. if (source.isEmpty())
  69446. return AffineTransform::identity;
  69447. float newX = destination.getX();
  69448. float newY = destination.getY();
  69449. float scaleX = destination.getWidth() / source.getWidth();
  69450. float scaleY = destination.getHeight() / source.getHeight();
  69451. if ((flags & stretchToFit) == 0)
  69452. {
  69453. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69454. : jmin (scaleX, scaleY);
  69455. if ((flags & onlyReduceInSize) != 0)
  69456. scaleX = jmin (scaleX, 1.0f);
  69457. if ((flags & onlyIncreaseInSize) != 0)
  69458. scaleX = jmax (scaleX, 1.0f);
  69459. scaleY = scaleX;
  69460. if ((flags & xRight) != 0)
  69461. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69462. else if ((flags & xLeft) == 0)
  69463. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69464. if ((flags & yBottom) != 0)
  69465. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69466. else if ((flags & yTop) == 0)
  69467. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69468. }
  69469. return AffineTransform::translation (-source.getX(), -source.getY())
  69470. .scaled (scaleX, scaleY)
  69471. .translated (newX, newY);
  69472. }
  69473. END_JUCE_NAMESPACE
  69474. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69475. /*** Start of inlined file: juce_Drawable.cpp ***/
  69476. BEGIN_JUCE_NAMESPACE
  69477. Drawable::Drawable()
  69478. {
  69479. setInterceptsMouseClicks (false, false);
  69480. setPaintingIsUnclipped (true);
  69481. }
  69482. Drawable::~Drawable()
  69483. {
  69484. }
  69485. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69486. {
  69487. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69488. }
  69489. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69490. {
  69491. Graphics::ScopedSaveState ss (g);
  69492. const float oldOpacity = getAlpha();
  69493. setAlpha (opacity);
  69494. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69495. (float) -originRelativeToComponent.getY())
  69496. .followedBy (getTransform())
  69497. .followedBy (transform));
  69498. if (! g.isClipEmpty())
  69499. paintEntireComponent (g, false);
  69500. setAlpha (oldOpacity);
  69501. }
  69502. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69503. {
  69504. draw (g, opacity, AffineTransform::translation (x, y));
  69505. }
  69506. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69507. {
  69508. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69509. }
  69510. DrawableComposite* Drawable::getParent() const
  69511. {
  69512. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69513. }
  69514. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69515. {
  69516. g.setOrigin (originRelativeToComponent.getX(),
  69517. originRelativeToComponent.getY());
  69518. }
  69519. void Drawable::parentHierarchyChanged()
  69520. {
  69521. setBoundsToEnclose (getDrawableBounds());
  69522. }
  69523. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69524. {
  69525. Drawable* const parent = getParent();
  69526. Point<int> parentOrigin;
  69527. if (parent != 0)
  69528. parentOrigin = parent->originRelativeToComponent;
  69529. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69530. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69531. setBounds (newBounds);
  69532. }
  69533. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69534. {
  69535. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69536. }
  69537. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69538. {
  69539. if (! area.isEmpty())
  69540. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69541. }
  69542. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69543. {
  69544. Drawable* result = 0;
  69545. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69546. if (image.isValid())
  69547. {
  69548. DrawableImage* const di = new DrawableImage();
  69549. di->setImage (image);
  69550. result = di;
  69551. }
  69552. else
  69553. {
  69554. const String asString (String::createStringFromData (data, (int) numBytes));
  69555. XmlDocument doc (asString);
  69556. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69557. if (outer != 0 && outer->hasTagName ("svg"))
  69558. {
  69559. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69560. if (svg != 0)
  69561. result = Drawable::createFromSVG (*svg);
  69562. }
  69563. }
  69564. return result;
  69565. }
  69566. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69567. {
  69568. MemoryOutputStream mo;
  69569. mo.writeFromInputStream (dataSource, -1);
  69570. return createFromImageData (mo.getData(), mo.getDataSize());
  69571. }
  69572. Drawable* Drawable::createFromImageFile (const File& file)
  69573. {
  69574. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69575. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69576. }
  69577. template <class DrawableClass>
  69578. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69579. {
  69580. public:
  69581. DrawableTypeHandler()
  69582. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69583. {
  69584. }
  69585. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69586. {
  69587. DrawableClass* const d = new DrawableClass();
  69588. if (parent != 0)
  69589. parent->addAndMakeVisible (d);
  69590. updateComponentFromState (d, state);
  69591. return d;
  69592. }
  69593. void updateComponentFromState (Component* component, const ValueTree& state)
  69594. {
  69595. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69596. jassert (d != 0);
  69597. d->refreshFromValueTree (state, *this->getBuilder());
  69598. }
  69599. };
  69600. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69601. {
  69602. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69603. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69604. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69605. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69606. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69607. }
  69608. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69609. {
  69610. ComponentBuilder builder (tree);
  69611. builder.setImageProvider (imageProvider);
  69612. registerDrawableTypeHandlers (builder);
  69613. ScopedPointer<Component> comp (builder.createComponent());
  69614. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69615. if (d != 0)
  69616. comp.release();
  69617. return d;
  69618. }
  69619. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69620. : state (state_)
  69621. {
  69622. }
  69623. const String Drawable::ValueTreeWrapperBase::getID() const
  69624. {
  69625. return state [ComponentBuilder::idProperty];
  69626. }
  69627. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69628. {
  69629. if (newID.isEmpty())
  69630. state.removeProperty (ComponentBuilder::idProperty, 0);
  69631. else
  69632. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69633. }
  69634. END_JUCE_NAMESPACE
  69635. /*** End of inlined file: juce_Drawable.cpp ***/
  69636. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69637. BEGIN_JUCE_NAMESPACE
  69638. DrawableShape::DrawableShape()
  69639. : strokeType (0.0f),
  69640. mainFill (Colours::black),
  69641. strokeFill (Colours::black)
  69642. {
  69643. }
  69644. DrawableShape::DrawableShape (const DrawableShape& other)
  69645. : strokeType (other.strokeType),
  69646. mainFill (other.mainFill),
  69647. strokeFill (other.strokeFill)
  69648. {
  69649. }
  69650. DrawableShape::~DrawableShape()
  69651. {
  69652. }
  69653. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69654. {
  69655. public:
  69656. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69657. : RelativeCoordinatePositionerBase (component_),
  69658. owner (component_),
  69659. fill (fill_),
  69660. isMainFill (isMainFill_)
  69661. {
  69662. }
  69663. bool registerCoordinates()
  69664. {
  69665. bool ok = addPoint (fill.gradientPoint1);
  69666. ok = addPoint (fill.gradientPoint2) && ok;
  69667. return addPoint (fill.gradientPoint3) && ok;
  69668. }
  69669. void applyToComponentBounds()
  69670. {
  69671. if (isMainFill ? owner.mainFill.recalculateCoords (this)
  69672. : owner.strokeFill.recalculateCoords (this))
  69673. owner.repaint();
  69674. }
  69675. private:
  69676. DrawableShape& owner;
  69677. const DrawableShape::RelativeFillType fill;
  69678. const bool isMainFill;
  69679. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69680. };
  69681. void DrawableShape::setFill (const FillType& newFill)
  69682. {
  69683. setFill (RelativeFillType (newFill));
  69684. }
  69685. void DrawableShape::setStrokeFill (const FillType& newFill)
  69686. {
  69687. setStrokeFill (RelativeFillType (newFill));
  69688. }
  69689. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69690. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69691. {
  69692. if (fill != newFill)
  69693. {
  69694. fill = newFill;
  69695. positioner = 0;
  69696. if (fill.isDynamic())
  69697. {
  69698. positioner = new RelativePositioner (*this, fill, true);
  69699. positioner->apply();
  69700. }
  69701. else
  69702. {
  69703. fill.recalculateCoords (0);
  69704. }
  69705. repaint();
  69706. }
  69707. }
  69708. void DrawableShape::setFill (const RelativeFillType& newFill)
  69709. {
  69710. setFillInternal (mainFill, newFill, mainFillPositioner);
  69711. }
  69712. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69713. {
  69714. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69715. }
  69716. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69717. {
  69718. if (strokeType != newStrokeType)
  69719. {
  69720. strokeType = newStrokeType;
  69721. strokeChanged();
  69722. }
  69723. }
  69724. void DrawableShape::setStrokeThickness (const float newThickness)
  69725. {
  69726. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69727. }
  69728. bool DrawableShape::isStrokeVisible() const throw()
  69729. {
  69730. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69731. }
  69732. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69733. {
  69734. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69735. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69736. }
  69737. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69738. {
  69739. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69740. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69741. state.setStrokeType (strokeType, undoManager);
  69742. }
  69743. void DrawableShape::paint (Graphics& g)
  69744. {
  69745. transformContextToCorrectOrigin (g);
  69746. g.setFillType (mainFill.fill);
  69747. g.fillPath (path);
  69748. if (isStrokeVisible())
  69749. {
  69750. g.setFillType (strokeFill.fill);
  69751. g.fillPath (strokePath);
  69752. }
  69753. }
  69754. void DrawableShape::pathChanged()
  69755. {
  69756. strokeChanged();
  69757. }
  69758. void DrawableShape::strokeChanged()
  69759. {
  69760. strokePath.clear();
  69761. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69762. setBoundsToEnclose (getDrawableBounds());
  69763. repaint();
  69764. }
  69765. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69766. {
  69767. if (isStrokeVisible())
  69768. return strokePath.getBounds();
  69769. else
  69770. return path.getBounds();
  69771. }
  69772. bool DrawableShape::hitTest (int x, int y) const
  69773. {
  69774. const float globalX = (float) (x - originRelativeToComponent.getX());
  69775. const float globalY = (float) (y - originRelativeToComponent.getY());
  69776. return path.contains (globalX, globalY)
  69777. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69778. }
  69779. DrawableShape::RelativeFillType::RelativeFillType()
  69780. {
  69781. }
  69782. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69783. : fill (fill_)
  69784. {
  69785. if (fill.isGradient())
  69786. {
  69787. const ColourGradient& g = *fill.gradient;
  69788. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69789. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69790. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69791. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69792. .transformedBy (fill.transform);
  69793. fill.transform = AffineTransform::identity;
  69794. }
  69795. }
  69796. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69797. : fill (other.fill),
  69798. gradientPoint1 (other.gradientPoint1),
  69799. gradientPoint2 (other.gradientPoint2),
  69800. gradientPoint3 (other.gradientPoint3)
  69801. {
  69802. }
  69803. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69804. {
  69805. fill = other.fill;
  69806. gradientPoint1 = other.gradientPoint1;
  69807. gradientPoint2 = other.gradientPoint2;
  69808. gradientPoint3 = other.gradientPoint3;
  69809. return *this;
  69810. }
  69811. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69812. {
  69813. return fill == other.fill
  69814. && ((! fill.isGradient())
  69815. || (gradientPoint1 == other.gradientPoint1
  69816. && gradientPoint2 == other.gradientPoint2
  69817. && gradientPoint3 == other.gradientPoint3));
  69818. }
  69819. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69820. {
  69821. return ! operator== (other);
  69822. }
  69823. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::EvaluationContext* context)
  69824. {
  69825. if (fill.isGradient())
  69826. {
  69827. const Point<float> g1 (gradientPoint1.resolve (context));
  69828. const Point<float> g2 (gradientPoint2.resolve (context));
  69829. AffineTransform t;
  69830. ColourGradient& g = *fill.gradient;
  69831. if (g.isRadial)
  69832. {
  69833. const Point<float> g3 (gradientPoint3.resolve (context));
  69834. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69835. g1.getY() + g1.getX() - g2.getX());
  69836. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69837. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69838. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69839. }
  69840. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69841. {
  69842. g.point1 = g1;
  69843. g.point2 = g2;
  69844. fill.transform = t;
  69845. return true;
  69846. }
  69847. }
  69848. return false;
  69849. }
  69850. bool DrawableShape::RelativeFillType::isDynamic() const
  69851. {
  69852. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69853. }
  69854. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69855. {
  69856. if (fill.isColour())
  69857. {
  69858. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69859. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69860. }
  69861. else if (fill.isGradient())
  69862. {
  69863. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69864. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69865. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69866. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69867. const ColourGradient& cg = *fill.gradient;
  69868. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69869. String s;
  69870. for (int i = 0; i < cg.getNumColours(); ++i)
  69871. s << ' ' << cg.getColourPosition (i)
  69872. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69873. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69874. }
  69875. else if (fill.isTiledImage())
  69876. {
  69877. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69878. if (imageProvider != 0)
  69879. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69880. if (fill.getOpacity() < 1.0f)
  69881. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69882. else
  69883. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69884. }
  69885. else
  69886. {
  69887. jassertfalse;
  69888. }
  69889. }
  69890. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69891. {
  69892. const String newType (v [FillAndStrokeState::type].toString());
  69893. if (newType == "solid")
  69894. {
  69895. const String colourString (v [FillAndStrokeState::colour].toString());
  69896. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69897. : (uint32) colourString.getHexValue32()));
  69898. return true;
  69899. }
  69900. else if (newType == "gradient")
  69901. {
  69902. ColourGradient g;
  69903. g.isRadial = v [FillAndStrokeState::radial];
  69904. StringArray colourSteps;
  69905. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69906. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69907. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69908. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69909. fill.setGradient (g);
  69910. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69911. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69912. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69913. return true;
  69914. }
  69915. else if (newType == "image")
  69916. {
  69917. Image im;
  69918. if (imageProvider != 0)
  69919. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69920. fill.setTiledImage (im, AffineTransform::identity);
  69921. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69922. return true;
  69923. }
  69924. jassertfalse;
  69925. return false;
  69926. }
  69927. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69928. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69929. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69930. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69931. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69932. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69933. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69934. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69935. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69936. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69937. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69938. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69939. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69940. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69941. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69942. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69943. : Drawable::ValueTreeWrapperBase (state_)
  69944. {
  69945. }
  69946. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69947. {
  69948. DrawableShape::RelativeFillType f;
  69949. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69950. return f;
  69951. }
  69952. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69953. {
  69954. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69955. if (v.isValid())
  69956. return v;
  69957. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69958. return getFillState (fillOrStrokeType);
  69959. }
  69960. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69961. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69962. {
  69963. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69964. newFill.writeTo (v, imageProvider, undoManager);
  69965. }
  69966. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69967. {
  69968. const String jointStyleString (state [jointStyle].toString());
  69969. const String capStyleString (state [capStyle].toString());
  69970. return PathStrokeType (state [strokeWidth],
  69971. jointStyleString == "curved" ? PathStrokeType::curved
  69972. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69973. : PathStrokeType::mitered),
  69974. capStyleString == "square" ? PathStrokeType::square
  69975. : (capStyleString == "round" ? PathStrokeType::rounded
  69976. : PathStrokeType::butt));
  69977. }
  69978. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69979. {
  69980. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69981. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69982. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69983. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69984. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69985. }
  69986. END_JUCE_NAMESPACE
  69987. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69988. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69989. BEGIN_JUCE_NAMESPACE
  69990. DrawableComposite::DrawableComposite()
  69991. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69992. updateBoundsReentrant (false)
  69993. {
  69994. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69995. RelativeCoordinate (100.0),
  69996. RelativeCoordinate (0.0),
  69997. RelativeCoordinate (100.0)));
  69998. }
  69999. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  70000. : bounds (other.bounds),
  70001. markersX (other.markersX),
  70002. markersY (other.markersY),
  70003. updateBoundsReentrant (false)
  70004. {
  70005. for (int i = 0; i < other.getNumChildComponents(); ++i)
  70006. {
  70007. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  70008. if (d != 0)
  70009. addAndMakeVisible (d->createCopy());
  70010. }
  70011. }
  70012. DrawableComposite::~DrawableComposite()
  70013. {
  70014. deleteAllChildren();
  70015. }
  70016. Drawable* DrawableComposite::createCopy() const
  70017. {
  70018. return new DrawableComposite (*this);
  70019. }
  70020. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  70021. {
  70022. Rectangle<float> r;
  70023. for (int i = getNumChildComponents(); --i >= 0;)
  70024. {
  70025. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70026. if (d != 0)
  70027. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  70028. : d->getDrawableBounds());
  70029. }
  70030. return r;
  70031. }
  70032. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  70033. {
  70034. return xAxis ? &markersX : &markersY;
  70035. }
  70036. const RelativeRectangle DrawableComposite::getContentArea() const
  70037. {
  70038. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  70039. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  70040. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  70041. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  70042. }
  70043. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  70044. {
  70045. markersX.setMarker (contentLeftMarkerName, newArea.left);
  70046. markersX.setMarker (contentRightMarkerName, newArea.right);
  70047. markersY.setMarker (contentTopMarkerName, newArea.top);
  70048. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  70049. }
  70050. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  70051. {
  70052. if (bounds != newBounds)
  70053. {
  70054. bounds = newBounds;
  70055. if (bounds.isDynamic())
  70056. {
  70057. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  70058. setPositioner (p);
  70059. p->apply();
  70060. }
  70061. else
  70062. {
  70063. setPositioner (0);
  70064. recalculateCoordinates (0);
  70065. }
  70066. }
  70067. }
  70068. void DrawableComposite::resetBoundingBoxToContentArea()
  70069. {
  70070. const RelativeRectangle content (getContentArea());
  70071. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70072. RelativePoint (content.right, content.top),
  70073. RelativePoint (content.left, content.bottom)));
  70074. }
  70075. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  70076. {
  70077. const Rectangle<float> activeArea (getDrawableBounds());
  70078. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  70079. RelativeCoordinate (activeArea.getRight()),
  70080. RelativeCoordinate (activeArea.getY()),
  70081. RelativeCoordinate (activeArea.getBottom())));
  70082. resetBoundingBoxToContentArea();
  70083. }
  70084. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70085. {
  70086. bool ok = positioner.addPoint (bounds.topLeft);
  70087. ok = positioner.addPoint (bounds.topRight) && ok;
  70088. return positioner.addPoint (bounds.bottomLeft) && ok;
  70089. }
  70090. void DrawableComposite::recalculateCoordinates (Expression::EvaluationContext* context)
  70091. {
  70092. Point<float> resolved[3];
  70093. bounds.resolveThreePoints (resolved, context);
  70094. const Rectangle<float> content (getContentArea().resolve (context));
  70095. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70096. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70097. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  70098. if (t.isSingularity())
  70099. t = AffineTransform::identity;
  70100. setTransform (t);
  70101. }
  70102. void DrawableComposite::parentHierarchyChanged()
  70103. {
  70104. DrawableComposite* parent = getParent();
  70105. if (parent != 0)
  70106. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  70107. }
  70108. void DrawableComposite::childBoundsChanged (Component*)
  70109. {
  70110. updateBoundsToFitChildren();
  70111. }
  70112. void DrawableComposite::childrenChanged()
  70113. {
  70114. updateBoundsToFitChildren();
  70115. }
  70116. struct RentrancyCheckSetter
  70117. {
  70118. RentrancyCheckSetter (bool& b_) : b (b_) { b_ = true; }
  70119. ~RentrancyCheckSetter() { b = false; }
  70120. private:
  70121. bool& b;
  70122. JUCE_DECLARE_NON_COPYABLE (RentrancyCheckSetter);
  70123. };
  70124. void DrawableComposite::updateBoundsToFitChildren()
  70125. {
  70126. if (! updateBoundsReentrant)
  70127. {
  70128. const RentrancyCheckSetter checkSetter (updateBoundsReentrant);
  70129. Rectangle<int> childArea;
  70130. for (int i = getNumChildComponents(); --i >= 0;)
  70131. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  70132. const Point<int> delta (childArea.getPosition());
  70133. childArea += getPosition();
  70134. if (childArea != getBounds())
  70135. {
  70136. if (! delta.isOrigin())
  70137. {
  70138. originRelativeToComponent -= delta;
  70139. for (int i = getNumChildComponents(); --i >= 0;)
  70140. {
  70141. Component* const c = getChildComponent(i);
  70142. if (c != 0)
  70143. c->setBounds (c->getBounds() - delta);
  70144. }
  70145. }
  70146. setBounds (childArea);
  70147. }
  70148. }
  70149. }
  70150. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70151. const char* const DrawableComposite::contentRightMarkerName = "right";
  70152. const char* const DrawableComposite::contentTopMarkerName = "top";
  70153. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70154. const Identifier DrawableComposite::valueTreeType ("Group");
  70155. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70156. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70157. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70158. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70159. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70160. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70161. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70162. : ValueTreeWrapperBase (state_)
  70163. {
  70164. jassert (state.hasType (valueTreeType));
  70165. }
  70166. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70167. {
  70168. return state.getChildWithName (childGroupTag);
  70169. }
  70170. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70171. {
  70172. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70173. }
  70174. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70175. {
  70176. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70177. state.getProperty (topRight, "100, 0"),
  70178. state.getProperty (bottomLeft, "0, 100"));
  70179. }
  70180. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70181. {
  70182. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70183. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70184. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70185. }
  70186. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70187. {
  70188. const RelativeRectangle content (getContentArea());
  70189. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70190. RelativePoint (content.right, content.top),
  70191. RelativePoint (content.left, content.bottom)), undoManager);
  70192. }
  70193. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70194. {
  70195. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70196. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70197. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70198. markersX.getMarker (markersX.getMarkerState (1)).position,
  70199. markersY.getMarker (markersY.getMarkerState (0)).position,
  70200. markersY.getMarker (markersY.getMarkerState (1)).position);
  70201. }
  70202. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70203. {
  70204. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70205. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70206. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70207. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70208. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70209. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70210. }
  70211. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70212. {
  70213. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70214. }
  70215. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70216. {
  70217. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70218. }
  70219. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70220. {
  70221. const ValueTreeWrapper wrapper (tree);
  70222. setComponentID (wrapper.getID());
  70223. wrapper.getMarkerList (true).applyTo (markersX);
  70224. wrapper.getMarkerList (false).applyTo (markersY);
  70225. setBoundingBox (wrapper.getBoundingBox());
  70226. builder.updateChildComponents (*this, wrapper.getChildList());
  70227. }
  70228. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70229. {
  70230. ValueTree tree (valueTreeType);
  70231. ValueTreeWrapper v (tree);
  70232. v.setID (getComponentID());
  70233. v.setBoundingBox (bounds, 0);
  70234. ValueTree childList (v.getChildListCreating (0));
  70235. for (int i = getNumChildComponents(); --i >= 0;)
  70236. {
  70237. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70238. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70239. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70240. }
  70241. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70242. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70243. return tree;
  70244. }
  70245. END_JUCE_NAMESPACE
  70246. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70247. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70248. BEGIN_JUCE_NAMESPACE
  70249. DrawableImage::DrawableImage()
  70250. : image (0),
  70251. opacity (1.0f),
  70252. overlayColour (0x00000000)
  70253. {
  70254. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70255. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70256. }
  70257. DrawableImage::DrawableImage (const DrawableImage& other)
  70258. : image (other.image),
  70259. opacity (other.opacity),
  70260. overlayColour (other.overlayColour),
  70261. bounds (other.bounds)
  70262. {
  70263. }
  70264. DrawableImage::~DrawableImage()
  70265. {
  70266. }
  70267. void DrawableImage::setImage (const Image& imageToUse)
  70268. {
  70269. image = imageToUse;
  70270. setBounds (imageToUse.getBounds());
  70271. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70272. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70273. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70274. recalculateCoordinates (0);
  70275. repaint();
  70276. }
  70277. void DrawableImage::setOpacity (const float newOpacity)
  70278. {
  70279. opacity = newOpacity;
  70280. }
  70281. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70282. {
  70283. overlayColour = newOverlayColour;
  70284. }
  70285. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70286. {
  70287. if (bounds != newBounds)
  70288. {
  70289. bounds = newBounds;
  70290. if (bounds.isDynamic())
  70291. {
  70292. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70293. setPositioner (p);
  70294. p->apply();
  70295. }
  70296. else
  70297. {
  70298. setPositioner (0);
  70299. recalculateCoordinates (0);
  70300. }
  70301. }
  70302. }
  70303. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70304. {
  70305. bool ok = positioner.addPoint (bounds.topLeft);
  70306. ok = positioner.addPoint (bounds.topRight) && ok;
  70307. return positioner.addPoint (bounds.bottomLeft) && ok;
  70308. }
  70309. void DrawableImage::recalculateCoordinates (Expression::EvaluationContext* context)
  70310. {
  70311. if (image.isValid())
  70312. {
  70313. Point<float> resolved[3];
  70314. bounds.resolveThreePoints (resolved, context);
  70315. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70316. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70317. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70318. tr.getX(), tr.getY(),
  70319. bl.getX(), bl.getY()));
  70320. if (t.isSingularity())
  70321. t = AffineTransform::identity;
  70322. setTransform (t);
  70323. }
  70324. }
  70325. void DrawableImage::paint (Graphics& g)
  70326. {
  70327. if (image.isValid())
  70328. {
  70329. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70330. {
  70331. g.setOpacity (opacity);
  70332. g.drawImageAt (image, 0, 0, false);
  70333. }
  70334. if (! overlayColour.isTransparent())
  70335. {
  70336. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70337. g.drawImageAt (image, 0, 0, true);
  70338. }
  70339. }
  70340. }
  70341. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70342. {
  70343. return image.getBounds().toFloat();
  70344. }
  70345. bool DrawableImage::hitTest (int x, int y) const
  70346. {
  70347. return (! image.isNull())
  70348. && image.getPixelAt (x, y).getAlpha() >= 127;
  70349. }
  70350. Drawable* DrawableImage::createCopy() const
  70351. {
  70352. return new DrawableImage (*this);
  70353. }
  70354. const Identifier DrawableImage::valueTreeType ("Image");
  70355. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70356. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70357. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70358. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70359. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70360. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70361. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70362. : ValueTreeWrapperBase (state_)
  70363. {
  70364. jassert (state.hasType (valueTreeType));
  70365. }
  70366. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70367. {
  70368. return state [image];
  70369. }
  70370. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70371. {
  70372. return state.getPropertyAsValue (image, undoManager);
  70373. }
  70374. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70375. {
  70376. state.setProperty (image, newIdentifier, undoManager);
  70377. }
  70378. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70379. {
  70380. return (float) state.getProperty (opacity, 1.0);
  70381. }
  70382. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70383. {
  70384. if (! state.hasProperty (opacity))
  70385. state.setProperty (opacity, 1.0, undoManager);
  70386. return state.getPropertyAsValue (opacity, undoManager);
  70387. }
  70388. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70389. {
  70390. state.setProperty (opacity, newOpacity, undoManager);
  70391. }
  70392. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70393. {
  70394. return Colour (state [overlay].toString().getHexValue32());
  70395. }
  70396. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70397. {
  70398. if (newColour.isTransparent())
  70399. state.removeProperty (overlay, undoManager);
  70400. else
  70401. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70402. }
  70403. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70404. {
  70405. return state.getPropertyAsValue (overlay, undoManager);
  70406. }
  70407. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70408. {
  70409. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70410. state.getProperty (topRight, "100, 0"),
  70411. state.getProperty (bottomLeft, "0, 100"));
  70412. }
  70413. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70414. {
  70415. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70416. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70417. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70418. }
  70419. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70420. {
  70421. const ValueTreeWrapper controller (tree);
  70422. setComponentID (controller.getID());
  70423. const float newOpacity = controller.getOpacity();
  70424. const Colour newOverlayColour (controller.getOverlayColour());
  70425. Image newImage;
  70426. const var imageIdentifier (controller.getImageIdentifier());
  70427. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70428. if (builder.getImageProvider() != 0)
  70429. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70430. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70431. if (bounds != newBounds || newOpacity != opacity
  70432. || overlayColour != newOverlayColour || image != newImage)
  70433. {
  70434. repaint();
  70435. opacity = newOpacity;
  70436. overlayColour = newOverlayColour;
  70437. if (image != newImage)
  70438. setImage (newImage);
  70439. setBoundingBox (newBounds);
  70440. }
  70441. }
  70442. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70443. {
  70444. ValueTree tree (valueTreeType);
  70445. ValueTreeWrapper v (tree);
  70446. v.setID (getComponentID());
  70447. v.setOpacity (opacity, 0);
  70448. v.setOverlayColour (overlayColour, 0);
  70449. v.setBoundingBox (bounds, 0);
  70450. if (image.isValid())
  70451. {
  70452. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70453. if (imageProvider != 0)
  70454. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70455. }
  70456. return tree;
  70457. }
  70458. END_JUCE_NAMESPACE
  70459. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70460. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70461. BEGIN_JUCE_NAMESPACE
  70462. DrawablePath::DrawablePath()
  70463. {
  70464. }
  70465. DrawablePath::DrawablePath (const DrawablePath& other)
  70466. : DrawableShape (other)
  70467. {
  70468. if (other.relativePath != 0)
  70469. setPath (*other.relativePath);
  70470. else
  70471. setPath (other.path);
  70472. }
  70473. DrawablePath::~DrawablePath()
  70474. {
  70475. }
  70476. Drawable* DrawablePath::createCopy() const
  70477. {
  70478. return new DrawablePath (*this);
  70479. }
  70480. void DrawablePath::setPath (const Path& newPath)
  70481. {
  70482. path = newPath;
  70483. pathChanged();
  70484. }
  70485. const Path& DrawablePath::getPath() const
  70486. {
  70487. return path;
  70488. }
  70489. const Path& DrawablePath::getStrokePath() const
  70490. {
  70491. return strokePath;
  70492. }
  70493. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::EvaluationContext* context)
  70494. {
  70495. Path newPath;
  70496. newRelativePath.createPath (newPath, context);
  70497. if (path != newPath)
  70498. {
  70499. path.swapWithPath (newPath);
  70500. pathChanged();
  70501. }
  70502. }
  70503. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70504. {
  70505. public:
  70506. RelativePositioner (DrawablePath& component_)
  70507. : RelativeCoordinatePositionerBase (component_),
  70508. owner (component_)
  70509. {
  70510. }
  70511. bool registerCoordinates()
  70512. {
  70513. bool ok = true;
  70514. jassert (owner.relativePath != 0);
  70515. const RelativePointPath& path = *owner.relativePath;
  70516. for (int i = 0; i < path.elements.size(); ++i)
  70517. {
  70518. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70519. int numPoints;
  70520. RelativePoint* const points = e->getControlPoints (numPoints);
  70521. for (int j = numPoints; --j >= 0;)
  70522. ok = addPoint (points[j]) && ok;
  70523. }
  70524. return ok;
  70525. }
  70526. void applyToComponentBounds()
  70527. {
  70528. jassert (owner.relativePath != 0);
  70529. owner.applyRelativePath (*owner.relativePath, this);
  70530. }
  70531. private:
  70532. DrawablePath& owner;
  70533. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70534. };
  70535. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70536. {
  70537. if (newRelativePath.containsAnyDynamicPoints())
  70538. {
  70539. if (relativePath == 0 || newRelativePath != *relativePath)
  70540. {
  70541. relativePath = new RelativePointPath (newRelativePath);
  70542. RelativePositioner* const p = new RelativePositioner (*this);
  70543. setPositioner (p);
  70544. p->apply();
  70545. }
  70546. }
  70547. else
  70548. {
  70549. relativePath = 0;
  70550. applyRelativePath (newRelativePath, 0);
  70551. }
  70552. }
  70553. const Identifier DrawablePath::valueTreeType ("Path");
  70554. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70555. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70556. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70557. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70558. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70559. : FillAndStrokeState (state_)
  70560. {
  70561. jassert (state.hasType (valueTreeType));
  70562. }
  70563. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70564. {
  70565. return state.getOrCreateChildWithName (path, 0);
  70566. }
  70567. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70568. {
  70569. return state [nonZeroWinding];
  70570. }
  70571. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70572. {
  70573. state.setProperty (nonZeroWinding, b, undoManager);
  70574. }
  70575. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70576. {
  70577. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70578. ValueTree pathTree (getPathState());
  70579. pathTree.removeAllChildren (undoManager);
  70580. for (int i = 0; i < relativePath.elements.size(); ++i)
  70581. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70582. }
  70583. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70584. {
  70585. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70586. RelativePoint points[3];
  70587. const ValueTree pathTree (state.getChildWithName (path));
  70588. const int num = pathTree.getNumChildren();
  70589. for (int i = 0; i < num; ++i)
  70590. {
  70591. const Element e (pathTree.getChild(i));
  70592. const int numCps = e.getNumControlPoints();
  70593. for (int j = 0; j < numCps; ++j)
  70594. points[j] = e.getControlPoint (j);
  70595. const Identifier type (e.getType());
  70596. RelativePointPath::ElementBase* newElement = 0;
  70597. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70598. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70599. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70600. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70601. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70602. else jassertfalse;
  70603. relativePath.addElement (newElement);
  70604. }
  70605. }
  70606. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70607. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70608. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70609. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70610. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70611. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70612. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70613. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70614. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70615. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70616. : state (state_)
  70617. {
  70618. }
  70619. DrawablePath::ValueTreeWrapper::Element::~Element()
  70620. {
  70621. }
  70622. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70623. {
  70624. return ValueTreeWrapper (state.getParent().getParent());
  70625. }
  70626. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70627. {
  70628. return Element (state.getSibling (-1));
  70629. }
  70630. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70631. {
  70632. const Identifier i (state.getType());
  70633. if (i == startSubPathElement || i == lineToElement) return 1;
  70634. if (i == quadraticToElement) return 2;
  70635. if (i == cubicToElement) return 3;
  70636. return 0;
  70637. }
  70638. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70639. {
  70640. jassert (index >= 0 && index < getNumControlPoints());
  70641. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70642. }
  70643. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70644. {
  70645. jassert (index >= 0 && index < getNumControlPoints());
  70646. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70647. }
  70648. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70649. {
  70650. jassert (index >= 0 && index < getNumControlPoints());
  70651. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70652. }
  70653. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70654. {
  70655. const Identifier i (state.getType());
  70656. if (i == startSubPathElement)
  70657. return getControlPoint (0);
  70658. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70659. return getPreviousElement().getEndPoint();
  70660. }
  70661. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70662. {
  70663. const Identifier i (state.getType());
  70664. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70665. if (i == quadraticToElement) return getControlPoint (1);
  70666. if (i == cubicToElement) return getControlPoint (2);
  70667. jassert (i == closeSubPathElement);
  70668. return RelativePoint();
  70669. }
  70670. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* context) const
  70671. {
  70672. const Identifier i (state.getType());
  70673. if (i == lineToElement || i == closeSubPathElement)
  70674. return getEndPoint().resolve (context).getDistanceFrom (getStartPoint().resolve (context));
  70675. if (i == cubicToElement)
  70676. {
  70677. Path p;
  70678. p.startNewSubPath (getStartPoint().resolve (context));
  70679. p.cubicTo (getControlPoint (0).resolve (context), getControlPoint (1).resolve (context), getControlPoint (2).resolve (context));
  70680. return p.getLength();
  70681. }
  70682. if (i == quadraticToElement)
  70683. {
  70684. Path p;
  70685. p.startNewSubPath (getStartPoint().resolve (context));
  70686. p.quadraticTo (getControlPoint (0).resolve (context), getControlPoint (1).resolve (context));
  70687. return p.getLength();
  70688. }
  70689. jassert (i == startSubPathElement);
  70690. return 0;
  70691. }
  70692. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70693. {
  70694. return state [mode].toString();
  70695. }
  70696. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70697. {
  70698. if (state.hasType (cubicToElement))
  70699. state.setProperty (mode, newMode, undoManager);
  70700. }
  70701. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70702. {
  70703. const Identifier i (state.getType());
  70704. if (i == quadraticToElement || i == cubicToElement)
  70705. {
  70706. ValueTree newState (lineToElement);
  70707. Element e (newState);
  70708. e.setControlPoint (0, getEndPoint(), undoManager);
  70709. state = newState;
  70710. }
  70711. }
  70712. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* context, UndoManager* undoManager)
  70713. {
  70714. const Identifier i (state.getType());
  70715. if (i == lineToElement || i == quadraticToElement)
  70716. {
  70717. ValueTree newState (cubicToElement);
  70718. Element e (newState);
  70719. const RelativePoint start (getStartPoint());
  70720. const RelativePoint end (getEndPoint());
  70721. const Point<float> startResolved (start.resolve (context));
  70722. const Point<float> endResolved (end.resolve (context));
  70723. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70724. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70725. e.setControlPoint (2, end, undoManager);
  70726. state = newState;
  70727. }
  70728. }
  70729. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70730. {
  70731. const Identifier i (state.getType());
  70732. if (i != startSubPathElement)
  70733. {
  70734. ValueTree newState (startSubPathElement);
  70735. Element e (newState);
  70736. e.setControlPoint (0, getEndPoint(), undoManager);
  70737. state = newState;
  70738. }
  70739. }
  70740. namespace DrawablePathHelpers
  70741. {
  70742. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70743. {
  70744. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70745. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70746. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70747. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70748. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70749. return newCp1 + (newCp2 - newCp1) * proportion;
  70750. }
  70751. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70752. {
  70753. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70754. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70755. return mid1 + (mid2 - mid1) * proportion;
  70756. }
  70757. }
  70758. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* context) const
  70759. {
  70760. using namespace DrawablePathHelpers;
  70761. const Identifier type (state.getType());
  70762. float bestProp = 0;
  70763. if (type == cubicToElement)
  70764. {
  70765. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70766. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context), rp4.resolve (context) };
  70767. float bestDistance = std::numeric_limits<float>::max();
  70768. for (int i = 110; --i >= 0;)
  70769. {
  70770. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70771. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70772. const float distance = centre.getDistanceFrom (targetPoint);
  70773. if (distance < bestDistance)
  70774. {
  70775. bestProp = prop;
  70776. bestDistance = distance;
  70777. }
  70778. }
  70779. }
  70780. else if (type == quadraticToElement)
  70781. {
  70782. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70783. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context) };
  70784. float bestDistance = std::numeric_limits<float>::max();
  70785. for (int i = 110; --i >= 0;)
  70786. {
  70787. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70788. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70789. const float distance = centre.getDistanceFrom (targetPoint);
  70790. if (distance < bestDistance)
  70791. {
  70792. bestProp = prop;
  70793. bestDistance = distance;
  70794. }
  70795. }
  70796. }
  70797. else if (type == lineToElement)
  70798. {
  70799. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70800. const Line<float> line (rp1.resolve (context), rp2.resolve (context));
  70801. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70802. }
  70803. return bestProp;
  70804. }
  70805. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* context, UndoManager* undoManager)
  70806. {
  70807. ValueTree newTree;
  70808. const Identifier type (state.getType());
  70809. if (type == cubicToElement)
  70810. {
  70811. float bestProp = findProportionAlongLine (targetPoint, context);
  70812. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70813. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context), rp4.resolve (context) };
  70814. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70815. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70816. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70817. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70818. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70819. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70820. setControlPoint (0, mid1, undoManager);
  70821. setControlPoint (1, newCp1, undoManager);
  70822. setControlPoint (2, newCentre, undoManager);
  70823. setModeOfEndPoint (roundedMode, undoManager);
  70824. Element newElement (newTree = ValueTree (cubicToElement));
  70825. newElement.setControlPoint (0, newCp2, 0);
  70826. newElement.setControlPoint (1, mid3, 0);
  70827. newElement.setControlPoint (2, rp4, 0);
  70828. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70829. }
  70830. else if (type == quadraticToElement)
  70831. {
  70832. float bestProp = findProportionAlongLine (targetPoint, context);
  70833. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70834. const Point<float> points[] = { rp1.resolve (context), rp2.resolve (context), rp3.resolve (context) };
  70835. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70836. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70837. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70838. setControlPoint (0, mid1, undoManager);
  70839. setControlPoint (1, newCentre, undoManager);
  70840. setModeOfEndPoint (roundedMode, undoManager);
  70841. Element newElement (newTree = ValueTree (quadraticToElement));
  70842. newElement.setControlPoint (0, mid2, 0);
  70843. newElement.setControlPoint (1, rp3, 0);
  70844. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70845. }
  70846. else if (type == lineToElement)
  70847. {
  70848. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70849. const Line<float> line (rp1.resolve (context), rp2.resolve (context));
  70850. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70851. setControlPoint (0, newPoint, undoManager);
  70852. Element newElement (newTree = ValueTree (lineToElement));
  70853. newElement.setControlPoint (0, rp2, 0);
  70854. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70855. }
  70856. else if (type == closeSubPathElement)
  70857. {
  70858. }
  70859. return newTree;
  70860. }
  70861. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70862. {
  70863. state.getParent().removeChild (state, undoManager);
  70864. }
  70865. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70866. {
  70867. ValueTreeWrapper v (tree);
  70868. setComponentID (v.getID());
  70869. refreshFillTypes (v, builder.getImageProvider());
  70870. setStrokeType (v.getStrokeType());
  70871. RelativePointPath newRelativePath;
  70872. v.writeTo (newRelativePath);
  70873. setPath (newRelativePath);
  70874. }
  70875. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70876. {
  70877. ValueTree tree (valueTreeType);
  70878. ValueTreeWrapper v (tree);
  70879. v.setID (getComponentID());
  70880. writeTo (v, imageProvider, 0);
  70881. if (relativePath != 0)
  70882. v.readFrom (*relativePath, 0);
  70883. else
  70884. v.readFrom (RelativePointPath (path), 0);
  70885. return tree;
  70886. }
  70887. END_JUCE_NAMESPACE
  70888. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70889. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70890. BEGIN_JUCE_NAMESPACE
  70891. DrawableRectangle::DrawableRectangle()
  70892. {
  70893. }
  70894. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70895. : DrawableShape (other),
  70896. bounds (other.bounds),
  70897. cornerSize (other.cornerSize)
  70898. {
  70899. }
  70900. DrawableRectangle::~DrawableRectangle()
  70901. {
  70902. }
  70903. Drawable* DrawableRectangle::createCopy() const
  70904. {
  70905. return new DrawableRectangle (*this);
  70906. }
  70907. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70908. {
  70909. if (bounds != newBounds)
  70910. {
  70911. bounds = newBounds;
  70912. rebuildPath();
  70913. }
  70914. }
  70915. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70916. {
  70917. if (cornerSize != newSize)
  70918. {
  70919. cornerSize = newSize;
  70920. rebuildPath();
  70921. }
  70922. }
  70923. void DrawableRectangle::rebuildPath()
  70924. {
  70925. if (bounds.isDynamic() || cornerSize.isDynamic())
  70926. {
  70927. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70928. setPositioner (p);
  70929. p->apply();
  70930. }
  70931. else
  70932. {
  70933. setPositioner (0);
  70934. recalculateCoordinates (0);
  70935. }
  70936. }
  70937. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70938. {
  70939. bool ok = positioner.addPoint (bounds.topLeft);
  70940. ok = positioner.addPoint (bounds.topRight) && ok;
  70941. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70942. return positioner.addPoint (cornerSize) && ok;
  70943. }
  70944. void DrawableRectangle::recalculateCoordinates (Expression::EvaluationContext* context)
  70945. {
  70946. Point<float> points[3];
  70947. bounds.resolveThreePoints (points, context);
  70948. const float cornerSizeX = (float) cornerSize.x.resolve (context);
  70949. const float cornerSizeY = (float) cornerSize.y.resolve (context);
  70950. const float w = Line<float> (points[0], points[1]).getLength();
  70951. const float h = Line<float> (points[0], points[2]).getLength();
  70952. Path newPath;
  70953. if (cornerSizeX > 0 && cornerSizeY > 0)
  70954. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70955. else
  70956. newPath.addRectangle (0, 0, w, h);
  70957. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70958. w, 0, points[1].getX(), points[1].getY(),
  70959. 0, h, points[2].getX(), points[2].getY()));
  70960. if (path != newPath)
  70961. {
  70962. path.swapWithPath (newPath);
  70963. pathChanged();
  70964. }
  70965. }
  70966. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70967. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70968. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70969. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70970. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70971. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70972. : FillAndStrokeState (state_)
  70973. {
  70974. jassert (state.hasType (valueTreeType));
  70975. }
  70976. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70977. {
  70978. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70979. state.getProperty (topRight, "100, 0"),
  70980. state.getProperty (bottomLeft, "0, 100"));
  70981. }
  70982. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70983. {
  70984. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70985. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70986. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70987. }
  70988. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70989. {
  70990. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70991. }
  70992. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70993. {
  70994. return RelativePoint (state [cornerSize]);
  70995. }
  70996. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70997. {
  70998. return state.getPropertyAsValue (cornerSize, undoManager);
  70999. }
  71000. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  71001. {
  71002. ValueTreeWrapper v (tree);
  71003. setComponentID (v.getID());
  71004. refreshFillTypes (v, builder.getImageProvider());
  71005. setStrokeType (v.getStrokeType());
  71006. setRectangle (v.getRectangle());
  71007. setCornerSize (v.getCornerSize());
  71008. }
  71009. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  71010. {
  71011. ValueTree tree (valueTreeType);
  71012. ValueTreeWrapper v (tree);
  71013. v.setID (getComponentID());
  71014. writeTo (v, imageProvider, 0);
  71015. v.setRectangle (bounds, 0);
  71016. v.setCornerSize (cornerSize, 0);
  71017. return tree;
  71018. }
  71019. END_JUCE_NAMESPACE
  71020. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71021. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71022. BEGIN_JUCE_NAMESPACE
  71023. DrawableText::DrawableText()
  71024. : colour (Colours::black),
  71025. justification (Justification::centredLeft)
  71026. {
  71027. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71028. RelativePoint (50.0f, 0.0f),
  71029. RelativePoint (0.0f, 20.0f)));
  71030. setFont (Font (15.0f), true);
  71031. }
  71032. DrawableText::DrawableText (const DrawableText& other)
  71033. : bounds (other.bounds),
  71034. fontSizeControlPoint (other.fontSizeControlPoint),
  71035. font (other.font),
  71036. text (other.text),
  71037. colour (other.colour),
  71038. justification (other.justification)
  71039. {
  71040. }
  71041. DrawableText::~DrawableText()
  71042. {
  71043. }
  71044. void DrawableText::setText (const String& newText)
  71045. {
  71046. if (text != newText)
  71047. {
  71048. text = newText;
  71049. refreshBounds();
  71050. }
  71051. }
  71052. void DrawableText::setColour (const Colour& newColour)
  71053. {
  71054. if (colour != newColour)
  71055. {
  71056. colour = newColour;
  71057. repaint();
  71058. }
  71059. }
  71060. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71061. {
  71062. if (font != newFont)
  71063. {
  71064. font = newFont;
  71065. if (applySizeAndScale)
  71066. {
  71067. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  71068. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71069. }
  71070. refreshBounds();
  71071. }
  71072. }
  71073. void DrawableText::setJustification (const Justification& newJustification)
  71074. {
  71075. justification = newJustification;
  71076. repaint();
  71077. }
  71078. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71079. {
  71080. if (bounds != newBounds)
  71081. {
  71082. bounds = newBounds;
  71083. refreshBounds();
  71084. }
  71085. }
  71086. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71087. {
  71088. if (fontSizeControlPoint != newPoint)
  71089. {
  71090. fontSizeControlPoint = newPoint;
  71091. refreshBounds();
  71092. }
  71093. }
  71094. void DrawableText::refreshBounds()
  71095. {
  71096. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  71097. {
  71098. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  71099. setPositioner (p);
  71100. p->apply();
  71101. }
  71102. else
  71103. {
  71104. setPositioner (0);
  71105. recalculateCoordinates (0);
  71106. }
  71107. }
  71108. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  71109. {
  71110. bool ok = positioner.addPoint (bounds.topLeft);
  71111. ok = positioner.addPoint (bounds.topRight) && ok;
  71112. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  71113. return positioner.addPoint (fontSizeControlPoint) && ok;
  71114. }
  71115. void DrawableText::recalculateCoordinates (Expression::EvaluationContext* context)
  71116. {
  71117. bounds.resolveThreePoints (resolvedPoints, context);
  71118. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71119. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71120. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (context)));
  71121. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71122. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71123. scaledFont = font;
  71124. scaledFont.setHeight (fontHeight);
  71125. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  71126. setBoundsToEnclose (getDrawableBounds());
  71127. repaint();
  71128. }
  71129. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  71130. {
  71131. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  71132. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  71133. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  71134. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  71135. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  71136. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  71137. }
  71138. void DrawableText::paint (Graphics& g)
  71139. {
  71140. transformContextToCorrectOrigin (g);
  71141. g.setColour (colour);
  71142. GlyphArrangement ga;
  71143. const AffineTransform transform (getArrangementAndTransform (ga));
  71144. ga.draw (g, transform);
  71145. }
  71146. const Rectangle<float> DrawableText::getDrawableBounds() const
  71147. {
  71148. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71149. }
  71150. Drawable* DrawableText::createCopy() const
  71151. {
  71152. return new DrawableText (*this);
  71153. }
  71154. const Identifier DrawableText::valueTreeType ("Text");
  71155. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71156. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71157. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71158. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71159. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71160. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71161. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71162. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71163. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71164. : ValueTreeWrapperBase (state_)
  71165. {
  71166. jassert (state.hasType (valueTreeType));
  71167. }
  71168. const String DrawableText::ValueTreeWrapper::getText() const
  71169. {
  71170. return state [text].toString();
  71171. }
  71172. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71173. {
  71174. state.setProperty (text, newText, undoManager);
  71175. }
  71176. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71177. {
  71178. return state.getPropertyAsValue (text, undoManager);
  71179. }
  71180. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71181. {
  71182. return Colour::fromString (state [colour].toString());
  71183. }
  71184. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71185. {
  71186. state.setProperty (colour, newColour.toString(), undoManager);
  71187. }
  71188. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71189. {
  71190. return Justification ((int) state [justification]);
  71191. }
  71192. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71193. {
  71194. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71195. }
  71196. const Font DrawableText::ValueTreeWrapper::getFont() const
  71197. {
  71198. return Font::fromString (state [font]);
  71199. }
  71200. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71201. {
  71202. state.setProperty (font, newFont.toString(), undoManager);
  71203. }
  71204. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71205. {
  71206. return state.getPropertyAsValue (font, undoManager);
  71207. }
  71208. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71209. {
  71210. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71211. }
  71212. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71213. {
  71214. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71215. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71216. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71217. }
  71218. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71219. {
  71220. return state [fontSizeAnchor].toString();
  71221. }
  71222. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71223. {
  71224. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71225. }
  71226. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71227. {
  71228. ValueTreeWrapper v (tree);
  71229. setComponentID (v.getID());
  71230. const RelativeParallelogram newBounds (v.getBoundingBox());
  71231. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71232. const Colour newColour (v.getColour());
  71233. const Justification newJustification (v.getJustification());
  71234. const String newText (v.getText());
  71235. const Font newFont (v.getFont());
  71236. if (text != newText || font != newFont || justification != newJustification
  71237. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71238. {
  71239. setBoundingBox (newBounds);
  71240. setFontSizeControlPoint (newFontPoint);
  71241. setColour (newColour);
  71242. setFont (newFont, false);
  71243. setJustification (newJustification);
  71244. setText (newText);
  71245. }
  71246. }
  71247. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71248. {
  71249. ValueTree tree (valueTreeType);
  71250. ValueTreeWrapper v (tree);
  71251. v.setID (getComponentID());
  71252. v.setText (text, 0);
  71253. v.setFont (font, 0);
  71254. v.setJustification (justification, 0);
  71255. v.setColour (colour, 0);
  71256. v.setBoundingBox (bounds, 0);
  71257. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71258. return tree;
  71259. }
  71260. END_JUCE_NAMESPACE
  71261. /*** End of inlined file: juce_DrawableText.cpp ***/
  71262. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71263. BEGIN_JUCE_NAMESPACE
  71264. class SVGState
  71265. {
  71266. public:
  71267. SVGState (const XmlElement* const topLevel)
  71268. : topLevelXml (topLevel),
  71269. elementX (0), elementY (0),
  71270. width (512), height (512),
  71271. viewBoxW (0), viewBoxH (0)
  71272. {
  71273. }
  71274. ~SVGState()
  71275. {
  71276. }
  71277. Drawable* parseSVGElement (const XmlElement& xml)
  71278. {
  71279. if (! xml.hasTagName ("svg"))
  71280. return 0;
  71281. DrawableComposite* const drawable = new DrawableComposite();
  71282. drawable->setName (xml.getStringAttribute ("id"));
  71283. SVGState newState (*this);
  71284. if (xml.hasAttribute ("transform"))
  71285. newState.addTransform (xml);
  71286. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71287. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71288. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71289. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71290. if (xml.hasAttribute ("viewBox"))
  71291. {
  71292. const String viewParams (xml.getStringAttribute ("viewBox"));
  71293. int i = 0;
  71294. float vx, vy, vw, vh;
  71295. if (parseCoords (viewParams, vx, vy, i, true)
  71296. && parseCoords (viewParams, vw, vh, i, true)
  71297. && vw > 0
  71298. && vh > 0)
  71299. {
  71300. newState.viewBoxW = vw;
  71301. newState.viewBoxH = vh;
  71302. int placementFlags = 0;
  71303. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71304. if (aspect.containsIgnoreCase ("none"))
  71305. {
  71306. placementFlags = RectanglePlacement::stretchToFit;
  71307. }
  71308. else
  71309. {
  71310. if (aspect.containsIgnoreCase ("slice"))
  71311. placementFlags |= RectanglePlacement::fillDestination;
  71312. if (aspect.containsIgnoreCase ("xMin"))
  71313. placementFlags |= RectanglePlacement::xLeft;
  71314. else if (aspect.containsIgnoreCase ("xMax"))
  71315. placementFlags |= RectanglePlacement::xRight;
  71316. else
  71317. placementFlags |= RectanglePlacement::xMid;
  71318. if (aspect.containsIgnoreCase ("yMin"))
  71319. placementFlags |= RectanglePlacement::yTop;
  71320. else if (aspect.containsIgnoreCase ("yMax"))
  71321. placementFlags |= RectanglePlacement::yBottom;
  71322. else
  71323. placementFlags |= RectanglePlacement::yMid;
  71324. }
  71325. const RectanglePlacement placement (placementFlags);
  71326. newState.transform
  71327. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71328. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71329. .followedBy (newState.transform);
  71330. }
  71331. }
  71332. else
  71333. {
  71334. if (viewBoxW == 0)
  71335. newState.viewBoxW = newState.width;
  71336. if (viewBoxH == 0)
  71337. newState.viewBoxH = newState.height;
  71338. }
  71339. newState.parseSubElements (xml, drawable);
  71340. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71341. return drawable;
  71342. }
  71343. private:
  71344. const XmlElement* const topLevelXml;
  71345. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71346. AffineTransform transform;
  71347. String cssStyleText;
  71348. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71349. {
  71350. forEachXmlChildElement (xml, e)
  71351. {
  71352. Drawable* d = 0;
  71353. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71354. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71355. else if (e->hasTagName ("path")) d = parsePath (*e);
  71356. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71357. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71358. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71359. else if (e->hasTagName ("line")) d = parseLine (*e);
  71360. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71361. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71362. else if (e->hasTagName ("text")) d = parseText (*e);
  71363. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71364. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71365. parentDrawable->addAndMakeVisible (d);
  71366. }
  71367. }
  71368. DrawableComposite* parseSwitch (const XmlElement& xml)
  71369. {
  71370. const XmlElement* const group = xml.getChildByName ("g");
  71371. if (group != 0)
  71372. return parseGroupElement (*group);
  71373. return 0;
  71374. }
  71375. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71376. {
  71377. DrawableComposite* const drawable = new DrawableComposite();
  71378. drawable->setName (xml.getStringAttribute ("id"));
  71379. if (xml.hasAttribute ("transform"))
  71380. {
  71381. SVGState newState (*this);
  71382. newState.addTransform (xml);
  71383. newState.parseSubElements (xml, drawable);
  71384. }
  71385. else
  71386. {
  71387. parseSubElements (xml, drawable);
  71388. }
  71389. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71390. return drawable;
  71391. }
  71392. Drawable* parsePath (const XmlElement& xml) const
  71393. {
  71394. const String d (xml.getStringAttribute ("d").trimStart());
  71395. Path path;
  71396. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71397. path.setUsingNonZeroWinding (false);
  71398. int index = 0;
  71399. float lastX = 0, lastY = 0;
  71400. float lastX2 = 0, lastY2 = 0;
  71401. juce_wchar lastCommandChar = 0;
  71402. bool isRelative = true;
  71403. bool carryOn = true;
  71404. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71405. while (d[index] != 0)
  71406. {
  71407. float x, y, x2, y2, x3, y3;
  71408. if (validCommandChars.containsChar (d[index]))
  71409. {
  71410. lastCommandChar = d [index++];
  71411. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71412. }
  71413. switch (lastCommandChar)
  71414. {
  71415. case 'M':
  71416. case 'm':
  71417. case 'L':
  71418. case 'l':
  71419. if (parseCoords (d, x, y, index, false))
  71420. {
  71421. if (isRelative)
  71422. {
  71423. x += lastX;
  71424. y += lastY;
  71425. }
  71426. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71427. {
  71428. path.startNewSubPath (x, y);
  71429. lastCommandChar = 'l';
  71430. }
  71431. else
  71432. path.lineTo (x, y);
  71433. lastX2 = lastX;
  71434. lastY2 = lastY;
  71435. lastX = x;
  71436. lastY = y;
  71437. }
  71438. else
  71439. {
  71440. ++index;
  71441. }
  71442. break;
  71443. case 'H':
  71444. case 'h':
  71445. if (parseCoord (d, x, index, false, true))
  71446. {
  71447. if (isRelative)
  71448. x += lastX;
  71449. path.lineTo (x, lastY);
  71450. lastX2 = lastX;
  71451. lastX = x;
  71452. }
  71453. else
  71454. {
  71455. ++index;
  71456. }
  71457. break;
  71458. case 'V':
  71459. case 'v':
  71460. if (parseCoord (d, y, index, false, false))
  71461. {
  71462. if (isRelative)
  71463. y += lastY;
  71464. path.lineTo (lastX, y);
  71465. lastY2 = lastY;
  71466. lastY = y;
  71467. }
  71468. else
  71469. {
  71470. ++index;
  71471. }
  71472. break;
  71473. case 'C':
  71474. case 'c':
  71475. if (parseCoords (d, x, y, index, false)
  71476. && parseCoords (d, x2, y2, index, false)
  71477. && parseCoords (d, x3, y3, index, false))
  71478. {
  71479. if (isRelative)
  71480. {
  71481. x += lastX;
  71482. y += lastY;
  71483. x2 += lastX;
  71484. y2 += lastY;
  71485. x3 += lastX;
  71486. y3 += lastY;
  71487. }
  71488. path.cubicTo (x, y, x2, y2, x3, y3);
  71489. lastX2 = x2;
  71490. lastY2 = y2;
  71491. lastX = x3;
  71492. lastY = y3;
  71493. }
  71494. else
  71495. {
  71496. ++index;
  71497. }
  71498. break;
  71499. case 'S':
  71500. case 's':
  71501. if (parseCoords (d, x, y, index, false)
  71502. && parseCoords (d, x3, y3, index, false))
  71503. {
  71504. if (isRelative)
  71505. {
  71506. x += lastX;
  71507. y += lastY;
  71508. x3 += lastX;
  71509. y3 += lastY;
  71510. }
  71511. x2 = lastX + (lastX - lastX2);
  71512. y2 = lastY + (lastY - lastY2);
  71513. path.cubicTo (x2, y2, x, y, x3, y3);
  71514. lastX2 = x;
  71515. lastY2 = y;
  71516. lastX = x3;
  71517. lastY = y3;
  71518. }
  71519. else
  71520. {
  71521. ++index;
  71522. }
  71523. break;
  71524. case 'Q':
  71525. case 'q':
  71526. if (parseCoords (d, x, y, index, false)
  71527. && parseCoords (d, x2, y2, index, false))
  71528. {
  71529. if (isRelative)
  71530. {
  71531. x += lastX;
  71532. y += lastY;
  71533. x2 += lastX;
  71534. y2 += lastY;
  71535. }
  71536. path.quadraticTo (x, y, x2, y2);
  71537. lastX2 = x;
  71538. lastY2 = y;
  71539. lastX = x2;
  71540. lastY = y2;
  71541. }
  71542. else
  71543. {
  71544. ++index;
  71545. }
  71546. break;
  71547. case 'T':
  71548. case 't':
  71549. if (parseCoords (d, x, y, index, false))
  71550. {
  71551. if (isRelative)
  71552. {
  71553. x += lastX;
  71554. y += lastY;
  71555. }
  71556. x2 = lastX + (lastX - lastX2);
  71557. y2 = lastY + (lastY - lastY2);
  71558. path.quadraticTo (x2, y2, x, y);
  71559. lastX2 = x2;
  71560. lastY2 = y2;
  71561. lastX = x;
  71562. lastY = y;
  71563. }
  71564. else
  71565. {
  71566. ++index;
  71567. }
  71568. break;
  71569. case 'A':
  71570. case 'a':
  71571. if (parseCoords (d, x, y, index, false))
  71572. {
  71573. String num;
  71574. if (parseNextNumber (d, num, index, false))
  71575. {
  71576. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71577. if (parseNextNumber (d, num, index, false))
  71578. {
  71579. const bool largeArc = num.getIntValue() != 0;
  71580. if (parseNextNumber (d, num, index, false))
  71581. {
  71582. const bool sweep = num.getIntValue() != 0;
  71583. if (parseCoords (d, x2, y2, index, false))
  71584. {
  71585. if (isRelative)
  71586. {
  71587. x2 += lastX;
  71588. y2 += lastY;
  71589. }
  71590. if (lastX != x2 || lastY != y2)
  71591. {
  71592. double centreX, centreY, startAngle, deltaAngle;
  71593. double rx = x, ry = y;
  71594. endpointToCentreParameters (lastX, lastY, x2, y2,
  71595. angle, largeArc, sweep,
  71596. rx, ry, centreX, centreY,
  71597. startAngle, deltaAngle);
  71598. path.addCentredArc ((float) centreX, (float) centreY,
  71599. (float) rx, (float) ry,
  71600. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71601. false);
  71602. path.lineTo (x2, y2);
  71603. }
  71604. lastX2 = lastX;
  71605. lastY2 = lastY;
  71606. lastX = x2;
  71607. lastY = y2;
  71608. }
  71609. }
  71610. }
  71611. }
  71612. }
  71613. else
  71614. {
  71615. ++index;
  71616. }
  71617. break;
  71618. case 'Z':
  71619. case 'z':
  71620. path.closeSubPath();
  71621. while (CharacterFunctions::isWhitespace (d [index]))
  71622. ++index;
  71623. break;
  71624. default:
  71625. carryOn = false;
  71626. break;
  71627. }
  71628. if (! carryOn)
  71629. break;
  71630. }
  71631. return parseShape (xml, path);
  71632. }
  71633. Drawable* parseRect (const XmlElement& xml) const
  71634. {
  71635. Path rect;
  71636. const bool hasRX = xml.hasAttribute ("rx");
  71637. const bool hasRY = xml.hasAttribute ("ry");
  71638. if (hasRX || hasRY)
  71639. {
  71640. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71641. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71642. if (! hasRX)
  71643. rx = ry;
  71644. else if (! hasRY)
  71645. ry = rx;
  71646. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71647. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71648. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71649. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71650. rx, ry);
  71651. }
  71652. else
  71653. {
  71654. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71655. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71656. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71657. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71658. }
  71659. return parseShape (xml, rect);
  71660. }
  71661. Drawable* parseCircle (const XmlElement& xml) const
  71662. {
  71663. Path circle;
  71664. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71665. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71666. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71667. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71668. return parseShape (xml, circle);
  71669. }
  71670. Drawable* parseEllipse (const XmlElement& xml) const
  71671. {
  71672. Path ellipse;
  71673. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71674. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71675. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71676. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71677. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71678. return parseShape (xml, ellipse);
  71679. }
  71680. Drawable* parseLine (const XmlElement& xml) const
  71681. {
  71682. Path line;
  71683. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71684. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71685. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71686. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71687. line.startNewSubPath (x1, y1);
  71688. line.lineTo (x2, y2);
  71689. return parseShape (xml, line);
  71690. }
  71691. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71692. {
  71693. const String points (xml.getStringAttribute ("points"));
  71694. Path path;
  71695. int index = 0;
  71696. float x, y;
  71697. if (parseCoords (points, x, y, index, true))
  71698. {
  71699. float firstX = x;
  71700. float firstY = y;
  71701. float lastX = 0, lastY = 0;
  71702. path.startNewSubPath (x, y);
  71703. while (parseCoords (points, x, y, index, true))
  71704. {
  71705. lastX = x;
  71706. lastY = y;
  71707. path.lineTo (x, y);
  71708. }
  71709. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71710. path.closeSubPath();
  71711. }
  71712. return parseShape (xml, path);
  71713. }
  71714. Drawable* parseShape (const XmlElement& xml, Path& path,
  71715. const bool shouldParseTransform = true) const
  71716. {
  71717. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71718. {
  71719. SVGState newState (*this);
  71720. newState.addTransform (xml);
  71721. return newState.parseShape (xml, path, false);
  71722. }
  71723. DrawablePath* dp = new DrawablePath();
  71724. dp->setName (xml.getStringAttribute ("id"));
  71725. dp->setFill (Colours::transparentBlack);
  71726. path.applyTransform (transform);
  71727. dp->setPath (path);
  71728. Path::Iterator iter (path);
  71729. bool containsClosedSubPath = false;
  71730. while (iter.next())
  71731. {
  71732. if (iter.elementType == Path::Iterator::closePath)
  71733. {
  71734. containsClosedSubPath = true;
  71735. break;
  71736. }
  71737. }
  71738. dp->setFill (getPathFillType (path,
  71739. getStyleAttribute (&xml, "fill"),
  71740. getStyleAttribute (&xml, "fill-opacity"),
  71741. getStyleAttribute (&xml, "opacity"),
  71742. containsClosedSubPath ? Colours::black
  71743. : Colours::transparentBlack));
  71744. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71745. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71746. {
  71747. dp->setStrokeFill (getPathFillType (path, strokeType,
  71748. getStyleAttribute (&xml, "stroke-opacity"),
  71749. getStyleAttribute (&xml, "opacity"),
  71750. Colours::transparentBlack));
  71751. dp->setStrokeType (getStrokeFor (&xml));
  71752. }
  71753. return dp;
  71754. }
  71755. const XmlElement* findLinkedElement (const XmlElement* e) const
  71756. {
  71757. const String id (e->getStringAttribute ("xlink:href"));
  71758. if (! id.startsWithChar ('#'))
  71759. return 0;
  71760. return findElementForId (topLevelXml, id.substring (1));
  71761. }
  71762. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71763. {
  71764. if (fillXml == 0)
  71765. return;
  71766. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71767. {
  71768. int index = 0;
  71769. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71770. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71771. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71772. double offset = e->getDoubleAttribute ("offset");
  71773. if (e->getStringAttribute ("offset").containsChar ('%'))
  71774. offset *= 0.01;
  71775. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71776. }
  71777. }
  71778. const FillType getPathFillType (const Path& path,
  71779. const String& fill,
  71780. const String& fillOpacity,
  71781. const String& overallOpacity,
  71782. const Colour& defaultColour) const
  71783. {
  71784. float opacity = 1.0f;
  71785. if (overallOpacity.isNotEmpty())
  71786. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71787. if (fillOpacity.isNotEmpty())
  71788. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71789. if (fill.startsWithIgnoreCase ("url"))
  71790. {
  71791. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71792. .upToLastOccurrenceOf (")", false, false).trim());
  71793. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71794. if (fillXml != 0
  71795. && (fillXml->hasTagName ("linearGradient")
  71796. || fillXml->hasTagName ("radialGradient")))
  71797. {
  71798. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71799. ColourGradient gradient;
  71800. addGradientStopsIn (gradient, inheritedFrom);
  71801. addGradientStopsIn (gradient, fillXml);
  71802. if (gradient.getNumColours() > 0)
  71803. {
  71804. gradient.addColour (0.0, gradient.getColour (0));
  71805. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71806. }
  71807. else
  71808. {
  71809. gradient.addColour (0.0, Colours::black);
  71810. gradient.addColour (1.0, Colours::black);
  71811. }
  71812. if (overallOpacity.isNotEmpty())
  71813. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71814. jassert (gradient.getNumColours() > 0);
  71815. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71816. float gradientWidth = viewBoxW;
  71817. float gradientHeight = viewBoxH;
  71818. float dx = 0.0f;
  71819. float dy = 0.0f;
  71820. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71821. if (! userSpace)
  71822. {
  71823. const Rectangle<float> bounds (path.getBounds());
  71824. dx = bounds.getX();
  71825. dy = bounds.getY();
  71826. gradientWidth = bounds.getWidth();
  71827. gradientHeight = bounds.getHeight();
  71828. }
  71829. if (gradient.isRadial)
  71830. {
  71831. if (userSpace)
  71832. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71833. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71834. else
  71835. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71836. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71837. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71838. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71839. //xxx (the fx, fy focal point isn't handled properly here..)
  71840. }
  71841. else
  71842. {
  71843. if (userSpace)
  71844. {
  71845. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71846. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71847. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71848. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71849. }
  71850. else
  71851. {
  71852. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71853. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71854. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71855. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71856. }
  71857. if (gradient.point1 == gradient.point2)
  71858. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71859. }
  71860. FillType type (gradient);
  71861. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71862. .followedBy (transform);
  71863. return type;
  71864. }
  71865. }
  71866. if (fill.equalsIgnoreCase ("none"))
  71867. return Colours::transparentBlack;
  71868. int i = 0;
  71869. const Colour colour (parseColour (fill, i, defaultColour));
  71870. return colour.withMultipliedAlpha (opacity);
  71871. }
  71872. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71873. {
  71874. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71875. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71876. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71877. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71878. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71879. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71880. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71881. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71882. if (join.equalsIgnoreCase ("round"))
  71883. joinStyle = PathStrokeType::curved;
  71884. else if (join.equalsIgnoreCase ("bevel"))
  71885. joinStyle = PathStrokeType::beveled;
  71886. if (cap.equalsIgnoreCase ("round"))
  71887. capStyle = PathStrokeType::rounded;
  71888. else if (cap.equalsIgnoreCase ("square"))
  71889. capStyle = PathStrokeType::square;
  71890. float ox = 0.0f, oy = 0.0f;
  71891. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71892. transform.transformPoints (ox, oy, x, y);
  71893. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71894. joinStyle, capStyle);
  71895. }
  71896. Drawable* parseText (const XmlElement& xml)
  71897. {
  71898. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71899. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71900. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71901. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71902. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71903. //xxx not done text yet!
  71904. forEachXmlChildElement (xml, e)
  71905. {
  71906. if (e->isTextElement())
  71907. {
  71908. const String text (e->getText());
  71909. Path path;
  71910. Drawable* s = parseShape (*e, path);
  71911. delete s; // xxx not finished!
  71912. }
  71913. else if (e->hasTagName ("tspan"))
  71914. {
  71915. Drawable* s = parseText (*e);
  71916. delete s; // xxx not finished!
  71917. }
  71918. }
  71919. return 0;
  71920. }
  71921. void addTransform (const XmlElement& xml)
  71922. {
  71923. transform = parseTransform (xml.getStringAttribute ("transform"))
  71924. .followedBy (transform);
  71925. }
  71926. bool parseCoord (const String& s, float& value, int& index,
  71927. const bool allowUnits, const bool isX) const
  71928. {
  71929. String number;
  71930. if (! parseNextNumber (s, number, index, allowUnits))
  71931. {
  71932. value = 0;
  71933. return false;
  71934. }
  71935. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71936. return true;
  71937. }
  71938. bool parseCoords (const String& s, float& x, float& y,
  71939. int& index, const bool allowUnits) const
  71940. {
  71941. return parseCoord (s, x, index, allowUnits, true)
  71942. && parseCoord (s, y, index, allowUnits, false);
  71943. }
  71944. float getCoordLength (const String& s, const float sizeForProportions) const
  71945. {
  71946. float n = s.getFloatValue();
  71947. const int len = s.length();
  71948. if (len > 2)
  71949. {
  71950. const float dpi = 96.0f;
  71951. const juce_wchar n1 = s [len - 2];
  71952. const juce_wchar n2 = s [len - 1];
  71953. if (n1 == 'i' && n2 == 'n')
  71954. n *= dpi;
  71955. else if (n1 == 'm' && n2 == 'm')
  71956. n *= dpi / 25.4f;
  71957. else if (n1 == 'c' && n2 == 'm')
  71958. n *= dpi / 2.54f;
  71959. else if (n1 == 'p' && n2 == 'c')
  71960. n *= 15.0f;
  71961. else if (n2 == '%')
  71962. n *= 0.01f * sizeForProportions;
  71963. }
  71964. return n;
  71965. }
  71966. void getCoordList (Array <float>& coords, const String& list,
  71967. const bool allowUnits, const bool isX) const
  71968. {
  71969. int index = 0;
  71970. float value;
  71971. while (parseCoord (list, value, index, allowUnits, isX))
  71972. coords.add (value);
  71973. }
  71974. void parseCSSStyle (const XmlElement& xml)
  71975. {
  71976. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71977. }
  71978. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71979. const String& defaultValue = String::empty) const
  71980. {
  71981. if (xml->hasAttribute (attributeName))
  71982. return xml->getStringAttribute (attributeName, defaultValue);
  71983. const String styleAtt (xml->getStringAttribute ("style"));
  71984. if (styleAtt.isNotEmpty())
  71985. {
  71986. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71987. if (value.isNotEmpty())
  71988. return value;
  71989. }
  71990. else if (xml->hasAttribute ("class"))
  71991. {
  71992. const String className ("." + xml->getStringAttribute ("class"));
  71993. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71994. if (index < 0)
  71995. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71996. if (index >= 0)
  71997. {
  71998. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71999. if (openBracket > index)
  72000. {
  72001. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72002. if (closeBracket > openBracket)
  72003. {
  72004. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72005. if (value.isNotEmpty())
  72006. return value;
  72007. }
  72008. }
  72009. }
  72010. }
  72011. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72012. if (xml != 0)
  72013. return getStyleAttribute (xml, attributeName, defaultValue);
  72014. return defaultValue;
  72015. }
  72016. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72017. {
  72018. if (xml->hasAttribute (attributeName))
  72019. return xml->getStringAttribute (attributeName);
  72020. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72021. if (xml != 0)
  72022. return getInheritedAttribute (xml, attributeName);
  72023. return String::empty;
  72024. }
  72025. static bool isIdentifierChar (const juce_wchar c)
  72026. {
  72027. return CharacterFunctions::isLetter (c) || c == '-';
  72028. }
  72029. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72030. {
  72031. int i = 0;
  72032. for (;;)
  72033. {
  72034. i = list.indexOf (i, attributeName);
  72035. if (i < 0)
  72036. break;
  72037. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72038. && ! isIdentifierChar (list [i + attributeName.length()]))
  72039. {
  72040. i = list.indexOfChar (i, ':');
  72041. if (i < 0)
  72042. break;
  72043. int end = list.indexOfChar (i, ';');
  72044. if (end < 0)
  72045. end = 0x7ffff;
  72046. return list.substring (i + 1, end).trim();
  72047. }
  72048. ++i;
  72049. }
  72050. return defaultValue;
  72051. }
  72052. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72053. {
  72054. const juce_wchar* const s = source;
  72055. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72056. ++index;
  72057. int start = index;
  72058. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72059. ++index;
  72060. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72061. ++index;
  72062. if ((s[index] == 'e' || s[index] == 'E')
  72063. && (CharacterFunctions::isDigit (s[index + 1])
  72064. || s[index + 1] == '-'
  72065. || s[index + 1] == '+'))
  72066. {
  72067. index += 2;
  72068. while (CharacterFunctions::isDigit (s[index]))
  72069. ++index;
  72070. }
  72071. if (allowUnits)
  72072. {
  72073. while (CharacterFunctions::isLetter (s[index]))
  72074. ++index;
  72075. }
  72076. if (index == start)
  72077. return false;
  72078. value = String (s + start, index - start);
  72079. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72080. ++index;
  72081. return true;
  72082. }
  72083. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72084. {
  72085. if (s [index] == '#')
  72086. {
  72087. uint32 hex [6];
  72088. zeromem (hex, sizeof (hex));
  72089. int numChars = 0;
  72090. for (int i = 6; --i >= 0;)
  72091. {
  72092. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72093. if (hexValue >= 0)
  72094. hex [numChars++] = hexValue;
  72095. else
  72096. break;
  72097. }
  72098. if (numChars <= 3)
  72099. return Colour ((uint8) (hex [0] * 0x11),
  72100. (uint8) (hex [1] * 0x11),
  72101. (uint8) (hex [2] * 0x11));
  72102. else
  72103. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72104. (uint8) ((hex [2] << 4) + hex [3]),
  72105. (uint8) ((hex [4] << 4) + hex [5]));
  72106. }
  72107. else if (s [index] == 'r'
  72108. && s [index + 1] == 'g'
  72109. && s [index + 2] == 'b')
  72110. {
  72111. const int openBracket = s.indexOfChar (index, '(');
  72112. const int closeBracket = s.indexOfChar (openBracket, ')');
  72113. if (openBracket >= 3 && closeBracket > openBracket)
  72114. {
  72115. index = closeBracket;
  72116. StringArray tokens;
  72117. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72118. tokens.trim();
  72119. tokens.removeEmptyStrings();
  72120. if (tokens[0].containsChar ('%'))
  72121. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72122. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72123. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72124. else
  72125. return Colour ((uint8) tokens[0].getIntValue(),
  72126. (uint8) tokens[1].getIntValue(),
  72127. (uint8) tokens[2].getIntValue());
  72128. }
  72129. }
  72130. return Colours::findColourForName (s, defaultColour);
  72131. }
  72132. static const AffineTransform parseTransform (String t)
  72133. {
  72134. AffineTransform result;
  72135. while (t.isNotEmpty())
  72136. {
  72137. StringArray tokens;
  72138. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72139. .upToFirstOccurrenceOf (")", false, false),
  72140. ", ", String::empty);
  72141. tokens.removeEmptyStrings (true);
  72142. float numbers [6];
  72143. for (int i = 0; i < 6; ++i)
  72144. numbers[i] = tokens[i].getFloatValue();
  72145. AffineTransform trans;
  72146. if (t.startsWithIgnoreCase ("matrix"))
  72147. {
  72148. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72149. numbers[1], numbers[3], numbers[5]);
  72150. }
  72151. else if (t.startsWithIgnoreCase ("translate"))
  72152. {
  72153. jassert (tokens.size() == 2);
  72154. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72155. }
  72156. else if (t.startsWithIgnoreCase ("scale"))
  72157. {
  72158. if (tokens.size() == 1)
  72159. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72160. else
  72161. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72162. }
  72163. else if (t.startsWithIgnoreCase ("rotate"))
  72164. {
  72165. if (tokens.size() != 3)
  72166. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72167. else
  72168. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72169. numbers[1], numbers[2]);
  72170. }
  72171. else if (t.startsWithIgnoreCase ("skewX"))
  72172. {
  72173. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72174. 0.0f, 1.0f, 0.0f);
  72175. }
  72176. else if (t.startsWithIgnoreCase ("skewY"))
  72177. {
  72178. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72179. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72180. }
  72181. result = trans.followedBy (result);
  72182. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72183. }
  72184. return result;
  72185. }
  72186. static void endpointToCentreParameters (const double x1, const double y1,
  72187. const double x2, const double y2,
  72188. const double angle,
  72189. const bool largeArc, const bool sweep,
  72190. double& rx, double& ry,
  72191. double& centreX, double& centreY,
  72192. double& startAngle, double& deltaAngle)
  72193. {
  72194. const double midX = (x1 - x2) * 0.5;
  72195. const double midY = (y1 - y2) * 0.5;
  72196. const double cosAngle = cos (angle);
  72197. const double sinAngle = sin (angle);
  72198. const double xp = cosAngle * midX + sinAngle * midY;
  72199. const double yp = cosAngle * midY - sinAngle * midX;
  72200. const double xp2 = xp * xp;
  72201. const double yp2 = yp * yp;
  72202. double rx2 = rx * rx;
  72203. double ry2 = ry * ry;
  72204. const double s = (xp2 / rx2) + (yp2 / ry2);
  72205. double c;
  72206. if (s <= 1.0)
  72207. {
  72208. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72209. / (( rx2 * yp2) + (ry2 * xp2))));
  72210. if (largeArc == sweep)
  72211. c = -c;
  72212. }
  72213. else
  72214. {
  72215. const double s2 = std::sqrt (s);
  72216. rx *= s2;
  72217. ry *= s2;
  72218. rx2 = rx * rx;
  72219. ry2 = ry * ry;
  72220. c = 0;
  72221. }
  72222. const double cpx = ((rx * yp) / ry) * c;
  72223. const double cpy = ((-ry * xp) / rx) * c;
  72224. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72225. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72226. const double ux = (xp - cpx) / rx;
  72227. const double uy = (yp - cpy) / ry;
  72228. const double vx = (-xp - cpx) / rx;
  72229. const double vy = (-yp - cpy) / ry;
  72230. const double length = juce_hypot (ux, uy);
  72231. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72232. if (uy < 0)
  72233. startAngle = -startAngle;
  72234. startAngle += double_Pi * 0.5;
  72235. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72236. / (length * juce_hypot (vx, vy))));
  72237. if ((ux * vy) - (uy * vx) < 0)
  72238. deltaAngle = -deltaAngle;
  72239. if (sweep)
  72240. {
  72241. if (deltaAngle < 0)
  72242. deltaAngle += double_Pi * 2.0;
  72243. }
  72244. else
  72245. {
  72246. if (deltaAngle > 0)
  72247. deltaAngle -= double_Pi * 2.0;
  72248. }
  72249. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72250. }
  72251. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72252. {
  72253. forEachXmlChildElement (*parent, e)
  72254. {
  72255. if (e->compareAttribute ("id", id))
  72256. return e;
  72257. const XmlElement* const found = findElementForId (e, id);
  72258. if (found != 0)
  72259. return found;
  72260. }
  72261. return 0;
  72262. }
  72263. SVGState& operator= (const SVGState&);
  72264. };
  72265. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72266. {
  72267. SVGState state (&svgDocument);
  72268. return state.parseSVGElement (svgDocument);
  72269. }
  72270. END_JUCE_NAMESPACE
  72271. /*** End of inlined file: juce_SVGParser.cpp ***/
  72272. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72273. BEGIN_JUCE_NAMESPACE
  72274. #if JUCE_MSVC && JUCE_DEBUG
  72275. #pragma optimize ("t", on)
  72276. #endif
  72277. DropShadowEffect::DropShadowEffect()
  72278. : offsetX (0),
  72279. offsetY (0),
  72280. radius (4),
  72281. opacity (0.6f)
  72282. {
  72283. }
  72284. DropShadowEffect::~DropShadowEffect()
  72285. {
  72286. }
  72287. void DropShadowEffect::setShadowProperties (const float newRadius,
  72288. const float newOpacity,
  72289. const int newShadowOffsetX,
  72290. const int newShadowOffsetY)
  72291. {
  72292. radius = jmax (1.1f, newRadius);
  72293. offsetX = newShadowOffsetX;
  72294. offsetY = newShadowOffsetY;
  72295. opacity = newOpacity;
  72296. }
  72297. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72298. {
  72299. const int w = image.getWidth();
  72300. const int h = image.getHeight();
  72301. Image shadowImage (Image::SingleChannel, w, h, false);
  72302. const Image::BitmapData srcData (image, false);
  72303. const Image::BitmapData destData (shadowImage, true);
  72304. const int filter = roundToInt (63.0f / radius);
  72305. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72306. for (int x = w; --x >= 0;)
  72307. {
  72308. int shadowAlpha = 0;
  72309. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72310. uint8* shadowPix = destData.data + x;
  72311. for (int y = h; --y >= 0;)
  72312. {
  72313. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72314. *shadowPix = (uint8) shadowAlpha;
  72315. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72316. shadowPix += destData.lineStride;
  72317. }
  72318. }
  72319. for (int y = h; --y >= 0;)
  72320. {
  72321. int shadowAlpha = 0;
  72322. uint8* shadowPix = destData.getLinePointer (y);
  72323. for (int x = w; --x >= 0;)
  72324. {
  72325. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72326. *shadowPix++ = (uint8) shadowAlpha;
  72327. }
  72328. }
  72329. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72330. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72331. g.setOpacity (alpha);
  72332. g.drawImageAt (image, 0, 0);
  72333. }
  72334. #if JUCE_MSVC && JUCE_DEBUG
  72335. #pragma optimize ("", on) // resets optimisations to the project defaults
  72336. #endif
  72337. END_JUCE_NAMESPACE
  72338. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72339. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72340. BEGIN_JUCE_NAMESPACE
  72341. GlowEffect::GlowEffect()
  72342. : radius (2.0f),
  72343. colour (Colours::white)
  72344. {
  72345. }
  72346. GlowEffect::~GlowEffect()
  72347. {
  72348. }
  72349. void GlowEffect::setGlowProperties (const float newRadius,
  72350. const Colour& newColour)
  72351. {
  72352. radius = newRadius;
  72353. colour = newColour;
  72354. }
  72355. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72356. {
  72357. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72358. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72359. blurKernel.createGaussianBlur (radius);
  72360. blurKernel.rescaleAllValues (radius);
  72361. blurKernel.applyToImage (temp, image, image.getBounds());
  72362. g.setColour (colour.withMultipliedAlpha (alpha));
  72363. g.drawImageAt (temp, 0, 0, true);
  72364. g.setOpacity (alpha);
  72365. g.drawImageAt (image, 0, 0, false);
  72366. }
  72367. END_JUCE_NAMESPACE
  72368. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72369. /*** Start of inlined file: juce_Font.cpp ***/
  72370. BEGIN_JUCE_NAMESPACE
  72371. namespace FontValues
  72372. {
  72373. float limitFontHeight (const float height) throw()
  72374. {
  72375. return jlimit (0.1f, 10000.0f, height);
  72376. }
  72377. const float defaultFontHeight = 14.0f;
  72378. String fallbackFont;
  72379. }
  72380. class TypefaceCache : public DeletedAtShutdown
  72381. {
  72382. public:
  72383. TypefaceCache()
  72384. : counter (0)
  72385. {
  72386. setSize (10);
  72387. }
  72388. ~TypefaceCache()
  72389. {
  72390. clearSingletonInstance();
  72391. }
  72392. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72393. void setSize (const int numToCache)
  72394. {
  72395. faces.clear();
  72396. faces.insertMultiple (-1, CachedFace(), numToCache);
  72397. }
  72398. const Typeface::Ptr findTypefaceFor (const Font& font)
  72399. {
  72400. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72401. const String faceName (font.getTypefaceName());
  72402. int i;
  72403. for (i = faces.size(); --i >= 0;)
  72404. {
  72405. CachedFace& face = faces.getReference(i);
  72406. if (face.flags == flags
  72407. && face.typefaceName == faceName
  72408. && face.typeface->isSuitableForFont (font))
  72409. {
  72410. face.lastUsageCount = ++counter;
  72411. return face.typeface;
  72412. }
  72413. }
  72414. int replaceIndex = 0;
  72415. int bestLastUsageCount = std::numeric_limits<int>::max();
  72416. for (i = faces.size(); --i >= 0;)
  72417. {
  72418. const int lu = faces.getReference(i).lastUsageCount;
  72419. if (bestLastUsageCount > lu)
  72420. {
  72421. bestLastUsageCount = lu;
  72422. replaceIndex = i;
  72423. }
  72424. }
  72425. CachedFace& face = faces.getReference (replaceIndex);
  72426. face.typefaceName = faceName;
  72427. face.flags = flags;
  72428. face.lastUsageCount = ++counter;
  72429. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72430. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72431. if (defaultFace == 0 && font == Font())
  72432. defaultFace = face.typeface;
  72433. return face.typeface;
  72434. }
  72435. const Typeface::Ptr getDefaultTypeface() const throw()
  72436. {
  72437. return defaultFace;
  72438. }
  72439. private:
  72440. struct CachedFace
  72441. {
  72442. CachedFace() throw()
  72443. : lastUsageCount (0), flags (-1)
  72444. {
  72445. }
  72446. // Although it seems a bit wacky to store the name here, it's because it may be a
  72447. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72448. // Since the typeface itself doesn't know that it may have this alias, the name under
  72449. // which it was fetched needs to be stored separately.
  72450. String typefaceName;
  72451. int lastUsageCount, flags;
  72452. Typeface::Ptr typeface;
  72453. };
  72454. Array <CachedFace> faces;
  72455. Typeface::Ptr defaultFace;
  72456. int counter;
  72457. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72458. };
  72459. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72460. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72461. {
  72462. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72463. }
  72464. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72465. : typefaceName (Font::getDefaultSansSerifFontName()),
  72466. height (height_),
  72467. horizontalScale (1.0f),
  72468. kerning (0),
  72469. ascent (0),
  72470. styleFlags (styleFlags_),
  72471. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72472. {
  72473. }
  72474. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72475. : typefaceName (typefaceName_),
  72476. height (height_),
  72477. horizontalScale (1.0f),
  72478. kerning (0),
  72479. ascent (0),
  72480. styleFlags (styleFlags_),
  72481. typeface (0)
  72482. {
  72483. }
  72484. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72485. : typefaceName (typeface_->getName()),
  72486. height (FontValues::defaultFontHeight),
  72487. horizontalScale (1.0f),
  72488. kerning (0),
  72489. ascent (0),
  72490. styleFlags (Font::plain),
  72491. typeface (typeface_)
  72492. {
  72493. }
  72494. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72495. : typefaceName (other.typefaceName),
  72496. height (other.height),
  72497. horizontalScale (other.horizontalScale),
  72498. kerning (other.kerning),
  72499. ascent (other.ascent),
  72500. styleFlags (other.styleFlags),
  72501. typeface (other.typeface)
  72502. {
  72503. }
  72504. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72505. {
  72506. return height == other.height
  72507. && styleFlags == other.styleFlags
  72508. && horizontalScale == other.horizontalScale
  72509. && kerning == other.kerning
  72510. && typefaceName == other.typefaceName;
  72511. }
  72512. Font::Font()
  72513. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72514. {
  72515. }
  72516. Font::Font (const float fontHeight, const int styleFlags_)
  72517. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72518. {
  72519. }
  72520. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72521. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72522. {
  72523. }
  72524. Font::Font (const Typeface::Ptr& typeface)
  72525. : font (new SharedFontInternal (typeface))
  72526. {
  72527. }
  72528. Font::Font (const Font& other) throw()
  72529. : font (other.font)
  72530. {
  72531. }
  72532. Font& Font::operator= (const Font& other) throw()
  72533. {
  72534. font = other.font;
  72535. return *this;
  72536. }
  72537. Font::~Font() throw()
  72538. {
  72539. }
  72540. bool Font::operator== (const Font& other) const throw()
  72541. {
  72542. return font == other.font
  72543. || *font == *other.font;
  72544. }
  72545. bool Font::operator!= (const Font& other) const throw()
  72546. {
  72547. return ! operator== (other);
  72548. }
  72549. void Font::dupeInternalIfShared()
  72550. {
  72551. if (font->getReferenceCount() > 1)
  72552. font = new SharedFontInternal (*font);
  72553. }
  72554. const String Font::getDefaultSansSerifFontName()
  72555. {
  72556. static const String name ("<Sans-Serif>");
  72557. return name;
  72558. }
  72559. const String Font::getDefaultSerifFontName()
  72560. {
  72561. static const String name ("<Serif>");
  72562. return name;
  72563. }
  72564. const String Font::getDefaultMonospacedFontName()
  72565. {
  72566. static const String name ("<Monospaced>");
  72567. return name;
  72568. }
  72569. void Font::setTypefaceName (const String& faceName)
  72570. {
  72571. if (faceName != font->typefaceName)
  72572. {
  72573. dupeInternalIfShared();
  72574. font->typefaceName = faceName;
  72575. font->typeface = 0;
  72576. font->ascent = 0;
  72577. }
  72578. }
  72579. const String Font::getFallbackFontName()
  72580. {
  72581. return FontValues::fallbackFont;
  72582. }
  72583. void Font::setFallbackFontName (const String& name)
  72584. {
  72585. FontValues::fallbackFont = name;
  72586. }
  72587. void Font::setHeight (float newHeight)
  72588. {
  72589. newHeight = FontValues::limitFontHeight (newHeight);
  72590. if (font->height != newHeight)
  72591. {
  72592. dupeInternalIfShared();
  72593. font->height = newHeight;
  72594. }
  72595. }
  72596. void Font::setHeightWithoutChangingWidth (float newHeight)
  72597. {
  72598. newHeight = FontValues::limitFontHeight (newHeight);
  72599. if (font->height != newHeight)
  72600. {
  72601. dupeInternalIfShared();
  72602. font->horizontalScale *= (font->height / newHeight);
  72603. font->height = newHeight;
  72604. }
  72605. }
  72606. void Font::setStyleFlags (const int newFlags)
  72607. {
  72608. if (font->styleFlags != newFlags)
  72609. {
  72610. dupeInternalIfShared();
  72611. font->styleFlags = newFlags;
  72612. font->typeface = 0;
  72613. font->ascent = 0;
  72614. }
  72615. }
  72616. void Font::setSizeAndStyle (float newHeight,
  72617. const int newStyleFlags,
  72618. const float newHorizontalScale,
  72619. const float newKerningAmount)
  72620. {
  72621. newHeight = FontValues::limitFontHeight (newHeight);
  72622. if (font->height != newHeight
  72623. || font->horizontalScale != newHorizontalScale
  72624. || font->kerning != newKerningAmount)
  72625. {
  72626. dupeInternalIfShared();
  72627. font->height = newHeight;
  72628. font->horizontalScale = newHorizontalScale;
  72629. font->kerning = newKerningAmount;
  72630. }
  72631. setStyleFlags (newStyleFlags);
  72632. }
  72633. void Font::setHorizontalScale (const float scaleFactor)
  72634. {
  72635. dupeInternalIfShared();
  72636. font->horizontalScale = scaleFactor;
  72637. }
  72638. void Font::setExtraKerningFactor (const float extraKerning)
  72639. {
  72640. dupeInternalIfShared();
  72641. font->kerning = extraKerning;
  72642. }
  72643. void Font::setBold (const bool shouldBeBold)
  72644. {
  72645. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72646. : (font->styleFlags & ~bold));
  72647. }
  72648. const Font Font::boldened() const
  72649. {
  72650. Font f (*this);
  72651. f.setBold (true);
  72652. return f;
  72653. }
  72654. bool Font::isBold() const throw()
  72655. {
  72656. return (font->styleFlags & bold) != 0;
  72657. }
  72658. void Font::setItalic (const bool shouldBeItalic)
  72659. {
  72660. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72661. : (font->styleFlags & ~italic));
  72662. }
  72663. const Font Font::italicised() const
  72664. {
  72665. Font f (*this);
  72666. f.setItalic (true);
  72667. return f;
  72668. }
  72669. bool Font::isItalic() const throw()
  72670. {
  72671. return (font->styleFlags & italic) != 0;
  72672. }
  72673. void Font::setUnderline (const bool shouldBeUnderlined)
  72674. {
  72675. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72676. : (font->styleFlags & ~underlined));
  72677. }
  72678. bool Font::isUnderlined() const throw()
  72679. {
  72680. return (font->styleFlags & underlined) != 0;
  72681. }
  72682. float Font::getAscent() const
  72683. {
  72684. if (font->ascent == 0)
  72685. font->ascent = getTypeface()->getAscent();
  72686. return font->height * font->ascent;
  72687. }
  72688. float Font::getDescent() const
  72689. {
  72690. return font->height - getAscent();
  72691. }
  72692. int Font::getStringWidth (const String& text) const
  72693. {
  72694. return roundToInt (getStringWidthFloat (text));
  72695. }
  72696. float Font::getStringWidthFloat (const String& text) const
  72697. {
  72698. float w = getTypeface()->getStringWidth (text);
  72699. if (font->kerning != 0)
  72700. w += font->kerning * text.length();
  72701. return w * font->height * font->horizontalScale;
  72702. }
  72703. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72704. {
  72705. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72706. const float scale = font->height * font->horizontalScale;
  72707. const int num = xOffsets.size();
  72708. if (num > 0)
  72709. {
  72710. float* const x = &(xOffsets.getReference(0));
  72711. if (font->kerning != 0)
  72712. {
  72713. for (int i = 0; i < num; ++i)
  72714. x[i] = (x[i] + i * font->kerning) * scale;
  72715. }
  72716. else
  72717. {
  72718. for (int i = 0; i < num; ++i)
  72719. x[i] *= scale;
  72720. }
  72721. }
  72722. }
  72723. void Font::findFonts (Array<Font>& destArray)
  72724. {
  72725. const StringArray names (findAllTypefaceNames());
  72726. for (int i = 0; i < names.size(); ++i)
  72727. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72728. }
  72729. const String Font::toString() const
  72730. {
  72731. String s (getTypefaceName());
  72732. if (s == getDefaultSansSerifFontName())
  72733. s = String::empty;
  72734. else
  72735. s += "; ";
  72736. s += String (getHeight(), 1);
  72737. if (isBold())
  72738. s += " bold";
  72739. if (isItalic())
  72740. s += " italic";
  72741. return s;
  72742. }
  72743. const Font Font::fromString (const String& fontDescription)
  72744. {
  72745. String name;
  72746. const int separator = fontDescription.indexOfChar (';');
  72747. if (separator > 0)
  72748. name = fontDescription.substring (0, separator).trim();
  72749. if (name.isEmpty())
  72750. name = getDefaultSansSerifFontName();
  72751. String sizeAndStyle (fontDescription.substring (separator + 1));
  72752. float height = sizeAndStyle.getFloatValue();
  72753. if (height <= 0)
  72754. height = 10.0f;
  72755. int flags = Font::plain;
  72756. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72757. flags |= Font::bold;
  72758. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72759. flags |= Font::italic;
  72760. return Font (name, height, flags);
  72761. }
  72762. Typeface* Font::getTypeface() const
  72763. {
  72764. if (font->typeface == 0)
  72765. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72766. return font->typeface;
  72767. }
  72768. END_JUCE_NAMESPACE
  72769. /*** End of inlined file: juce_Font.cpp ***/
  72770. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72771. BEGIN_JUCE_NAMESPACE
  72772. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72773. const juce_wchar character_, const int glyph_)
  72774. : x (x_),
  72775. y (y_),
  72776. w (w_),
  72777. font (font_),
  72778. character (character_),
  72779. glyph (glyph_)
  72780. {
  72781. }
  72782. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72783. : x (other.x),
  72784. y (other.y),
  72785. w (other.w),
  72786. font (other.font),
  72787. character (other.character),
  72788. glyph (other.glyph)
  72789. {
  72790. }
  72791. void PositionedGlyph::draw (const Graphics& g) const
  72792. {
  72793. if (! isWhitespace())
  72794. {
  72795. g.getInternalContext()->setFont (font);
  72796. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72797. }
  72798. }
  72799. void PositionedGlyph::draw (const Graphics& g,
  72800. const AffineTransform& transform) const
  72801. {
  72802. if (! isWhitespace())
  72803. {
  72804. g.getInternalContext()->setFont (font);
  72805. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72806. .followedBy (transform));
  72807. }
  72808. }
  72809. void PositionedGlyph::createPath (Path& path) const
  72810. {
  72811. if (! isWhitespace())
  72812. {
  72813. Typeface* const t = font.getTypeface();
  72814. if (t != 0)
  72815. {
  72816. Path p;
  72817. t->getOutlineForGlyph (glyph, p);
  72818. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72819. .translated (x, y));
  72820. }
  72821. }
  72822. }
  72823. bool PositionedGlyph::hitTest (float px, float py) const
  72824. {
  72825. if (getBounds().contains (px, py) && ! isWhitespace())
  72826. {
  72827. Typeface* const t = font.getTypeface();
  72828. if (t != 0)
  72829. {
  72830. Path p;
  72831. t->getOutlineForGlyph (glyph, p);
  72832. AffineTransform::translation (-x, -y)
  72833. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72834. .transformPoint (px, py);
  72835. return p.contains (px, py);
  72836. }
  72837. }
  72838. return false;
  72839. }
  72840. void PositionedGlyph::moveBy (const float deltaX,
  72841. const float deltaY)
  72842. {
  72843. x += deltaX;
  72844. y += deltaY;
  72845. }
  72846. GlyphArrangement::GlyphArrangement()
  72847. {
  72848. glyphs.ensureStorageAllocated (128);
  72849. }
  72850. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72851. {
  72852. addGlyphArrangement (other);
  72853. }
  72854. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72855. {
  72856. if (this != &other)
  72857. {
  72858. clear();
  72859. addGlyphArrangement (other);
  72860. }
  72861. return *this;
  72862. }
  72863. GlyphArrangement::~GlyphArrangement()
  72864. {
  72865. }
  72866. void GlyphArrangement::clear()
  72867. {
  72868. glyphs.clear();
  72869. }
  72870. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72871. {
  72872. jassert (isPositiveAndBelow (index, glyphs.size()));
  72873. return *glyphs [index];
  72874. }
  72875. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72876. {
  72877. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72878. glyphs.addCopiesOf (other.glyphs);
  72879. }
  72880. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72881. {
  72882. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72883. }
  72884. void GlyphArrangement::addLineOfText (const Font& font,
  72885. const String& text,
  72886. const float xOffset,
  72887. const float yOffset)
  72888. {
  72889. addCurtailedLineOfText (font, text,
  72890. xOffset, yOffset,
  72891. 1.0e10f, false);
  72892. }
  72893. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72894. const String& text,
  72895. float xOffset,
  72896. const float yOffset,
  72897. const float maxWidthPixels,
  72898. const bool useEllipsis)
  72899. {
  72900. if (text.isNotEmpty())
  72901. {
  72902. Array <int> newGlyphs;
  72903. Array <float> xOffsets;
  72904. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72905. const int textLen = newGlyphs.size();
  72906. const juce_wchar* const unicodeText = text;
  72907. for (int i = 0; i < textLen; ++i)
  72908. {
  72909. const float thisX = xOffsets.getUnchecked (i);
  72910. const float nextX = xOffsets.getUnchecked (i + 1);
  72911. if (nextX > maxWidthPixels + 1.0f)
  72912. {
  72913. // curtail the string if it's too wide..
  72914. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72915. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72916. break;
  72917. }
  72918. else
  72919. {
  72920. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72921. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72922. }
  72923. }
  72924. }
  72925. }
  72926. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72927. const int startIndex, int endIndex)
  72928. {
  72929. int numDeleted = 0;
  72930. if (glyphs.size() > 0)
  72931. {
  72932. Array<int> dotGlyphs;
  72933. Array<float> dotXs;
  72934. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72935. const float dx = dotXs[1];
  72936. float xOffset = 0.0f, yOffset = 0.0f;
  72937. while (endIndex > startIndex)
  72938. {
  72939. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72940. xOffset = pg->x;
  72941. yOffset = pg->y;
  72942. glyphs.remove (endIndex);
  72943. ++numDeleted;
  72944. if (xOffset + dx * 3 <= maxXPos)
  72945. break;
  72946. }
  72947. for (int i = 3; --i >= 0;)
  72948. {
  72949. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72950. font, '.', dotGlyphs.getFirst()));
  72951. --numDeleted;
  72952. xOffset += dx;
  72953. if (xOffset > maxXPos)
  72954. break;
  72955. }
  72956. }
  72957. return numDeleted;
  72958. }
  72959. void GlyphArrangement::addJustifiedText (const Font& font,
  72960. const String& text,
  72961. float x, float y,
  72962. const float maxLineWidth,
  72963. const Justification& horizontalLayout)
  72964. {
  72965. int lineStartIndex = glyphs.size();
  72966. addLineOfText (font, text, x, y);
  72967. const float originalY = y;
  72968. while (lineStartIndex < glyphs.size())
  72969. {
  72970. int i = lineStartIndex;
  72971. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72972. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72973. ++i;
  72974. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72975. int lastWordBreakIndex = -1;
  72976. while (i < glyphs.size())
  72977. {
  72978. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72979. const juce_wchar c = pg->getCharacter();
  72980. if (c == '\r' || c == '\n')
  72981. {
  72982. ++i;
  72983. if (c == '\r' && i < glyphs.size()
  72984. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72985. ++i;
  72986. break;
  72987. }
  72988. else if (pg->isWhitespace())
  72989. {
  72990. lastWordBreakIndex = i + 1;
  72991. }
  72992. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72993. {
  72994. if (lastWordBreakIndex >= 0)
  72995. i = lastWordBreakIndex;
  72996. break;
  72997. }
  72998. ++i;
  72999. }
  73000. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73001. float currentLineEndX = currentLineStartX;
  73002. for (int j = i; --j >= lineStartIndex;)
  73003. {
  73004. if (! glyphs.getUnchecked (j)->isWhitespace())
  73005. {
  73006. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73007. break;
  73008. }
  73009. }
  73010. float deltaX = 0.0f;
  73011. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73012. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73013. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73014. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73015. else if (horizontalLayout.testFlags (Justification::right))
  73016. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73017. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73018. x + deltaX - currentLineStartX, y - originalY);
  73019. lineStartIndex = i;
  73020. y += font.getHeight();
  73021. }
  73022. }
  73023. void GlyphArrangement::addFittedText (const Font& f,
  73024. const String& text,
  73025. const float x, const float y,
  73026. const float width, const float height,
  73027. const Justification& layout,
  73028. int maximumLines,
  73029. const float minimumHorizontalScale)
  73030. {
  73031. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73032. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73033. if (text.containsAnyOf ("\r\n"))
  73034. {
  73035. GlyphArrangement ga;
  73036. ga.addJustifiedText (f, text, x, y, width, layout);
  73037. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73038. float dy = y - bb.getY();
  73039. if (layout.testFlags (Justification::verticallyCentred))
  73040. dy += (height - bb.getHeight()) * 0.5f;
  73041. else if (layout.testFlags (Justification::bottom))
  73042. dy += height - bb.getHeight();
  73043. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73044. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73045. for (int i = 0; i < ga.glyphs.size(); ++i)
  73046. glyphs.add (ga.glyphs.getUnchecked (i));
  73047. ga.glyphs.clear (false);
  73048. return;
  73049. }
  73050. int startIndex = glyphs.size();
  73051. addLineOfText (f, text.trim(), x, y);
  73052. if (glyphs.size() > startIndex)
  73053. {
  73054. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73055. - glyphs.getUnchecked (startIndex)->getLeft();
  73056. if (lineWidth <= 0)
  73057. return;
  73058. if (lineWidth * minimumHorizontalScale < width)
  73059. {
  73060. if (lineWidth > width)
  73061. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73062. width / lineWidth);
  73063. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73064. x, y, width, height, layout);
  73065. }
  73066. else if (maximumLines <= 1)
  73067. {
  73068. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73069. x, y, width, height, f, layout, minimumHorizontalScale);
  73070. }
  73071. else
  73072. {
  73073. Font font (f);
  73074. String txt (text.trim());
  73075. const int length = txt.length();
  73076. const int originalStartIndex = startIndex;
  73077. int numLines = 1;
  73078. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73079. maximumLines = 1;
  73080. maximumLines = jmin (maximumLines, length);
  73081. while (numLines < maximumLines)
  73082. {
  73083. ++numLines;
  73084. const float newFontHeight = height / (float) numLines;
  73085. if (newFontHeight < font.getHeight())
  73086. {
  73087. font.setHeight (jmax (8.0f, newFontHeight));
  73088. removeRangeOfGlyphs (startIndex, -1);
  73089. addLineOfText (font, txt, x, y);
  73090. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73091. - glyphs.getUnchecked (startIndex)->getLeft();
  73092. }
  73093. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73094. break;
  73095. }
  73096. if (numLines < 1)
  73097. numLines = 1;
  73098. float lineY = y;
  73099. float widthPerLine = lineWidth / numLines;
  73100. int lastLineStartIndex = 0;
  73101. for (int line = 0; line < numLines; ++line)
  73102. {
  73103. int i = startIndex;
  73104. lastLineStartIndex = i;
  73105. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73106. if (line == numLines - 1)
  73107. {
  73108. widthPerLine = width;
  73109. i = glyphs.size();
  73110. }
  73111. else
  73112. {
  73113. while (i < glyphs.size())
  73114. {
  73115. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73116. if (lineWidth > widthPerLine)
  73117. {
  73118. // got to a point where the line's too long, so skip forward to find a
  73119. // good place to break it..
  73120. const int searchStartIndex = i;
  73121. while (i < glyphs.size())
  73122. {
  73123. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73124. {
  73125. if (glyphs.getUnchecked (i)->isWhitespace()
  73126. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73127. {
  73128. ++i;
  73129. break;
  73130. }
  73131. }
  73132. else
  73133. {
  73134. // can't find a suitable break, so try looking backwards..
  73135. i = searchStartIndex;
  73136. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73137. {
  73138. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73139. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73140. {
  73141. i -= back - 1;
  73142. break;
  73143. }
  73144. }
  73145. break;
  73146. }
  73147. ++i;
  73148. }
  73149. break;
  73150. }
  73151. ++i;
  73152. }
  73153. int wsStart = i;
  73154. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73155. --wsStart;
  73156. int wsEnd = i;
  73157. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73158. ++wsEnd;
  73159. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73160. i = jmax (wsStart, startIndex + 1);
  73161. }
  73162. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73163. x, lineY, width, font.getHeight(), font,
  73164. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73165. minimumHorizontalScale);
  73166. startIndex = i;
  73167. lineY += font.getHeight();
  73168. if (startIndex >= glyphs.size())
  73169. break;
  73170. }
  73171. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73172. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73173. }
  73174. }
  73175. }
  73176. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73177. const float dx, const float dy)
  73178. {
  73179. jassert (startIndex >= 0);
  73180. if (dx != 0.0f || dy != 0.0f)
  73181. {
  73182. if (num < 0 || startIndex + num > glyphs.size())
  73183. num = glyphs.size() - startIndex;
  73184. while (--num >= 0)
  73185. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73186. }
  73187. }
  73188. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73189. const Justification& justification, float minimumHorizontalScale)
  73190. {
  73191. int numDeleted = 0;
  73192. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73193. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73194. if (lineWidth > w)
  73195. {
  73196. if (minimumHorizontalScale < 1.0f)
  73197. {
  73198. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73199. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73200. }
  73201. if (lineWidth > w)
  73202. {
  73203. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73204. numGlyphs -= numDeleted;
  73205. }
  73206. }
  73207. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73208. return numDeleted;
  73209. }
  73210. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73211. const float horizontalScaleFactor)
  73212. {
  73213. jassert (startIndex >= 0);
  73214. if (num < 0 || startIndex + num > glyphs.size())
  73215. num = glyphs.size() - startIndex;
  73216. if (num > 0)
  73217. {
  73218. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73219. while (--num >= 0)
  73220. {
  73221. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73222. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73223. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73224. pg->w *= horizontalScaleFactor;
  73225. }
  73226. }
  73227. }
  73228. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73229. {
  73230. jassert (startIndex >= 0);
  73231. if (num < 0 || startIndex + num > glyphs.size())
  73232. num = glyphs.size() - startIndex;
  73233. Rectangle<float> result;
  73234. while (--num >= 0)
  73235. {
  73236. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73237. if (includeWhitespace || ! pg->isWhitespace())
  73238. result = result.getUnion (pg->getBounds());
  73239. }
  73240. return result;
  73241. }
  73242. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73243. const float x, const float y, const float width, const float height,
  73244. const Justification& justification)
  73245. {
  73246. jassert (num >= 0 && startIndex >= 0);
  73247. if (glyphs.size() > 0 && num > 0)
  73248. {
  73249. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73250. | Justification::horizontallyCentred)));
  73251. float deltaX = 0.0f;
  73252. if (justification.testFlags (Justification::horizontallyJustified))
  73253. deltaX = x - bb.getX();
  73254. else if (justification.testFlags (Justification::horizontallyCentred))
  73255. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73256. else if (justification.testFlags (Justification::right))
  73257. deltaX = (x + width) - bb.getRight();
  73258. else
  73259. deltaX = x - bb.getX();
  73260. float deltaY = 0.0f;
  73261. if (justification.testFlags (Justification::top))
  73262. deltaY = y - bb.getY();
  73263. else if (justification.testFlags (Justification::bottom))
  73264. deltaY = (y + height) - bb.getBottom();
  73265. else
  73266. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73267. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73268. if (justification.testFlags (Justification::horizontallyJustified))
  73269. {
  73270. int lineStart = 0;
  73271. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73272. int i;
  73273. for (i = 0; i < num; ++i)
  73274. {
  73275. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73276. if (glyphY != baseY)
  73277. {
  73278. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73279. lineStart = i;
  73280. baseY = glyphY;
  73281. }
  73282. }
  73283. if (i > lineStart)
  73284. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73285. }
  73286. }
  73287. }
  73288. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73289. {
  73290. if (start + num < glyphs.size()
  73291. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73292. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73293. {
  73294. int numSpaces = 0;
  73295. int spacesAtEnd = 0;
  73296. for (int i = 0; i < num; ++i)
  73297. {
  73298. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73299. {
  73300. ++spacesAtEnd;
  73301. ++numSpaces;
  73302. }
  73303. else
  73304. {
  73305. spacesAtEnd = 0;
  73306. }
  73307. }
  73308. numSpaces -= spacesAtEnd;
  73309. if (numSpaces > 0)
  73310. {
  73311. const float startX = glyphs.getUnchecked (start)->getLeft();
  73312. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73313. const float extraPaddingBetweenWords
  73314. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73315. float deltaX = 0.0f;
  73316. for (int i = 0; i < num; ++i)
  73317. {
  73318. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73319. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73320. deltaX += extraPaddingBetweenWords;
  73321. }
  73322. }
  73323. }
  73324. }
  73325. void GlyphArrangement::draw (const Graphics& g) const
  73326. {
  73327. for (int i = 0; i < glyphs.size(); ++i)
  73328. {
  73329. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73330. if (pg->font.isUnderlined())
  73331. {
  73332. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73333. float nextX = pg->x + pg->w;
  73334. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73335. nextX = glyphs.getUnchecked (i + 1)->x;
  73336. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73337. nextX - pg->x, lineThickness);
  73338. }
  73339. pg->draw (g);
  73340. }
  73341. }
  73342. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73343. {
  73344. for (int i = 0; i < glyphs.size(); ++i)
  73345. {
  73346. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73347. if (pg->font.isUnderlined())
  73348. {
  73349. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73350. float nextX = pg->x + pg->w;
  73351. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73352. nextX = glyphs.getUnchecked (i + 1)->x;
  73353. Path p;
  73354. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73355. nextX, pg->y + lineThickness * 2.0f),
  73356. lineThickness);
  73357. g.fillPath (p, transform);
  73358. }
  73359. pg->draw (g, transform);
  73360. }
  73361. }
  73362. void GlyphArrangement::createPath (Path& path) const
  73363. {
  73364. for (int i = 0; i < glyphs.size(); ++i)
  73365. glyphs.getUnchecked (i)->createPath (path);
  73366. }
  73367. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73368. {
  73369. for (int i = 0; i < glyphs.size(); ++i)
  73370. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73371. return i;
  73372. return -1;
  73373. }
  73374. END_JUCE_NAMESPACE
  73375. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73376. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73377. BEGIN_JUCE_NAMESPACE
  73378. class TextLayout::Token
  73379. {
  73380. public:
  73381. Token (const String& t,
  73382. const Font& f,
  73383. const bool isWhitespace_)
  73384. : text (t),
  73385. font (f),
  73386. x(0),
  73387. y(0),
  73388. isWhitespace (isWhitespace_)
  73389. {
  73390. w = font.getStringWidth (t);
  73391. h = roundToInt (f.getHeight());
  73392. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73393. }
  73394. Token (const Token& other)
  73395. : text (other.text),
  73396. font (other.font),
  73397. x (other.x),
  73398. y (other.y),
  73399. w (other.w),
  73400. h (other.h),
  73401. line (other.line),
  73402. lineHeight (other.lineHeight),
  73403. isWhitespace (other.isWhitespace),
  73404. isNewLine (other.isNewLine)
  73405. {
  73406. }
  73407. void draw (Graphics& g,
  73408. const int xOffset,
  73409. const int yOffset)
  73410. {
  73411. if (! isWhitespace)
  73412. {
  73413. g.setFont (font);
  73414. g.drawSingleLineText (text.trimEnd(),
  73415. xOffset + x,
  73416. yOffset + y + (lineHeight - h)
  73417. + roundToInt (font.getAscent()));
  73418. }
  73419. }
  73420. String text;
  73421. Font font;
  73422. int x, y, w, h;
  73423. int line, lineHeight;
  73424. bool isWhitespace, isNewLine;
  73425. private:
  73426. JUCE_LEAK_DETECTOR (Token);
  73427. };
  73428. TextLayout::TextLayout()
  73429. : totalLines (0)
  73430. {
  73431. tokens.ensureStorageAllocated (64);
  73432. }
  73433. TextLayout::TextLayout (const String& text, const Font& font)
  73434. : totalLines (0)
  73435. {
  73436. tokens.ensureStorageAllocated (64);
  73437. appendText (text, font);
  73438. }
  73439. TextLayout::TextLayout (const TextLayout& other)
  73440. : totalLines (0)
  73441. {
  73442. *this = other;
  73443. }
  73444. TextLayout& TextLayout::operator= (const TextLayout& other)
  73445. {
  73446. if (this != &other)
  73447. {
  73448. clear();
  73449. totalLines = other.totalLines;
  73450. tokens.addCopiesOf (other.tokens);
  73451. }
  73452. return *this;
  73453. }
  73454. TextLayout::~TextLayout()
  73455. {
  73456. clear();
  73457. }
  73458. void TextLayout::clear()
  73459. {
  73460. tokens.clear();
  73461. totalLines = 0;
  73462. }
  73463. bool TextLayout::isEmpty() const
  73464. {
  73465. return tokens.size() == 0;
  73466. }
  73467. void TextLayout::appendText (const String& text, const Font& font)
  73468. {
  73469. const juce_wchar* t = text;
  73470. String currentString;
  73471. int lastCharType = 0;
  73472. for (;;)
  73473. {
  73474. const juce_wchar c = *t++;
  73475. if (c == 0)
  73476. break;
  73477. int charType;
  73478. if (c == '\r' || c == '\n')
  73479. {
  73480. charType = 0;
  73481. }
  73482. else if (CharacterFunctions::isWhitespace (c))
  73483. {
  73484. charType = 2;
  73485. }
  73486. else
  73487. {
  73488. charType = 1;
  73489. }
  73490. if (charType == 0 || charType != lastCharType)
  73491. {
  73492. if (currentString.isNotEmpty())
  73493. {
  73494. tokens.add (new Token (currentString, font,
  73495. lastCharType == 2 || lastCharType == 0));
  73496. }
  73497. currentString = String::charToString (c);
  73498. if (c == '\r' && *t == '\n')
  73499. currentString += *t++;
  73500. }
  73501. else
  73502. {
  73503. currentString += c;
  73504. }
  73505. lastCharType = charType;
  73506. }
  73507. if (currentString.isNotEmpty())
  73508. tokens.add (new Token (currentString, font, lastCharType == 2));
  73509. }
  73510. void TextLayout::setText (const String& text, const Font& font)
  73511. {
  73512. clear();
  73513. appendText (text, font);
  73514. }
  73515. void TextLayout::layout (int maxWidth,
  73516. const Justification& justification,
  73517. const bool attemptToBalanceLineLengths)
  73518. {
  73519. if (attemptToBalanceLineLengths)
  73520. {
  73521. const int originalW = maxWidth;
  73522. int bestWidth = maxWidth;
  73523. float bestLineProportion = 0.0f;
  73524. while (maxWidth > originalW / 2)
  73525. {
  73526. layout (maxWidth, justification, false);
  73527. if (getNumLines() <= 1)
  73528. return;
  73529. const int lastLineW = getLineWidth (getNumLines() - 1);
  73530. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73531. const float prop = lastLineW / (float) lastButOneLineW;
  73532. if (prop > 0.9f)
  73533. return;
  73534. if (prop > bestLineProportion)
  73535. {
  73536. bestLineProportion = prop;
  73537. bestWidth = maxWidth;
  73538. }
  73539. maxWidth -= 10;
  73540. }
  73541. layout (bestWidth, justification, false);
  73542. }
  73543. else
  73544. {
  73545. int x = 0;
  73546. int y = 0;
  73547. int h = 0;
  73548. totalLines = 0;
  73549. int i;
  73550. for (i = 0; i < tokens.size(); ++i)
  73551. {
  73552. Token* const t = tokens.getUnchecked(i);
  73553. t->x = x;
  73554. t->y = y;
  73555. t->line = totalLines;
  73556. x += t->w;
  73557. h = jmax (h, t->h);
  73558. const Token* nextTok = tokens [i + 1];
  73559. if (nextTok == 0)
  73560. break;
  73561. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73562. {
  73563. // finished a line, so go back and update the heights of the things on it
  73564. for (int j = i; j >= 0; --j)
  73565. {
  73566. Token* const tok = tokens.getUnchecked(j);
  73567. if (tok->line == totalLines)
  73568. tok->lineHeight = h;
  73569. else
  73570. break;
  73571. }
  73572. x = 0;
  73573. y += h;
  73574. h = 0;
  73575. ++totalLines;
  73576. }
  73577. }
  73578. // finished a line, so go back and update the heights of the things on it
  73579. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73580. {
  73581. Token* const t = tokens.getUnchecked(j);
  73582. if (t->line == totalLines)
  73583. t->lineHeight = h;
  73584. else
  73585. break;
  73586. }
  73587. ++totalLines;
  73588. if (! justification.testFlags (Justification::left))
  73589. {
  73590. int totalW = getWidth();
  73591. for (i = totalLines; --i >= 0;)
  73592. {
  73593. const int lineW = getLineWidth (i);
  73594. int dx = 0;
  73595. if (justification.testFlags (Justification::horizontallyCentred))
  73596. dx = (totalW - lineW) / 2;
  73597. else if (justification.testFlags (Justification::right))
  73598. dx = totalW - lineW;
  73599. for (int j = tokens.size(); --j >= 0;)
  73600. {
  73601. Token* const t = tokens.getUnchecked(j);
  73602. if (t->line == i)
  73603. t->x += dx;
  73604. }
  73605. }
  73606. }
  73607. }
  73608. }
  73609. int TextLayout::getLineWidth (const int lineNumber) const
  73610. {
  73611. int maxW = 0;
  73612. for (int i = tokens.size(); --i >= 0;)
  73613. {
  73614. const Token* const t = tokens.getUnchecked(i);
  73615. if (t->line == lineNumber && ! t->isWhitespace)
  73616. maxW = jmax (maxW, t->x + t->w);
  73617. }
  73618. return maxW;
  73619. }
  73620. int TextLayout::getWidth() const
  73621. {
  73622. int maxW = 0;
  73623. for (int i = tokens.size(); --i >= 0;)
  73624. {
  73625. const Token* const t = tokens.getUnchecked(i);
  73626. if (! t->isWhitespace)
  73627. maxW = jmax (maxW, t->x + t->w);
  73628. }
  73629. return maxW;
  73630. }
  73631. int TextLayout::getHeight() const
  73632. {
  73633. int maxH = 0;
  73634. for (int i = tokens.size(); --i >= 0;)
  73635. {
  73636. const Token* const t = tokens.getUnchecked(i);
  73637. if (! t->isWhitespace)
  73638. maxH = jmax (maxH, t->y + t->h);
  73639. }
  73640. return maxH;
  73641. }
  73642. void TextLayout::draw (Graphics& g,
  73643. const int xOffset,
  73644. const int yOffset) const
  73645. {
  73646. for (int i = tokens.size(); --i >= 0;)
  73647. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73648. }
  73649. void TextLayout::drawWithin (Graphics& g,
  73650. int x, int y, int w, int h,
  73651. const Justification& justification) const
  73652. {
  73653. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73654. x, y, w, h);
  73655. draw (g, x, y);
  73656. }
  73657. END_JUCE_NAMESPACE
  73658. /*** End of inlined file: juce_TextLayout.cpp ***/
  73659. /*** Start of inlined file: juce_Typeface.cpp ***/
  73660. BEGIN_JUCE_NAMESPACE
  73661. Typeface::Typeface (const String& name_) throw()
  73662. : name (name_), isFallbackFont (false)
  73663. {
  73664. }
  73665. Typeface::~Typeface()
  73666. {
  73667. }
  73668. const Typeface::Ptr Typeface::getFallbackTypeface()
  73669. {
  73670. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73671. Typeface* t = fallbackFont.getTypeface();
  73672. t->isFallbackFont = true;
  73673. return t;
  73674. }
  73675. class CustomTypeface::GlyphInfo
  73676. {
  73677. public:
  73678. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73679. : character (character_), path (path_), width (width_)
  73680. {
  73681. }
  73682. struct KerningPair
  73683. {
  73684. juce_wchar character2;
  73685. float kerningAmount;
  73686. };
  73687. void addKerningPair (const juce_wchar subsequentCharacter,
  73688. const float extraKerningAmount) throw()
  73689. {
  73690. KerningPair kp;
  73691. kp.character2 = subsequentCharacter;
  73692. kp.kerningAmount = extraKerningAmount;
  73693. kerningPairs.add (kp);
  73694. }
  73695. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73696. {
  73697. if (subsequentCharacter != 0)
  73698. {
  73699. for (int i = kerningPairs.size(); --i >= 0;)
  73700. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73701. return width + kerningPairs.getReference(i).kerningAmount;
  73702. }
  73703. return width;
  73704. }
  73705. const juce_wchar character;
  73706. const Path path;
  73707. float width;
  73708. Array <KerningPair> kerningPairs;
  73709. private:
  73710. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73711. };
  73712. CustomTypeface::CustomTypeface()
  73713. : Typeface (String::empty)
  73714. {
  73715. clear();
  73716. }
  73717. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73718. : Typeface (String::empty)
  73719. {
  73720. clear();
  73721. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73722. BufferedInputStream in (gzin, 32768);
  73723. name = in.readString();
  73724. isBold = in.readBool();
  73725. isItalic = in.readBool();
  73726. ascent = in.readFloat();
  73727. defaultCharacter = (juce_wchar) in.readShort();
  73728. int i, numChars = in.readInt();
  73729. for (i = 0; i < numChars; ++i)
  73730. {
  73731. const juce_wchar c = (juce_wchar) in.readShort();
  73732. const float width = in.readFloat();
  73733. Path p;
  73734. p.loadPathFromStream (in);
  73735. addGlyph (c, p, width);
  73736. }
  73737. const int numKerningPairs = in.readInt();
  73738. for (i = 0; i < numKerningPairs; ++i)
  73739. {
  73740. const juce_wchar char1 = (juce_wchar) in.readShort();
  73741. const juce_wchar char2 = (juce_wchar) in.readShort();
  73742. addKerningPair (char1, char2, in.readFloat());
  73743. }
  73744. }
  73745. CustomTypeface::~CustomTypeface()
  73746. {
  73747. }
  73748. void CustomTypeface::clear()
  73749. {
  73750. defaultCharacter = 0;
  73751. ascent = 1.0f;
  73752. isBold = isItalic = false;
  73753. zeromem (lookupTable, sizeof (lookupTable));
  73754. glyphs.clear();
  73755. }
  73756. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73757. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73758. {
  73759. name = name_;
  73760. defaultCharacter = defaultCharacter_;
  73761. ascent = ascent_;
  73762. isBold = isBold_;
  73763. isItalic = isItalic_;
  73764. }
  73765. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73766. {
  73767. // Check that you're not trying to add the same character twice..
  73768. jassert (findGlyph (character, false) == 0);
  73769. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73770. lookupTable [character] = (short) glyphs.size();
  73771. glyphs.add (new GlyphInfo (character, path, width));
  73772. }
  73773. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73774. {
  73775. if (extraAmount != 0)
  73776. {
  73777. GlyphInfo* const g = findGlyph (char1, true);
  73778. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73779. if (g != 0)
  73780. g->addKerningPair (char2, extraAmount);
  73781. }
  73782. }
  73783. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73784. {
  73785. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73786. return glyphs [(int) lookupTable [(int) character]];
  73787. for (int i = 0; i < glyphs.size(); ++i)
  73788. {
  73789. GlyphInfo* const g = glyphs.getUnchecked(i);
  73790. if (g->character == character)
  73791. return g;
  73792. }
  73793. if (loadIfNeeded && loadGlyphIfPossible (character))
  73794. return findGlyph (character, false);
  73795. return 0;
  73796. }
  73797. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73798. {
  73799. GlyphInfo* glyph = findGlyph (character, true);
  73800. if (glyph == 0)
  73801. {
  73802. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73803. glyph = findGlyph (L' ', true);
  73804. if (glyph == 0)
  73805. {
  73806. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73807. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73808. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73809. {
  73810. Path path;
  73811. fallbackTypeface->getOutlineForGlyph (character, path);
  73812. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73813. }
  73814. if (glyph == 0)
  73815. glyph = findGlyph (defaultCharacter, true);
  73816. }
  73817. }
  73818. return glyph;
  73819. }
  73820. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73821. {
  73822. return false;
  73823. }
  73824. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73825. {
  73826. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73827. for (int i = 0; i < numCharacters; ++i)
  73828. {
  73829. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73830. Array <int> glyphIndexes;
  73831. Array <float> offsets;
  73832. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73833. const int glyphIndex = glyphIndexes.getFirst();
  73834. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73835. {
  73836. const float glyphWidth = offsets[1];
  73837. Path p;
  73838. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73839. addGlyph (c, p, glyphWidth);
  73840. for (int j = glyphs.size() - 1; --j >= 0;)
  73841. {
  73842. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73843. glyphIndexes.clearQuick();
  73844. offsets.clearQuick();
  73845. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73846. if (offsets.size() > 1)
  73847. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73848. }
  73849. }
  73850. }
  73851. }
  73852. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73853. {
  73854. GZIPCompressorOutputStream out (&outputStream);
  73855. out.writeString (name);
  73856. out.writeBool (isBold);
  73857. out.writeBool (isItalic);
  73858. out.writeFloat (ascent);
  73859. out.writeShort ((short) (unsigned short) defaultCharacter);
  73860. out.writeInt (glyphs.size());
  73861. int i, numKerningPairs = 0;
  73862. for (i = 0; i < glyphs.size(); ++i)
  73863. {
  73864. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73865. out.writeShort ((short) (unsigned short) g->character);
  73866. out.writeFloat (g->width);
  73867. g->path.writePathToStream (out);
  73868. numKerningPairs += g->kerningPairs.size();
  73869. }
  73870. out.writeInt (numKerningPairs);
  73871. for (i = 0; i < glyphs.size(); ++i)
  73872. {
  73873. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73874. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73875. {
  73876. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73877. out.writeShort ((short) (unsigned short) g->character);
  73878. out.writeShort ((short) (unsigned short) p.character2);
  73879. out.writeFloat (p.kerningAmount);
  73880. }
  73881. }
  73882. return true;
  73883. }
  73884. float CustomTypeface::getAscent() const
  73885. {
  73886. return ascent;
  73887. }
  73888. float CustomTypeface::getDescent() const
  73889. {
  73890. return 1.0f - ascent;
  73891. }
  73892. float CustomTypeface::getStringWidth (const String& text)
  73893. {
  73894. float x = 0;
  73895. const juce_wchar* t = text;
  73896. while (*t != 0)
  73897. {
  73898. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73899. if (glyph == 0 && ! isFallbackFont)
  73900. {
  73901. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73902. if (fallbackTypeface != 0)
  73903. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73904. }
  73905. if (glyph != 0)
  73906. x += glyph->getHorizontalSpacing (*t);
  73907. }
  73908. return x;
  73909. }
  73910. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73911. {
  73912. xOffsets.add (0);
  73913. float x = 0;
  73914. const juce_wchar* t = text;
  73915. while (*t != 0)
  73916. {
  73917. const juce_wchar c = *t++;
  73918. const GlyphInfo* const glyph = findGlyph (c, true);
  73919. if (glyph == 0 && ! isFallbackFont)
  73920. {
  73921. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73922. if (fallbackTypeface != 0)
  73923. {
  73924. Array <int> subGlyphs;
  73925. Array <float> subOffsets;
  73926. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73927. if (subGlyphs.size() > 0)
  73928. {
  73929. resultGlyphs.add (subGlyphs.getFirst());
  73930. x += subOffsets[1];
  73931. xOffsets.add (x);
  73932. }
  73933. }
  73934. }
  73935. if (glyph != 0)
  73936. {
  73937. x += glyph->getHorizontalSpacing (*t);
  73938. resultGlyphs.add ((int) glyph->character);
  73939. xOffsets.add (x);
  73940. }
  73941. }
  73942. }
  73943. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73944. {
  73945. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73946. if (glyph == 0 && ! isFallbackFont)
  73947. {
  73948. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73949. if (fallbackTypeface != 0)
  73950. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73951. }
  73952. if (glyph != 0)
  73953. {
  73954. path = glyph->path;
  73955. return true;
  73956. }
  73957. return false;
  73958. }
  73959. END_JUCE_NAMESPACE
  73960. /*** End of inlined file: juce_Typeface.cpp ***/
  73961. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73962. BEGIN_JUCE_NAMESPACE
  73963. AffineTransform::AffineTransform() throw()
  73964. : mat00 (1.0f), mat01 (0), mat02 (0),
  73965. mat10 (0), mat11 (1.0f), mat12 (0)
  73966. {
  73967. }
  73968. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73969. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73970. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73971. {
  73972. }
  73973. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73974. const float mat10_, const float mat11_, const float mat12_) throw()
  73975. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73976. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73977. {
  73978. }
  73979. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73980. {
  73981. mat00 = other.mat00;
  73982. mat01 = other.mat01;
  73983. mat02 = other.mat02;
  73984. mat10 = other.mat10;
  73985. mat11 = other.mat11;
  73986. mat12 = other.mat12;
  73987. return *this;
  73988. }
  73989. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73990. {
  73991. return mat00 == other.mat00
  73992. && mat01 == other.mat01
  73993. && mat02 == other.mat02
  73994. && mat10 == other.mat10
  73995. && mat11 == other.mat11
  73996. && mat12 == other.mat12;
  73997. }
  73998. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73999. {
  74000. return ! operator== (other);
  74001. }
  74002. bool AffineTransform::isIdentity() const throw()
  74003. {
  74004. return (mat01 == 0)
  74005. && (mat02 == 0)
  74006. && (mat10 == 0)
  74007. && (mat12 == 0)
  74008. && (mat00 == 1.0f)
  74009. && (mat11 == 1.0f);
  74010. }
  74011. const AffineTransform AffineTransform::identity;
  74012. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74013. {
  74014. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74015. other.mat00 * mat01 + other.mat01 * mat11,
  74016. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74017. other.mat10 * mat00 + other.mat11 * mat10,
  74018. other.mat10 * mat01 + other.mat11 * mat11,
  74019. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74020. }
  74021. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  74022. {
  74023. return AffineTransform (mat00, mat01, mat02 + dx,
  74024. mat10, mat11, mat12 + dy);
  74025. }
  74026. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  74027. {
  74028. return AffineTransform (1.0f, 0, dx,
  74029. 0, 1.0f, dy);
  74030. }
  74031. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74032. {
  74033. const float cosRad = std::cos (rad);
  74034. const float sinRad = std::sin (rad);
  74035. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  74036. cosRad * mat01 + -sinRad * mat11,
  74037. cosRad * mat02 + -sinRad * mat12,
  74038. sinRad * mat00 + cosRad * mat10,
  74039. sinRad * mat01 + cosRad * mat11,
  74040. sinRad * mat02 + cosRad * mat12);
  74041. }
  74042. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74043. {
  74044. const float cosRad = std::cos (rad);
  74045. const float sinRad = std::sin (rad);
  74046. return AffineTransform (cosRad, -sinRad, 0,
  74047. sinRad, cosRad, 0);
  74048. }
  74049. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  74050. {
  74051. const float cosRad = std::cos (rad);
  74052. const float sinRad = std::sin (rad);
  74053. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  74054. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  74055. }
  74056. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  74057. {
  74058. return followedBy (rotation (angle, pivotX, pivotY));
  74059. }
  74060. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  74061. {
  74062. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74063. factorY * mat10, factorY * mat11, factorY * mat12);
  74064. }
  74065. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  74066. {
  74067. return AffineTransform (factorX, 0, 0,
  74068. 0, factorY, 0);
  74069. }
  74070. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  74071. const float pivotX, const float pivotY) const throw()
  74072. {
  74073. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  74074. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  74075. }
  74076. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  74077. const float pivotX, const float pivotY) throw()
  74078. {
  74079. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  74080. 0, factorY, pivotY * (1.0f - factorY));
  74081. }
  74082. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  74083. {
  74084. return AffineTransform (1.0f, shearX, 0,
  74085. shearY, 1.0f, 0);
  74086. }
  74087. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  74088. {
  74089. return AffineTransform (mat00 + shearX * mat10,
  74090. mat01 + shearX * mat11,
  74091. mat02 + shearX * mat12,
  74092. shearY * mat00 + mat10,
  74093. shearY * mat01 + mat11,
  74094. shearY * mat02 + mat12);
  74095. }
  74096. const AffineTransform AffineTransform::inverted() const throw()
  74097. {
  74098. double determinant = (mat00 * mat11 - mat10 * mat01);
  74099. if (determinant != 0.0)
  74100. {
  74101. determinant = 1.0 / determinant;
  74102. const float dst00 = (float) (mat11 * determinant);
  74103. const float dst10 = (float) (-mat10 * determinant);
  74104. const float dst01 = (float) (-mat01 * determinant);
  74105. const float dst11 = (float) (mat00 * determinant);
  74106. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74107. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74108. }
  74109. else
  74110. {
  74111. // singularity..
  74112. return *this;
  74113. }
  74114. }
  74115. bool AffineTransform::isSingularity() const throw()
  74116. {
  74117. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  74118. }
  74119. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74120. const float x10, const float y10,
  74121. const float x01, const float y01) throw()
  74122. {
  74123. return AffineTransform (x10 - x00, x01 - x00, x00,
  74124. y10 - y00, y01 - y00, y00);
  74125. }
  74126. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74127. const float sx2, const float sy2, const float tx2, const float ty2,
  74128. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74129. {
  74130. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74131. .inverted()
  74132. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74133. }
  74134. bool AffineTransform::isOnlyTranslation() const throw()
  74135. {
  74136. return (mat01 == 0)
  74137. && (mat10 == 0)
  74138. && (mat00 == 1.0f)
  74139. && (mat11 == 1.0f);
  74140. }
  74141. float AffineTransform::getScaleFactor() const throw()
  74142. {
  74143. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74144. }
  74145. END_JUCE_NAMESPACE
  74146. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74147. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74148. BEGIN_JUCE_NAMESPACE
  74149. BorderSize::BorderSize() throw()
  74150. : top (0),
  74151. left (0),
  74152. bottom (0),
  74153. right (0)
  74154. {
  74155. }
  74156. BorderSize::BorderSize (const BorderSize& other) throw()
  74157. : top (other.top),
  74158. left (other.left),
  74159. bottom (other.bottom),
  74160. right (other.right)
  74161. {
  74162. }
  74163. BorderSize::BorderSize (const int topGap,
  74164. const int leftGap,
  74165. const int bottomGap,
  74166. const int rightGap) throw()
  74167. : top (topGap),
  74168. left (leftGap),
  74169. bottom (bottomGap),
  74170. right (rightGap)
  74171. {
  74172. }
  74173. BorderSize::BorderSize (const int allGaps) throw()
  74174. : top (allGaps),
  74175. left (allGaps),
  74176. bottom (allGaps),
  74177. right (allGaps)
  74178. {
  74179. }
  74180. BorderSize::~BorderSize() throw()
  74181. {
  74182. }
  74183. void BorderSize::setTop (const int newTopGap) throw()
  74184. {
  74185. top = newTopGap;
  74186. }
  74187. void BorderSize::setLeft (const int newLeftGap) throw()
  74188. {
  74189. left = newLeftGap;
  74190. }
  74191. void BorderSize::setBottom (const int newBottomGap) throw()
  74192. {
  74193. bottom = newBottomGap;
  74194. }
  74195. void BorderSize::setRight (const int newRightGap) throw()
  74196. {
  74197. right = newRightGap;
  74198. }
  74199. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74200. {
  74201. return Rectangle<int> (r.getX() + left,
  74202. r.getY() + top,
  74203. r.getWidth() - (left + right),
  74204. r.getHeight() - (top + bottom));
  74205. }
  74206. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74207. {
  74208. r.setBounds (r.getX() + left,
  74209. r.getY() + top,
  74210. r.getWidth() - (left + right),
  74211. r.getHeight() - (top + bottom));
  74212. }
  74213. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74214. {
  74215. return Rectangle<int> (r.getX() - left,
  74216. r.getY() - top,
  74217. r.getWidth() + (left + right),
  74218. r.getHeight() + (top + bottom));
  74219. }
  74220. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74221. {
  74222. r.setBounds (r.getX() - left,
  74223. r.getY() - top,
  74224. r.getWidth() + (left + right),
  74225. r.getHeight() + (top + bottom));
  74226. }
  74227. bool BorderSize::operator== (const BorderSize& other) const throw()
  74228. {
  74229. return top == other.top
  74230. && left == other.left
  74231. && bottom == other.bottom
  74232. && right == other.right;
  74233. }
  74234. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74235. {
  74236. return ! operator== (other);
  74237. }
  74238. END_JUCE_NAMESPACE
  74239. /*** End of inlined file: juce_BorderSize.cpp ***/
  74240. /*** Start of inlined file: juce_Path.cpp ***/
  74241. BEGIN_JUCE_NAMESPACE
  74242. // tests that some co-ords aren't NaNs
  74243. #define CHECK_COORDS_ARE_VALID(x, y) \
  74244. jassert (x == x && y == y);
  74245. namespace PathHelpers
  74246. {
  74247. const float ellipseAngularIncrement = 0.05f;
  74248. const String nextToken (const juce_wchar*& t)
  74249. {
  74250. while (CharacterFunctions::isWhitespace (*t))
  74251. ++t;
  74252. const juce_wchar* const start = t;
  74253. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74254. ++t;
  74255. return String (start, (int) (t - start));
  74256. }
  74257. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74258. {
  74259. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74260. }
  74261. }
  74262. const float Path::lineMarker = 100001.0f;
  74263. const float Path::moveMarker = 100002.0f;
  74264. const float Path::quadMarker = 100003.0f;
  74265. const float Path::cubicMarker = 100004.0f;
  74266. const float Path::closeSubPathMarker = 100005.0f;
  74267. Path::Path()
  74268. : numElements (0),
  74269. pathXMin (0),
  74270. pathXMax (0),
  74271. pathYMin (0),
  74272. pathYMax (0),
  74273. useNonZeroWinding (true)
  74274. {
  74275. }
  74276. Path::~Path()
  74277. {
  74278. }
  74279. Path::Path (const Path& other)
  74280. : numElements (other.numElements),
  74281. pathXMin (other.pathXMin),
  74282. pathXMax (other.pathXMax),
  74283. pathYMin (other.pathYMin),
  74284. pathYMax (other.pathYMax),
  74285. useNonZeroWinding (other.useNonZeroWinding)
  74286. {
  74287. if (numElements > 0)
  74288. {
  74289. data.setAllocatedSize ((int) numElements);
  74290. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74291. }
  74292. }
  74293. Path& Path::operator= (const Path& other)
  74294. {
  74295. if (this != &other)
  74296. {
  74297. data.ensureAllocatedSize ((int) other.numElements);
  74298. numElements = other.numElements;
  74299. pathXMin = other.pathXMin;
  74300. pathXMax = other.pathXMax;
  74301. pathYMin = other.pathYMin;
  74302. pathYMax = other.pathYMax;
  74303. useNonZeroWinding = other.useNonZeroWinding;
  74304. if (numElements > 0)
  74305. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74306. }
  74307. return *this;
  74308. }
  74309. bool Path::operator== (const Path& other) const throw()
  74310. {
  74311. return ! operator!= (other);
  74312. }
  74313. bool Path::operator!= (const Path& other) const throw()
  74314. {
  74315. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74316. return true;
  74317. for (size_t i = 0; i < numElements; ++i)
  74318. if (data.elements[i] != other.data.elements[i])
  74319. return true;
  74320. return false;
  74321. }
  74322. void Path::clear() throw()
  74323. {
  74324. numElements = 0;
  74325. pathXMin = 0;
  74326. pathYMin = 0;
  74327. pathYMax = 0;
  74328. pathXMax = 0;
  74329. }
  74330. void Path::swapWithPath (Path& other) throw()
  74331. {
  74332. data.swapWith (other.data);
  74333. swapVariables <size_t> (numElements, other.numElements);
  74334. swapVariables <float> (pathXMin, other.pathXMin);
  74335. swapVariables <float> (pathXMax, other.pathXMax);
  74336. swapVariables <float> (pathYMin, other.pathYMin);
  74337. swapVariables <float> (pathYMax, other.pathYMax);
  74338. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74339. }
  74340. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74341. {
  74342. useNonZeroWinding = isNonZero;
  74343. }
  74344. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74345. const bool preserveProportions) throw()
  74346. {
  74347. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74348. }
  74349. bool Path::isEmpty() const throw()
  74350. {
  74351. size_t i = 0;
  74352. while (i < numElements)
  74353. {
  74354. const float type = data.elements [i++];
  74355. if (type == moveMarker)
  74356. {
  74357. i += 2;
  74358. }
  74359. else if (type == lineMarker
  74360. || type == quadMarker
  74361. || type == cubicMarker)
  74362. {
  74363. return false;
  74364. }
  74365. }
  74366. return true;
  74367. }
  74368. const Rectangle<float> Path::getBounds() const throw()
  74369. {
  74370. return Rectangle<float> (pathXMin, pathYMin,
  74371. pathXMax - pathXMin,
  74372. pathYMax - pathYMin);
  74373. }
  74374. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74375. {
  74376. return getBounds().transformed (transform);
  74377. }
  74378. void Path::startNewSubPath (const float x, const float y)
  74379. {
  74380. CHECK_COORDS_ARE_VALID (x, y);
  74381. if (numElements == 0)
  74382. {
  74383. pathXMin = pathXMax = x;
  74384. pathYMin = pathYMax = y;
  74385. }
  74386. else
  74387. {
  74388. pathXMin = jmin (pathXMin, x);
  74389. pathXMax = jmax (pathXMax, x);
  74390. pathYMin = jmin (pathYMin, y);
  74391. pathYMax = jmax (pathYMax, y);
  74392. }
  74393. data.ensureAllocatedSize ((int) numElements + 3);
  74394. data.elements [numElements++] = moveMarker;
  74395. data.elements [numElements++] = x;
  74396. data.elements [numElements++] = y;
  74397. }
  74398. void Path::startNewSubPath (const Point<float>& start)
  74399. {
  74400. startNewSubPath (start.getX(), start.getY());
  74401. }
  74402. void Path::lineTo (const float x, const float y)
  74403. {
  74404. CHECK_COORDS_ARE_VALID (x, y);
  74405. if (numElements == 0)
  74406. startNewSubPath (0, 0);
  74407. data.ensureAllocatedSize ((int) numElements + 3);
  74408. data.elements [numElements++] = lineMarker;
  74409. data.elements [numElements++] = x;
  74410. data.elements [numElements++] = y;
  74411. pathXMin = jmin (pathXMin, x);
  74412. pathXMax = jmax (pathXMax, x);
  74413. pathYMin = jmin (pathYMin, y);
  74414. pathYMax = jmax (pathYMax, y);
  74415. }
  74416. void Path::lineTo (const Point<float>& end)
  74417. {
  74418. lineTo (end.getX(), end.getY());
  74419. }
  74420. void Path::quadraticTo (const float x1, const float y1,
  74421. const float x2, const float y2)
  74422. {
  74423. CHECK_COORDS_ARE_VALID (x1, y1);
  74424. CHECK_COORDS_ARE_VALID (x2, y2);
  74425. if (numElements == 0)
  74426. startNewSubPath (0, 0);
  74427. data.ensureAllocatedSize ((int) numElements + 5);
  74428. data.elements [numElements++] = quadMarker;
  74429. data.elements [numElements++] = x1;
  74430. data.elements [numElements++] = y1;
  74431. data.elements [numElements++] = x2;
  74432. data.elements [numElements++] = y2;
  74433. pathXMin = jmin (pathXMin, x1, x2);
  74434. pathXMax = jmax (pathXMax, x1, x2);
  74435. pathYMin = jmin (pathYMin, y1, y2);
  74436. pathYMax = jmax (pathYMax, y1, y2);
  74437. }
  74438. void Path::quadraticTo (const Point<float>& controlPoint,
  74439. const Point<float>& endPoint)
  74440. {
  74441. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74442. endPoint.getX(), endPoint.getY());
  74443. }
  74444. void Path::cubicTo (const float x1, const float y1,
  74445. const float x2, const float y2,
  74446. const float x3, const float y3)
  74447. {
  74448. CHECK_COORDS_ARE_VALID (x1, y1);
  74449. CHECK_COORDS_ARE_VALID (x2, y2);
  74450. CHECK_COORDS_ARE_VALID (x3, y3);
  74451. if (numElements == 0)
  74452. startNewSubPath (0, 0);
  74453. data.ensureAllocatedSize ((int) numElements + 7);
  74454. data.elements [numElements++] = cubicMarker;
  74455. data.elements [numElements++] = x1;
  74456. data.elements [numElements++] = y1;
  74457. data.elements [numElements++] = x2;
  74458. data.elements [numElements++] = y2;
  74459. data.elements [numElements++] = x3;
  74460. data.elements [numElements++] = y3;
  74461. pathXMin = jmin (pathXMin, x1, x2, x3);
  74462. pathXMax = jmax (pathXMax, x1, x2, x3);
  74463. pathYMin = jmin (pathYMin, y1, y2, y3);
  74464. pathYMax = jmax (pathYMax, y1, y2, y3);
  74465. }
  74466. void Path::cubicTo (const Point<float>& controlPoint1,
  74467. const Point<float>& controlPoint2,
  74468. const Point<float>& endPoint)
  74469. {
  74470. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74471. controlPoint2.getX(), controlPoint2.getY(),
  74472. endPoint.getX(), endPoint.getY());
  74473. }
  74474. void Path::closeSubPath()
  74475. {
  74476. if (numElements > 0
  74477. && data.elements [numElements - 1] != closeSubPathMarker)
  74478. {
  74479. data.ensureAllocatedSize ((int) numElements + 1);
  74480. data.elements [numElements++] = closeSubPathMarker;
  74481. }
  74482. }
  74483. const Point<float> Path::getCurrentPosition() const
  74484. {
  74485. size_t i = numElements - 1;
  74486. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74487. {
  74488. while (i >= 0)
  74489. {
  74490. if (data.elements[i] == moveMarker)
  74491. {
  74492. i += 2;
  74493. break;
  74494. }
  74495. --i;
  74496. }
  74497. }
  74498. if (i > 0)
  74499. return Point<float> (data.elements [i - 1], data.elements [i]);
  74500. return Point<float>();
  74501. }
  74502. void Path::addRectangle (const float x, const float y,
  74503. const float w, const float h)
  74504. {
  74505. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74506. if (w < 0)
  74507. swapVariables (x1, x2);
  74508. if (h < 0)
  74509. swapVariables (y1, y2);
  74510. data.ensureAllocatedSize ((int) numElements + 13);
  74511. if (numElements == 0)
  74512. {
  74513. pathXMin = x1;
  74514. pathXMax = x2;
  74515. pathYMin = y1;
  74516. pathYMax = y2;
  74517. }
  74518. else
  74519. {
  74520. pathXMin = jmin (pathXMin, x1);
  74521. pathXMax = jmax (pathXMax, x2);
  74522. pathYMin = jmin (pathYMin, y1);
  74523. pathYMax = jmax (pathYMax, y2);
  74524. }
  74525. data.elements [numElements++] = moveMarker;
  74526. data.elements [numElements++] = x1;
  74527. data.elements [numElements++] = y2;
  74528. data.elements [numElements++] = lineMarker;
  74529. data.elements [numElements++] = x1;
  74530. data.elements [numElements++] = y1;
  74531. data.elements [numElements++] = lineMarker;
  74532. data.elements [numElements++] = x2;
  74533. data.elements [numElements++] = y1;
  74534. data.elements [numElements++] = lineMarker;
  74535. data.elements [numElements++] = x2;
  74536. data.elements [numElements++] = y2;
  74537. data.elements [numElements++] = closeSubPathMarker;
  74538. }
  74539. void Path::addRoundedRectangle (const float x, const float y,
  74540. const float w, const float h,
  74541. float csx,
  74542. float csy)
  74543. {
  74544. csx = jmin (csx, w * 0.5f);
  74545. csy = jmin (csy, h * 0.5f);
  74546. const float cs45x = csx * 0.45f;
  74547. const float cs45y = csy * 0.45f;
  74548. const float x2 = x + w;
  74549. const float y2 = y + h;
  74550. startNewSubPath (x + csx, y);
  74551. lineTo (x2 - csx, y);
  74552. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74553. lineTo (x2, y2 - csy);
  74554. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74555. lineTo (x + csx, y2);
  74556. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74557. lineTo (x, y + csy);
  74558. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74559. closeSubPath();
  74560. }
  74561. void Path::addRoundedRectangle (const float x, const float y,
  74562. const float w, const float h,
  74563. float cs)
  74564. {
  74565. addRoundedRectangle (x, y, w, h, cs, cs);
  74566. }
  74567. void Path::addTriangle (const float x1, const float y1,
  74568. const float x2, const float y2,
  74569. const float x3, const float y3)
  74570. {
  74571. startNewSubPath (x1, y1);
  74572. lineTo (x2, y2);
  74573. lineTo (x3, y3);
  74574. closeSubPath();
  74575. }
  74576. void Path::addQuadrilateral (const float x1, const float y1,
  74577. const float x2, const float y2,
  74578. const float x3, const float y3,
  74579. const float x4, const float y4)
  74580. {
  74581. startNewSubPath (x1, y1);
  74582. lineTo (x2, y2);
  74583. lineTo (x3, y3);
  74584. lineTo (x4, y4);
  74585. closeSubPath();
  74586. }
  74587. void Path::addEllipse (const float x, const float y,
  74588. const float w, const float h)
  74589. {
  74590. const float hw = w * 0.5f;
  74591. const float hw55 = hw * 0.55f;
  74592. const float hh = h * 0.5f;
  74593. const float hh55 = hh * 0.55f;
  74594. const float cx = x + hw;
  74595. const float cy = y + hh;
  74596. startNewSubPath (cx, cy - hh);
  74597. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74598. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74599. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74600. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74601. closeSubPath();
  74602. }
  74603. void Path::addArc (const float x, const float y,
  74604. const float w, const float h,
  74605. const float fromRadians,
  74606. const float toRadians,
  74607. const bool startAsNewSubPath)
  74608. {
  74609. const float radiusX = w / 2.0f;
  74610. const float radiusY = h / 2.0f;
  74611. addCentredArc (x + radiusX,
  74612. y + radiusY,
  74613. radiusX, radiusY,
  74614. 0.0f,
  74615. fromRadians, toRadians,
  74616. startAsNewSubPath);
  74617. }
  74618. void Path::addCentredArc (const float centreX, const float centreY,
  74619. const float radiusX, const float radiusY,
  74620. const float rotationOfEllipse,
  74621. const float fromRadians,
  74622. const float toRadians,
  74623. const bool startAsNewSubPath)
  74624. {
  74625. if (radiusX > 0.0f && radiusY > 0.0f)
  74626. {
  74627. const Point<float> centre (centreX, centreY);
  74628. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74629. float angle = fromRadians;
  74630. if (startAsNewSubPath)
  74631. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74632. if (fromRadians < toRadians)
  74633. {
  74634. if (startAsNewSubPath)
  74635. angle += PathHelpers::ellipseAngularIncrement;
  74636. while (angle < toRadians)
  74637. {
  74638. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74639. angle += PathHelpers::ellipseAngularIncrement;
  74640. }
  74641. }
  74642. else
  74643. {
  74644. if (startAsNewSubPath)
  74645. angle -= PathHelpers::ellipseAngularIncrement;
  74646. while (angle > toRadians)
  74647. {
  74648. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74649. angle -= PathHelpers::ellipseAngularIncrement;
  74650. }
  74651. }
  74652. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74653. }
  74654. }
  74655. void Path::addPieSegment (const float x, const float y,
  74656. const float width, const float height,
  74657. const float fromRadians,
  74658. const float toRadians,
  74659. const float innerCircleProportionalSize)
  74660. {
  74661. float radiusX = width * 0.5f;
  74662. float radiusY = height * 0.5f;
  74663. const Point<float> centre (x + radiusX, y + radiusY);
  74664. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74665. addArc (x, y, width, height, fromRadians, toRadians);
  74666. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74667. {
  74668. closeSubPath();
  74669. if (innerCircleProportionalSize > 0)
  74670. {
  74671. radiusX *= innerCircleProportionalSize;
  74672. radiusY *= innerCircleProportionalSize;
  74673. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74674. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74675. }
  74676. }
  74677. else
  74678. {
  74679. if (innerCircleProportionalSize > 0)
  74680. {
  74681. radiusX *= innerCircleProportionalSize;
  74682. radiusY *= innerCircleProportionalSize;
  74683. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74684. }
  74685. else
  74686. {
  74687. lineTo (centre);
  74688. }
  74689. }
  74690. closeSubPath();
  74691. }
  74692. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74693. {
  74694. const Line<float> reversed (line.reversed());
  74695. lineThickness *= 0.5f;
  74696. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74697. lineTo (line.getPointAlongLine (0, -lineThickness));
  74698. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74699. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74700. closeSubPath();
  74701. }
  74702. void Path::addArrow (const Line<float>& line, float lineThickness,
  74703. float arrowheadWidth, float arrowheadLength)
  74704. {
  74705. const Line<float> reversed (line.reversed());
  74706. lineThickness *= 0.5f;
  74707. arrowheadWidth *= 0.5f;
  74708. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74709. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74710. lineTo (line.getPointAlongLine (0, -lineThickness));
  74711. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74712. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74713. lineTo (line.getEnd());
  74714. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74715. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74716. closeSubPath();
  74717. }
  74718. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74719. const float radius, const float startAngle)
  74720. {
  74721. jassert (numberOfSides > 1); // this would be silly.
  74722. if (numberOfSides > 1)
  74723. {
  74724. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74725. for (int i = 0; i < numberOfSides; ++i)
  74726. {
  74727. const float angle = startAngle + i * angleBetweenPoints;
  74728. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74729. if (i == 0)
  74730. startNewSubPath (p);
  74731. else
  74732. lineTo (p);
  74733. }
  74734. closeSubPath();
  74735. }
  74736. }
  74737. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74738. const float innerRadius, const float outerRadius, const float startAngle)
  74739. {
  74740. jassert (numberOfPoints > 1); // this would be silly.
  74741. if (numberOfPoints > 1)
  74742. {
  74743. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74744. for (int i = 0; i < numberOfPoints; ++i)
  74745. {
  74746. const float angle = startAngle + i * angleBetweenPoints;
  74747. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74748. if (i == 0)
  74749. startNewSubPath (p);
  74750. else
  74751. lineTo (p);
  74752. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74753. }
  74754. closeSubPath();
  74755. }
  74756. }
  74757. void Path::addBubble (float x, float y,
  74758. float w, float h,
  74759. float cs,
  74760. float tipX,
  74761. float tipY,
  74762. int whichSide,
  74763. float arrowPos,
  74764. float arrowWidth)
  74765. {
  74766. if (w > 1.0f && h > 1.0f)
  74767. {
  74768. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74769. const float cs2 = 2.0f * cs;
  74770. startNewSubPath (x + cs, y);
  74771. if (whichSide == 0)
  74772. {
  74773. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74774. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74775. lineTo (arrowX1, y);
  74776. lineTo (tipX, tipY);
  74777. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74778. }
  74779. lineTo (x + w - cs, y);
  74780. if (cs > 0.0f)
  74781. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74782. if (whichSide == 3)
  74783. {
  74784. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74785. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74786. lineTo (x + w, arrowY1);
  74787. lineTo (tipX, tipY);
  74788. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74789. }
  74790. lineTo (x + w, y + h - cs);
  74791. if (cs > 0.0f)
  74792. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74793. if (whichSide == 2)
  74794. {
  74795. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74796. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74797. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74798. lineTo (tipX, tipY);
  74799. lineTo (arrowX1, y + h);
  74800. }
  74801. lineTo (x + cs, y + h);
  74802. if (cs > 0.0f)
  74803. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74804. if (whichSide == 1)
  74805. {
  74806. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74807. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74808. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74809. lineTo (tipX, tipY);
  74810. lineTo (x, arrowY1);
  74811. }
  74812. lineTo (x, y + cs);
  74813. if (cs > 0.0f)
  74814. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74815. closeSubPath();
  74816. }
  74817. }
  74818. void Path::addPath (const Path& other)
  74819. {
  74820. size_t i = 0;
  74821. while (i < other.numElements)
  74822. {
  74823. const float type = other.data.elements [i++];
  74824. if (type == moveMarker)
  74825. {
  74826. startNewSubPath (other.data.elements [i],
  74827. other.data.elements [i + 1]);
  74828. i += 2;
  74829. }
  74830. else if (type == lineMarker)
  74831. {
  74832. lineTo (other.data.elements [i],
  74833. other.data.elements [i + 1]);
  74834. i += 2;
  74835. }
  74836. else if (type == quadMarker)
  74837. {
  74838. quadraticTo (other.data.elements [i],
  74839. other.data.elements [i + 1],
  74840. other.data.elements [i + 2],
  74841. other.data.elements [i + 3]);
  74842. i += 4;
  74843. }
  74844. else if (type == cubicMarker)
  74845. {
  74846. cubicTo (other.data.elements [i],
  74847. other.data.elements [i + 1],
  74848. other.data.elements [i + 2],
  74849. other.data.elements [i + 3],
  74850. other.data.elements [i + 4],
  74851. other.data.elements [i + 5]);
  74852. i += 6;
  74853. }
  74854. else if (type == closeSubPathMarker)
  74855. {
  74856. closeSubPath();
  74857. }
  74858. else
  74859. {
  74860. // something's gone wrong with the element list!
  74861. jassertfalse;
  74862. }
  74863. }
  74864. }
  74865. void Path::addPath (const Path& other,
  74866. const AffineTransform& transformToApply)
  74867. {
  74868. size_t i = 0;
  74869. while (i < other.numElements)
  74870. {
  74871. const float type = other.data.elements [i++];
  74872. if (type == closeSubPathMarker)
  74873. {
  74874. closeSubPath();
  74875. }
  74876. else
  74877. {
  74878. float x = other.data.elements [i++];
  74879. float y = other.data.elements [i++];
  74880. transformToApply.transformPoint (x, y);
  74881. if (type == moveMarker)
  74882. {
  74883. startNewSubPath (x, y);
  74884. }
  74885. else if (type == lineMarker)
  74886. {
  74887. lineTo (x, y);
  74888. }
  74889. else if (type == quadMarker)
  74890. {
  74891. float x2 = other.data.elements [i++];
  74892. float y2 = other.data.elements [i++];
  74893. transformToApply.transformPoint (x2, y2);
  74894. quadraticTo (x, y, x2, y2);
  74895. }
  74896. else if (type == cubicMarker)
  74897. {
  74898. float x2 = other.data.elements [i++];
  74899. float y2 = other.data.elements [i++];
  74900. float x3 = other.data.elements [i++];
  74901. float y3 = other.data.elements [i++];
  74902. transformToApply.transformPoints (x2, y2, x3, y3);
  74903. cubicTo (x, y, x2, y2, x3, y3);
  74904. }
  74905. else
  74906. {
  74907. // something's gone wrong with the element list!
  74908. jassertfalse;
  74909. }
  74910. }
  74911. }
  74912. }
  74913. void Path::applyTransform (const AffineTransform& transform) throw()
  74914. {
  74915. size_t i = 0;
  74916. pathYMin = pathXMin = 0;
  74917. pathYMax = pathXMax = 0;
  74918. bool setMaxMin = false;
  74919. while (i < numElements)
  74920. {
  74921. const float type = data.elements [i++];
  74922. if (type == moveMarker)
  74923. {
  74924. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74925. if (setMaxMin)
  74926. {
  74927. pathXMin = jmin (pathXMin, data.elements [i]);
  74928. pathXMax = jmax (pathXMax, data.elements [i]);
  74929. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74930. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74931. }
  74932. else
  74933. {
  74934. pathXMin = pathXMax = data.elements [i];
  74935. pathYMin = pathYMax = data.elements [i + 1];
  74936. setMaxMin = true;
  74937. }
  74938. i += 2;
  74939. }
  74940. else if (type == lineMarker)
  74941. {
  74942. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74943. pathXMin = jmin (pathXMin, data.elements [i]);
  74944. pathXMax = jmax (pathXMax, data.elements [i]);
  74945. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74946. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74947. i += 2;
  74948. }
  74949. else if (type == quadMarker)
  74950. {
  74951. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74952. data.elements [i + 2], data.elements [i + 3]);
  74953. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74954. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74955. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74956. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74957. i += 4;
  74958. }
  74959. else if (type == cubicMarker)
  74960. {
  74961. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74962. data.elements [i + 2], data.elements [i + 3],
  74963. data.elements [i + 4], data.elements [i + 5]);
  74964. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74965. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74966. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74967. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74968. i += 6;
  74969. }
  74970. }
  74971. }
  74972. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74973. const float w, const float h,
  74974. const bool preserveProportions,
  74975. const Justification& justification) const
  74976. {
  74977. Rectangle<float> bounds (getBounds());
  74978. if (preserveProportions)
  74979. {
  74980. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74981. return AffineTransform::identity;
  74982. float newW, newH;
  74983. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74984. if (srcRatio > h / w)
  74985. {
  74986. newW = h / srcRatio;
  74987. newH = h;
  74988. }
  74989. else
  74990. {
  74991. newW = w;
  74992. newH = w * srcRatio;
  74993. }
  74994. float newXCentre = x;
  74995. float newYCentre = y;
  74996. if (justification.testFlags (Justification::left))
  74997. newXCentre += newW * 0.5f;
  74998. else if (justification.testFlags (Justification::right))
  74999. newXCentre += w - newW * 0.5f;
  75000. else
  75001. newXCentre += w * 0.5f;
  75002. if (justification.testFlags (Justification::top))
  75003. newYCentre += newH * 0.5f;
  75004. else if (justification.testFlags (Justification::bottom))
  75005. newYCentre += h - newH * 0.5f;
  75006. else
  75007. newYCentre += h * 0.5f;
  75008. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75009. bounds.getHeight() * -0.5f - bounds.getY())
  75010. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75011. .translated (newXCentre, newYCentre);
  75012. }
  75013. else
  75014. {
  75015. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75016. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75017. .translated (x, y);
  75018. }
  75019. }
  75020. bool Path::contains (const float x, const float y, const float tolerance) const
  75021. {
  75022. if (x <= pathXMin || x >= pathXMax
  75023. || y <= pathYMin || y >= pathYMax)
  75024. return false;
  75025. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75026. int positiveCrossings = 0;
  75027. int negativeCrossings = 0;
  75028. while (i.next())
  75029. {
  75030. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75031. {
  75032. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75033. if (intersectX <= x)
  75034. {
  75035. if (i.y1 < i.y2)
  75036. ++positiveCrossings;
  75037. else
  75038. ++negativeCrossings;
  75039. }
  75040. }
  75041. }
  75042. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75043. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75044. }
  75045. bool Path::contains (const Point<float>& point, const float tolerance) const
  75046. {
  75047. return contains (point.getX(), point.getY(), tolerance);
  75048. }
  75049. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  75050. {
  75051. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  75052. Point<float> intersection;
  75053. while (i.next())
  75054. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75055. return true;
  75056. return false;
  75057. }
  75058. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75059. {
  75060. Line<float> result (line);
  75061. const bool startInside = contains (line.getStart());
  75062. const bool endInside = contains (line.getEnd());
  75063. if (startInside == endInside)
  75064. {
  75065. if (keepSectionOutsidePath == startInside)
  75066. result = Line<float>();
  75067. }
  75068. else
  75069. {
  75070. PathFlatteningIterator i (*this, AffineTransform::identity);
  75071. Point<float> intersection;
  75072. while (i.next())
  75073. {
  75074. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75075. {
  75076. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75077. result.setStart (intersection);
  75078. else
  75079. result.setEnd (intersection);
  75080. }
  75081. }
  75082. }
  75083. return result;
  75084. }
  75085. float Path::getLength (const AffineTransform& transform) const
  75086. {
  75087. float length = 0;
  75088. PathFlatteningIterator i (*this, transform);
  75089. while (i.next())
  75090. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75091. return length;
  75092. }
  75093. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75094. {
  75095. PathFlatteningIterator i (*this, transform);
  75096. while (i.next())
  75097. {
  75098. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75099. const float lineLength = line.getLength();
  75100. if (distanceFromStart <= lineLength)
  75101. return line.getPointAlongLine (distanceFromStart);
  75102. distanceFromStart -= lineLength;
  75103. }
  75104. return Point<float> (i.x2, i.y2);
  75105. }
  75106. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75107. const AffineTransform& transform) const
  75108. {
  75109. PathFlatteningIterator i (*this, transform);
  75110. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75111. float length = 0;
  75112. Point<float> pointOnLine;
  75113. while (i.next())
  75114. {
  75115. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75116. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75117. if (distance < bestDistance)
  75118. {
  75119. bestDistance = distance;
  75120. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75121. pointOnPath = pointOnLine;
  75122. }
  75123. length += line.getLength();
  75124. }
  75125. return bestPosition;
  75126. }
  75127. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75128. {
  75129. if (cornerRadius <= 0.01f)
  75130. return *this;
  75131. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75132. size_t n = 0;
  75133. bool lastWasLine = false, firstWasLine = false;
  75134. Path p;
  75135. while (n < numElements)
  75136. {
  75137. const float type = data.elements [n++];
  75138. if (type == moveMarker)
  75139. {
  75140. indexOfPathStart = p.numElements;
  75141. indexOfPathStartThis = n - 1;
  75142. const float x = data.elements [n++];
  75143. const float y = data.elements [n++];
  75144. p.startNewSubPath (x, y);
  75145. lastWasLine = false;
  75146. firstWasLine = (data.elements [n] == lineMarker);
  75147. }
  75148. else if (type == lineMarker || type == closeSubPathMarker)
  75149. {
  75150. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75151. if (type == lineMarker)
  75152. {
  75153. endX = data.elements [n++];
  75154. endY = data.elements [n++];
  75155. if (n > 8)
  75156. {
  75157. startX = data.elements [n - 8];
  75158. startY = data.elements [n - 7];
  75159. joinX = data.elements [n - 5];
  75160. joinY = data.elements [n - 4];
  75161. }
  75162. }
  75163. else
  75164. {
  75165. endX = data.elements [indexOfPathStartThis + 1];
  75166. endY = data.elements [indexOfPathStartThis + 2];
  75167. if (n > 6)
  75168. {
  75169. startX = data.elements [n - 6];
  75170. startY = data.elements [n - 5];
  75171. joinX = data.elements [n - 3];
  75172. joinY = data.elements [n - 2];
  75173. }
  75174. }
  75175. if (lastWasLine)
  75176. {
  75177. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75178. if (len1 > 0)
  75179. {
  75180. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75181. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75182. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75183. }
  75184. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75185. if (len2 > 0)
  75186. {
  75187. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75188. p.quadraticTo (joinX, joinY,
  75189. (float) (joinX + (endX - joinX) * propNeeded),
  75190. (float) (joinY + (endY - joinY) * propNeeded));
  75191. }
  75192. p.lineTo (endX, endY);
  75193. }
  75194. else if (type == lineMarker)
  75195. {
  75196. p.lineTo (endX, endY);
  75197. lastWasLine = true;
  75198. }
  75199. if (type == closeSubPathMarker)
  75200. {
  75201. if (firstWasLine)
  75202. {
  75203. startX = data.elements [n - 3];
  75204. startY = data.elements [n - 2];
  75205. joinX = endX;
  75206. joinY = endY;
  75207. endX = data.elements [indexOfPathStartThis + 4];
  75208. endY = data.elements [indexOfPathStartThis + 5];
  75209. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  75210. if (len1 > 0)
  75211. {
  75212. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75213. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75214. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75215. }
  75216. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  75217. if (len2 > 0)
  75218. {
  75219. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75220. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75221. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75222. p.quadraticTo (joinX, joinY, endX, endY);
  75223. p.data.elements [indexOfPathStart + 1] = endX;
  75224. p.data.elements [indexOfPathStart + 2] = endY;
  75225. }
  75226. }
  75227. p.closeSubPath();
  75228. }
  75229. }
  75230. else if (type == quadMarker)
  75231. {
  75232. lastWasLine = false;
  75233. const float x1 = data.elements [n++];
  75234. const float y1 = data.elements [n++];
  75235. const float x2 = data.elements [n++];
  75236. const float y2 = data.elements [n++];
  75237. p.quadraticTo (x1, y1, x2, y2);
  75238. }
  75239. else if (type == cubicMarker)
  75240. {
  75241. lastWasLine = false;
  75242. const float x1 = data.elements [n++];
  75243. const float y1 = data.elements [n++];
  75244. const float x2 = data.elements [n++];
  75245. const float y2 = data.elements [n++];
  75246. const float x3 = data.elements [n++];
  75247. const float y3 = data.elements [n++];
  75248. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75249. }
  75250. }
  75251. return p;
  75252. }
  75253. void Path::loadPathFromStream (InputStream& source)
  75254. {
  75255. while (! source.isExhausted())
  75256. {
  75257. switch (source.readByte())
  75258. {
  75259. case 'm':
  75260. {
  75261. const float x = source.readFloat();
  75262. const float y = source.readFloat();
  75263. startNewSubPath (x, y);
  75264. break;
  75265. }
  75266. case 'l':
  75267. {
  75268. const float x = source.readFloat();
  75269. const float y = source.readFloat();
  75270. lineTo (x, y);
  75271. break;
  75272. }
  75273. case 'q':
  75274. {
  75275. const float x1 = source.readFloat();
  75276. const float y1 = source.readFloat();
  75277. const float x2 = source.readFloat();
  75278. const float y2 = source.readFloat();
  75279. quadraticTo (x1, y1, x2, y2);
  75280. break;
  75281. }
  75282. case 'b':
  75283. {
  75284. const float x1 = source.readFloat();
  75285. const float y1 = source.readFloat();
  75286. const float x2 = source.readFloat();
  75287. const float y2 = source.readFloat();
  75288. const float x3 = source.readFloat();
  75289. const float y3 = source.readFloat();
  75290. cubicTo (x1, y1, x2, y2, x3, y3);
  75291. break;
  75292. }
  75293. case 'c':
  75294. closeSubPath();
  75295. break;
  75296. case 'n':
  75297. useNonZeroWinding = true;
  75298. break;
  75299. case 'z':
  75300. useNonZeroWinding = false;
  75301. break;
  75302. case 'e':
  75303. return; // end of path marker
  75304. default:
  75305. jassertfalse; // illegal char in the stream
  75306. break;
  75307. }
  75308. }
  75309. }
  75310. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75311. {
  75312. MemoryInputStream in (pathData, numberOfBytes, false);
  75313. loadPathFromStream (in);
  75314. }
  75315. void Path::writePathToStream (OutputStream& dest) const
  75316. {
  75317. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75318. size_t i = 0;
  75319. while (i < numElements)
  75320. {
  75321. const float type = data.elements [i++];
  75322. if (type == moveMarker)
  75323. {
  75324. dest.writeByte ('m');
  75325. dest.writeFloat (data.elements [i++]);
  75326. dest.writeFloat (data.elements [i++]);
  75327. }
  75328. else if (type == lineMarker)
  75329. {
  75330. dest.writeByte ('l');
  75331. dest.writeFloat (data.elements [i++]);
  75332. dest.writeFloat (data.elements [i++]);
  75333. }
  75334. else if (type == quadMarker)
  75335. {
  75336. dest.writeByte ('q');
  75337. dest.writeFloat (data.elements [i++]);
  75338. dest.writeFloat (data.elements [i++]);
  75339. dest.writeFloat (data.elements [i++]);
  75340. dest.writeFloat (data.elements [i++]);
  75341. }
  75342. else if (type == cubicMarker)
  75343. {
  75344. dest.writeByte ('b');
  75345. dest.writeFloat (data.elements [i++]);
  75346. dest.writeFloat (data.elements [i++]);
  75347. dest.writeFloat (data.elements [i++]);
  75348. dest.writeFloat (data.elements [i++]);
  75349. dest.writeFloat (data.elements [i++]);
  75350. dest.writeFloat (data.elements [i++]);
  75351. }
  75352. else if (type == closeSubPathMarker)
  75353. {
  75354. dest.writeByte ('c');
  75355. }
  75356. }
  75357. dest.writeByte ('e'); // marks the end-of-path
  75358. }
  75359. const String Path::toString() const
  75360. {
  75361. MemoryOutputStream s (2048);
  75362. if (! useNonZeroWinding)
  75363. s << 'a';
  75364. size_t i = 0;
  75365. float lastMarker = 0.0f;
  75366. while (i < numElements)
  75367. {
  75368. const float marker = data.elements [i++];
  75369. char markerChar = 0;
  75370. int numCoords = 0;
  75371. if (marker == moveMarker)
  75372. {
  75373. markerChar = 'm';
  75374. numCoords = 2;
  75375. }
  75376. else if (marker == lineMarker)
  75377. {
  75378. markerChar = 'l';
  75379. numCoords = 2;
  75380. }
  75381. else if (marker == quadMarker)
  75382. {
  75383. markerChar = 'q';
  75384. numCoords = 4;
  75385. }
  75386. else if (marker == cubicMarker)
  75387. {
  75388. markerChar = 'c';
  75389. numCoords = 6;
  75390. }
  75391. else
  75392. {
  75393. jassert (marker == closeSubPathMarker);
  75394. markerChar = 'z';
  75395. }
  75396. if (marker != lastMarker)
  75397. {
  75398. if (s.getDataSize() != 0)
  75399. s << ' ';
  75400. s << markerChar;
  75401. lastMarker = marker;
  75402. }
  75403. while (--numCoords >= 0 && i < numElements)
  75404. {
  75405. String coord (data.elements [i++], 3);
  75406. while (coord.endsWithChar ('0') && coord != "0")
  75407. coord = coord.dropLastCharacters (1);
  75408. if (coord.endsWithChar ('.'))
  75409. coord = coord.dropLastCharacters (1);
  75410. if (s.getDataSize() != 0)
  75411. s << ' ';
  75412. s << coord;
  75413. }
  75414. }
  75415. return s.toUTF8();
  75416. }
  75417. void Path::restoreFromString (const String& stringVersion)
  75418. {
  75419. clear();
  75420. setUsingNonZeroWinding (true);
  75421. const juce_wchar* t = stringVersion;
  75422. juce_wchar marker = 'm';
  75423. int numValues = 2;
  75424. float values [6];
  75425. for (;;)
  75426. {
  75427. const String token (PathHelpers::nextToken (t));
  75428. const juce_wchar firstChar = token[0];
  75429. int startNum = 0;
  75430. if (firstChar == 0)
  75431. break;
  75432. if (firstChar == 'm' || firstChar == 'l')
  75433. {
  75434. marker = firstChar;
  75435. numValues = 2;
  75436. }
  75437. else if (firstChar == 'q')
  75438. {
  75439. marker = firstChar;
  75440. numValues = 4;
  75441. }
  75442. else if (firstChar == 'c')
  75443. {
  75444. marker = firstChar;
  75445. numValues = 6;
  75446. }
  75447. else if (firstChar == 'z')
  75448. {
  75449. marker = firstChar;
  75450. numValues = 0;
  75451. }
  75452. else if (firstChar == 'a')
  75453. {
  75454. setUsingNonZeroWinding (false);
  75455. continue;
  75456. }
  75457. else
  75458. {
  75459. ++startNum;
  75460. values [0] = token.getFloatValue();
  75461. }
  75462. for (int i = startNum; i < numValues; ++i)
  75463. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75464. switch (marker)
  75465. {
  75466. case 'm': startNewSubPath (values[0], values[1]); break;
  75467. case 'l': lineTo (values[0], values[1]); break;
  75468. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75469. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75470. case 'z': closeSubPath(); break;
  75471. default: jassertfalse; break; // illegal string format?
  75472. }
  75473. }
  75474. }
  75475. Path::Iterator::Iterator (const Path& path_)
  75476. : path (path_),
  75477. index (0)
  75478. {
  75479. }
  75480. Path::Iterator::~Iterator()
  75481. {
  75482. }
  75483. bool Path::Iterator::next()
  75484. {
  75485. const float* const elements = path.data.elements;
  75486. if (index < path.numElements)
  75487. {
  75488. const float type = elements [index++];
  75489. if (type == moveMarker)
  75490. {
  75491. elementType = startNewSubPath;
  75492. x1 = elements [index++];
  75493. y1 = elements [index++];
  75494. }
  75495. else if (type == lineMarker)
  75496. {
  75497. elementType = lineTo;
  75498. x1 = elements [index++];
  75499. y1 = elements [index++];
  75500. }
  75501. else if (type == quadMarker)
  75502. {
  75503. elementType = quadraticTo;
  75504. x1 = elements [index++];
  75505. y1 = elements [index++];
  75506. x2 = elements [index++];
  75507. y2 = elements [index++];
  75508. }
  75509. else if (type == cubicMarker)
  75510. {
  75511. elementType = cubicTo;
  75512. x1 = elements [index++];
  75513. y1 = elements [index++];
  75514. x2 = elements [index++];
  75515. y2 = elements [index++];
  75516. x3 = elements [index++];
  75517. y3 = elements [index++];
  75518. }
  75519. else if (type == closeSubPathMarker)
  75520. {
  75521. elementType = closePath;
  75522. }
  75523. return true;
  75524. }
  75525. return false;
  75526. }
  75527. END_JUCE_NAMESPACE
  75528. /*** End of inlined file: juce_Path.cpp ***/
  75529. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75530. BEGIN_JUCE_NAMESPACE
  75531. #if JUCE_MSVC && JUCE_DEBUG
  75532. #pragma optimize ("t", on)
  75533. #endif
  75534. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75535. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75536. const AffineTransform& transform_,
  75537. const float tolerance)
  75538. : x2 (0),
  75539. y2 (0),
  75540. closesSubPath (false),
  75541. subPathIndex (-1),
  75542. path (path_),
  75543. transform (transform_),
  75544. points (path_.data.elements),
  75545. toleranceSquared (tolerance * tolerance),
  75546. subPathCloseX (0),
  75547. subPathCloseY (0),
  75548. isIdentityTransform (transform_.isIdentity()),
  75549. stackBase (32),
  75550. index (0),
  75551. stackSize (32)
  75552. {
  75553. stackPos = stackBase;
  75554. }
  75555. PathFlatteningIterator::~PathFlatteningIterator()
  75556. {
  75557. }
  75558. bool PathFlatteningIterator::next()
  75559. {
  75560. x1 = x2;
  75561. y1 = y2;
  75562. float x3 = 0;
  75563. float y3 = 0;
  75564. float x4 = 0;
  75565. float y4 = 0;
  75566. float type;
  75567. for (;;)
  75568. {
  75569. if (stackPos == stackBase)
  75570. {
  75571. if (index >= path.numElements)
  75572. {
  75573. return false;
  75574. }
  75575. else
  75576. {
  75577. type = points [index++];
  75578. if (type != Path::closeSubPathMarker)
  75579. {
  75580. x2 = points [index++];
  75581. y2 = points [index++];
  75582. if (type == Path::quadMarker)
  75583. {
  75584. x3 = points [index++];
  75585. y3 = points [index++];
  75586. if (! isIdentityTransform)
  75587. transform.transformPoints (x2, y2, x3, y3);
  75588. }
  75589. else if (type == Path::cubicMarker)
  75590. {
  75591. x3 = points [index++];
  75592. y3 = points [index++];
  75593. x4 = points [index++];
  75594. y4 = points [index++];
  75595. if (! isIdentityTransform)
  75596. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75597. }
  75598. else
  75599. {
  75600. if (! isIdentityTransform)
  75601. transform.transformPoint (x2, y2);
  75602. }
  75603. }
  75604. }
  75605. }
  75606. else
  75607. {
  75608. type = *--stackPos;
  75609. if (type != Path::closeSubPathMarker)
  75610. {
  75611. x2 = *--stackPos;
  75612. y2 = *--stackPos;
  75613. if (type == Path::quadMarker)
  75614. {
  75615. x3 = *--stackPos;
  75616. y3 = *--stackPos;
  75617. }
  75618. else if (type == Path::cubicMarker)
  75619. {
  75620. x3 = *--stackPos;
  75621. y3 = *--stackPos;
  75622. x4 = *--stackPos;
  75623. y4 = *--stackPos;
  75624. }
  75625. }
  75626. }
  75627. if (type == Path::lineMarker)
  75628. {
  75629. ++subPathIndex;
  75630. closesSubPath = (stackPos == stackBase)
  75631. && (index < path.numElements)
  75632. && (points [index] == Path::closeSubPathMarker)
  75633. && x2 == subPathCloseX
  75634. && y2 == subPathCloseY;
  75635. return true;
  75636. }
  75637. else if (type == Path::quadMarker)
  75638. {
  75639. const size_t offset = (size_t) (stackPos - stackBase);
  75640. if (offset >= stackSize - 10)
  75641. {
  75642. stackSize <<= 1;
  75643. stackBase.realloc (stackSize);
  75644. stackPos = stackBase + offset;
  75645. }
  75646. const float m1x = (x1 + x2) * 0.5f;
  75647. const float m1y = (y1 + y2) * 0.5f;
  75648. const float m2x = (x2 + x3) * 0.5f;
  75649. const float m2y = (y2 + y3) * 0.5f;
  75650. const float m3x = (m1x + m2x) * 0.5f;
  75651. const float m3y = (m1y + m2y) * 0.5f;
  75652. const float errorX = m3x - x2;
  75653. const float errorY = m3y - y2;
  75654. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75655. {
  75656. *stackPos++ = y3;
  75657. *stackPos++ = x3;
  75658. *stackPos++ = m2y;
  75659. *stackPos++ = m2x;
  75660. *stackPos++ = Path::quadMarker;
  75661. *stackPos++ = m3y;
  75662. *stackPos++ = m3x;
  75663. *stackPos++ = m1y;
  75664. *stackPos++ = m1x;
  75665. *stackPos++ = Path::quadMarker;
  75666. }
  75667. else
  75668. {
  75669. *stackPos++ = y3;
  75670. *stackPos++ = x3;
  75671. *stackPos++ = Path::lineMarker;
  75672. *stackPos++ = m3y;
  75673. *stackPos++ = m3x;
  75674. *stackPos++ = Path::lineMarker;
  75675. }
  75676. jassert (stackPos < stackBase + stackSize);
  75677. }
  75678. else if (type == Path::cubicMarker)
  75679. {
  75680. const size_t offset = (size_t) (stackPos - stackBase);
  75681. if (offset >= stackSize - 16)
  75682. {
  75683. stackSize <<= 1;
  75684. stackBase.realloc (stackSize);
  75685. stackPos = stackBase + offset;
  75686. }
  75687. const float m1x = (x1 + x2) * 0.5f;
  75688. const float m1y = (y1 + y2) * 0.5f;
  75689. const float m2x = (x3 + x2) * 0.5f;
  75690. const float m2y = (y3 + y2) * 0.5f;
  75691. const float m3x = (x3 + x4) * 0.5f;
  75692. const float m3y = (y3 + y4) * 0.5f;
  75693. const float m4x = (m1x + m2x) * 0.5f;
  75694. const float m4y = (m1y + m2y) * 0.5f;
  75695. const float m5x = (m3x + m2x) * 0.5f;
  75696. const float m5y = (m3y + m2y) * 0.5f;
  75697. const float error1X = m4x - x2;
  75698. const float error1Y = m4y - y2;
  75699. const float error2X = m5x - x3;
  75700. const float error2Y = m5y - y3;
  75701. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75702. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75703. {
  75704. *stackPos++ = y4;
  75705. *stackPos++ = x4;
  75706. *stackPos++ = m3y;
  75707. *stackPos++ = m3x;
  75708. *stackPos++ = m5y;
  75709. *stackPos++ = m5x;
  75710. *stackPos++ = Path::cubicMarker;
  75711. *stackPos++ = (m4y + m5y) * 0.5f;
  75712. *stackPos++ = (m4x + m5x) * 0.5f;
  75713. *stackPos++ = m4y;
  75714. *stackPos++ = m4x;
  75715. *stackPos++ = m1y;
  75716. *stackPos++ = m1x;
  75717. *stackPos++ = Path::cubicMarker;
  75718. }
  75719. else
  75720. {
  75721. *stackPos++ = y4;
  75722. *stackPos++ = x4;
  75723. *stackPos++ = Path::lineMarker;
  75724. *stackPos++ = m5y;
  75725. *stackPos++ = m5x;
  75726. *stackPos++ = Path::lineMarker;
  75727. *stackPos++ = m4y;
  75728. *stackPos++ = m4x;
  75729. *stackPos++ = Path::lineMarker;
  75730. }
  75731. }
  75732. else if (type == Path::closeSubPathMarker)
  75733. {
  75734. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75735. {
  75736. x1 = x2;
  75737. y1 = y2;
  75738. x2 = subPathCloseX;
  75739. y2 = subPathCloseY;
  75740. closesSubPath = true;
  75741. return true;
  75742. }
  75743. }
  75744. else
  75745. {
  75746. jassert (type == Path::moveMarker);
  75747. subPathIndex = -1;
  75748. subPathCloseX = x1 = x2;
  75749. subPathCloseY = y1 = y2;
  75750. }
  75751. }
  75752. }
  75753. #if JUCE_MSVC && JUCE_DEBUG
  75754. #pragma optimize ("", on) // resets optimisations to the project defaults
  75755. #endif
  75756. END_JUCE_NAMESPACE
  75757. /*** End of inlined file: juce_PathIterator.cpp ***/
  75758. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75759. BEGIN_JUCE_NAMESPACE
  75760. PathStrokeType::PathStrokeType (const float strokeThickness,
  75761. const JointStyle jointStyle_,
  75762. const EndCapStyle endStyle_) throw()
  75763. : thickness (strokeThickness),
  75764. jointStyle (jointStyle_),
  75765. endStyle (endStyle_)
  75766. {
  75767. }
  75768. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75769. : thickness (other.thickness),
  75770. jointStyle (other.jointStyle),
  75771. endStyle (other.endStyle)
  75772. {
  75773. }
  75774. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75775. {
  75776. thickness = other.thickness;
  75777. jointStyle = other.jointStyle;
  75778. endStyle = other.endStyle;
  75779. return *this;
  75780. }
  75781. PathStrokeType::~PathStrokeType() throw()
  75782. {
  75783. }
  75784. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75785. {
  75786. return thickness == other.thickness
  75787. && jointStyle == other.jointStyle
  75788. && endStyle == other.endStyle;
  75789. }
  75790. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75791. {
  75792. return ! operator== (other);
  75793. }
  75794. namespace PathStrokeHelpers
  75795. {
  75796. bool lineIntersection (const float x1, const float y1,
  75797. const float x2, const float y2,
  75798. const float x3, const float y3,
  75799. const float x4, const float y4,
  75800. float& intersectionX,
  75801. float& intersectionY,
  75802. float& distanceBeyondLine1EndSquared) throw()
  75803. {
  75804. if (x2 != x3 || y2 != y3)
  75805. {
  75806. const float dx1 = x2 - x1;
  75807. const float dy1 = y2 - y1;
  75808. const float dx2 = x4 - x3;
  75809. const float dy2 = y4 - y3;
  75810. const float divisor = dx1 * dy2 - dx2 * dy1;
  75811. if (divisor == 0)
  75812. {
  75813. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75814. {
  75815. if (dy1 == 0 && dy2 != 0)
  75816. {
  75817. const float along = (y1 - y3) / dy2;
  75818. intersectionX = x3 + along * dx2;
  75819. intersectionY = y1;
  75820. distanceBeyondLine1EndSquared = intersectionX - x2;
  75821. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75822. if ((x2 > x1) == (intersectionX < x2))
  75823. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75824. return along >= 0 && along <= 1.0f;
  75825. }
  75826. else if (dy2 == 0 && dy1 != 0)
  75827. {
  75828. const float along = (y3 - y1) / dy1;
  75829. intersectionX = x1 + along * dx1;
  75830. intersectionY = y3;
  75831. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75832. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75833. if (along < 1.0f)
  75834. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75835. return along >= 0 && along <= 1.0f;
  75836. }
  75837. else if (dx1 == 0 && dx2 != 0)
  75838. {
  75839. const float along = (x1 - x3) / dx2;
  75840. intersectionX = x1;
  75841. intersectionY = y3 + along * dy2;
  75842. distanceBeyondLine1EndSquared = intersectionY - y2;
  75843. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75844. if ((y2 > y1) == (intersectionY < y2))
  75845. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75846. return along >= 0 && along <= 1.0f;
  75847. }
  75848. else if (dx2 == 0 && dx1 != 0)
  75849. {
  75850. const float along = (x3 - x1) / dx1;
  75851. intersectionX = x3;
  75852. intersectionY = y1 + along * dy1;
  75853. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75854. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75855. if (along < 1.0f)
  75856. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75857. return along >= 0 && along <= 1.0f;
  75858. }
  75859. }
  75860. intersectionX = 0.5f * (x2 + x3);
  75861. intersectionY = 0.5f * (y2 + y3);
  75862. distanceBeyondLine1EndSquared = 0.0f;
  75863. return false;
  75864. }
  75865. else
  75866. {
  75867. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75868. intersectionX = x1 + along1 * dx1;
  75869. intersectionY = y1 + along1 * dy1;
  75870. if (along1 >= 0 && along1 <= 1.0f)
  75871. {
  75872. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75873. if (along2 >= 0 && along2 <= divisor)
  75874. {
  75875. distanceBeyondLine1EndSquared = 0.0f;
  75876. return true;
  75877. }
  75878. }
  75879. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75880. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75881. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75882. if (along1 < 1.0f)
  75883. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75884. return false;
  75885. }
  75886. }
  75887. intersectionX = x2;
  75888. intersectionY = y2;
  75889. distanceBeyondLine1EndSquared = 0.0f;
  75890. return true;
  75891. }
  75892. void addEdgeAndJoint (Path& destPath,
  75893. const PathStrokeType::JointStyle style,
  75894. const float maxMiterExtensionSquared, const float width,
  75895. const float x1, const float y1,
  75896. const float x2, const float y2,
  75897. const float x3, const float y3,
  75898. const float x4, const float y4,
  75899. const float midX, const float midY)
  75900. {
  75901. if (style == PathStrokeType::beveled
  75902. || (x3 == x4 && y3 == y4)
  75903. || (x1 == x2 && y1 == y2))
  75904. {
  75905. destPath.lineTo (x2, y2);
  75906. destPath.lineTo (x3, y3);
  75907. }
  75908. else
  75909. {
  75910. float jx, jy, distanceBeyondLine1EndSquared;
  75911. // if they intersect, use this point..
  75912. if (lineIntersection (x1, y1, x2, y2,
  75913. x3, y3, x4, y4,
  75914. jx, jy, distanceBeyondLine1EndSquared))
  75915. {
  75916. destPath.lineTo (jx, jy);
  75917. }
  75918. else
  75919. {
  75920. if (style == PathStrokeType::mitered)
  75921. {
  75922. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75923. && distanceBeyondLine1EndSquared > 0.0f)
  75924. {
  75925. destPath.lineTo (jx, jy);
  75926. }
  75927. else
  75928. {
  75929. // the end sticks out too far, so just use a blunt joint
  75930. destPath.lineTo (x2, y2);
  75931. destPath.lineTo (x3, y3);
  75932. }
  75933. }
  75934. else
  75935. {
  75936. // curved joints
  75937. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75938. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75939. const float angleIncrement = 0.1f;
  75940. destPath.lineTo (x2, y2);
  75941. if (std::abs (angle1 - angle2) > angleIncrement)
  75942. {
  75943. if (angle2 > angle1 + float_Pi
  75944. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75945. {
  75946. if (angle2 > angle1)
  75947. angle2 -= float_Pi * 2.0f;
  75948. jassert (angle1 <= angle2 + float_Pi);
  75949. angle1 -= angleIncrement;
  75950. while (angle1 > angle2)
  75951. {
  75952. destPath.lineTo (midX + width * std::sin (angle1),
  75953. midY + width * std::cos (angle1));
  75954. angle1 -= angleIncrement;
  75955. }
  75956. }
  75957. else
  75958. {
  75959. if (angle1 > angle2)
  75960. angle1 -= float_Pi * 2.0f;
  75961. jassert (angle1 >= angle2 - float_Pi);
  75962. angle1 += angleIncrement;
  75963. while (angle1 < angle2)
  75964. {
  75965. destPath.lineTo (midX + width * std::sin (angle1),
  75966. midY + width * std::cos (angle1));
  75967. angle1 += angleIncrement;
  75968. }
  75969. }
  75970. }
  75971. destPath.lineTo (x3, y3);
  75972. }
  75973. }
  75974. }
  75975. }
  75976. void addLineEnd (Path& destPath,
  75977. const PathStrokeType::EndCapStyle style,
  75978. const float x1, const float y1,
  75979. const float x2, const float y2,
  75980. const float width)
  75981. {
  75982. if (style == PathStrokeType::butt)
  75983. {
  75984. destPath.lineTo (x2, y2);
  75985. }
  75986. else
  75987. {
  75988. float offx1, offy1, offx2, offy2;
  75989. float dx = x2 - x1;
  75990. float dy = y2 - y1;
  75991. const float len = juce_hypot (dx, dy);
  75992. if (len == 0)
  75993. {
  75994. offx1 = offx2 = x1;
  75995. offy1 = offy2 = y1;
  75996. }
  75997. else
  75998. {
  75999. const float offset = width / len;
  76000. dx *= offset;
  76001. dy *= offset;
  76002. offx1 = x1 + dy;
  76003. offy1 = y1 - dx;
  76004. offx2 = x2 + dy;
  76005. offy2 = y2 - dx;
  76006. }
  76007. if (style == PathStrokeType::square)
  76008. {
  76009. // sqaure ends
  76010. destPath.lineTo (offx1, offy1);
  76011. destPath.lineTo (offx2, offy2);
  76012. destPath.lineTo (x2, y2);
  76013. }
  76014. else
  76015. {
  76016. // rounded ends
  76017. const float midx = (offx1 + offx2) * 0.5f;
  76018. const float midy = (offy1 + offy2) * 0.5f;
  76019. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76020. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76021. midx, midy);
  76022. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76023. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76024. x2, y2);
  76025. }
  76026. }
  76027. }
  76028. struct Arrowhead
  76029. {
  76030. float startWidth, startLength;
  76031. float endWidth, endLength;
  76032. };
  76033. void addArrowhead (Path& destPath,
  76034. const float x1, const float y1,
  76035. const float x2, const float y2,
  76036. const float tipX, const float tipY,
  76037. const float width,
  76038. const float arrowheadWidth)
  76039. {
  76040. Line<float> line (x1, y1, x2, y2);
  76041. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76042. destPath.lineTo (tipX, tipY);
  76043. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76044. destPath.lineTo (x2, y2);
  76045. }
  76046. struct LineSection
  76047. {
  76048. float x1, y1, x2, y2; // original line
  76049. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76050. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76051. };
  76052. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76053. {
  76054. while (amountAtEnd > 0 && subPath.size() > 0)
  76055. {
  76056. LineSection& l = subPath.getReference (subPath.size() - 1);
  76057. float dx = l.rx2 - l.rx1;
  76058. float dy = l.ry2 - l.ry1;
  76059. const float len = juce_hypot (dx, dy);
  76060. if (len <= amountAtEnd && subPath.size() > 1)
  76061. {
  76062. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76063. prev.x2 = l.x2;
  76064. prev.y2 = l.y2;
  76065. subPath.removeLast();
  76066. amountAtEnd -= len;
  76067. }
  76068. else
  76069. {
  76070. const float prop = jmin (0.9999f, amountAtEnd / len);
  76071. dx *= prop;
  76072. dy *= prop;
  76073. l.rx1 += dx;
  76074. l.ry1 += dy;
  76075. l.lx2 += dx;
  76076. l.ly2 += dy;
  76077. break;
  76078. }
  76079. }
  76080. while (amountAtStart > 0 && subPath.size() > 0)
  76081. {
  76082. LineSection& l = subPath.getReference (0);
  76083. float dx = l.rx2 - l.rx1;
  76084. float dy = l.ry2 - l.ry1;
  76085. const float len = juce_hypot (dx, dy);
  76086. if (len <= amountAtStart && subPath.size() > 1)
  76087. {
  76088. LineSection& next = subPath.getReference (1);
  76089. next.x1 = l.x1;
  76090. next.y1 = l.y1;
  76091. subPath.remove (0);
  76092. amountAtStart -= len;
  76093. }
  76094. else
  76095. {
  76096. const float prop = jmin (0.9999f, amountAtStart / len);
  76097. dx *= prop;
  76098. dy *= prop;
  76099. l.rx2 -= dx;
  76100. l.ry2 -= dy;
  76101. l.lx1 -= dx;
  76102. l.ly1 -= dy;
  76103. break;
  76104. }
  76105. }
  76106. }
  76107. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76108. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76109. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76110. const Arrowhead* const arrowhead)
  76111. {
  76112. jassert (subPath.size() > 0);
  76113. if (arrowhead != 0)
  76114. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76115. const LineSection& firstLine = subPath.getReference (0);
  76116. float lastX1 = firstLine.lx1;
  76117. float lastY1 = firstLine.ly1;
  76118. float lastX2 = firstLine.lx2;
  76119. float lastY2 = firstLine.ly2;
  76120. if (isClosed)
  76121. {
  76122. destPath.startNewSubPath (lastX1, lastY1);
  76123. }
  76124. else
  76125. {
  76126. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76127. if (arrowhead != 0)
  76128. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76129. width, arrowhead->startWidth);
  76130. else
  76131. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76132. }
  76133. int i;
  76134. for (i = 1; i < subPath.size(); ++i)
  76135. {
  76136. const LineSection& l = subPath.getReference (i);
  76137. addEdgeAndJoint (destPath, jointStyle,
  76138. maxMiterExtensionSquared, width,
  76139. lastX1, lastY1, lastX2, lastY2,
  76140. l.lx1, l.ly1, l.lx2, l.ly2,
  76141. l.x1, l.y1);
  76142. lastX1 = l.lx1;
  76143. lastY1 = l.ly1;
  76144. lastX2 = l.lx2;
  76145. lastY2 = l.ly2;
  76146. }
  76147. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76148. if (isClosed)
  76149. {
  76150. const LineSection& l = subPath.getReference (0);
  76151. addEdgeAndJoint (destPath, jointStyle,
  76152. maxMiterExtensionSquared, width,
  76153. lastX1, lastY1, lastX2, lastY2,
  76154. l.lx1, l.ly1, l.lx2, l.ly2,
  76155. l.x1, l.y1);
  76156. destPath.closeSubPath();
  76157. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76158. }
  76159. else
  76160. {
  76161. destPath.lineTo (lastX2, lastY2);
  76162. if (arrowhead != 0)
  76163. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76164. width, arrowhead->endWidth);
  76165. else
  76166. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76167. }
  76168. lastX1 = lastLine.rx1;
  76169. lastY1 = lastLine.ry1;
  76170. lastX2 = lastLine.rx2;
  76171. lastY2 = lastLine.ry2;
  76172. for (i = subPath.size() - 1; --i >= 0;)
  76173. {
  76174. const LineSection& l = subPath.getReference (i);
  76175. addEdgeAndJoint (destPath, jointStyle,
  76176. maxMiterExtensionSquared, width,
  76177. lastX1, lastY1, lastX2, lastY2,
  76178. l.rx1, l.ry1, l.rx2, l.ry2,
  76179. l.x2, l.y2);
  76180. lastX1 = l.rx1;
  76181. lastY1 = l.ry1;
  76182. lastX2 = l.rx2;
  76183. lastY2 = l.ry2;
  76184. }
  76185. if (isClosed)
  76186. {
  76187. addEdgeAndJoint (destPath, jointStyle,
  76188. maxMiterExtensionSquared, width,
  76189. lastX1, lastY1, lastX2, lastY2,
  76190. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76191. lastLine.x2, lastLine.y2);
  76192. }
  76193. else
  76194. {
  76195. // do the last line
  76196. destPath.lineTo (lastX2, lastY2);
  76197. }
  76198. destPath.closeSubPath();
  76199. }
  76200. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76201. const PathStrokeType::EndCapStyle endStyle,
  76202. Path& destPath, const Path& source,
  76203. const AffineTransform& transform,
  76204. const float extraAccuracy, const Arrowhead* const arrowhead)
  76205. {
  76206. jassert (extraAccuracy > 0);
  76207. if (thickness <= 0)
  76208. {
  76209. destPath.clear();
  76210. return;
  76211. }
  76212. const Path* sourcePath = &source;
  76213. Path temp;
  76214. if (sourcePath == &destPath)
  76215. {
  76216. destPath.swapWithPath (temp);
  76217. sourcePath = &temp;
  76218. }
  76219. else
  76220. {
  76221. destPath.clear();
  76222. }
  76223. destPath.setUsingNonZeroWinding (true);
  76224. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76225. const float width = 0.5f * thickness;
  76226. // Iterate the path, creating a list of the
  76227. // left/right-hand lines along either side of it...
  76228. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76229. Array <LineSection> subPath;
  76230. subPath.ensureStorageAllocated (512);
  76231. LineSection l;
  76232. l.x1 = 0;
  76233. l.y1 = 0;
  76234. const float minSegmentLength = 0.0001f;
  76235. while (it.next())
  76236. {
  76237. if (it.subPathIndex == 0)
  76238. {
  76239. if (subPath.size() > 0)
  76240. {
  76241. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76242. subPath.clearQuick();
  76243. }
  76244. l.x1 = it.x1;
  76245. l.y1 = it.y1;
  76246. }
  76247. l.x2 = it.x2;
  76248. l.y2 = it.y2;
  76249. float dx = l.x2 - l.x1;
  76250. float dy = l.y2 - l.y1;
  76251. const float hypotSquared = dx*dx + dy*dy;
  76252. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76253. {
  76254. const float len = std::sqrt (hypotSquared);
  76255. if (len == 0)
  76256. {
  76257. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76258. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76259. }
  76260. else
  76261. {
  76262. const float offset = width / len;
  76263. dx *= offset;
  76264. dy *= offset;
  76265. l.rx2 = l.x1 - dy;
  76266. l.ry2 = l.y1 + dx;
  76267. l.lx1 = l.x1 + dy;
  76268. l.ly1 = l.y1 - dx;
  76269. l.lx2 = l.x2 + dy;
  76270. l.ly2 = l.y2 - dx;
  76271. l.rx1 = l.x2 - dy;
  76272. l.ry1 = l.y2 + dx;
  76273. }
  76274. subPath.add (l);
  76275. if (it.closesSubPath)
  76276. {
  76277. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76278. subPath.clearQuick();
  76279. }
  76280. else
  76281. {
  76282. l.x1 = it.x2;
  76283. l.y1 = it.y2;
  76284. }
  76285. }
  76286. }
  76287. if (subPath.size() > 0)
  76288. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76289. }
  76290. }
  76291. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76292. const AffineTransform& transform, const float extraAccuracy) const
  76293. {
  76294. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76295. transform, extraAccuracy, 0);
  76296. }
  76297. void PathStrokeType::createDashedStroke (Path& destPath,
  76298. const Path& sourcePath,
  76299. const float* dashLengths,
  76300. int numDashLengths,
  76301. const AffineTransform& transform,
  76302. const float extraAccuracy) const
  76303. {
  76304. jassert (extraAccuracy > 0);
  76305. if (thickness <= 0)
  76306. return;
  76307. // this should really be an even number..
  76308. jassert ((numDashLengths & 1) == 0);
  76309. Path newDestPath;
  76310. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76311. bool first = true;
  76312. int dashNum = 0;
  76313. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76314. float dx = 0.0f, dy = 0.0f;
  76315. for (;;)
  76316. {
  76317. const bool isSolid = ((dashNum & 1) == 0);
  76318. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76319. jassert (dashLen > 0); // must be a positive increment!
  76320. if (dashLen <= 0)
  76321. break;
  76322. pos += dashLen;
  76323. while (pos > lineEndPos)
  76324. {
  76325. if (! it.next())
  76326. {
  76327. if (isSolid && ! first)
  76328. newDestPath.lineTo (it.x2, it.y2);
  76329. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76330. return;
  76331. }
  76332. if (isSolid && ! first)
  76333. newDestPath.lineTo (it.x1, it.y1);
  76334. else
  76335. newDestPath.startNewSubPath (it.x1, it.y1);
  76336. dx = it.x2 - it.x1;
  76337. dy = it.y2 - it.y1;
  76338. lineLen = juce_hypot (dx, dy);
  76339. lineEndPos += lineLen;
  76340. first = it.closesSubPath;
  76341. }
  76342. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76343. if (isSolid)
  76344. newDestPath.lineTo (it.x1 + dx * alpha,
  76345. it.y1 + dy * alpha);
  76346. else
  76347. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76348. it.y1 + dy * alpha);
  76349. }
  76350. }
  76351. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76352. const Path& sourcePath,
  76353. const float arrowheadStartWidth, const float arrowheadStartLength,
  76354. const float arrowheadEndWidth, const float arrowheadEndLength,
  76355. const AffineTransform& transform,
  76356. const float extraAccuracy) const
  76357. {
  76358. PathStrokeHelpers::Arrowhead head;
  76359. head.startWidth = arrowheadStartWidth;
  76360. head.startLength = arrowheadStartLength;
  76361. head.endWidth = arrowheadEndWidth;
  76362. head.endLength = arrowheadEndLength;
  76363. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76364. destPath, sourcePath, transform, extraAccuracy, &head);
  76365. }
  76366. END_JUCE_NAMESPACE
  76367. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76368. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76369. BEGIN_JUCE_NAMESPACE
  76370. PositionedRectangle::PositionedRectangle() throw()
  76371. : x (0.0),
  76372. y (0.0),
  76373. w (0.0),
  76374. h (0.0),
  76375. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76376. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76377. wMode (absoluteSize),
  76378. hMode (absoluteSize)
  76379. {
  76380. }
  76381. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76382. : x (other.x),
  76383. y (other.y),
  76384. w (other.w),
  76385. h (other.h),
  76386. xMode (other.xMode),
  76387. yMode (other.yMode),
  76388. wMode (other.wMode),
  76389. hMode (other.hMode)
  76390. {
  76391. }
  76392. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76393. {
  76394. x = other.x;
  76395. y = other.y;
  76396. w = other.w;
  76397. h = other.h;
  76398. xMode = other.xMode;
  76399. yMode = other.yMode;
  76400. wMode = other.wMode;
  76401. hMode = other.hMode;
  76402. return *this;
  76403. }
  76404. PositionedRectangle::~PositionedRectangle() throw()
  76405. {
  76406. }
  76407. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76408. {
  76409. return x == other.x
  76410. && y == other.y
  76411. && w == other.w
  76412. && h == other.h
  76413. && xMode == other.xMode
  76414. && yMode == other.yMode
  76415. && wMode == other.wMode
  76416. && hMode == other.hMode;
  76417. }
  76418. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76419. {
  76420. return ! operator== (other);
  76421. }
  76422. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76423. {
  76424. StringArray tokens;
  76425. tokens.addTokens (stringVersion, false);
  76426. decodePosString (tokens [0], xMode, x);
  76427. decodePosString (tokens [1], yMode, y);
  76428. decodeSizeString (tokens [2], wMode, w);
  76429. decodeSizeString (tokens [3], hMode, h);
  76430. }
  76431. const String PositionedRectangle::toString() const throw()
  76432. {
  76433. String s;
  76434. s.preallocateStorage (12);
  76435. addPosDescription (s, xMode, x);
  76436. s << ' ';
  76437. addPosDescription (s, yMode, y);
  76438. s << ' ';
  76439. addSizeDescription (s, wMode, w);
  76440. s << ' ';
  76441. addSizeDescription (s, hMode, h);
  76442. return s;
  76443. }
  76444. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76445. {
  76446. jassert (! target.isEmpty());
  76447. double x_, y_, w_, h_;
  76448. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76449. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76450. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76451. roundToInt (w_), roundToInt (h_));
  76452. }
  76453. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76454. double& x_, double& y_,
  76455. double& w_, double& h_) const throw()
  76456. {
  76457. jassert (! target.isEmpty());
  76458. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76459. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76460. }
  76461. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76462. {
  76463. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76464. }
  76465. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76466. const Rectangle<int>& target) throw()
  76467. {
  76468. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76469. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76470. }
  76471. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76472. const double newW, const double newH,
  76473. const Rectangle<int>& target) throw()
  76474. {
  76475. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76476. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76477. }
  76478. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76479. {
  76480. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76481. updateFrom (comp.getBounds(), Rectangle<int>());
  76482. else
  76483. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76484. }
  76485. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76486. {
  76487. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76488. }
  76489. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76490. {
  76491. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76492. | absoluteFromParentBottomRight
  76493. | absoluteFromParentCentre
  76494. | proportionOfParentSize));
  76495. }
  76496. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76497. {
  76498. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76499. }
  76500. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76501. {
  76502. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76503. | absoluteFromParentBottomRight
  76504. | absoluteFromParentCentre
  76505. | proportionOfParentSize));
  76506. }
  76507. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76508. {
  76509. return (SizeMode) wMode;
  76510. }
  76511. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76512. {
  76513. return (SizeMode) hMode;
  76514. }
  76515. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76516. const PositionMode xMode_,
  76517. const AnchorPoint yAnchor,
  76518. const PositionMode yMode_,
  76519. const SizeMode widthMode,
  76520. const SizeMode heightMode,
  76521. const Rectangle<int>& target) throw()
  76522. {
  76523. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76524. {
  76525. double tx, tw;
  76526. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76527. xMode = (uint8) (xAnchor | xMode_);
  76528. wMode = (uint8) widthMode;
  76529. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76530. }
  76531. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76532. {
  76533. double ty, th;
  76534. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76535. yMode = (uint8) (yAnchor | yMode_);
  76536. hMode = (uint8) heightMode;
  76537. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76538. }
  76539. }
  76540. bool PositionedRectangle::isPositionAbsolute() const throw()
  76541. {
  76542. return xMode == absoluteFromParentTopLeft
  76543. && yMode == absoluteFromParentTopLeft
  76544. && wMode == absoluteSize
  76545. && hMode == absoluteSize;
  76546. }
  76547. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76548. {
  76549. if ((mode & proportionOfParentSize) != 0)
  76550. {
  76551. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76552. }
  76553. else
  76554. {
  76555. s << (roundToInt (value * 100.0) / 100.0);
  76556. if ((mode & absoluteFromParentBottomRight) != 0)
  76557. s << 'R';
  76558. else if ((mode & absoluteFromParentCentre) != 0)
  76559. s << 'C';
  76560. }
  76561. if ((mode & anchorAtRightOrBottom) != 0)
  76562. s << 'r';
  76563. else if ((mode & anchorAtCentre) != 0)
  76564. s << 'c';
  76565. }
  76566. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76567. {
  76568. if (mode == proportionalSize)
  76569. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76570. else if (mode == parentSizeMinusAbsolute)
  76571. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76572. else
  76573. s << (roundToInt (value * 100.0) / 100.0);
  76574. }
  76575. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76576. {
  76577. if (s.containsChar ('r'))
  76578. mode = anchorAtRightOrBottom;
  76579. else if (s.containsChar ('c'))
  76580. mode = anchorAtCentre;
  76581. else
  76582. mode = anchorAtLeftOrTop;
  76583. if (s.containsChar ('%'))
  76584. {
  76585. mode |= proportionOfParentSize;
  76586. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76587. }
  76588. else
  76589. {
  76590. if (s.containsChar ('R'))
  76591. mode |= absoluteFromParentBottomRight;
  76592. else if (s.containsChar ('C'))
  76593. mode |= absoluteFromParentCentre;
  76594. else
  76595. mode |= absoluteFromParentTopLeft;
  76596. value = s.removeCharacters ("rcRC").getDoubleValue();
  76597. }
  76598. }
  76599. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76600. {
  76601. if (s.containsChar ('%'))
  76602. {
  76603. mode = proportionalSize;
  76604. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76605. }
  76606. else if (s.containsChar ('M'))
  76607. {
  76608. mode = parentSizeMinusAbsolute;
  76609. value = s.getDoubleValue();
  76610. }
  76611. else
  76612. {
  76613. mode = absoluteSize;
  76614. value = s.getDoubleValue();
  76615. }
  76616. }
  76617. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76618. const double x_, const double w_,
  76619. const uint8 xMode_, const uint8 wMode_,
  76620. const int parentPos,
  76621. const int parentSize) const throw()
  76622. {
  76623. if (wMode_ == proportionalSize)
  76624. wOut = roundToInt (w_ * parentSize);
  76625. else if (wMode_ == parentSizeMinusAbsolute)
  76626. wOut = jmax (0, parentSize - roundToInt (w_));
  76627. else
  76628. wOut = roundToInt (w_);
  76629. if ((xMode_ & proportionOfParentSize) != 0)
  76630. xOut = parentPos + x_ * parentSize;
  76631. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76632. xOut = (parentPos + parentSize) - x_;
  76633. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76634. xOut = x_ + (parentPos + parentSize / 2);
  76635. else
  76636. xOut = x_ + parentPos;
  76637. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76638. xOut -= wOut;
  76639. else if ((xMode_ & anchorAtCentre) != 0)
  76640. xOut -= wOut / 2;
  76641. }
  76642. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76643. double x_, const double w_,
  76644. const uint8 xMode_, const uint8 wMode_,
  76645. const int parentPos,
  76646. const int parentSize) const throw()
  76647. {
  76648. if (wMode_ == proportionalSize)
  76649. {
  76650. if (parentSize > 0)
  76651. wOut = w_ / parentSize;
  76652. }
  76653. else if (wMode_ == parentSizeMinusAbsolute)
  76654. wOut = parentSize - w_;
  76655. else
  76656. wOut = w_;
  76657. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76658. x_ += w_;
  76659. else if ((xMode_ & anchorAtCentre) != 0)
  76660. x_ += w_ / 2;
  76661. if ((xMode_ & proportionOfParentSize) != 0)
  76662. {
  76663. if (parentSize > 0)
  76664. xOut = (x_ - parentPos) / parentSize;
  76665. }
  76666. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76667. xOut = (parentPos + parentSize) - x_;
  76668. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76669. xOut = x_ - (parentPos + parentSize / 2);
  76670. else
  76671. xOut = x_ - parentPos;
  76672. }
  76673. END_JUCE_NAMESPACE
  76674. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76675. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76676. BEGIN_JUCE_NAMESPACE
  76677. RectangleList::RectangleList() throw()
  76678. {
  76679. }
  76680. RectangleList::RectangleList (const Rectangle<int>& rect)
  76681. {
  76682. if (! rect.isEmpty())
  76683. rects.add (rect);
  76684. }
  76685. RectangleList::RectangleList (const RectangleList& other)
  76686. : rects (other.rects)
  76687. {
  76688. }
  76689. RectangleList& RectangleList::operator= (const RectangleList& other)
  76690. {
  76691. rects = other.rects;
  76692. return *this;
  76693. }
  76694. RectangleList::~RectangleList()
  76695. {
  76696. }
  76697. void RectangleList::clear()
  76698. {
  76699. rects.clearQuick();
  76700. }
  76701. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76702. {
  76703. if (isPositiveAndBelow (index, rects.size()))
  76704. return rects.getReference (index);
  76705. return Rectangle<int>();
  76706. }
  76707. bool RectangleList::isEmpty() const throw()
  76708. {
  76709. return rects.size() == 0;
  76710. }
  76711. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76712. : current (0),
  76713. owner (list),
  76714. index (list.rects.size())
  76715. {
  76716. }
  76717. RectangleList::Iterator::~Iterator()
  76718. {
  76719. }
  76720. bool RectangleList::Iterator::next() throw()
  76721. {
  76722. if (--index >= 0)
  76723. {
  76724. current = & (owner.rects.getReference (index));
  76725. return true;
  76726. }
  76727. return false;
  76728. }
  76729. void RectangleList::add (const Rectangle<int>& rect)
  76730. {
  76731. if (! rect.isEmpty())
  76732. {
  76733. if (rects.size() == 0)
  76734. {
  76735. rects.add (rect);
  76736. }
  76737. else
  76738. {
  76739. bool anyOverlaps = false;
  76740. int i;
  76741. for (i = rects.size(); --i >= 0;)
  76742. {
  76743. Rectangle<int>& ourRect = rects.getReference (i);
  76744. if (rect.intersects (ourRect))
  76745. {
  76746. if (rect.contains (ourRect))
  76747. rects.remove (i);
  76748. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76749. anyOverlaps = true;
  76750. }
  76751. }
  76752. if (anyOverlaps && rects.size() > 0)
  76753. {
  76754. RectangleList r (rect);
  76755. for (i = rects.size(); --i >= 0;)
  76756. {
  76757. const Rectangle<int>& ourRect = rects.getReference (i);
  76758. if (rect.intersects (ourRect))
  76759. {
  76760. r.subtract (ourRect);
  76761. if (r.rects.size() == 0)
  76762. return;
  76763. }
  76764. }
  76765. for (i = r.getNumRectangles(); --i >= 0;)
  76766. rects.add (r.rects.getReference (i));
  76767. }
  76768. else
  76769. {
  76770. rects.add (rect);
  76771. }
  76772. }
  76773. }
  76774. }
  76775. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76776. {
  76777. if (! rect.isEmpty())
  76778. rects.add (rect);
  76779. }
  76780. void RectangleList::add (const int x, const int y, const int w, const int h)
  76781. {
  76782. if (rects.size() == 0)
  76783. {
  76784. if (w > 0 && h > 0)
  76785. rects.add (Rectangle<int> (x, y, w, h));
  76786. }
  76787. else
  76788. {
  76789. add (Rectangle<int> (x, y, w, h));
  76790. }
  76791. }
  76792. void RectangleList::add (const RectangleList& other)
  76793. {
  76794. for (int i = 0; i < other.rects.size(); ++i)
  76795. add (other.rects.getReference (i));
  76796. }
  76797. void RectangleList::subtract (const Rectangle<int>& rect)
  76798. {
  76799. const int originalNumRects = rects.size();
  76800. if (originalNumRects > 0)
  76801. {
  76802. const int x1 = rect.x;
  76803. const int y1 = rect.y;
  76804. const int x2 = x1 + rect.w;
  76805. const int y2 = y1 + rect.h;
  76806. for (int i = getNumRectangles(); --i >= 0;)
  76807. {
  76808. Rectangle<int>& r = rects.getReference (i);
  76809. const int rx1 = r.x;
  76810. const int ry1 = r.y;
  76811. const int rx2 = rx1 + r.w;
  76812. const int ry2 = ry1 + r.h;
  76813. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76814. {
  76815. if (x1 > rx1 && x1 < rx2)
  76816. {
  76817. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76818. {
  76819. r.w = x1 - rx1;
  76820. }
  76821. else
  76822. {
  76823. r.x = x1;
  76824. r.w = rx2 - x1;
  76825. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76826. i += 2;
  76827. }
  76828. }
  76829. else if (x2 > rx1 && x2 < rx2)
  76830. {
  76831. r.x = x2;
  76832. r.w = rx2 - x2;
  76833. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76834. {
  76835. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76836. i += 2;
  76837. }
  76838. }
  76839. else if (y1 > ry1 && y1 < ry2)
  76840. {
  76841. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76842. {
  76843. r.h = y1 - ry1;
  76844. }
  76845. else
  76846. {
  76847. r.y = y1;
  76848. r.h = ry2 - y1;
  76849. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76850. i += 2;
  76851. }
  76852. }
  76853. else if (y2 > ry1 && y2 < ry2)
  76854. {
  76855. r.y = y2;
  76856. r.h = ry2 - y2;
  76857. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76858. {
  76859. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76860. i += 2;
  76861. }
  76862. }
  76863. else
  76864. {
  76865. rects.remove (i);
  76866. }
  76867. }
  76868. }
  76869. }
  76870. }
  76871. bool RectangleList::subtract (const RectangleList& otherList)
  76872. {
  76873. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76874. subtract (otherList.rects.getReference (i));
  76875. return rects.size() > 0;
  76876. }
  76877. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76878. {
  76879. bool notEmpty = false;
  76880. if (rect.isEmpty())
  76881. {
  76882. clear();
  76883. }
  76884. else
  76885. {
  76886. for (int i = rects.size(); --i >= 0;)
  76887. {
  76888. Rectangle<int>& r = rects.getReference (i);
  76889. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76890. rects.remove (i);
  76891. else
  76892. notEmpty = true;
  76893. }
  76894. }
  76895. return notEmpty;
  76896. }
  76897. bool RectangleList::clipTo (const RectangleList& other)
  76898. {
  76899. if (rects.size() == 0)
  76900. return false;
  76901. RectangleList result;
  76902. for (int j = 0; j < rects.size(); ++j)
  76903. {
  76904. const Rectangle<int>& rect = rects.getReference (j);
  76905. for (int i = other.rects.size(); --i >= 0;)
  76906. {
  76907. Rectangle<int> r (other.rects.getReference (i));
  76908. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76909. result.rects.add (r);
  76910. }
  76911. }
  76912. swapWith (result);
  76913. return ! isEmpty();
  76914. }
  76915. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76916. {
  76917. destRegion.clear();
  76918. if (! rect.isEmpty())
  76919. {
  76920. for (int i = rects.size(); --i >= 0;)
  76921. {
  76922. Rectangle<int> r (rects.getReference (i));
  76923. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76924. destRegion.rects.add (r);
  76925. }
  76926. }
  76927. return destRegion.rects.size() > 0;
  76928. }
  76929. void RectangleList::swapWith (RectangleList& otherList) throw()
  76930. {
  76931. rects.swapWithArray (otherList.rects);
  76932. }
  76933. void RectangleList::consolidate()
  76934. {
  76935. int i;
  76936. for (i = 0; i < getNumRectangles() - 1; ++i)
  76937. {
  76938. Rectangle<int>& r = rects.getReference (i);
  76939. const int rx1 = r.x;
  76940. const int ry1 = r.y;
  76941. const int rx2 = rx1 + r.w;
  76942. const int ry2 = ry1 + r.h;
  76943. for (int j = rects.size(); --j > i;)
  76944. {
  76945. Rectangle<int>& r2 = rects.getReference (j);
  76946. const int jrx1 = r2.x;
  76947. const int jry1 = r2.y;
  76948. const int jrx2 = jrx1 + r2.w;
  76949. const int jry2 = jry1 + r2.h;
  76950. // if the vertical edges of any blocks are touching and their horizontals don't
  76951. // line up, split them horizontally..
  76952. if (jrx1 == rx2 || jrx2 == rx1)
  76953. {
  76954. if (jry1 > ry1 && jry1 < ry2)
  76955. {
  76956. r.h = jry1 - ry1;
  76957. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76958. i = -1;
  76959. break;
  76960. }
  76961. if (jry2 > ry1 && jry2 < ry2)
  76962. {
  76963. r.h = jry2 - ry1;
  76964. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76965. i = -1;
  76966. break;
  76967. }
  76968. else if (ry1 > jry1 && ry1 < jry2)
  76969. {
  76970. r2.h = ry1 - jry1;
  76971. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76972. i = -1;
  76973. break;
  76974. }
  76975. else if (ry2 > jry1 && ry2 < jry2)
  76976. {
  76977. r2.h = ry2 - jry1;
  76978. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76979. i = -1;
  76980. break;
  76981. }
  76982. }
  76983. }
  76984. }
  76985. for (i = 0; i < rects.size() - 1; ++i)
  76986. {
  76987. Rectangle<int>& r = rects.getReference (i);
  76988. for (int j = rects.size(); --j > i;)
  76989. {
  76990. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76991. {
  76992. rects.remove (j);
  76993. i = -1;
  76994. break;
  76995. }
  76996. }
  76997. }
  76998. }
  76999. bool RectangleList::containsPoint (const int x, const int y) const throw()
  77000. {
  77001. for (int i = getNumRectangles(); --i >= 0;)
  77002. if (rects.getReference (i).contains (x, y))
  77003. return true;
  77004. return false;
  77005. }
  77006. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  77007. {
  77008. if (rects.size() > 1)
  77009. {
  77010. RectangleList r (rectangleToCheck);
  77011. for (int i = rects.size(); --i >= 0;)
  77012. {
  77013. r.subtract (rects.getReference (i));
  77014. if (r.rects.size() == 0)
  77015. return true;
  77016. }
  77017. }
  77018. else if (rects.size() > 0)
  77019. {
  77020. return rects.getReference (0).contains (rectangleToCheck);
  77021. }
  77022. return false;
  77023. }
  77024. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  77025. {
  77026. for (int i = rects.size(); --i >= 0;)
  77027. if (rects.getReference (i).intersects (rectangleToCheck))
  77028. return true;
  77029. return false;
  77030. }
  77031. bool RectangleList::intersects (const RectangleList& other) const throw()
  77032. {
  77033. for (int i = rects.size(); --i >= 0;)
  77034. if (other.intersectsRectangle (rects.getReference (i)))
  77035. return true;
  77036. return false;
  77037. }
  77038. const Rectangle<int> RectangleList::getBounds() const throw()
  77039. {
  77040. if (rects.size() <= 1)
  77041. {
  77042. if (rects.size() == 0)
  77043. return Rectangle<int>();
  77044. else
  77045. return rects.getReference (0);
  77046. }
  77047. else
  77048. {
  77049. const Rectangle<int>& r = rects.getReference (0);
  77050. int minX = r.x;
  77051. int minY = r.y;
  77052. int maxX = minX + r.w;
  77053. int maxY = minY + r.h;
  77054. for (int i = rects.size(); --i > 0;)
  77055. {
  77056. const Rectangle<int>& r2 = rects.getReference (i);
  77057. minX = jmin (minX, r2.x);
  77058. minY = jmin (minY, r2.y);
  77059. maxX = jmax (maxX, r2.getRight());
  77060. maxY = jmax (maxY, r2.getBottom());
  77061. }
  77062. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77063. }
  77064. }
  77065. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77066. {
  77067. for (int i = rects.size(); --i >= 0;)
  77068. {
  77069. Rectangle<int>& r = rects.getReference (i);
  77070. r.x += dx;
  77071. r.y += dy;
  77072. }
  77073. }
  77074. const Path RectangleList::toPath() const
  77075. {
  77076. Path p;
  77077. for (int i = rects.size(); --i >= 0;)
  77078. {
  77079. const Rectangle<int>& r = rects.getReference (i);
  77080. p.addRectangle ((float) r.x,
  77081. (float) r.y,
  77082. (float) r.w,
  77083. (float) r.h);
  77084. }
  77085. return p;
  77086. }
  77087. END_JUCE_NAMESPACE
  77088. /*** End of inlined file: juce_RectangleList.cpp ***/
  77089. /*** Start of inlined file: juce_Image.cpp ***/
  77090. BEGIN_JUCE_NAMESPACE
  77091. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77092. : format (format_), width (width_), height (height_)
  77093. {
  77094. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77095. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77096. }
  77097. Image::SharedImage::~SharedImage()
  77098. {
  77099. }
  77100. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  77101. {
  77102. return imageData + lineStride * y + pixelStride * x;
  77103. }
  77104. class SoftwareSharedImage : public Image::SharedImage
  77105. {
  77106. public:
  77107. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77108. : Image::SharedImage (format_, width_, height_)
  77109. {
  77110. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  77111. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  77112. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  77113. imageData = imageDataAllocated;
  77114. }
  77115. Image::ImageType getType() const
  77116. {
  77117. return Image::SoftwareImage;
  77118. }
  77119. LowLevelGraphicsContext* createLowLevelContext()
  77120. {
  77121. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77122. }
  77123. Image::SharedImage* clone()
  77124. {
  77125. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77126. memcpy (s->imageData, imageData, lineStride * height);
  77127. return s;
  77128. }
  77129. private:
  77130. HeapBlock<uint8> imageDataAllocated;
  77131. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  77132. };
  77133. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77134. {
  77135. return new SoftwareSharedImage (format, width, height, clearImage);
  77136. }
  77137. class SubsectionSharedImage : public Image::SharedImage
  77138. {
  77139. public:
  77140. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77141. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77142. image (image_), area (area_)
  77143. {
  77144. pixelStride = image_->getPixelStride();
  77145. lineStride = image_->getLineStride();
  77146. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77147. }
  77148. Image::ImageType getType() const
  77149. {
  77150. return Image::SoftwareImage;
  77151. }
  77152. LowLevelGraphicsContext* createLowLevelContext()
  77153. {
  77154. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77155. g->clipToRectangle (area);
  77156. g->setOrigin (area.getX(), area.getY());
  77157. return g;
  77158. }
  77159. Image::SharedImage* clone()
  77160. {
  77161. return new SubsectionSharedImage (image->clone(), area);
  77162. }
  77163. private:
  77164. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77165. const Rectangle<int> area;
  77166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  77167. };
  77168. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77169. {
  77170. if (area.contains (getBounds()))
  77171. return *this;
  77172. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77173. if (validArea.isEmpty())
  77174. return Image::null;
  77175. return Image (new SubsectionSharedImage (image, validArea));
  77176. }
  77177. Image::Image()
  77178. {
  77179. }
  77180. Image::Image (SharedImage* const instance)
  77181. : image (instance)
  77182. {
  77183. }
  77184. Image::Image (const PixelFormat format,
  77185. const int width, const int height,
  77186. const bool clearImage, const ImageType type)
  77187. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77188. : new SoftwareSharedImage (format, width, height, clearImage))
  77189. {
  77190. }
  77191. Image::Image (const Image& other)
  77192. : image (other.image)
  77193. {
  77194. }
  77195. Image& Image::operator= (const Image& other)
  77196. {
  77197. image = other.image;
  77198. return *this;
  77199. }
  77200. Image::~Image()
  77201. {
  77202. }
  77203. const Image Image::null;
  77204. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77205. {
  77206. return image == 0 ? 0 : image->createLowLevelContext();
  77207. }
  77208. void Image::duplicateIfShared()
  77209. {
  77210. if (image != 0 && image->getReferenceCount() > 1)
  77211. image = image->clone();
  77212. }
  77213. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77214. {
  77215. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77216. return *this;
  77217. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77218. Graphics g (newImage);
  77219. g.setImageResamplingQuality (quality);
  77220. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77221. return newImage;
  77222. }
  77223. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77224. {
  77225. if (image == 0 || newFormat == image->format)
  77226. return *this;
  77227. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77228. if (newFormat == SingleChannel)
  77229. {
  77230. if (! hasAlphaChannel())
  77231. {
  77232. newImage.clear (getBounds(), Colours::black);
  77233. }
  77234. else
  77235. {
  77236. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77237. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77238. for (int y = 0; y < image->height; ++y)
  77239. {
  77240. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77241. uint8* dst = destData.getLinePointer (y);
  77242. for (int x = image->width; --x >= 0;)
  77243. {
  77244. *dst++ = src->getAlpha();
  77245. ++src;
  77246. }
  77247. }
  77248. }
  77249. }
  77250. else
  77251. {
  77252. if (hasAlphaChannel())
  77253. newImage.clear (getBounds());
  77254. Graphics g (newImage);
  77255. g.drawImageAt (*this, 0, 0);
  77256. }
  77257. return newImage;
  77258. }
  77259. NamedValueSet* Image::getProperties() const
  77260. {
  77261. return image == 0 ? 0 : &(image->userData);
  77262. }
  77263. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77264. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77265. pixelFormat (image.getFormat()),
  77266. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77267. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77268. width (w),
  77269. height (h)
  77270. {
  77271. jassert (data != 0);
  77272. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77273. }
  77274. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77275. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77276. pixelFormat (image.getFormat()),
  77277. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77278. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77279. width (w),
  77280. height (h)
  77281. {
  77282. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77283. }
  77284. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77285. : data (image.image == 0 ? 0 : image.image->imageData),
  77286. pixelFormat (image.getFormat()),
  77287. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77288. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77289. width (image.getWidth()),
  77290. height (image.getHeight())
  77291. {
  77292. }
  77293. Image::BitmapData::~BitmapData()
  77294. {
  77295. }
  77296. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77297. {
  77298. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77299. const uint8* const pixel = getPixelPointer (x, y);
  77300. switch (pixelFormat)
  77301. {
  77302. case Image::ARGB:
  77303. {
  77304. PixelARGB p (*(const PixelARGB*) pixel);
  77305. p.unpremultiply();
  77306. return Colour (p.getARGB());
  77307. }
  77308. case Image::RGB:
  77309. return Colour (((const PixelRGB*) pixel)->getARGB());
  77310. case Image::SingleChannel:
  77311. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77312. default:
  77313. jassertfalse;
  77314. break;
  77315. }
  77316. return Colour();
  77317. }
  77318. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77319. {
  77320. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  77321. uint8* const pixel = getPixelPointer (x, y);
  77322. const PixelARGB col (colour.getPixelARGB());
  77323. switch (pixelFormat)
  77324. {
  77325. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77326. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77327. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77328. default: jassertfalse; break;
  77329. }
  77330. }
  77331. void Image::setPixelData (int x, int y, int w, int h,
  77332. const uint8* const sourcePixelData, const int sourceLineStride)
  77333. {
  77334. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77335. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77336. {
  77337. const BitmapData dest (*this, x, y, w, h, true);
  77338. for (int i = 0; i < h; ++i)
  77339. {
  77340. memcpy (dest.getLinePointer(i),
  77341. sourcePixelData + sourceLineStride * i,
  77342. w * dest.pixelStride);
  77343. }
  77344. }
  77345. }
  77346. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77347. {
  77348. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77349. if (! clipped.isEmpty())
  77350. {
  77351. const PixelARGB col (colourToClearTo.getPixelARGB());
  77352. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77353. uint8* dest = destData.data;
  77354. int dh = clipped.getHeight();
  77355. while (--dh >= 0)
  77356. {
  77357. uint8* line = dest;
  77358. dest += destData.lineStride;
  77359. if (isARGB())
  77360. {
  77361. for (int x = clipped.getWidth(); --x >= 0;)
  77362. {
  77363. ((PixelARGB*) line)->set (col);
  77364. line += destData.pixelStride;
  77365. }
  77366. }
  77367. else if (isRGB())
  77368. {
  77369. for (int x = clipped.getWidth(); --x >= 0;)
  77370. {
  77371. ((PixelRGB*) line)->set (col);
  77372. line += destData.pixelStride;
  77373. }
  77374. }
  77375. else
  77376. {
  77377. for (int x = clipped.getWidth(); --x >= 0;)
  77378. {
  77379. *line = col.getAlpha();
  77380. line += destData.pixelStride;
  77381. }
  77382. }
  77383. }
  77384. }
  77385. }
  77386. const Colour Image::getPixelAt (const int x, const int y) const
  77387. {
  77388. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77389. {
  77390. const BitmapData srcData (*this, x, y, 1, 1);
  77391. return srcData.getPixelColour (0, 0);
  77392. }
  77393. return Colour();
  77394. }
  77395. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77396. {
  77397. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  77398. {
  77399. const BitmapData destData (*this, x, y, 1, 1, true);
  77400. destData.setPixelColour (0, 0, colour);
  77401. }
  77402. }
  77403. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77404. {
  77405. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  77406. && hasAlphaChannel())
  77407. {
  77408. const BitmapData destData (*this, x, y, 1, 1, true);
  77409. if (isARGB())
  77410. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77411. else
  77412. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77413. }
  77414. }
  77415. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77416. {
  77417. if (hasAlphaChannel())
  77418. {
  77419. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77420. if (isARGB())
  77421. {
  77422. for (int y = 0; y < destData.height; ++y)
  77423. {
  77424. uint8* p = destData.getLinePointer (y);
  77425. for (int x = 0; x < destData.width; ++x)
  77426. {
  77427. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77428. p += destData.pixelStride;
  77429. }
  77430. }
  77431. }
  77432. else
  77433. {
  77434. for (int y = 0; y < destData.height; ++y)
  77435. {
  77436. uint8* p = destData.getLinePointer (y);
  77437. for (int x = 0; x < destData.width; ++x)
  77438. {
  77439. *p = (uint8) (*p * amountToMultiplyBy);
  77440. p += destData.pixelStride;
  77441. }
  77442. }
  77443. }
  77444. }
  77445. else
  77446. {
  77447. jassertfalse; // can't do this without an alpha-channel!
  77448. }
  77449. }
  77450. void Image::desaturate()
  77451. {
  77452. if (isARGB() || isRGB())
  77453. {
  77454. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77455. if (isARGB())
  77456. {
  77457. for (int y = 0; y < destData.height; ++y)
  77458. {
  77459. uint8* p = destData.getLinePointer (y);
  77460. for (int x = 0; x < destData.width; ++x)
  77461. {
  77462. ((PixelARGB*) p)->desaturate();
  77463. p += destData.pixelStride;
  77464. }
  77465. }
  77466. }
  77467. else
  77468. {
  77469. for (int y = 0; y < destData.height; ++y)
  77470. {
  77471. uint8* p = destData.getLinePointer (y);
  77472. for (int x = 0; x < destData.width; ++x)
  77473. {
  77474. ((PixelRGB*) p)->desaturate();
  77475. p += destData.pixelStride;
  77476. }
  77477. }
  77478. }
  77479. }
  77480. }
  77481. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77482. {
  77483. if (hasAlphaChannel())
  77484. {
  77485. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77486. SparseSet<int> pixelsOnRow;
  77487. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77488. for (int y = 0; y < srcData.height; ++y)
  77489. {
  77490. pixelsOnRow.clear();
  77491. const uint8* lineData = srcData.getLinePointer (y);
  77492. if (isARGB())
  77493. {
  77494. for (int x = 0; x < srcData.width; ++x)
  77495. {
  77496. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77497. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77498. lineData += srcData.pixelStride;
  77499. }
  77500. }
  77501. else
  77502. {
  77503. for (int x = 0; x < srcData.width; ++x)
  77504. {
  77505. if (*lineData >= threshold)
  77506. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77507. lineData += srcData.pixelStride;
  77508. }
  77509. }
  77510. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77511. {
  77512. const Range<int> range (pixelsOnRow.getRange (i));
  77513. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77514. }
  77515. result.consolidate();
  77516. }
  77517. }
  77518. else
  77519. {
  77520. result.add (0, 0, getWidth(), getHeight());
  77521. }
  77522. }
  77523. void Image::moveImageSection (int dx, int dy,
  77524. int sx, int sy,
  77525. int w, int h)
  77526. {
  77527. if (dx < 0)
  77528. {
  77529. w += dx;
  77530. sx -= dx;
  77531. dx = 0;
  77532. }
  77533. if (dy < 0)
  77534. {
  77535. h += dy;
  77536. sy -= dy;
  77537. dy = 0;
  77538. }
  77539. if (sx < 0)
  77540. {
  77541. w += sx;
  77542. dx -= sx;
  77543. sx = 0;
  77544. }
  77545. if (sy < 0)
  77546. {
  77547. h += sy;
  77548. dy -= sy;
  77549. sy = 0;
  77550. }
  77551. const int minX = jmin (dx, sx);
  77552. const int minY = jmin (dy, sy);
  77553. w = jmin (w, getWidth() - jmax (sx, dx));
  77554. h = jmin (h, getHeight() - jmax (sy, dy));
  77555. if (w > 0 && h > 0)
  77556. {
  77557. const int maxX = jmax (dx, sx) + w;
  77558. const int maxY = jmax (dy, sy) + h;
  77559. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77560. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77561. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77562. const int lineSize = destData.pixelStride * w;
  77563. if (dy > sy)
  77564. {
  77565. while (--h >= 0)
  77566. {
  77567. const int offset = h * destData.lineStride;
  77568. memmove (dst + offset, src + offset, lineSize);
  77569. }
  77570. }
  77571. else if (dst != src)
  77572. {
  77573. while (--h >= 0)
  77574. {
  77575. memmove (dst, src, lineSize);
  77576. dst += destData.lineStride;
  77577. src += destData.lineStride;
  77578. }
  77579. }
  77580. }
  77581. }
  77582. END_JUCE_NAMESPACE
  77583. /*** End of inlined file: juce_Image.cpp ***/
  77584. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77585. BEGIN_JUCE_NAMESPACE
  77586. class ImageCache::Pimpl : public Timer,
  77587. public DeletedAtShutdown
  77588. {
  77589. public:
  77590. Pimpl()
  77591. : cacheTimeout (5000)
  77592. {
  77593. }
  77594. ~Pimpl()
  77595. {
  77596. clearSingletonInstance();
  77597. }
  77598. const Image getFromHashCode (const int64 hashCode)
  77599. {
  77600. const ScopedLock sl (lock);
  77601. for (int i = images.size(); --i >= 0;)
  77602. {
  77603. Item* const item = images.getUnchecked(i);
  77604. if (item->hashCode == hashCode)
  77605. return item->image;
  77606. }
  77607. return Image::null;
  77608. }
  77609. void addImageToCache (const Image& image, const int64 hashCode)
  77610. {
  77611. if (image.isValid())
  77612. {
  77613. if (! isTimerRunning())
  77614. startTimer (2000);
  77615. Item* const item = new Item();
  77616. item->hashCode = hashCode;
  77617. item->image = image;
  77618. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77619. const ScopedLock sl (lock);
  77620. images.add (item);
  77621. }
  77622. }
  77623. void timerCallback()
  77624. {
  77625. const uint32 now = Time::getApproximateMillisecondCounter();
  77626. const ScopedLock sl (lock);
  77627. for (int i = images.size(); --i >= 0;)
  77628. {
  77629. Item* const item = images.getUnchecked(i);
  77630. if (item->image.getReferenceCount() <= 1)
  77631. {
  77632. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77633. images.remove (i);
  77634. }
  77635. else
  77636. {
  77637. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77638. }
  77639. }
  77640. if (images.size() == 0)
  77641. stopTimer();
  77642. }
  77643. struct Item
  77644. {
  77645. Image image;
  77646. int64 hashCode;
  77647. uint32 lastUseTime;
  77648. };
  77649. int cacheTimeout;
  77650. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77651. private:
  77652. OwnedArray<Item> images;
  77653. CriticalSection lock;
  77654. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77655. };
  77656. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77657. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77658. {
  77659. if (Pimpl::getInstanceWithoutCreating() != 0)
  77660. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77661. return Image::null;
  77662. }
  77663. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77664. {
  77665. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77666. }
  77667. const Image ImageCache::getFromFile (const File& file)
  77668. {
  77669. const int64 hashCode = file.hashCode64();
  77670. Image image (getFromHashCode (hashCode));
  77671. if (image.isNull())
  77672. {
  77673. image = ImageFileFormat::loadFrom (file);
  77674. addImageToCache (image, hashCode);
  77675. }
  77676. return image;
  77677. }
  77678. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77679. {
  77680. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77681. Image image (getFromHashCode (hashCode));
  77682. if (image.isNull())
  77683. {
  77684. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77685. addImageToCache (image, hashCode);
  77686. }
  77687. return image;
  77688. }
  77689. void ImageCache::setCacheTimeout (const int millisecs)
  77690. {
  77691. Pimpl::getInstance()->cacheTimeout = millisecs;
  77692. }
  77693. END_JUCE_NAMESPACE
  77694. /*** End of inlined file: juce_ImageCache.cpp ***/
  77695. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77696. BEGIN_JUCE_NAMESPACE
  77697. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77698. : values (size_ * size_),
  77699. size (size_)
  77700. {
  77701. clear();
  77702. }
  77703. ImageConvolutionKernel::~ImageConvolutionKernel()
  77704. {
  77705. }
  77706. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77707. {
  77708. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77709. return values [x + y * size];
  77710. jassertfalse;
  77711. return 0;
  77712. }
  77713. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77714. {
  77715. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77716. {
  77717. values [x + y * size] = value;
  77718. }
  77719. else
  77720. {
  77721. jassertfalse;
  77722. }
  77723. }
  77724. void ImageConvolutionKernel::clear()
  77725. {
  77726. for (int i = size * size; --i >= 0;)
  77727. values[i] = 0;
  77728. }
  77729. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77730. {
  77731. double currentTotal = 0.0;
  77732. for (int i = size * size; --i >= 0;)
  77733. currentTotal += values[i];
  77734. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77735. }
  77736. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77737. {
  77738. for (int i = size * size; --i >= 0;)
  77739. values[i] *= multiplier;
  77740. }
  77741. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77742. {
  77743. const double radiusFactor = -1.0 / (radius * radius * 2);
  77744. const int centre = size >> 1;
  77745. for (int y = size; --y >= 0;)
  77746. {
  77747. for (int x = size; --x >= 0;)
  77748. {
  77749. const int cx = x - centre;
  77750. const int cy = y - centre;
  77751. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77752. }
  77753. }
  77754. setOverallSum (1.0f);
  77755. }
  77756. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77757. const Image& sourceImage,
  77758. const Rectangle<int>& destinationArea) const
  77759. {
  77760. if (sourceImage == destImage)
  77761. {
  77762. destImage.duplicateIfShared();
  77763. }
  77764. else
  77765. {
  77766. if (sourceImage.getWidth() != destImage.getWidth()
  77767. || sourceImage.getHeight() != destImage.getHeight()
  77768. || sourceImage.getFormat() != destImage.getFormat())
  77769. {
  77770. jassertfalse;
  77771. return;
  77772. }
  77773. }
  77774. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77775. if (area.isEmpty())
  77776. return;
  77777. const int right = area.getRight();
  77778. const int bottom = area.getBottom();
  77779. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77780. uint8* line = destData.data;
  77781. const Image::BitmapData srcData (sourceImage, false);
  77782. if (destData.pixelStride == 4)
  77783. {
  77784. for (int y = area.getY(); y < bottom; ++y)
  77785. {
  77786. uint8* dest = line;
  77787. line += destData.lineStride;
  77788. for (int x = area.getX(); x < right; ++x)
  77789. {
  77790. float c1 = 0;
  77791. float c2 = 0;
  77792. float c3 = 0;
  77793. float c4 = 0;
  77794. for (int yy = 0; yy < size; ++yy)
  77795. {
  77796. const int sy = y + yy - (size >> 1);
  77797. if (sy >= srcData.height)
  77798. break;
  77799. if (sy >= 0)
  77800. {
  77801. int sx = x - (size >> 1);
  77802. const uint8* src = srcData.getPixelPointer (sx, sy);
  77803. for (int xx = 0; xx < size; ++xx)
  77804. {
  77805. if (sx >= srcData.width)
  77806. break;
  77807. if (sx >= 0)
  77808. {
  77809. const float kernelMult = values [xx + yy * size];
  77810. c1 += kernelMult * *src++;
  77811. c2 += kernelMult * *src++;
  77812. c3 += kernelMult * *src++;
  77813. c4 += kernelMult * *src++;
  77814. }
  77815. else
  77816. {
  77817. src += 4;
  77818. }
  77819. ++sx;
  77820. }
  77821. }
  77822. }
  77823. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77824. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77825. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77826. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77827. }
  77828. }
  77829. }
  77830. else if (destData.pixelStride == 3)
  77831. {
  77832. for (int y = area.getY(); y < bottom; ++y)
  77833. {
  77834. uint8* dest = line;
  77835. line += destData.lineStride;
  77836. for (int x = area.getX(); x < right; ++x)
  77837. {
  77838. float c1 = 0;
  77839. float c2 = 0;
  77840. float c3 = 0;
  77841. for (int yy = 0; yy < size; ++yy)
  77842. {
  77843. const int sy = y + yy - (size >> 1);
  77844. if (sy >= srcData.height)
  77845. break;
  77846. if (sy >= 0)
  77847. {
  77848. int sx = x - (size >> 1);
  77849. const uint8* src = srcData.getPixelPointer (sx, sy);
  77850. for (int xx = 0; xx < size; ++xx)
  77851. {
  77852. if (sx >= srcData.width)
  77853. break;
  77854. if (sx >= 0)
  77855. {
  77856. const float kernelMult = values [xx + yy * size];
  77857. c1 += kernelMult * *src++;
  77858. c2 += kernelMult * *src++;
  77859. c3 += kernelMult * *src++;
  77860. }
  77861. else
  77862. {
  77863. src += 3;
  77864. }
  77865. ++sx;
  77866. }
  77867. }
  77868. }
  77869. *dest++ = (uint8) roundToInt (c1);
  77870. *dest++ = (uint8) roundToInt (c2);
  77871. *dest++ = (uint8) roundToInt (c3);
  77872. }
  77873. }
  77874. }
  77875. }
  77876. END_JUCE_NAMESPACE
  77877. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77878. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77879. BEGIN_JUCE_NAMESPACE
  77880. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77881. {
  77882. static PNGImageFormat png;
  77883. static JPEGImageFormat jpg;
  77884. static GIFImageFormat gif;
  77885. ImageFileFormat* formats[4];
  77886. int numFormats = 0;
  77887. formats [numFormats++] = &png;
  77888. formats [numFormats++] = &jpg;
  77889. formats [numFormats++] = &gif;
  77890. const int64 streamPos = input.getPosition();
  77891. for (int i = 0; i < numFormats; ++i)
  77892. {
  77893. const bool found = formats[i]->canUnderstand (input);
  77894. input.setPosition (streamPos);
  77895. if (found)
  77896. return formats[i];
  77897. }
  77898. return 0;
  77899. }
  77900. const Image ImageFileFormat::loadFrom (InputStream& input)
  77901. {
  77902. ImageFileFormat* const format = findImageFormatForStream (input);
  77903. if (format != 0)
  77904. return format->decodeImage (input);
  77905. return Image::null;
  77906. }
  77907. const Image ImageFileFormat::loadFrom (const File& file)
  77908. {
  77909. InputStream* const in = file.createInputStream();
  77910. if (in != 0)
  77911. {
  77912. BufferedInputStream b (in, 8192, true);
  77913. return loadFrom (b);
  77914. }
  77915. return Image::null;
  77916. }
  77917. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77918. {
  77919. if (rawData != 0 && numBytes > 4)
  77920. {
  77921. MemoryInputStream stream (rawData, numBytes, false);
  77922. return loadFrom (stream);
  77923. }
  77924. return Image::null;
  77925. }
  77926. END_JUCE_NAMESPACE
  77927. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77928. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77929. BEGIN_JUCE_NAMESPACE
  77930. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77931. const Image juce_loadWithCoreImage (InputStream& input);
  77932. #else
  77933. class GIFLoader
  77934. {
  77935. public:
  77936. GIFLoader (InputStream& in)
  77937. : input (in),
  77938. dataBlockIsZero (false),
  77939. fresh (false),
  77940. finished (false)
  77941. {
  77942. currentBit = lastBit = lastByteIndex = 0;
  77943. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77944. firstcode = oldcode = 0;
  77945. clearCode = end_code = 0;
  77946. int imageWidth, imageHeight;
  77947. int transparent = -1;
  77948. if (! getSizeFromHeader (imageWidth, imageHeight))
  77949. return;
  77950. if ((imageWidth <= 0) || (imageHeight <= 0))
  77951. return;
  77952. unsigned char buf [16];
  77953. if (in.read (buf, 3) != 3)
  77954. return;
  77955. int numColours = 2 << (buf[0] & 7);
  77956. if ((buf[0] & 0x80) != 0)
  77957. readPalette (numColours);
  77958. for (;;)
  77959. {
  77960. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77961. break;
  77962. if (buf[0] == '!')
  77963. {
  77964. if (input.read (buf, 1) != 1)
  77965. break;
  77966. if (processExtension (buf[0], transparent) < 0)
  77967. break;
  77968. continue;
  77969. }
  77970. if (buf[0] != ',')
  77971. continue;
  77972. if (input.read (buf, 9) != 9)
  77973. break;
  77974. imageWidth = makeWord (buf[4], buf[5]);
  77975. imageHeight = makeWord (buf[6], buf[7]);
  77976. numColours = 2 << (buf[8] & 7);
  77977. if ((buf[8] & 0x80) != 0)
  77978. if (! readPalette (numColours))
  77979. break;
  77980. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77981. imageWidth, imageHeight, (transparent >= 0));
  77982. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77983. readImage ((buf[8] & 0x40) != 0, transparent);
  77984. break;
  77985. }
  77986. }
  77987. ~GIFLoader() {}
  77988. Image image;
  77989. private:
  77990. InputStream& input;
  77991. uint8 buffer [300];
  77992. uint8 palette [256][4];
  77993. bool dataBlockIsZero, fresh, finished;
  77994. int currentBit, lastBit, lastByteIndex;
  77995. int codeSize, setCodeSize;
  77996. int maxCode, maxCodeSize;
  77997. int firstcode, oldcode;
  77998. int clearCode, end_code;
  77999. enum { maxGifCode = 1 << 12 };
  78000. int table [2] [maxGifCode];
  78001. int stack [2 * maxGifCode];
  78002. int *sp;
  78003. bool getSizeFromHeader (int& w, int& h)
  78004. {
  78005. char b[8];
  78006. if (input.read (b, 6) == 6)
  78007. {
  78008. if ((strncmp ("GIF87a", b, 6) == 0)
  78009. || (strncmp ("GIF89a", b, 6) == 0))
  78010. {
  78011. if (input.read (b, 4) == 4)
  78012. {
  78013. w = makeWord (b[0], b[1]);
  78014. h = makeWord (b[2], b[3]);
  78015. return true;
  78016. }
  78017. }
  78018. }
  78019. return false;
  78020. }
  78021. bool readPalette (const int numCols)
  78022. {
  78023. unsigned char rgb[4];
  78024. for (int i = 0; i < numCols; ++i)
  78025. {
  78026. input.read (rgb, 3);
  78027. palette [i][0] = rgb[0];
  78028. palette [i][1] = rgb[1];
  78029. palette [i][2] = rgb[2];
  78030. palette [i][3] = 0xff;
  78031. }
  78032. return true;
  78033. }
  78034. int readDataBlock (unsigned char* dest)
  78035. {
  78036. unsigned char n;
  78037. if (input.read (&n, 1) == 1)
  78038. {
  78039. dataBlockIsZero = (n == 0);
  78040. if (dataBlockIsZero || (input.read (dest, n) == n))
  78041. return n;
  78042. }
  78043. return -1;
  78044. }
  78045. int processExtension (const int type, int& transparent)
  78046. {
  78047. unsigned char b [300];
  78048. int n = 0;
  78049. if (type == 0xf9)
  78050. {
  78051. n = readDataBlock (b);
  78052. if (n < 0)
  78053. return 1;
  78054. if ((b[0] & 0x1) != 0)
  78055. transparent = b[3];
  78056. }
  78057. do
  78058. {
  78059. n = readDataBlock (b);
  78060. }
  78061. while (n > 0);
  78062. return n;
  78063. }
  78064. int readLZWByte (const bool initialise, const int inputCodeSize)
  78065. {
  78066. int code, incode, i;
  78067. if (initialise)
  78068. {
  78069. setCodeSize = inputCodeSize;
  78070. codeSize = setCodeSize + 1;
  78071. clearCode = 1 << setCodeSize;
  78072. end_code = clearCode + 1;
  78073. maxCodeSize = 2 * clearCode;
  78074. maxCode = clearCode + 2;
  78075. getCode (0, true);
  78076. fresh = true;
  78077. for (i = 0; i < clearCode; ++i)
  78078. {
  78079. table[0][i] = 0;
  78080. table[1][i] = i;
  78081. }
  78082. for (; i < maxGifCode; ++i)
  78083. {
  78084. table[0][i] = 0;
  78085. table[1][i] = 0;
  78086. }
  78087. sp = stack;
  78088. return 0;
  78089. }
  78090. else if (fresh)
  78091. {
  78092. fresh = false;
  78093. do
  78094. {
  78095. firstcode = oldcode
  78096. = getCode (codeSize, false);
  78097. }
  78098. while (firstcode == clearCode);
  78099. return firstcode;
  78100. }
  78101. if (sp > stack)
  78102. return *--sp;
  78103. while ((code = getCode (codeSize, false)) >= 0)
  78104. {
  78105. if (code == clearCode)
  78106. {
  78107. for (i = 0; i < clearCode; ++i)
  78108. {
  78109. table[0][i] = 0;
  78110. table[1][i] = i;
  78111. }
  78112. for (; i < maxGifCode; ++i)
  78113. {
  78114. table[0][i] = 0;
  78115. table[1][i] = 0;
  78116. }
  78117. codeSize = setCodeSize + 1;
  78118. maxCodeSize = 2 * clearCode;
  78119. maxCode = clearCode + 2;
  78120. sp = stack;
  78121. firstcode = oldcode = getCode (codeSize, false);
  78122. return firstcode;
  78123. }
  78124. else if (code == end_code)
  78125. {
  78126. if (dataBlockIsZero)
  78127. return -2;
  78128. unsigned char buf [260];
  78129. int n;
  78130. while ((n = readDataBlock (buf)) > 0)
  78131. {}
  78132. if (n != 0)
  78133. return -2;
  78134. }
  78135. incode = code;
  78136. if (code >= maxCode)
  78137. {
  78138. *sp++ = firstcode;
  78139. code = oldcode;
  78140. }
  78141. while (code >= clearCode)
  78142. {
  78143. *sp++ = table[1][code];
  78144. if (code == table[0][code])
  78145. return -2;
  78146. code = table[0][code];
  78147. }
  78148. *sp++ = firstcode = table[1][code];
  78149. if ((code = maxCode) < maxGifCode)
  78150. {
  78151. table[0][code] = oldcode;
  78152. table[1][code] = firstcode;
  78153. ++maxCode;
  78154. if ((maxCode >= maxCodeSize)
  78155. && (maxCodeSize < maxGifCode))
  78156. {
  78157. maxCodeSize <<= 1;
  78158. ++codeSize;
  78159. }
  78160. }
  78161. oldcode = incode;
  78162. if (sp > stack)
  78163. return *--sp;
  78164. }
  78165. return code;
  78166. }
  78167. int getCode (const int codeSize_, const bool initialise)
  78168. {
  78169. if (initialise)
  78170. {
  78171. currentBit = 0;
  78172. lastBit = 0;
  78173. finished = false;
  78174. return 0;
  78175. }
  78176. if ((currentBit + codeSize_) >= lastBit)
  78177. {
  78178. if (finished)
  78179. return -1;
  78180. buffer[0] = buffer [lastByteIndex - 2];
  78181. buffer[1] = buffer [lastByteIndex - 1];
  78182. const int n = readDataBlock (&buffer[2]);
  78183. if (n == 0)
  78184. finished = true;
  78185. lastByteIndex = 2 + n;
  78186. currentBit = (currentBit - lastBit) + 16;
  78187. lastBit = (2 + n) * 8 ;
  78188. }
  78189. int result = 0;
  78190. int i = currentBit;
  78191. for (int j = 0; j < codeSize_; ++j)
  78192. {
  78193. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78194. ++i;
  78195. }
  78196. currentBit += codeSize_;
  78197. return result;
  78198. }
  78199. bool readImage (const int interlace, const int transparent)
  78200. {
  78201. unsigned char c;
  78202. if (input.read (&c, 1) != 1
  78203. || readLZWByte (true, c) < 0)
  78204. return false;
  78205. if (transparent >= 0)
  78206. {
  78207. palette [transparent][0] = 0;
  78208. palette [transparent][1] = 0;
  78209. palette [transparent][2] = 0;
  78210. palette [transparent][3] = 0;
  78211. }
  78212. int index;
  78213. int xpos = 0, ypos = 0, pass = 0;
  78214. const Image::BitmapData destData (image, true);
  78215. uint8* p = destData.data;
  78216. const bool hasAlpha = image.hasAlphaChannel();
  78217. while ((index = readLZWByte (false, c)) >= 0)
  78218. {
  78219. const uint8* const paletteEntry = palette [index];
  78220. if (hasAlpha)
  78221. {
  78222. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78223. paletteEntry[0],
  78224. paletteEntry[1],
  78225. paletteEntry[2]);
  78226. ((PixelARGB*) p)->premultiply();
  78227. }
  78228. else
  78229. {
  78230. ((PixelRGB*) p)->setARGB (0,
  78231. paletteEntry[0],
  78232. paletteEntry[1],
  78233. paletteEntry[2]);
  78234. }
  78235. p += destData.pixelStride;
  78236. ++xpos;
  78237. if (xpos == destData.width)
  78238. {
  78239. xpos = 0;
  78240. if (interlace)
  78241. {
  78242. switch (pass)
  78243. {
  78244. case 0:
  78245. case 1: ypos += 8; break;
  78246. case 2: ypos += 4; break;
  78247. case 3: ypos += 2; break;
  78248. }
  78249. while (ypos >= destData.height)
  78250. {
  78251. ++pass;
  78252. switch (pass)
  78253. {
  78254. case 1: ypos = 4; break;
  78255. case 2: ypos = 2; break;
  78256. case 3: ypos = 1; break;
  78257. default: return true;
  78258. }
  78259. }
  78260. }
  78261. else
  78262. {
  78263. ++ypos;
  78264. }
  78265. p = destData.getPixelPointer (xpos, ypos);
  78266. }
  78267. if (ypos >= destData.height)
  78268. break;
  78269. }
  78270. return true;
  78271. }
  78272. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78273. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  78274. };
  78275. #endif
  78276. GIFImageFormat::GIFImageFormat() {}
  78277. GIFImageFormat::~GIFImageFormat() {}
  78278. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78279. bool GIFImageFormat::canUnderstand (InputStream& in)
  78280. {
  78281. char header [4];
  78282. return (in.read (header, sizeof (header)) == sizeof (header))
  78283. && header[0] == 'G'
  78284. && header[1] == 'I'
  78285. && header[2] == 'F';
  78286. }
  78287. const Image GIFImageFormat::decodeImage (InputStream& in)
  78288. {
  78289. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78290. return juce_loadWithCoreImage (in);
  78291. #else
  78292. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78293. return loader->image;
  78294. #endif
  78295. }
  78296. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78297. {
  78298. jassertfalse; // writing isn't implemented for GIFs!
  78299. return false;
  78300. }
  78301. END_JUCE_NAMESPACE
  78302. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78303. #endif
  78304. //==============================================================================
  78305. // some files include lots of library code, so leave them to the end to avoid cluttering
  78306. // up the build for the clean files.
  78307. #if JUCE_BUILD_CORE
  78308. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78309. namespace zlibNamespace
  78310. {
  78311. #if JUCE_INCLUDE_ZLIB_CODE
  78312. #undef OS_CODE
  78313. #undef fdopen
  78314. /*** Start of inlined file: zlib.h ***/
  78315. #ifndef ZLIB_H
  78316. #define ZLIB_H
  78317. /*** Start of inlined file: zconf.h ***/
  78318. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78319. #ifndef ZCONF_H
  78320. #define ZCONF_H
  78321. // *** Just a few hacks here to make it compile nicely with Juce..
  78322. #define Z_PREFIX 1
  78323. #undef __MACTYPES__
  78324. #ifdef _MSC_VER
  78325. #pragma warning (disable : 4131 4127 4244 4267)
  78326. #endif
  78327. /*
  78328. * If you *really* need a unique prefix for all types and library functions,
  78329. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78330. */
  78331. #ifdef Z_PREFIX
  78332. # define deflateInit_ z_deflateInit_
  78333. # define deflate z_deflate
  78334. # define deflateEnd z_deflateEnd
  78335. # define inflateInit_ z_inflateInit_
  78336. # define inflate z_inflate
  78337. # define inflateEnd z_inflateEnd
  78338. # define inflatePrime z_inflatePrime
  78339. # define inflateGetHeader z_inflateGetHeader
  78340. # define adler32_combine z_adler32_combine
  78341. # define crc32_combine z_crc32_combine
  78342. # define deflateInit2_ z_deflateInit2_
  78343. # define deflateSetDictionary z_deflateSetDictionary
  78344. # define deflateCopy z_deflateCopy
  78345. # define deflateReset z_deflateReset
  78346. # define deflateParams z_deflateParams
  78347. # define deflateBound z_deflateBound
  78348. # define deflatePrime z_deflatePrime
  78349. # define inflateInit2_ z_inflateInit2_
  78350. # define inflateSetDictionary z_inflateSetDictionary
  78351. # define inflateSync z_inflateSync
  78352. # define inflateSyncPoint z_inflateSyncPoint
  78353. # define inflateCopy z_inflateCopy
  78354. # define inflateReset z_inflateReset
  78355. # define inflateBack z_inflateBack
  78356. # define inflateBackEnd z_inflateBackEnd
  78357. # define compress z_compress
  78358. # define compress2 z_compress2
  78359. # define compressBound z_compressBound
  78360. # define uncompress z_uncompress
  78361. # define adler32 z_adler32
  78362. # define crc32 z_crc32
  78363. # define get_crc_table z_get_crc_table
  78364. # define zError z_zError
  78365. # define alloc_func z_alloc_func
  78366. # define free_func z_free_func
  78367. # define in_func z_in_func
  78368. # define out_func z_out_func
  78369. # define Byte z_Byte
  78370. # define uInt z_uInt
  78371. # define uLong z_uLong
  78372. # define Bytef z_Bytef
  78373. # define charf z_charf
  78374. # define intf z_intf
  78375. # define uIntf z_uIntf
  78376. # define uLongf z_uLongf
  78377. # define voidpf z_voidpf
  78378. # define voidp z_voidp
  78379. #endif
  78380. #if defined(__MSDOS__) && !defined(MSDOS)
  78381. # define MSDOS
  78382. #endif
  78383. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78384. # define OS2
  78385. #endif
  78386. #if defined(_WINDOWS) && !defined(WINDOWS)
  78387. # define WINDOWS
  78388. #endif
  78389. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78390. # ifndef WIN32
  78391. # define WIN32
  78392. # endif
  78393. #endif
  78394. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78395. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78396. # ifndef SYS16BIT
  78397. # define SYS16BIT
  78398. # endif
  78399. # endif
  78400. #endif
  78401. /*
  78402. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78403. * than 64k bytes at a time (needed on systems with 16-bit int).
  78404. */
  78405. #ifdef SYS16BIT
  78406. # define MAXSEG_64K
  78407. #endif
  78408. #ifdef MSDOS
  78409. # define UNALIGNED_OK
  78410. #endif
  78411. #ifdef __STDC_VERSION__
  78412. # ifndef STDC
  78413. # define STDC
  78414. # endif
  78415. # if __STDC_VERSION__ >= 199901L
  78416. # ifndef STDC99
  78417. # define STDC99
  78418. # endif
  78419. # endif
  78420. #endif
  78421. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78422. # define STDC
  78423. #endif
  78424. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78425. # define STDC
  78426. #endif
  78427. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78428. # define STDC
  78429. #endif
  78430. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78431. # define STDC
  78432. #endif
  78433. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78434. # define STDC
  78435. #endif
  78436. #ifndef STDC
  78437. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78438. # define const /* note: need a more gentle solution here */
  78439. # endif
  78440. #endif
  78441. /* Some Mac compilers merge all .h files incorrectly: */
  78442. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78443. # define NO_DUMMY_DECL
  78444. #endif
  78445. /* Maximum value for memLevel in deflateInit2 */
  78446. #ifndef MAX_MEM_LEVEL
  78447. # ifdef MAXSEG_64K
  78448. # define MAX_MEM_LEVEL 8
  78449. # else
  78450. # define MAX_MEM_LEVEL 9
  78451. # endif
  78452. #endif
  78453. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78454. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78455. * created by gzip. (Files created by minigzip can still be extracted by
  78456. * gzip.)
  78457. */
  78458. #ifndef MAX_WBITS
  78459. # define MAX_WBITS 15 /* 32K LZ77 window */
  78460. #endif
  78461. /* The memory requirements for deflate are (in bytes):
  78462. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78463. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78464. plus a few kilobytes for small objects. For example, if you want to reduce
  78465. the default memory requirements from 256K to 128K, compile with
  78466. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78467. Of course this will generally degrade compression (there's no free lunch).
  78468. The memory requirements for inflate are (in bytes) 1 << windowBits
  78469. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78470. for small objects.
  78471. */
  78472. /* Type declarations */
  78473. #ifndef OF /* function prototypes */
  78474. # ifdef STDC
  78475. # define OF(args) args
  78476. # else
  78477. # define OF(args) ()
  78478. # endif
  78479. #endif
  78480. /* The following definitions for FAR are needed only for MSDOS mixed
  78481. * model programming (small or medium model with some far allocations).
  78482. * This was tested only with MSC; for other MSDOS compilers you may have
  78483. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78484. * just define FAR to be empty.
  78485. */
  78486. #ifdef SYS16BIT
  78487. # if defined(M_I86SM) || defined(M_I86MM)
  78488. /* MSC small or medium model */
  78489. # define SMALL_MEDIUM
  78490. # ifdef _MSC_VER
  78491. # define FAR _far
  78492. # else
  78493. # define FAR far
  78494. # endif
  78495. # endif
  78496. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78497. /* Turbo C small or medium model */
  78498. # define SMALL_MEDIUM
  78499. # ifdef __BORLANDC__
  78500. # define FAR _far
  78501. # else
  78502. # define FAR far
  78503. # endif
  78504. # endif
  78505. #endif
  78506. #if defined(WINDOWS) || defined(WIN32)
  78507. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78508. * This is not mandatory, but it offers a little performance increase.
  78509. */
  78510. # ifdef ZLIB_DLL
  78511. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78512. # ifdef ZLIB_INTERNAL
  78513. # define ZEXTERN extern __declspec(dllexport)
  78514. # else
  78515. # define ZEXTERN extern __declspec(dllimport)
  78516. # endif
  78517. # endif
  78518. # endif /* ZLIB_DLL */
  78519. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78520. * define ZLIB_WINAPI.
  78521. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78522. */
  78523. # ifdef ZLIB_WINAPI
  78524. # ifdef FAR
  78525. # undef FAR
  78526. # endif
  78527. # include <windows.h>
  78528. /* No need for _export, use ZLIB.DEF instead. */
  78529. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78530. # define ZEXPORT WINAPI
  78531. # ifdef WIN32
  78532. # define ZEXPORTVA WINAPIV
  78533. # else
  78534. # define ZEXPORTVA FAR CDECL
  78535. # endif
  78536. # endif
  78537. #endif
  78538. #if defined (__BEOS__)
  78539. # ifdef ZLIB_DLL
  78540. # ifdef ZLIB_INTERNAL
  78541. # define ZEXPORT __declspec(dllexport)
  78542. # define ZEXPORTVA __declspec(dllexport)
  78543. # else
  78544. # define ZEXPORT __declspec(dllimport)
  78545. # define ZEXPORTVA __declspec(dllimport)
  78546. # endif
  78547. # endif
  78548. #endif
  78549. #ifndef ZEXTERN
  78550. # define ZEXTERN extern
  78551. #endif
  78552. #ifndef ZEXPORT
  78553. # define ZEXPORT
  78554. #endif
  78555. #ifndef ZEXPORTVA
  78556. # define ZEXPORTVA
  78557. #endif
  78558. #ifndef FAR
  78559. # define FAR
  78560. #endif
  78561. #if !defined(__MACTYPES__)
  78562. typedef unsigned char Byte; /* 8 bits */
  78563. #endif
  78564. typedef unsigned int uInt; /* 16 bits or more */
  78565. typedef unsigned long uLong; /* 32 bits or more */
  78566. #ifdef SMALL_MEDIUM
  78567. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78568. # define Bytef Byte FAR
  78569. #else
  78570. typedef Byte FAR Bytef;
  78571. #endif
  78572. typedef char FAR charf;
  78573. typedef int FAR intf;
  78574. typedef uInt FAR uIntf;
  78575. typedef uLong FAR uLongf;
  78576. #ifdef STDC
  78577. typedef void const *voidpc;
  78578. typedef void FAR *voidpf;
  78579. typedef void *voidp;
  78580. #else
  78581. typedef Byte const *voidpc;
  78582. typedef Byte FAR *voidpf;
  78583. typedef Byte *voidp;
  78584. #endif
  78585. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78586. # include <sys/types.h> /* for off_t */
  78587. # include <unistd.h> /* for SEEK_* and off_t */
  78588. # ifdef VMS
  78589. # include <unixio.h> /* for off_t */
  78590. # endif
  78591. # define z_off_t off_t
  78592. #endif
  78593. #ifndef SEEK_SET
  78594. # define SEEK_SET 0 /* Seek from beginning of file. */
  78595. # define SEEK_CUR 1 /* Seek from current position. */
  78596. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78597. #endif
  78598. #ifndef z_off_t
  78599. # define z_off_t long
  78600. #endif
  78601. #if defined(__OS400__)
  78602. # define NO_vsnprintf
  78603. #endif
  78604. #if defined(__MVS__)
  78605. # define NO_vsnprintf
  78606. # ifdef FAR
  78607. # undef FAR
  78608. # endif
  78609. #endif
  78610. /* MVS linker does not support external names larger than 8 bytes */
  78611. #if defined(__MVS__)
  78612. # pragma map(deflateInit_,"DEIN")
  78613. # pragma map(deflateInit2_,"DEIN2")
  78614. # pragma map(deflateEnd,"DEEND")
  78615. # pragma map(deflateBound,"DEBND")
  78616. # pragma map(inflateInit_,"ININ")
  78617. # pragma map(inflateInit2_,"ININ2")
  78618. # pragma map(inflateEnd,"INEND")
  78619. # pragma map(inflateSync,"INSY")
  78620. # pragma map(inflateSetDictionary,"INSEDI")
  78621. # pragma map(compressBound,"CMBND")
  78622. # pragma map(inflate_table,"INTABL")
  78623. # pragma map(inflate_fast,"INFA")
  78624. # pragma map(inflate_copyright,"INCOPY")
  78625. #endif
  78626. #endif /* ZCONF_H */
  78627. /*** End of inlined file: zconf.h ***/
  78628. #ifdef __cplusplus
  78629. //extern "C" {
  78630. #endif
  78631. #define ZLIB_VERSION "1.2.3"
  78632. #define ZLIB_VERNUM 0x1230
  78633. /*
  78634. The 'zlib' compression library provides in-memory compression and
  78635. decompression functions, including integrity checks of the uncompressed
  78636. data. This version of the library supports only one compression method
  78637. (deflation) but other algorithms will be added later and will have the same
  78638. stream interface.
  78639. Compression can be done in a single step if the buffers are large
  78640. enough (for example if an input file is mmap'ed), or can be done by
  78641. repeated calls of the compression function. In the latter case, the
  78642. application must provide more input and/or consume the output
  78643. (providing more output space) before each call.
  78644. The compressed data format used by default by the in-memory functions is
  78645. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78646. around a deflate stream, which is itself documented in RFC 1951.
  78647. The library also supports reading and writing files in gzip (.gz) format
  78648. with an interface similar to that of stdio using the functions that start
  78649. with "gz". The gzip format is different from the zlib format. gzip is a
  78650. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78651. This library can optionally read and write gzip streams in memory as well.
  78652. The zlib format was designed to be compact and fast for use in memory
  78653. and on communications channels. The gzip format was designed for single-
  78654. file compression on file systems, has a larger header than zlib to maintain
  78655. directory information, and uses a different, slower check method than zlib.
  78656. The library does not install any signal handler. The decoder checks
  78657. the consistency of the compressed data, so the library should never
  78658. crash even in case of corrupted input.
  78659. */
  78660. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78661. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78662. struct internal_state;
  78663. typedef struct z_stream_s {
  78664. Bytef *next_in; /* next input byte */
  78665. uInt avail_in; /* number of bytes available at next_in */
  78666. uLong total_in; /* total nb of input bytes read so far */
  78667. Bytef *next_out; /* next output byte should be put there */
  78668. uInt avail_out; /* remaining free space at next_out */
  78669. uLong total_out; /* total nb of bytes output so far */
  78670. char *msg; /* last error message, NULL if no error */
  78671. struct internal_state FAR *state; /* not visible by applications */
  78672. alloc_func zalloc; /* used to allocate the internal state */
  78673. free_func zfree; /* used to free the internal state */
  78674. voidpf opaque; /* private data object passed to zalloc and zfree */
  78675. int data_type; /* best guess about the data type: binary or text */
  78676. uLong adler; /* adler32 value of the uncompressed data */
  78677. uLong reserved; /* reserved for future use */
  78678. } z_stream;
  78679. typedef z_stream FAR *z_streamp;
  78680. /*
  78681. gzip header information passed to and from zlib routines. See RFC 1952
  78682. for more details on the meanings of these fields.
  78683. */
  78684. typedef struct gz_header_s {
  78685. int text; /* true if compressed data believed to be text */
  78686. uLong time; /* modification time */
  78687. int xflags; /* extra flags (not used when writing a gzip file) */
  78688. int os; /* operating system */
  78689. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78690. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78691. uInt extra_max; /* space at extra (only when reading header) */
  78692. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78693. uInt name_max; /* space at name (only when reading header) */
  78694. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78695. uInt comm_max; /* space at comment (only when reading header) */
  78696. int hcrc; /* true if there was or will be a header crc */
  78697. int done; /* true when done reading gzip header (not used
  78698. when writing a gzip file) */
  78699. } gz_header;
  78700. typedef gz_header FAR *gz_headerp;
  78701. /*
  78702. The application must update next_in and avail_in when avail_in has
  78703. dropped to zero. It must update next_out and avail_out when avail_out
  78704. has dropped to zero. The application must initialize zalloc, zfree and
  78705. opaque before calling the init function. All other fields are set by the
  78706. compression library and must not be updated by the application.
  78707. The opaque value provided by the application will be passed as the first
  78708. parameter for calls of zalloc and zfree. This can be useful for custom
  78709. memory management. The compression library attaches no meaning to the
  78710. opaque value.
  78711. zalloc must return Z_NULL if there is not enough memory for the object.
  78712. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78713. thread safe.
  78714. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78715. exactly 65536 bytes, but will not be required to allocate more than this
  78716. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78717. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78718. have their offset normalized to zero. The default allocation function
  78719. provided by this library ensures this (see zutil.c). To reduce memory
  78720. requirements and avoid any allocation of 64K objects, at the expense of
  78721. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78722. The fields total_in and total_out can be used for statistics or
  78723. progress reports. After compression, total_in holds the total size of
  78724. the uncompressed data and may be saved for use in the decompressor
  78725. (particularly if the decompressor wants to decompress everything in
  78726. a single step).
  78727. */
  78728. /* constants */
  78729. #define Z_NO_FLUSH 0
  78730. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78731. #define Z_SYNC_FLUSH 2
  78732. #define Z_FULL_FLUSH 3
  78733. #define Z_FINISH 4
  78734. #define Z_BLOCK 5
  78735. /* Allowed flush values; see deflate() and inflate() below for details */
  78736. #define Z_OK 0
  78737. #define Z_STREAM_END 1
  78738. #define Z_NEED_DICT 2
  78739. #define Z_ERRNO (-1)
  78740. #define Z_STREAM_ERROR (-2)
  78741. #define Z_DATA_ERROR (-3)
  78742. #define Z_MEM_ERROR (-4)
  78743. #define Z_BUF_ERROR (-5)
  78744. #define Z_VERSION_ERROR (-6)
  78745. /* Return codes for the compression/decompression functions. Negative
  78746. * values are errors, positive values are used for special but normal events.
  78747. */
  78748. #define Z_NO_COMPRESSION 0
  78749. #define Z_BEST_SPEED 1
  78750. #define Z_BEST_COMPRESSION 9
  78751. #define Z_DEFAULT_COMPRESSION (-1)
  78752. /* compression levels */
  78753. #define Z_FILTERED 1
  78754. #define Z_HUFFMAN_ONLY 2
  78755. #define Z_RLE 3
  78756. #define Z_FIXED 4
  78757. #define Z_DEFAULT_STRATEGY 0
  78758. /* compression strategy; see deflateInit2() below for details */
  78759. #define Z_BINARY 0
  78760. #define Z_TEXT 1
  78761. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78762. #define Z_UNKNOWN 2
  78763. /* Possible values of the data_type field (though see inflate()) */
  78764. #define Z_DEFLATED 8
  78765. /* The deflate compression method (the only one supported in this version) */
  78766. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78767. #define zlib_version zlibVersion()
  78768. /* for compatibility with versions < 1.0.2 */
  78769. /* basic functions */
  78770. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78771. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78772. If the first character differs, the library code actually used is
  78773. not compatible with the zlib.h header file used by the application.
  78774. This check is automatically made by deflateInit and inflateInit.
  78775. */
  78776. /*
  78777. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78778. Initializes the internal stream state for compression. The fields
  78779. zalloc, zfree and opaque must be initialized before by the caller.
  78780. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78781. use default allocation functions.
  78782. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78783. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78784. all (the input data is simply copied a block at a time).
  78785. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78786. compression (currently equivalent to level 6).
  78787. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78788. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78789. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78790. with the version assumed by the caller (ZLIB_VERSION).
  78791. msg is set to null if there is no error message. deflateInit does not
  78792. perform any compression: this will be done by deflate().
  78793. */
  78794. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78795. /*
  78796. deflate compresses as much data as possible, and stops when the input
  78797. buffer becomes empty or the output buffer becomes full. It may introduce some
  78798. output latency (reading input without producing any output) except when
  78799. forced to flush.
  78800. The detailed semantics are as follows. deflate performs one or both of the
  78801. following actions:
  78802. - Compress more input starting at next_in and update next_in and avail_in
  78803. accordingly. If not all input can be processed (because there is not
  78804. enough room in the output buffer), next_in and avail_in are updated and
  78805. processing will resume at this point for the next call of deflate().
  78806. - Provide more output starting at next_out and update next_out and avail_out
  78807. accordingly. This action is forced if the parameter flush is non zero.
  78808. Forcing flush frequently degrades the compression ratio, so this parameter
  78809. should be set only when necessary (in interactive applications).
  78810. Some output may be provided even if flush is not set.
  78811. Before the call of deflate(), the application should ensure that at least
  78812. one of the actions is possible, by providing more input and/or consuming
  78813. more output, and updating avail_in or avail_out accordingly; avail_out
  78814. should never be zero before the call. The application can consume the
  78815. compressed output when it wants, for example when the output buffer is full
  78816. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78817. and with zero avail_out, it must be called again after making room in the
  78818. output buffer because there might be more output pending.
  78819. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78820. decide how much data to accumualte before producing output, in order to
  78821. maximize compression.
  78822. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78823. flushed to the output buffer and the output is aligned on a byte boundary, so
  78824. that the decompressor can get all input data available so far. (In particular
  78825. avail_in is zero after the call if enough output space has been provided
  78826. before the call.) Flushing may degrade compression for some compression
  78827. algorithms and so it should be used only when necessary.
  78828. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78829. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78830. restart from this point if previous compressed data has been damaged or if
  78831. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78832. compression.
  78833. If deflate returns with avail_out == 0, this function must be called again
  78834. with the same value of the flush parameter and more output space (updated
  78835. avail_out), until the flush is complete (deflate returns with non-zero
  78836. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78837. avail_out is greater than six to avoid repeated flush markers due to
  78838. avail_out == 0 on return.
  78839. If the parameter flush is set to Z_FINISH, pending input is processed,
  78840. pending output is flushed and deflate returns with Z_STREAM_END if there
  78841. was enough output space; if deflate returns with Z_OK, this function must be
  78842. called again with Z_FINISH and more output space (updated avail_out) but no
  78843. more input data, until it returns with Z_STREAM_END or an error. After
  78844. deflate has returned Z_STREAM_END, the only possible operations on the
  78845. stream are deflateReset or deflateEnd.
  78846. Z_FINISH can be used immediately after deflateInit if all the compression
  78847. is to be done in a single step. In this case, avail_out must be at least
  78848. the value returned by deflateBound (see below). If deflate does not return
  78849. Z_STREAM_END, then it must be called again as described above.
  78850. deflate() sets strm->adler to the adler32 checksum of all input read
  78851. so far (that is, total_in bytes).
  78852. deflate() may update strm->data_type if it can make a good guess about
  78853. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78854. binary. This field is only for information purposes and does not affect
  78855. the compression algorithm in any manner.
  78856. deflate() returns Z_OK if some progress has been made (more input
  78857. processed or more output produced), Z_STREAM_END if all input has been
  78858. consumed and all output has been produced (only when flush is set to
  78859. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78860. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78861. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78862. fatal, and deflate() can be called again with more input and more output
  78863. space to continue compressing.
  78864. */
  78865. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78866. /*
  78867. All dynamically allocated data structures for this stream are freed.
  78868. This function discards any unprocessed input and does not flush any
  78869. pending output.
  78870. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78871. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78872. prematurely (some input or output was discarded). In the error case,
  78873. msg may be set but then points to a static string (which must not be
  78874. deallocated).
  78875. */
  78876. /*
  78877. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78878. Initializes the internal stream state for decompression. The fields
  78879. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78880. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78881. value depends on the compression method), inflateInit determines the
  78882. compression method from the zlib header and allocates all data structures
  78883. accordingly; otherwise the allocation will be deferred to the first call of
  78884. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78885. use default allocation functions.
  78886. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78887. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78888. version assumed by the caller. msg is set to null if there is no error
  78889. message. inflateInit does not perform any decompression apart from reading
  78890. the zlib header if present: this will be done by inflate(). (So next_in and
  78891. avail_in may be modified, but next_out and avail_out are unchanged.)
  78892. */
  78893. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78894. /*
  78895. inflate decompresses as much data as possible, and stops when the input
  78896. buffer becomes empty or the output buffer becomes full. It may introduce
  78897. some output latency (reading input without producing any output) except when
  78898. forced to flush.
  78899. The detailed semantics are as follows. inflate performs one or both of the
  78900. following actions:
  78901. - Decompress more input starting at next_in and update next_in and avail_in
  78902. accordingly. If not all input can be processed (because there is not
  78903. enough room in the output buffer), next_in is updated and processing
  78904. will resume at this point for the next call of inflate().
  78905. - Provide more output starting at next_out and update next_out and avail_out
  78906. accordingly. inflate() provides as much output as possible, until there
  78907. is no more input data or no more space in the output buffer (see below
  78908. about the flush parameter).
  78909. Before the call of inflate(), the application should ensure that at least
  78910. one of the actions is possible, by providing more input and/or consuming
  78911. more output, and updating the next_* and avail_* values accordingly.
  78912. The application can consume the uncompressed output when it wants, for
  78913. example when the output buffer is full (avail_out == 0), or after each
  78914. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78915. must be called again after making room in the output buffer because there
  78916. might be more output pending.
  78917. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78918. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78919. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78920. if and when it gets to the next deflate block boundary. When decoding the
  78921. zlib or gzip format, this will cause inflate() to return immediately after
  78922. the header and before the first block. When doing a raw inflate, inflate()
  78923. will go ahead and process the first block, and will return when it gets to
  78924. the end of that block, or when it runs out of data.
  78925. The Z_BLOCK option assists in appending to or combining deflate streams.
  78926. Also to assist in this, on return inflate() will set strm->data_type to the
  78927. number of unused bits in the last byte taken from strm->next_in, plus 64
  78928. if inflate() is currently decoding the last block in the deflate stream,
  78929. plus 128 if inflate() returned immediately after decoding an end-of-block
  78930. code or decoding the complete header up to just before the first byte of the
  78931. deflate stream. The end-of-block will not be indicated until all of the
  78932. uncompressed data from that block has been written to strm->next_out. The
  78933. number of unused bits may in general be greater than seven, except when
  78934. bit 7 of data_type is set, in which case the number of unused bits will be
  78935. less than eight.
  78936. inflate() should normally be called until it returns Z_STREAM_END or an
  78937. error. However if all decompression is to be performed in a single step
  78938. (a single call of inflate), the parameter flush should be set to
  78939. Z_FINISH. In this case all pending input is processed and all pending
  78940. output is flushed; avail_out must be large enough to hold all the
  78941. uncompressed data. (The size of the uncompressed data may have been saved
  78942. by the compressor for this purpose.) The next operation on this stream must
  78943. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78944. is never required, but can be used to inform inflate that a faster approach
  78945. may be used for the single inflate() call.
  78946. In this implementation, inflate() always flushes as much output as
  78947. possible to the output buffer, and always uses the faster approach on the
  78948. first call. So the only effect of the flush parameter in this implementation
  78949. is on the return value of inflate(), as noted below, or when it returns early
  78950. because Z_BLOCK is used.
  78951. If a preset dictionary is needed after this call (see inflateSetDictionary
  78952. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78953. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78954. strm->adler to the adler32 checksum of all output produced so far (that is,
  78955. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78956. below. At the end of the stream, inflate() checks that its computed adler32
  78957. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78958. only if the checksum is correct.
  78959. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78960. deflate data. The header type is detected automatically. Any information
  78961. contained in the gzip header is not retained, so applications that need that
  78962. information should instead use raw inflate, see inflateInit2() below, or
  78963. inflateBack() and perform their own processing of the gzip header and
  78964. trailer.
  78965. inflate() returns Z_OK if some progress has been made (more input processed
  78966. or more output produced), Z_STREAM_END if the end of the compressed data has
  78967. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78968. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78969. corrupted (input stream not conforming to the zlib format or incorrect check
  78970. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78971. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78972. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78973. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78974. inflate() can be called again with more input and more output space to
  78975. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78976. call inflateSync() to look for a good compression block if a partial recovery
  78977. of the data is desired.
  78978. */
  78979. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78980. /*
  78981. All dynamically allocated data structures for this stream are freed.
  78982. This function discards any unprocessed input and does not flush any
  78983. pending output.
  78984. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78985. was inconsistent. In the error case, msg may be set but then points to a
  78986. static string (which must not be deallocated).
  78987. */
  78988. /* Advanced functions */
  78989. /*
  78990. The following functions are needed only in some special applications.
  78991. */
  78992. /*
  78993. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78994. int level,
  78995. int method,
  78996. int windowBits,
  78997. int memLevel,
  78998. int strategy));
  78999. This is another version of deflateInit with more compression options. The
  79000. fields next_in, zalloc, zfree and opaque must be initialized before by
  79001. the caller.
  79002. The method parameter is the compression method. It must be Z_DEFLATED in
  79003. this version of the library.
  79004. The windowBits parameter is the base two logarithm of the window size
  79005. (the size of the history buffer). It should be in the range 8..15 for this
  79006. version of the library. Larger values of this parameter result in better
  79007. compression at the expense of memory usage. The default value is 15 if
  79008. deflateInit is used instead.
  79009. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  79010. determines the window size. deflate() will then generate raw deflate data
  79011. with no zlib header or trailer, and will not compute an adler32 check value.
  79012. windowBits can also be greater than 15 for optional gzip encoding. Add
  79013. 16 to windowBits to write a simple gzip header and trailer around the
  79014. compressed data instead of a zlib wrapper. The gzip header will have no
  79015. file name, no extra data, no comment, no modification time (set to zero),
  79016. no header crc, and the operating system will be set to 255 (unknown). If a
  79017. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  79018. The memLevel parameter specifies how much memory should be allocated
  79019. for the internal compression state. memLevel=1 uses minimum memory but
  79020. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79021. for optimal speed. The default value is 8. See zconf.h for total memory
  79022. usage as a function of windowBits and memLevel.
  79023. The strategy parameter is used to tune the compression algorithm. Use the
  79024. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79025. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79026. string match), or Z_RLE to limit match distances to one (run-length
  79027. encoding). Filtered data consists mostly of small values with a somewhat
  79028. random distribution. In this case, the compression algorithm is tuned to
  79029. compress them better. The effect of Z_FILTERED is to force more Huffman
  79030. coding and less string matching; it is somewhat intermediate between
  79031. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79032. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79033. parameter only affects the compression ratio but not the correctness of the
  79034. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79035. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79036. applications.
  79037. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79038. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79039. method). msg is set to null if there is no error message. deflateInit2 does
  79040. not perform any compression: this will be done by deflate().
  79041. */
  79042. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79043. const Bytef *dictionary,
  79044. uInt dictLength));
  79045. /*
  79046. Initializes the compression dictionary from the given byte sequence
  79047. without producing any compressed output. This function must be called
  79048. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79049. call of deflate. The compressor and decompressor must use exactly the same
  79050. dictionary (see inflateSetDictionary).
  79051. The dictionary should consist of strings (byte sequences) that are likely
  79052. to be encountered later in the data to be compressed, with the most commonly
  79053. used strings preferably put towards the end of the dictionary. Using a
  79054. dictionary is most useful when the data to be compressed is short and can be
  79055. predicted with good accuracy; the data can then be compressed better than
  79056. with the default empty dictionary.
  79057. Depending on the size of the compression data structures selected by
  79058. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79059. discarded, for example if the dictionary is larger than the window size in
  79060. deflate or deflate2. Thus the strings most likely to be useful should be
  79061. put at the end of the dictionary, not at the front. In addition, the
  79062. current implementation of deflate will use at most the window size minus
  79063. 262 bytes of the provided dictionary.
  79064. Upon return of this function, strm->adler is set to the adler32 value
  79065. of the dictionary; the decompressor may later use this value to determine
  79066. which dictionary has been used by the compressor. (The adler32 value
  79067. applies to the whole dictionary even if only a subset of the dictionary is
  79068. actually used by the compressor.) If a raw deflate was requested, then the
  79069. adler32 value is not computed and strm->adler is not set.
  79070. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79071. parameter is invalid (such as NULL dictionary) or the stream state is
  79072. inconsistent (for example if deflate has already been called for this stream
  79073. or if the compression method is bsort). deflateSetDictionary does not
  79074. perform any compression: this will be done by deflate().
  79075. */
  79076. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79077. z_streamp source));
  79078. /*
  79079. Sets the destination stream as a complete copy of the source stream.
  79080. This function can be useful when several compression strategies will be
  79081. tried, for example when there are several ways of pre-processing the input
  79082. data with a filter. The streams that will be discarded should then be freed
  79083. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79084. compression state which can be quite large, so this strategy is slow and
  79085. can consume lots of memory.
  79086. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79087. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79088. (such as zalloc being NULL). msg is left unchanged in both source and
  79089. destination.
  79090. */
  79091. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79092. /*
  79093. This function is equivalent to deflateEnd followed by deflateInit,
  79094. but does not free and reallocate all the internal compression state.
  79095. The stream will keep the same compression level and any other attributes
  79096. that may have been set by deflateInit2.
  79097. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79098. stream state was inconsistent (such as zalloc or state being NULL).
  79099. */
  79100. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79101. int level,
  79102. int strategy));
  79103. /*
  79104. Dynamically update the compression level and compression strategy. The
  79105. interpretation of level and strategy is as in deflateInit2. This can be
  79106. used to switch between compression and straight copy of the input data, or
  79107. to switch to a different kind of input data requiring a different
  79108. strategy. If the compression level is changed, the input available so far
  79109. is compressed with the old level (and may be flushed); the new level will
  79110. take effect only at the next call of deflate().
  79111. Before the call of deflateParams, the stream state must be set as for
  79112. a call of deflate(), since the currently available input may have to
  79113. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79114. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79115. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79116. if strm->avail_out was zero.
  79117. */
  79118. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79119. int good_length,
  79120. int max_lazy,
  79121. int nice_length,
  79122. int max_chain));
  79123. /*
  79124. Fine tune deflate's internal compression parameters. This should only be
  79125. used by someone who understands the algorithm used by zlib's deflate for
  79126. searching for the best matching string, and even then only by the most
  79127. fanatic optimizer trying to squeeze out the last compressed bit for their
  79128. specific input data. Read the deflate.c source code for the meaning of the
  79129. max_lazy, good_length, nice_length, and max_chain parameters.
  79130. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79131. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79132. */
  79133. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79134. uLong sourceLen));
  79135. /*
  79136. deflateBound() returns an upper bound on the compressed size after
  79137. deflation of sourceLen bytes. It must be called after deflateInit()
  79138. or deflateInit2(). This would be used to allocate an output buffer
  79139. for deflation in a single pass, and so would be called before deflate().
  79140. */
  79141. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79142. int bits,
  79143. int value));
  79144. /*
  79145. deflatePrime() inserts bits in the deflate output stream. The intent
  79146. is that this function is used to start off the deflate output with the
  79147. bits leftover from a previous deflate stream when appending to it. As such,
  79148. this function can only be used for raw deflate, and must be used before the
  79149. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79150. less than or equal to 16, and that many of the least significant bits of
  79151. value will be inserted in the output.
  79152. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79153. stream state was inconsistent.
  79154. */
  79155. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79156. gz_headerp head));
  79157. /*
  79158. deflateSetHeader() provides gzip header information for when a gzip
  79159. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79160. after deflateInit2() or deflateReset() and before the first call of
  79161. deflate(). The text, time, os, extra field, name, and comment information
  79162. in the provided gz_header structure are written to the gzip header (xflag is
  79163. ignored -- the extra flags are set according to the compression level). The
  79164. caller must assure that, if not Z_NULL, name and comment are terminated with
  79165. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79166. available there. If hcrc is true, a gzip header crc is included. Note that
  79167. the current versions of the command-line version of gzip (up through version
  79168. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79169. gzip file" and give up.
  79170. If deflateSetHeader is not used, the default gzip header has text false,
  79171. the time set to zero, and os set to 255, with no extra, name, or comment
  79172. fields. The gzip header is returned to the default state by deflateReset().
  79173. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79174. stream state was inconsistent.
  79175. */
  79176. /*
  79177. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79178. int windowBits));
  79179. This is another version of inflateInit with an extra parameter. The
  79180. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79181. before by the caller.
  79182. The windowBits parameter is the base two logarithm of the maximum window
  79183. size (the size of the history buffer). It should be in the range 8..15 for
  79184. this version of the library. The default value is 15 if inflateInit is used
  79185. instead. windowBits must be greater than or equal to the windowBits value
  79186. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79187. deflateInit2() was not used. If a compressed stream with a larger window
  79188. size is given as input, inflate() will return with the error code
  79189. Z_DATA_ERROR instead of trying to allocate a larger window.
  79190. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79191. determines the window size. inflate() will then process raw deflate data,
  79192. not looking for a zlib or gzip header, not generating a check value, and not
  79193. looking for any check values for comparison at the end of the stream. This
  79194. is for use with other formats that use the deflate compressed data format
  79195. such as zip. Those formats provide their own check values. If a custom
  79196. format is developed using the raw deflate format for compressed data, it is
  79197. recommended that a check value such as an adler32 or a crc32 be applied to
  79198. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79199. most applications, the zlib format should be used as is. Note that comments
  79200. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79201. windowBits can also be greater than 15 for optional gzip decoding. Add
  79202. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79203. detection, or add 16 to decode only the gzip format (the zlib format will
  79204. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79205. a crc32 instead of an adler32.
  79206. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79207. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79208. is set to null if there is no error message. inflateInit2 does not perform
  79209. any decompression apart from reading the zlib header if present: this will
  79210. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79211. and avail_out are unchanged.)
  79212. */
  79213. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79214. const Bytef *dictionary,
  79215. uInt dictLength));
  79216. /*
  79217. Initializes the decompression dictionary from the given uncompressed byte
  79218. sequence. This function must be called immediately after a call of inflate,
  79219. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79220. can be determined from the adler32 value returned by that call of inflate.
  79221. The compressor and decompressor must use exactly the same dictionary (see
  79222. deflateSetDictionary). For raw inflate, this function can be called
  79223. immediately after inflateInit2() or inflateReset() and before any call of
  79224. inflate() to set the dictionary. The application must insure that the
  79225. dictionary that was used for compression is provided.
  79226. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79227. parameter is invalid (such as NULL dictionary) or the stream state is
  79228. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79229. expected one (incorrect adler32 value). inflateSetDictionary does not
  79230. perform any decompression: this will be done by subsequent calls of
  79231. inflate().
  79232. */
  79233. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79234. /*
  79235. Skips invalid compressed data until a full flush point (see above the
  79236. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79237. available input is skipped. No output is provided.
  79238. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79239. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79240. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79241. case, the application may save the current current value of total_in which
  79242. indicates where valid compressed data was found. In the error case, the
  79243. application may repeatedly call inflateSync, providing more input each time,
  79244. until success or end of the input data.
  79245. */
  79246. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79247. z_streamp source));
  79248. /*
  79249. Sets the destination stream as a complete copy of the source stream.
  79250. This function can be useful when randomly accessing a large stream. The
  79251. first pass through the stream can periodically record the inflate state,
  79252. allowing restarting inflate at those points when randomly accessing the
  79253. stream.
  79254. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79255. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79256. (such as zalloc being NULL). msg is left unchanged in both source and
  79257. destination.
  79258. */
  79259. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79260. /*
  79261. This function is equivalent to inflateEnd followed by inflateInit,
  79262. but does not free and reallocate all the internal decompression state.
  79263. The stream will keep attributes that may have been set by inflateInit2.
  79264. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79265. stream state was inconsistent (such as zalloc or state being NULL).
  79266. */
  79267. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79268. int bits,
  79269. int value));
  79270. /*
  79271. This function inserts bits in the inflate input stream. The intent is
  79272. that this function is used to start inflating at a bit position in the
  79273. middle of a byte. The provided bits will be used before any bytes are used
  79274. from next_in. This function should only be used with raw inflate, and
  79275. should be used before the first inflate() call after inflateInit2() or
  79276. inflateReset(). bits must be less than or equal to 16, and that many of the
  79277. least significant bits of value will be inserted in the input.
  79278. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79279. stream state was inconsistent.
  79280. */
  79281. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79282. gz_headerp head));
  79283. /*
  79284. inflateGetHeader() requests that gzip header information be stored in the
  79285. provided gz_header structure. inflateGetHeader() may be called after
  79286. inflateInit2() or inflateReset(), and before the first call of inflate().
  79287. As inflate() processes the gzip stream, head->done is zero until the header
  79288. is completed, at which time head->done is set to one. If a zlib stream is
  79289. being decoded, then head->done is set to -1 to indicate that there will be
  79290. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79291. force inflate() to return immediately after header processing is complete
  79292. and before any actual data is decompressed.
  79293. The text, time, xflags, and os fields are filled in with the gzip header
  79294. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79295. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79296. contains the maximum number of bytes to write to extra. Once done is true,
  79297. extra_len contains the actual extra field length, and extra contains the
  79298. extra field, or that field truncated if extra_max is less than extra_len.
  79299. If name is not Z_NULL, then up to name_max characters are written there,
  79300. terminated with a zero unless the length is greater than name_max. If
  79301. comment is not Z_NULL, then up to comm_max characters are written there,
  79302. terminated with a zero unless the length is greater than comm_max. When
  79303. any of extra, name, or comment are not Z_NULL and the respective field is
  79304. not present in the header, then that field is set to Z_NULL to signal its
  79305. absence. This allows the use of deflateSetHeader() with the returned
  79306. structure to duplicate the header. However if those fields are set to
  79307. allocated memory, then the application will need to save those pointers
  79308. elsewhere so that they can be eventually freed.
  79309. If inflateGetHeader is not used, then the header information is simply
  79310. discarded. The header is always checked for validity, including the header
  79311. CRC if present. inflateReset() will reset the process to discard the header
  79312. information. The application would need to call inflateGetHeader() again to
  79313. retrieve the header from the next gzip stream.
  79314. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79315. stream state was inconsistent.
  79316. */
  79317. /*
  79318. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79319. unsigned char FAR *window));
  79320. Initialize the internal stream state for decompression using inflateBack()
  79321. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79322. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79323. derived memory allocation routines are used. windowBits is the base two
  79324. logarithm of the window size, in the range 8..15. window is a caller
  79325. supplied buffer of that size. Except for special applications where it is
  79326. assured that deflate was used with small window sizes, windowBits must be 15
  79327. and a 32K byte window must be supplied to be able to decompress general
  79328. deflate streams.
  79329. See inflateBack() for the usage of these routines.
  79330. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79331. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79332. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79333. match the version of the header file.
  79334. */
  79335. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79336. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79337. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79338. in_func in, void FAR *in_desc,
  79339. out_func out, void FAR *out_desc));
  79340. /*
  79341. inflateBack() does a raw inflate with a single call using a call-back
  79342. interface for input and output. This is more efficient than inflate() for
  79343. file i/o applications in that it avoids copying between the output and the
  79344. sliding window by simply making the window itself the output buffer. This
  79345. function trusts the application to not change the output buffer passed by
  79346. the output function, at least until inflateBack() returns.
  79347. inflateBackInit() must be called first to allocate the internal state
  79348. and to initialize the state with the user-provided window buffer.
  79349. inflateBack() may then be used multiple times to inflate a complete, raw
  79350. deflate stream with each call. inflateBackEnd() is then called to free
  79351. the allocated state.
  79352. A raw deflate stream is one with no zlib or gzip header or trailer.
  79353. This routine would normally be used in a utility that reads zip or gzip
  79354. files and writes out uncompressed files. The utility would decode the
  79355. header and process the trailer on its own, hence this routine expects
  79356. only the raw deflate stream to decompress. This is different from the
  79357. normal behavior of inflate(), which expects either a zlib or gzip header and
  79358. trailer around the deflate stream.
  79359. inflateBack() uses two subroutines supplied by the caller that are then
  79360. called by inflateBack() for input and output. inflateBack() calls those
  79361. routines until it reads a complete deflate stream and writes out all of the
  79362. uncompressed data, or until it encounters an error. The function's
  79363. parameters and return types are defined above in the in_func and out_func
  79364. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79365. number of bytes of provided input, and a pointer to that input in buf. If
  79366. there is no input available, in() must return zero--buf is ignored in that
  79367. case--and inflateBack() will return a buffer error. inflateBack() will call
  79368. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79369. should return zero on success, or non-zero on failure. If out() returns
  79370. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79371. are permitted to change the contents of the window provided to
  79372. inflateBackInit(), which is also the buffer that out() uses to write from.
  79373. The length written by out() will be at most the window size. Any non-zero
  79374. amount of input may be provided by in().
  79375. For convenience, inflateBack() can be provided input on the first call by
  79376. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79377. in() will be called. Therefore strm->next_in must be initialized before
  79378. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79379. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79380. must also be initialized, and then if strm->avail_in is not zero, input will
  79381. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79382. The in_desc and out_desc parameters of inflateBack() is passed as the
  79383. first parameter of in() and out() respectively when they are called. These
  79384. descriptors can be optionally used to pass any information that the caller-
  79385. supplied in() and out() functions need to do their job.
  79386. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79387. pass back any unused input that was provided by the last in() call. The
  79388. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79389. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79390. error in the deflate stream (in which case strm->msg is set to indicate the
  79391. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79392. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79393. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79394. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79395. out() returning non-zero. (in() will always be called before out(), so
  79396. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79397. that inflateBack() cannot return Z_OK.
  79398. */
  79399. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79400. /*
  79401. All memory allocated by inflateBackInit() is freed.
  79402. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79403. state was inconsistent.
  79404. */
  79405. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79406. /* Return flags indicating compile-time options.
  79407. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79408. 1.0: size of uInt
  79409. 3.2: size of uLong
  79410. 5.4: size of voidpf (pointer)
  79411. 7.6: size of z_off_t
  79412. Compiler, assembler, and debug options:
  79413. 8: DEBUG
  79414. 9: ASMV or ASMINF -- use ASM code
  79415. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79416. 11: 0 (reserved)
  79417. One-time table building (smaller code, but not thread-safe if true):
  79418. 12: BUILDFIXED -- build static block decoding tables when needed
  79419. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79420. 14,15: 0 (reserved)
  79421. Library content (indicates missing functionality):
  79422. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79423. deflate code when not needed)
  79424. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79425. and decode gzip streams (to avoid linking crc code)
  79426. 18-19: 0 (reserved)
  79427. Operation variations (changes in library functionality):
  79428. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79429. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79430. 22,23: 0 (reserved)
  79431. The sprintf variant used by gzprintf (zero is best):
  79432. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79433. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79434. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79435. Remainder:
  79436. 27-31: 0 (reserved)
  79437. */
  79438. /* utility functions */
  79439. /*
  79440. The following utility functions are implemented on top of the
  79441. basic stream-oriented functions. To simplify the interface, some
  79442. default options are assumed (compression level and memory usage,
  79443. standard memory allocation functions). The source code of these
  79444. utility functions can easily be modified if you need special options.
  79445. */
  79446. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79447. const Bytef *source, uLong sourceLen));
  79448. /*
  79449. Compresses the source buffer into the destination buffer. sourceLen is
  79450. the byte length of the source buffer. Upon entry, destLen is the total
  79451. size of the destination buffer, which must be at least the value returned
  79452. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79453. compressed buffer.
  79454. This function can be used to compress a whole file at once if the
  79455. input file is mmap'ed.
  79456. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79457. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79458. buffer.
  79459. */
  79460. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79461. const Bytef *source, uLong sourceLen,
  79462. int level));
  79463. /*
  79464. Compresses the source buffer into the destination buffer. The level
  79465. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79466. length of the source buffer. Upon entry, destLen is the total size of the
  79467. destination buffer, which must be at least the value returned by
  79468. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79469. compressed buffer.
  79470. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79471. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79472. Z_STREAM_ERROR if the level parameter is invalid.
  79473. */
  79474. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79475. /*
  79476. compressBound() returns an upper bound on the compressed size after
  79477. compress() or compress2() on sourceLen bytes. It would be used before
  79478. a compress() or compress2() call to allocate the destination buffer.
  79479. */
  79480. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79481. const Bytef *source, uLong sourceLen));
  79482. /*
  79483. Decompresses the source buffer into the destination buffer. sourceLen is
  79484. the byte length of the source buffer. Upon entry, destLen is the total
  79485. size of the destination buffer, which must be large enough to hold the
  79486. entire uncompressed data. (The size of the uncompressed data must have
  79487. been saved previously by the compressor and transmitted to the decompressor
  79488. by some mechanism outside the scope of this compression library.)
  79489. Upon exit, destLen is the actual size of the compressed buffer.
  79490. This function can be used to decompress a whole file at once if the
  79491. input file is mmap'ed.
  79492. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79493. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79494. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79495. */
  79496. typedef voidp gzFile;
  79497. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79498. /*
  79499. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79500. is as in fopen ("rb" or "wb") but can also include a compression level
  79501. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79502. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79503. as in "wb1R". (See the description of deflateInit2 for more information
  79504. about the strategy parameter.)
  79505. gzopen can be used to read a file which is not in gzip format; in this
  79506. case gzread will directly read from the file without decompression.
  79507. gzopen returns NULL if the file could not be opened or if there was
  79508. insufficient memory to allocate the (de)compression state; errno
  79509. can be checked to distinguish the two cases (if errno is zero, the
  79510. zlib error is Z_MEM_ERROR). */
  79511. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79512. /*
  79513. gzdopen() associates a gzFile with the file descriptor fd. File
  79514. descriptors are obtained from calls like open, dup, creat, pipe or
  79515. fileno (in the file has been previously opened with fopen).
  79516. The mode parameter is as in gzopen.
  79517. The next call of gzclose on the returned gzFile will also close the
  79518. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79519. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79520. gzdopen returns NULL if there was insufficient memory to allocate
  79521. the (de)compression state.
  79522. */
  79523. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79524. /*
  79525. Dynamically update the compression level or strategy. See the description
  79526. of deflateInit2 for the meaning of these parameters.
  79527. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79528. opened for writing.
  79529. */
  79530. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79531. /*
  79532. Reads the given number of uncompressed bytes from the compressed file.
  79533. If the input file was not in gzip format, gzread copies the given number
  79534. of bytes into the buffer.
  79535. gzread returns the number of uncompressed bytes actually read (0 for
  79536. end of file, -1 for error). */
  79537. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79538. voidpc buf, unsigned len));
  79539. /*
  79540. Writes the given number of uncompressed bytes into the compressed file.
  79541. gzwrite returns the number of uncompressed bytes actually written
  79542. (0 in case of error).
  79543. */
  79544. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79545. /*
  79546. Converts, formats, and writes the args to the compressed file under
  79547. control of the format string, as in fprintf. gzprintf returns the number of
  79548. uncompressed bytes actually written (0 in case of error). The number of
  79549. uncompressed bytes written is limited to 4095. The caller should assure that
  79550. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79551. return an error (0) with nothing written. In this case, there may also be a
  79552. buffer overflow with unpredictable consequences, which is possible only if
  79553. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79554. because the secure snprintf() or vsnprintf() functions were not available.
  79555. */
  79556. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79557. /*
  79558. Writes the given null-terminated string to the compressed file, excluding
  79559. the terminating null character.
  79560. gzputs returns the number of characters written, or -1 in case of error.
  79561. */
  79562. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79563. /*
  79564. Reads bytes from the compressed file until len-1 characters are read, or
  79565. a newline character is read and transferred to buf, or an end-of-file
  79566. condition is encountered. The string is then terminated with a null
  79567. character.
  79568. gzgets returns buf, or Z_NULL in case of error.
  79569. */
  79570. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79571. /*
  79572. Writes c, converted to an unsigned char, into the compressed file.
  79573. gzputc returns the value that was written, or -1 in case of error.
  79574. */
  79575. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79576. /*
  79577. Reads one byte from the compressed file. gzgetc returns this byte
  79578. or -1 in case of end of file or error.
  79579. */
  79580. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79581. /*
  79582. Push one character back onto the stream to be read again later.
  79583. Only one character of push-back is allowed. gzungetc() returns the
  79584. character pushed, or -1 on failure. gzungetc() will fail if a
  79585. character has been pushed but not read yet, or if c is -1. The pushed
  79586. character will be discarded if the stream is repositioned with gzseek()
  79587. or gzrewind().
  79588. */
  79589. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79590. /*
  79591. Flushes all pending output into the compressed file. The parameter
  79592. flush is as in the deflate() function. The return value is the zlib
  79593. error number (see function gzerror below). gzflush returns Z_OK if
  79594. the flush parameter is Z_FINISH and all output could be flushed.
  79595. gzflush should be called only when strictly necessary because it can
  79596. degrade compression.
  79597. */
  79598. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79599. z_off_t offset, int whence));
  79600. /*
  79601. Sets the starting position for the next gzread or gzwrite on the
  79602. given compressed file. The offset represents a number of bytes in the
  79603. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79604. the value SEEK_END is not supported.
  79605. If the file is opened for reading, this function is emulated but can be
  79606. extremely slow. If the file is opened for writing, only forward seeks are
  79607. supported; gzseek then compresses a sequence of zeroes up to the new
  79608. starting position.
  79609. gzseek returns the resulting offset location as measured in bytes from
  79610. the beginning of the uncompressed stream, or -1 in case of error, in
  79611. particular if the file is opened for writing and the new starting position
  79612. would be before the current position.
  79613. */
  79614. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79615. /*
  79616. Rewinds the given file. This function is supported only for reading.
  79617. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79618. */
  79619. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79620. /*
  79621. Returns the starting position for the next gzread or gzwrite on the
  79622. given compressed file. This position represents a number of bytes in the
  79623. uncompressed data stream.
  79624. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79625. */
  79626. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79627. /*
  79628. Returns 1 when EOF has previously been detected reading the given
  79629. input stream, otherwise zero.
  79630. */
  79631. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79632. /*
  79633. Returns 1 if file is being read directly without decompression, otherwise
  79634. zero.
  79635. */
  79636. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79637. /*
  79638. Flushes all pending output if necessary, closes the compressed file
  79639. and deallocates all the (de)compression state. The return value is the zlib
  79640. error number (see function gzerror below).
  79641. */
  79642. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79643. /*
  79644. Returns the error message for the last error which occurred on the
  79645. given compressed file. errnum is set to zlib error number. If an
  79646. error occurred in the file system and not in the compression library,
  79647. errnum is set to Z_ERRNO and the application may consult errno
  79648. to get the exact error code.
  79649. */
  79650. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79651. /*
  79652. Clears the error and end-of-file flags for file. This is analogous to the
  79653. clearerr() function in stdio. This is useful for continuing to read a gzip
  79654. file that is being written concurrently.
  79655. */
  79656. /* checksum functions */
  79657. /*
  79658. These functions are not related to compression but are exported
  79659. anyway because they might be useful in applications using the
  79660. compression library.
  79661. */
  79662. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79663. /*
  79664. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79665. return the updated checksum. If buf is NULL, this function returns
  79666. the required initial value for the checksum.
  79667. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79668. much faster. Usage example:
  79669. uLong adler = adler32(0L, Z_NULL, 0);
  79670. while (read_buffer(buffer, length) != EOF) {
  79671. adler = adler32(adler, buffer, length);
  79672. }
  79673. if (adler != original_adler) error();
  79674. */
  79675. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79676. z_off_t len2));
  79677. /*
  79678. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79679. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79680. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79681. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79682. */
  79683. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79684. /*
  79685. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79686. updated CRC-32. If buf is NULL, this function returns the required initial
  79687. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79688. performed within this function so it shouldn't be done by the application.
  79689. Usage example:
  79690. uLong crc = crc32(0L, Z_NULL, 0);
  79691. while (read_buffer(buffer, length) != EOF) {
  79692. crc = crc32(crc, buffer, length);
  79693. }
  79694. if (crc != original_crc) error();
  79695. */
  79696. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79697. /*
  79698. Combine two CRC-32 check values into one. For two sequences of bytes,
  79699. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79700. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79701. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79702. len2.
  79703. */
  79704. /* various hacks, don't look :) */
  79705. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79706. * and the compiler's view of z_stream:
  79707. */
  79708. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79709. const char *version, int stream_size));
  79710. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79711. const char *version, int stream_size));
  79712. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79713. int windowBits, int memLevel,
  79714. int strategy, const char *version,
  79715. int stream_size));
  79716. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79717. const char *version, int stream_size));
  79718. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79719. unsigned char FAR *window,
  79720. const char *version,
  79721. int stream_size));
  79722. #define deflateInit(strm, level) \
  79723. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79724. #define inflateInit(strm) \
  79725. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79726. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79727. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79728. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79729. #define inflateInit2(strm, windowBits) \
  79730. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79731. #define inflateBackInit(strm, windowBits, window) \
  79732. inflateBackInit_((strm), (windowBits), (window), \
  79733. ZLIB_VERSION, sizeof(z_stream))
  79734. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79735. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79736. #endif
  79737. ZEXTERN const char * ZEXPORT zError OF((int));
  79738. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79739. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79740. #ifdef __cplusplus
  79741. //}
  79742. #endif
  79743. #endif /* ZLIB_H */
  79744. /*** End of inlined file: zlib.h ***/
  79745. #undef OS_CODE
  79746. #else
  79747. #include <zlib.h>
  79748. #endif
  79749. }
  79750. BEGIN_JUCE_NAMESPACE
  79751. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79752. {
  79753. public:
  79754. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79755. : data (0),
  79756. dataSize (0),
  79757. compLevel (compressionLevel),
  79758. strategy (0),
  79759. setParams (true),
  79760. streamIsValid (false),
  79761. finished (false),
  79762. shouldFinish (false)
  79763. {
  79764. using namespace zlibNamespace;
  79765. zerostruct (stream);
  79766. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79767. windowBits != 0 ? windowBits : MAX_WBITS,
  79768. 8, strategy) == Z_OK);
  79769. }
  79770. ~GZIPCompressorHelper()
  79771. {
  79772. using namespace zlibNamespace;
  79773. if (streamIsValid)
  79774. deflateEnd (&stream);
  79775. }
  79776. bool needsInput() const throw()
  79777. {
  79778. return dataSize <= 0;
  79779. }
  79780. void setInput (const uint8* const newData, const int size) throw()
  79781. {
  79782. data = newData;
  79783. dataSize = size;
  79784. }
  79785. int doNextBlock (uint8* const dest, const int destSize) throw()
  79786. {
  79787. using namespace zlibNamespace;
  79788. if (streamIsValid)
  79789. {
  79790. stream.next_in = const_cast <uint8*> (data);
  79791. stream.next_out = dest;
  79792. stream.avail_in = dataSize;
  79793. stream.avail_out = destSize;
  79794. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79795. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79796. setParams = false;
  79797. switch (result)
  79798. {
  79799. case Z_STREAM_END:
  79800. finished = true;
  79801. // Deliberate fall-through..
  79802. case Z_OK:
  79803. data += dataSize - stream.avail_in;
  79804. dataSize = stream.avail_in;
  79805. return destSize - stream.avail_out;
  79806. default:
  79807. break;
  79808. }
  79809. }
  79810. return 0;
  79811. }
  79812. enum { gzipCompBufferSize = 32768 };
  79813. private:
  79814. zlibNamespace::z_stream stream;
  79815. const uint8* data;
  79816. int dataSize, compLevel, strategy;
  79817. bool setParams, streamIsValid;
  79818. public:
  79819. bool finished, shouldFinish;
  79820. };
  79821. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79822. int compressionLevel,
  79823. const bool deleteDestStream,
  79824. const int windowBits)
  79825. : destStream (destStream_),
  79826. streamToDelete (deleteDestStream ? destStream_ : 0),
  79827. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79828. {
  79829. if (compressionLevel < 1 || compressionLevel > 9)
  79830. compressionLevel = -1;
  79831. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79832. }
  79833. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79834. {
  79835. flush();
  79836. }
  79837. void GZIPCompressorOutputStream::flush()
  79838. {
  79839. if (! helper->finished)
  79840. {
  79841. helper->shouldFinish = true;
  79842. while (! helper->finished)
  79843. doNextBlock();
  79844. }
  79845. destStream->flush();
  79846. }
  79847. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79848. {
  79849. if (! helper->finished)
  79850. {
  79851. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79852. while (! helper->needsInput())
  79853. {
  79854. if (! doNextBlock())
  79855. return false;
  79856. }
  79857. }
  79858. return true;
  79859. }
  79860. bool GZIPCompressorOutputStream::doNextBlock()
  79861. {
  79862. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79863. return len <= 0 || destStream->write (buffer, len);
  79864. }
  79865. int64 GZIPCompressorOutputStream::getPosition()
  79866. {
  79867. return destStream->getPosition();
  79868. }
  79869. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79870. {
  79871. jassertfalse; // can't do it!
  79872. return false;
  79873. }
  79874. END_JUCE_NAMESPACE
  79875. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79876. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79877. #if JUCE_MSVC
  79878. #pragma warning (push)
  79879. #pragma warning (disable: 4309 4305)
  79880. #endif
  79881. namespace zlibNamespace
  79882. {
  79883. #if JUCE_INCLUDE_ZLIB_CODE
  79884. #undef OS_CODE
  79885. #undef fdopen
  79886. #define ZLIB_INTERNAL
  79887. #define NO_DUMMY_DECL
  79888. /*** Start of inlined file: adler32.c ***/
  79889. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79890. #define ZLIB_INTERNAL
  79891. #define BASE 65521UL /* largest prime smaller than 65536 */
  79892. #define NMAX 5552
  79893. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79894. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79895. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79896. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79897. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79898. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79899. /* use NO_DIVIDE if your processor does not do division in hardware */
  79900. #ifdef NO_DIVIDE
  79901. # define MOD(a) \
  79902. do { \
  79903. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79904. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79905. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79906. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79907. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79908. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79909. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79910. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79911. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79912. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79913. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79914. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79915. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79916. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79917. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79918. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79919. if (a >= BASE) a -= BASE; \
  79920. } while (0)
  79921. # define MOD4(a) \
  79922. do { \
  79923. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79924. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79925. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79926. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79927. if (a >= BASE) a -= BASE; \
  79928. } while (0)
  79929. #else
  79930. # define MOD(a) a %= BASE
  79931. # define MOD4(a) a %= BASE
  79932. #endif
  79933. /* ========================================================================= */
  79934. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79935. {
  79936. unsigned long sum2;
  79937. unsigned n;
  79938. /* split Adler-32 into component sums */
  79939. sum2 = (adler >> 16) & 0xffff;
  79940. adler &= 0xffff;
  79941. /* in case user likes doing a byte at a time, keep it fast */
  79942. if (len == 1) {
  79943. adler += buf[0];
  79944. if (adler >= BASE)
  79945. adler -= BASE;
  79946. sum2 += adler;
  79947. if (sum2 >= BASE)
  79948. sum2 -= BASE;
  79949. return adler | (sum2 << 16);
  79950. }
  79951. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79952. if (buf == Z_NULL)
  79953. return 1L;
  79954. /* in case short lengths are provided, keep it somewhat fast */
  79955. if (len < 16) {
  79956. while (len--) {
  79957. adler += *buf++;
  79958. sum2 += adler;
  79959. }
  79960. if (adler >= BASE)
  79961. adler -= BASE;
  79962. MOD4(sum2); /* only added so many BASE's */
  79963. return adler | (sum2 << 16);
  79964. }
  79965. /* do length NMAX blocks -- requires just one modulo operation */
  79966. while (len >= NMAX) {
  79967. len -= NMAX;
  79968. n = NMAX / 16; /* NMAX is divisible by 16 */
  79969. do {
  79970. DO16(buf); /* 16 sums unrolled */
  79971. buf += 16;
  79972. } while (--n);
  79973. MOD(adler);
  79974. MOD(sum2);
  79975. }
  79976. /* do remaining bytes (less than NMAX, still just one modulo) */
  79977. if (len) { /* avoid modulos if none remaining */
  79978. while (len >= 16) {
  79979. len -= 16;
  79980. DO16(buf);
  79981. buf += 16;
  79982. }
  79983. while (len--) {
  79984. adler += *buf++;
  79985. sum2 += adler;
  79986. }
  79987. MOD(adler);
  79988. MOD(sum2);
  79989. }
  79990. /* return recombined sums */
  79991. return adler | (sum2 << 16);
  79992. }
  79993. /* ========================================================================= */
  79994. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79995. {
  79996. unsigned long sum1;
  79997. unsigned long sum2;
  79998. unsigned rem;
  79999. /* the derivation of this formula is left as an exercise for the reader */
  80000. rem = (unsigned)(len2 % BASE);
  80001. sum1 = adler1 & 0xffff;
  80002. sum2 = rem * sum1;
  80003. MOD(sum2);
  80004. sum1 += (adler2 & 0xffff) + BASE - 1;
  80005. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  80006. if (sum1 > BASE) sum1 -= BASE;
  80007. if (sum1 > BASE) sum1 -= BASE;
  80008. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  80009. if (sum2 > BASE) sum2 -= BASE;
  80010. return sum1 | (sum2 << 16);
  80011. }
  80012. /*** End of inlined file: adler32.c ***/
  80013. /*** Start of inlined file: compress.c ***/
  80014. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80015. #define ZLIB_INTERNAL
  80016. /* ===========================================================================
  80017. Compresses the source buffer into the destination buffer. The level
  80018. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80019. length of the source buffer. Upon entry, destLen is the total size of the
  80020. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80021. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80022. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80023. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80024. Z_STREAM_ERROR if the level parameter is invalid.
  80025. */
  80026. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80027. uLong sourceLen, int level)
  80028. {
  80029. z_stream stream;
  80030. int err;
  80031. stream.next_in = (Bytef*)source;
  80032. stream.avail_in = (uInt)sourceLen;
  80033. #ifdef MAXSEG_64K
  80034. /* Check for source > 64K on 16-bit machine: */
  80035. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80036. #endif
  80037. stream.next_out = dest;
  80038. stream.avail_out = (uInt)*destLen;
  80039. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80040. stream.zalloc = (alloc_func)0;
  80041. stream.zfree = (free_func)0;
  80042. stream.opaque = (voidpf)0;
  80043. err = deflateInit(&stream, level);
  80044. if (err != Z_OK) return err;
  80045. err = deflate(&stream, Z_FINISH);
  80046. if (err != Z_STREAM_END) {
  80047. deflateEnd(&stream);
  80048. return err == Z_OK ? Z_BUF_ERROR : err;
  80049. }
  80050. *destLen = stream.total_out;
  80051. err = deflateEnd(&stream);
  80052. return err;
  80053. }
  80054. /* ===========================================================================
  80055. */
  80056. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80057. {
  80058. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80059. }
  80060. /* ===========================================================================
  80061. If the default memLevel or windowBits for deflateInit() is changed, then
  80062. this function needs to be updated.
  80063. */
  80064. uLong ZEXPORT compressBound (uLong sourceLen)
  80065. {
  80066. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80067. }
  80068. /*** End of inlined file: compress.c ***/
  80069. #undef DO1
  80070. #undef DO8
  80071. /*** Start of inlined file: crc32.c ***/
  80072. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80073. /*
  80074. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80075. protection on the static variables used to control the first-use generation
  80076. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80077. first call get_crc_table() to initialize the tables before allowing more than
  80078. one thread to use crc32().
  80079. */
  80080. #ifdef MAKECRCH
  80081. # include <stdio.h>
  80082. # ifndef DYNAMIC_CRC_TABLE
  80083. # define DYNAMIC_CRC_TABLE
  80084. # endif /* !DYNAMIC_CRC_TABLE */
  80085. #endif /* MAKECRCH */
  80086. /*** Start of inlined file: zutil.h ***/
  80087. /* WARNING: this file should *not* be used by applications. It is
  80088. part of the implementation of the compression library and is
  80089. subject to change. Applications should only use zlib.h.
  80090. */
  80091. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80092. #ifndef ZUTIL_H
  80093. #define ZUTIL_H
  80094. #define ZLIB_INTERNAL
  80095. #ifdef STDC
  80096. # ifndef _WIN32_WCE
  80097. # include <stddef.h>
  80098. # endif
  80099. # include <string.h>
  80100. # include <stdlib.h>
  80101. #endif
  80102. #ifdef NO_ERRNO_H
  80103. # ifdef _WIN32_WCE
  80104. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80105. * errno. We define it as a global variable to simplify porting.
  80106. * Its value is always 0 and should not be used. We rename it to
  80107. * avoid conflict with other libraries that use the same workaround.
  80108. */
  80109. # define errno z_errno
  80110. # endif
  80111. extern int errno;
  80112. #else
  80113. # ifndef _WIN32_WCE
  80114. # include <errno.h>
  80115. # endif
  80116. #endif
  80117. #ifndef local
  80118. # define local static
  80119. #endif
  80120. /* compile with -Dlocal if your debugger can't find static symbols */
  80121. typedef unsigned char uch;
  80122. typedef uch FAR uchf;
  80123. typedef unsigned short ush;
  80124. typedef ush FAR ushf;
  80125. typedef unsigned long ulg;
  80126. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80127. /* (size given to avoid silly warnings with Visual C++) */
  80128. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80129. #define ERR_RETURN(strm,err) \
  80130. return (strm->msg = (char*)ERR_MSG(err), (err))
  80131. /* To be used only when the state is known to be valid */
  80132. /* common constants */
  80133. #ifndef DEF_WBITS
  80134. # define DEF_WBITS MAX_WBITS
  80135. #endif
  80136. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80137. #if MAX_MEM_LEVEL >= 8
  80138. # define DEF_MEM_LEVEL 8
  80139. #else
  80140. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80141. #endif
  80142. /* default memLevel */
  80143. #define STORED_BLOCK 0
  80144. #define STATIC_TREES 1
  80145. #define DYN_TREES 2
  80146. /* The three kinds of block type */
  80147. #define MIN_MATCH 3
  80148. #define MAX_MATCH 258
  80149. /* The minimum and maximum match lengths */
  80150. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80151. /* target dependencies */
  80152. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80153. # define OS_CODE 0x00
  80154. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80155. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80156. /* Allow compilation with ANSI keywords only enabled */
  80157. void _Cdecl farfree( void *block );
  80158. void *_Cdecl farmalloc( unsigned long nbytes );
  80159. # else
  80160. # include <alloc.h>
  80161. # endif
  80162. # else /* MSC or DJGPP */
  80163. # include <malloc.h>
  80164. # endif
  80165. #endif
  80166. #ifdef AMIGA
  80167. # define OS_CODE 0x01
  80168. #endif
  80169. #if defined(VAXC) || defined(VMS)
  80170. # define OS_CODE 0x02
  80171. # define F_OPEN(name, mode) \
  80172. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80173. #endif
  80174. #if defined(ATARI) || defined(atarist)
  80175. # define OS_CODE 0x05
  80176. #endif
  80177. #ifdef OS2
  80178. # define OS_CODE 0x06
  80179. # ifdef M_I86
  80180. #include <malloc.h>
  80181. # endif
  80182. #endif
  80183. #if defined(MACOS) || TARGET_OS_MAC
  80184. # define OS_CODE 0x07
  80185. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80186. # include <unix.h> /* for fdopen */
  80187. # else
  80188. # ifndef fdopen
  80189. # define fdopen(fd,mode) NULL /* No fdopen() */
  80190. # endif
  80191. # endif
  80192. #endif
  80193. #ifdef TOPS20
  80194. # define OS_CODE 0x0a
  80195. #endif
  80196. #ifdef WIN32
  80197. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80198. # define OS_CODE 0x0b
  80199. # endif
  80200. #endif
  80201. #ifdef __50SERIES /* Prime/PRIMOS */
  80202. # define OS_CODE 0x0f
  80203. #endif
  80204. #if defined(_BEOS_) || defined(RISCOS)
  80205. # define fdopen(fd,mode) NULL /* No fdopen() */
  80206. #endif
  80207. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80208. # if defined(_WIN32_WCE)
  80209. # define fdopen(fd,mode) NULL /* No fdopen() */
  80210. # ifndef _PTRDIFF_T_DEFINED
  80211. typedef int ptrdiff_t;
  80212. # define _PTRDIFF_T_DEFINED
  80213. # endif
  80214. # else
  80215. # define fdopen(fd,type) _fdopen(fd,type)
  80216. # endif
  80217. #endif
  80218. /* common defaults */
  80219. #ifndef OS_CODE
  80220. # define OS_CODE 0x03 /* assume Unix */
  80221. #endif
  80222. #ifndef F_OPEN
  80223. # define F_OPEN(name, mode) fopen((name), (mode))
  80224. #endif
  80225. /* functions */
  80226. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80227. # ifndef HAVE_VSNPRINTF
  80228. # define HAVE_VSNPRINTF
  80229. # endif
  80230. #endif
  80231. #if defined(__CYGWIN__)
  80232. # ifndef HAVE_VSNPRINTF
  80233. # define HAVE_VSNPRINTF
  80234. # endif
  80235. #endif
  80236. #ifndef HAVE_VSNPRINTF
  80237. # ifdef MSDOS
  80238. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80239. but for now we just assume it doesn't. */
  80240. # define NO_vsnprintf
  80241. # endif
  80242. # ifdef __TURBOC__
  80243. # define NO_vsnprintf
  80244. # endif
  80245. # ifdef WIN32
  80246. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80247. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80248. # define vsnprintf _vsnprintf
  80249. # endif
  80250. # endif
  80251. # ifdef __SASC
  80252. # define NO_vsnprintf
  80253. # endif
  80254. #endif
  80255. #ifdef VMS
  80256. # define NO_vsnprintf
  80257. #endif
  80258. #if defined(pyr)
  80259. # define NO_MEMCPY
  80260. #endif
  80261. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80262. /* Use our own functions for small and medium model with MSC <= 5.0.
  80263. * You may have to use the same strategy for Borland C (untested).
  80264. * The __SC__ check is for Symantec.
  80265. */
  80266. # define NO_MEMCPY
  80267. #endif
  80268. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80269. # define HAVE_MEMCPY
  80270. #endif
  80271. #ifdef HAVE_MEMCPY
  80272. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80273. # define zmemcpy _fmemcpy
  80274. # define zmemcmp _fmemcmp
  80275. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80276. # else
  80277. # define zmemcpy memcpy
  80278. # define zmemcmp memcmp
  80279. # define zmemzero(dest, len) memset(dest, 0, len)
  80280. # endif
  80281. #else
  80282. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80283. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80284. extern void zmemzero OF((Bytef* dest, uInt len));
  80285. #endif
  80286. /* Diagnostic functions */
  80287. #ifdef DEBUG
  80288. # include <stdio.h>
  80289. extern int z_verbose;
  80290. extern void z_error OF((const char *m));
  80291. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80292. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80293. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80294. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80295. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80296. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80297. #else
  80298. # define Assert(cond,msg)
  80299. # define Trace(x)
  80300. # define Tracev(x)
  80301. # define Tracevv(x)
  80302. # define Tracec(c,x)
  80303. # define Tracecv(c,x)
  80304. #endif
  80305. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80306. void zcfree OF((voidpf opaque, voidpf ptr));
  80307. #define ZALLOC(strm, items, size) \
  80308. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80309. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80310. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80311. #endif /* ZUTIL_H */
  80312. /*** End of inlined file: zutil.h ***/
  80313. /* for STDC and FAR definitions */
  80314. #define local static
  80315. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80316. #ifndef NOBYFOUR
  80317. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80318. # include <limits.h>
  80319. # define BYFOUR
  80320. # if (UINT_MAX == 0xffffffffUL)
  80321. typedef unsigned int u4;
  80322. # else
  80323. # if (ULONG_MAX == 0xffffffffUL)
  80324. typedef unsigned long u4;
  80325. # else
  80326. # if (USHRT_MAX == 0xffffffffUL)
  80327. typedef unsigned short u4;
  80328. # else
  80329. # undef BYFOUR /* can't find a four-byte integer type! */
  80330. # endif
  80331. # endif
  80332. # endif
  80333. # endif /* STDC */
  80334. #endif /* !NOBYFOUR */
  80335. /* Definitions for doing the crc four data bytes at a time. */
  80336. #ifdef BYFOUR
  80337. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80338. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80339. local unsigned long crc32_little OF((unsigned long,
  80340. const unsigned char FAR *, unsigned));
  80341. local unsigned long crc32_big OF((unsigned long,
  80342. const unsigned char FAR *, unsigned));
  80343. # define TBLS 8
  80344. #else
  80345. # define TBLS 1
  80346. #endif /* BYFOUR */
  80347. /* Local functions for crc concatenation */
  80348. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80349. unsigned long vec));
  80350. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80351. #ifdef DYNAMIC_CRC_TABLE
  80352. local volatile int crc_table_empty = 1;
  80353. local unsigned long FAR crc_table[TBLS][256];
  80354. local void make_crc_table OF((void));
  80355. #ifdef MAKECRCH
  80356. local void write_table OF((FILE *, const unsigned long FAR *));
  80357. #endif /* MAKECRCH */
  80358. /*
  80359. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80360. 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.
  80361. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80362. with the lowest powers in the most significant bit. Then adding polynomials
  80363. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80364. one. If we call the above polynomial p, and represent a byte as the
  80365. polynomial q, also with the lowest power in the most significant bit (so the
  80366. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80367. where a mod b means the remainder after dividing a by b.
  80368. This calculation is done using the shift-register method of multiplying and
  80369. taking the remainder. The register is initialized to zero, and for each
  80370. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80371. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80372. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80373. out is a one). We start with the highest power (least significant bit) of
  80374. q and repeat for all eight bits of q.
  80375. The first table is simply the CRC of all possible eight bit values. This is
  80376. all the information needed to generate CRCs on data a byte at a time for all
  80377. combinations of CRC register values and incoming bytes. The remaining tables
  80378. allow for word-at-a-time CRC calculation for both big-endian and little-
  80379. endian machines, where a word is four bytes.
  80380. */
  80381. local void make_crc_table()
  80382. {
  80383. unsigned long c;
  80384. int n, k;
  80385. unsigned long poly; /* polynomial exclusive-or pattern */
  80386. /* terms of polynomial defining this crc (except x^32): */
  80387. static volatile int first = 1; /* flag to limit concurrent making */
  80388. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80389. /* See if another task is already doing this (not thread-safe, but better
  80390. than nothing -- significantly reduces duration of vulnerability in
  80391. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80392. if (first) {
  80393. first = 0;
  80394. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80395. poly = 0UL;
  80396. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80397. poly |= 1UL << (31 - p[n]);
  80398. /* generate a crc for every 8-bit value */
  80399. for (n = 0; n < 256; n++) {
  80400. c = (unsigned long)n;
  80401. for (k = 0; k < 8; k++)
  80402. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80403. crc_table[0][n] = c;
  80404. }
  80405. #ifdef BYFOUR
  80406. /* generate crc for each value followed by one, two, and three zeros,
  80407. and then the byte reversal of those as well as the first table */
  80408. for (n = 0; n < 256; n++) {
  80409. c = crc_table[0][n];
  80410. crc_table[4][n] = REV(c);
  80411. for (k = 1; k < 4; k++) {
  80412. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80413. crc_table[k][n] = c;
  80414. crc_table[k + 4][n] = REV(c);
  80415. }
  80416. }
  80417. #endif /* BYFOUR */
  80418. crc_table_empty = 0;
  80419. }
  80420. else { /* not first */
  80421. /* wait for the other guy to finish (not efficient, but rare) */
  80422. while (crc_table_empty)
  80423. ;
  80424. }
  80425. #ifdef MAKECRCH
  80426. /* write out CRC tables to crc32.h */
  80427. {
  80428. FILE *out;
  80429. out = fopen("crc32.h", "w");
  80430. if (out == NULL) return;
  80431. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80432. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80433. fprintf(out, "local const unsigned long FAR ");
  80434. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80435. write_table(out, crc_table[0]);
  80436. # ifdef BYFOUR
  80437. fprintf(out, "#ifdef BYFOUR\n");
  80438. for (k = 1; k < 8; k++) {
  80439. fprintf(out, " },\n {\n");
  80440. write_table(out, crc_table[k]);
  80441. }
  80442. fprintf(out, "#endif\n");
  80443. # endif /* BYFOUR */
  80444. fprintf(out, " }\n};\n");
  80445. fclose(out);
  80446. }
  80447. #endif /* MAKECRCH */
  80448. }
  80449. #ifdef MAKECRCH
  80450. local void write_table(out, table)
  80451. FILE *out;
  80452. const unsigned long FAR *table;
  80453. {
  80454. int n;
  80455. for (n = 0; n < 256; n++)
  80456. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80457. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80458. }
  80459. #endif /* MAKECRCH */
  80460. #else /* !DYNAMIC_CRC_TABLE */
  80461. /* ========================================================================
  80462. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80463. */
  80464. /*** Start of inlined file: crc32.h ***/
  80465. local const unsigned long FAR crc_table[TBLS][256] =
  80466. {
  80467. {
  80468. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80469. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80470. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80471. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80472. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80473. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80474. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80475. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80476. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80477. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80478. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80479. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80480. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80481. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80482. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80483. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80484. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80485. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80486. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80487. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80488. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80489. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80490. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80491. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80492. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80493. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80494. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80495. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80496. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80497. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80498. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80499. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80500. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80501. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80502. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80503. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80504. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80505. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80506. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80507. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80508. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80509. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80510. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80511. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80512. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80513. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80514. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80515. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80516. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80517. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80518. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80519. 0x2d02ef8dUL
  80520. #ifdef BYFOUR
  80521. },
  80522. {
  80523. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80524. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80525. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80526. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80527. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80528. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80529. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80530. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80531. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80532. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80533. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80534. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80535. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80536. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80537. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80538. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80539. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80540. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80541. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80542. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80543. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80544. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80545. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80546. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80547. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80548. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80549. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80550. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80551. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80552. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80553. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80554. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80555. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80556. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80557. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80558. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80559. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80560. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80561. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80562. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80563. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80564. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80565. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80566. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80567. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80568. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80569. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80570. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80571. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80572. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80573. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80574. 0x9324fd72UL
  80575. },
  80576. {
  80577. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80578. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80579. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80580. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80581. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80582. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80583. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80584. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80585. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80586. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80587. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80588. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80589. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80590. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80591. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80592. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80593. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80594. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80595. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80596. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80597. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80598. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80599. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80600. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80601. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80602. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80603. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80604. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80605. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80606. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80607. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80608. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80609. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80610. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80611. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80612. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80613. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80614. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80615. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80616. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80617. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80618. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80619. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80620. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80621. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80622. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80623. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80624. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80625. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80626. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80627. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80628. 0xbe9834edUL
  80629. },
  80630. {
  80631. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80632. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80633. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80634. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80635. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80636. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80637. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80638. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80639. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80640. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80641. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80642. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80643. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80644. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80645. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80646. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80647. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80648. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80649. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80650. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80651. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80652. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80653. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80654. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80655. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80656. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80657. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80658. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80659. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80660. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80661. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80662. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80663. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80664. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80665. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80666. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80667. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80668. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80669. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80670. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80671. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80672. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80673. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80674. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80675. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80676. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80677. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80678. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80679. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80680. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80681. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80682. 0xde0506f1UL
  80683. },
  80684. {
  80685. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80686. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80687. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80688. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80689. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80690. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80691. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80692. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80693. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80694. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80695. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80696. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80697. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80698. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80699. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80700. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80701. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80702. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80703. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80704. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80705. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80706. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80707. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80708. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80709. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80710. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80711. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80712. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80713. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80714. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80715. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80716. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80717. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80718. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80719. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80720. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80721. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80722. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80723. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80724. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80725. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80726. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80727. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80728. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80729. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80730. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80731. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80732. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80733. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80734. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80735. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80736. 0x8def022dUL
  80737. },
  80738. {
  80739. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80740. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80741. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80742. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80743. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80744. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80745. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80746. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80747. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80748. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80749. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80750. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80751. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80752. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80753. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80754. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80755. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80756. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80757. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80758. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80759. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80760. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80761. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80762. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80763. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80764. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80765. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80766. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80767. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80768. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80769. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80770. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80771. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80772. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80773. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80774. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80775. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80776. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80777. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80778. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80779. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80780. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80781. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80782. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80783. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80784. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80785. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80786. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80787. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80788. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80789. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80790. 0x72fd2493UL
  80791. },
  80792. {
  80793. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80794. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80795. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80796. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80797. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80798. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80799. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80800. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80801. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80802. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80803. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80804. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80805. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80806. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80807. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80808. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80809. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80810. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80811. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80812. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80813. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80814. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80815. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80816. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80817. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80818. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80819. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80820. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80821. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80822. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80823. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80824. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80825. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80826. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80827. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80828. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80829. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80830. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80831. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80832. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80833. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80834. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80835. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80836. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80837. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80838. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80839. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80840. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80841. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80842. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80843. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80844. 0xed3498beUL
  80845. },
  80846. {
  80847. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80848. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80849. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80850. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80851. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80852. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80853. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80854. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80855. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80856. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80857. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80858. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80859. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80860. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80861. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80862. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80863. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80864. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80865. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80866. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80867. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80868. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80869. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80870. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80871. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80872. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80873. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80874. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80875. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80876. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80877. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80878. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80879. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80880. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80881. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80882. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80883. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80884. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80885. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80886. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80887. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80888. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80889. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80890. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80891. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80892. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80893. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80894. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80895. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80896. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80897. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80898. 0xf10605deUL
  80899. #endif
  80900. }
  80901. };
  80902. /*** End of inlined file: crc32.h ***/
  80903. #endif /* DYNAMIC_CRC_TABLE */
  80904. /* =========================================================================
  80905. * This function can be used by asm versions of crc32()
  80906. */
  80907. const unsigned long FAR * ZEXPORT get_crc_table()
  80908. {
  80909. #ifdef DYNAMIC_CRC_TABLE
  80910. if (crc_table_empty)
  80911. make_crc_table();
  80912. #endif /* DYNAMIC_CRC_TABLE */
  80913. return (const unsigned long FAR *)crc_table;
  80914. }
  80915. /* ========================================================================= */
  80916. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80917. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80918. /* ========================================================================= */
  80919. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80920. {
  80921. if (buf == Z_NULL) return 0UL;
  80922. #ifdef DYNAMIC_CRC_TABLE
  80923. if (crc_table_empty)
  80924. make_crc_table();
  80925. #endif /* DYNAMIC_CRC_TABLE */
  80926. #ifdef BYFOUR
  80927. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80928. u4 endian;
  80929. endian = 1;
  80930. if (*((unsigned char *)(&endian)))
  80931. return crc32_little(crc, buf, len);
  80932. else
  80933. return crc32_big(crc, buf, len);
  80934. }
  80935. #endif /* BYFOUR */
  80936. crc = crc ^ 0xffffffffUL;
  80937. while (len >= 8) {
  80938. DO8;
  80939. len -= 8;
  80940. }
  80941. if (len) do {
  80942. DO1;
  80943. } while (--len);
  80944. return crc ^ 0xffffffffUL;
  80945. }
  80946. #ifdef BYFOUR
  80947. /* ========================================================================= */
  80948. #define DOLIT4 c ^= *buf4++; \
  80949. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80950. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80951. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80952. /* ========================================================================= */
  80953. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80954. {
  80955. register u4 c;
  80956. register const u4 FAR *buf4;
  80957. c = (u4)crc;
  80958. c = ~c;
  80959. while (len && ((ptrdiff_t)buf & 3)) {
  80960. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80961. len--;
  80962. }
  80963. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80964. while (len >= 32) {
  80965. DOLIT32;
  80966. len -= 32;
  80967. }
  80968. while (len >= 4) {
  80969. DOLIT4;
  80970. len -= 4;
  80971. }
  80972. buf = (const unsigned char FAR *)buf4;
  80973. if (len) do {
  80974. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80975. } while (--len);
  80976. c = ~c;
  80977. return (unsigned long)c;
  80978. }
  80979. /* ========================================================================= */
  80980. #define DOBIG4 c ^= *++buf4; \
  80981. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80982. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80983. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80984. /* ========================================================================= */
  80985. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80986. {
  80987. register u4 c;
  80988. register const u4 FAR *buf4;
  80989. c = REV((u4)crc);
  80990. c = ~c;
  80991. while (len && ((ptrdiff_t)buf & 3)) {
  80992. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80993. len--;
  80994. }
  80995. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80996. buf4--;
  80997. while (len >= 32) {
  80998. DOBIG32;
  80999. len -= 32;
  81000. }
  81001. while (len >= 4) {
  81002. DOBIG4;
  81003. len -= 4;
  81004. }
  81005. buf4++;
  81006. buf = (const unsigned char FAR *)buf4;
  81007. if (len) do {
  81008. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81009. } while (--len);
  81010. c = ~c;
  81011. return (unsigned long)(REV(c));
  81012. }
  81013. #endif /* BYFOUR */
  81014. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81015. /* ========================================================================= */
  81016. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81017. {
  81018. unsigned long sum;
  81019. sum = 0;
  81020. while (vec) {
  81021. if (vec & 1)
  81022. sum ^= *mat;
  81023. vec >>= 1;
  81024. mat++;
  81025. }
  81026. return sum;
  81027. }
  81028. /* ========================================================================= */
  81029. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81030. {
  81031. int n;
  81032. for (n = 0; n < GF2_DIM; n++)
  81033. square[n] = gf2_matrix_times(mat, mat[n]);
  81034. }
  81035. /* ========================================================================= */
  81036. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81037. {
  81038. int n;
  81039. unsigned long row;
  81040. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81041. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81042. /* degenerate case */
  81043. if (len2 == 0)
  81044. return crc1;
  81045. /* put operator for one zero bit in odd */
  81046. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81047. row = 1;
  81048. for (n = 1; n < GF2_DIM; n++) {
  81049. odd[n] = row;
  81050. row <<= 1;
  81051. }
  81052. /* put operator for two zero bits in even */
  81053. gf2_matrix_square(even, odd);
  81054. /* put operator for four zero bits in odd */
  81055. gf2_matrix_square(odd, even);
  81056. /* apply len2 zeros to crc1 (first square will put the operator for one
  81057. zero byte, eight zero bits, in even) */
  81058. do {
  81059. /* apply zeros operator for this bit of len2 */
  81060. gf2_matrix_square(even, odd);
  81061. if (len2 & 1)
  81062. crc1 = gf2_matrix_times(even, crc1);
  81063. len2 >>= 1;
  81064. /* if no more bits set, then done */
  81065. if (len2 == 0)
  81066. break;
  81067. /* another iteration of the loop with odd and even swapped */
  81068. gf2_matrix_square(odd, even);
  81069. if (len2 & 1)
  81070. crc1 = gf2_matrix_times(odd, crc1);
  81071. len2 >>= 1;
  81072. /* if no more bits set, then done */
  81073. } while (len2 != 0);
  81074. /* return combined crc */
  81075. crc1 ^= crc2;
  81076. return crc1;
  81077. }
  81078. /*** End of inlined file: crc32.c ***/
  81079. /*** Start of inlined file: deflate.c ***/
  81080. /*
  81081. * ALGORITHM
  81082. *
  81083. * The "deflation" process depends on being able to identify portions
  81084. * of the input text which are identical to earlier input (within a
  81085. * sliding window trailing behind the input currently being processed).
  81086. *
  81087. * The most straightforward technique turns out to be the fastest for
  81088. * most input files: try all possible matches and select the longest.
  81089. * The key feature of this algorithm is that insertions into the string
  81090. * dictionary are very simple and thus fast, and deletions are avoided
  81091. * completely. Insertions are performed at each input character, whereas
  81092. * string matches are performed only when the previous match ends. So it
  81093. * is preferable to spend more time in matches to allow very fast string
  81094. * insertions and avoid deletions. The matching algorithm for small
  81095. * strings is inspired from that of Rabin & Karp. A brute force approach
  81096. * is used to find longer strings when a small match has been found.
  81097. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81098. * (by Leonid Broukhis).
  81099. * A previous version of this file used a more sophisticated algorithm
  81100. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81101. * time, but has a larger average cost, uses more memory and is patented.
  81102. * However the F&G algorithm may be faster for some highly redundant
  81103. * files if the parameter max_chain_length (described below) is too large.
  81104. *
  81105. * ACKNOWLEDGEMENTS
  81106. *
  81107. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81108. * I found it in 'freeze' written by Leonid Broukhis.
  81109. * Thanks to many people for bug reports and testing.
  81110. *
  81111. * REFERENCES
  81112. *
  81113. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81114. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81115. *
  81116. * A description of the Rabin and Karp algorithm is given in the book
  81117. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81118. *
  81119. * Fiala,E.R., and Greene,D.H.
  81120. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81121. *
  81122. */
  81123. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81124. /*** Start of inlined file: deflate.h ***/
  81125. /* WARNING: this file should *not* be used by applications. It is
  81126. part of the implementation of the compression library and is
  81127. subject to change. Applications should only use zlib.h.
  81128. */
  81129. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81130. #ifndef DEFLATE_H
  81131. #define DEFLATE_H
  81132. /* define NO_GZIP when compiling if you want to disable gzip header and
  81133. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81134. the crc code when it is not needed. For shared libraries, gzip encoding
  81135. should be left enabled. */
  81136. #ifndef NO_GZIP
  81137. # define GZIP
  81138. #endif
  81139. #define NO_DUMMY_DECL
  81140. /* ===========================================================================
  81141. * Internal compression state.
  81142. */
  81143. #define LENGTH_CODES 29
  81144. /* number of length codes, not counting the special END_BLOCK code */
  81145. #define LITERALS 256
  81146. /* number of literal bytes 0..255 */
  81147. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81148. /* number of Literal or Length codes, including the END_BLOCK code */
  81149. #define D_CODES 30
  81150. /* number of distance codes */
  81151. #define BL_CODES 19
  81152. /* number of codes used to transfer the bit lengths */
  81153. #define HEAP_SIZE (2*L_CODES+1)
  81154. /* maximum heap size */
  81155. #define MAX_BITS 15
  81156. /* All codes must not exceed MAX_BITS bits */
  81157. #define INIT_STATE 42
  81158. #define EXTRA_STATE 69
  81159. #define NAME_STATE 73
  81160. #define COMMENT_STATE 91
  81161. #define HCRC_STATE 103
  81162. #define BUSY_STATE 113
  81163. #define FINISH_STATE 666
  81164. /* Stream status */
  81165. /* Data structure describing a single value and its code string. */
  81166. typedef struct ct_data_s {
  81167. union {
  81168. ush freq; /* frequency count */
  81169. ush code; /* bit string */
  81170. } fc;
  81171. union {
  81172. ush dad; /* father node in Huffman tree */
  81173. ush len; /* length of bit string */
  81174. } dl;
  81175. } FAR ct_data;
  81176. #define Freq fc.freq
  81177. #define Code fc.code
  81178. #define Dad dl.dad
  81179. #define Len dl.len
  81180. typedef struct static_tree_desc_s static_tree_desc;
  81181. typedef struct tree_desc_s {
  81182. ct_data *dyn_tree; /* the dynamic tree */
  81183. int max_code; /* largest code with non zero frequency */
  81184. static_tree_desc *stat_desc; /* the corresponding static tree */
  81185. } FAR tree_desc;
  81186. typedef ush Pos;
  81187. typedef Pos FAR Posf;
  81188. typedef unsigned IPos;
  81189. /* A Pos is an index in the character window. We use short instead of int to
  81190. * save space in the various tables. IPos is used only for parameter passing.
  81191. */
  81192. typedef struct internal_state {
  81193. z_streamp strm; /* pointer back to this zlib stream */
  81194. int status; /* as the name implies */
  81195. Bytef *pending_buf; /* output still pending */
  81196. ulg pending_buf_size; /* size of pending_buf */
  81197. Bytef *pending_out; /* next pending byte to output to the stream */
  81198. uInt pending; /* nb of bytes in the pending buffer */
  81199. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81200. gz_headerp gzhead; /* gzip header information to write */
  81201. uInt gzindex; /* where in extra, name, or comment */
  81202. Byte method; /* STORED (for zip only) or DEFLATED */
  81203. int last_flush; /* value of flush param for previous deflate call */
  81204. /* used by deflate.c: */
  81205. uInt w_size; /* LZ77 window size (32K by default) */
  81206. uInt w_bits; /* log2(w_size) (8..16) */
  81207. uInt w_mask; /* w_size - 1 */
  81208. Bytef *window;
  81209. /* Sliding window. Input bytes are read into the second half of the window,
  81210. * and move to the first half later to keep a dictionary of at least wSize
  81211. * bytes. With this organization, matches are limited to a distance of
  81212. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81213. * performed with a length multiple of the block size. Also, it limits
  81214. * the window size to 64K, which is quite useful on MSDOS.
  81215. * To do: use the user input buffer as sliding window.
  81216. */
  81217. ulg window_size;
  81218. /* Actual size of window: 2*wSize, except when the user input buffer
  81219. * is directly used as sliding window.
  81220. */
  81221. Posf *prev;
  81222. /* Link to older string with same hash index. To limit the size of this
  81223. * array to 64K, this link is maintained only for the last 32K strings.
  81224. * An index in this array is thus a window index modulo 32K.
  81225. */
  81226. Posf *head; /* Heads of the hash chains or NIL. */
  81227. uInt ins_h; /* hash index of string to be inserted */
  81228. uInt hash_size; /* number of elements in hash table */
  81229. uInt hash_bits; /* log2(hash_size) */
  81230. uInt hash_mask; /* hash_size-1 */
  81231. uInt hash_shift;
  81232. /* Number of bits by which ins_h must be shifted at each input
  81233. * step. It must be such that after MIN_MATCH steps, the oldest
  81234. * byte no longer takes part in the hash key, that is:
  81235. * hash_shift * MIN_MATCH >= hash_bits
  81236. */
  81237. long block_start;
  81238. /* Window position at the beginning of the current output block. Gets
  81239. * negative when the window is moved backwards.
  81240. */
  81241. uInt match_length; /* length of best match */
  81242. IPos prev_match; /* previous match */
  81243. int match_available; /* set if previous match exists */
  81244. uInt strstart; /* start of string to insert */
  81245. uInt match_start; /* start of matching string */
  81246. uInt lookahead; /* number of valid bytes ahead in window */
  81247. uInt prev_length;
  81248. /* Length of the best match at previous step. Matches not greater than this
  81249. * are discarded. This is used in the lazy match evaluation.
  81250. */
  81251. uInt max_chain_length;
  81252. /* To speed up deflation, hash chains are never searched beyond this
  81253. * length. A higher limit improves compression ratio but degrades the
  81254. * speed.
  81255. */
  81256. uInt max_lazy_match;
  81257. /* Attempt to find a better match only when the current match is strictly
  81258. * smaller than this value. This mechanism is used only for compression
  81259. * levels >= 4.
  81260. */
  81261. # define max_insert_length max_lazy_match
  81262. /* Insert new strings in the hash table only if the match length is not
  81263. * greater than this length. This saves time but degrades compression.
  81264. * max_insert_length is used only for compression levels <= 3.
  81265. */
  81266. int level; /* compression level (1..9) */
  81267. int strategy; /* favor or force Huffman coding*/
  81268. uInt good_match;
  81269. /* Use a faster search when the previous match is longer than this */
  81270. int nice_match; /* Stop searching when current match exceeds this */
  81271. /* used by trees.c: */
  81272. /* Didn't use ct_data typedef below to supress compiler warning */
  81273. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81274. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81275. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81276. struct tree_desc_s l_desc; /* desc. for literal tree */
  81277. struct tree_desc_s d_desc; /* desc. for distance tree */
  81278. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81279. ush bl_count[MAX_BITS+1];
  81280. /* number of codes at each bit length for an optimal tree */
  81281. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81282. int heap_len; /* number of elements in the heap */
  81283. int heap_max; /* element of largest frequency */
  81284. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81285. * The same heap array is used to build all trees.
  81286. */
  81287. uch depth[2*L_CODES+1];
  81288. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81289. */
  81290. uchf *l_buf; /* buffer for literals or lengths */
  81291. uInt lit_bufsize;
  81292. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81293. * limiting lit_bufsize to 64K:
  81294. * - frequencies can be kept in 16 bit counters
  81295. * - if compression is not successful for the first block, all input
  81296. * data is still in the window so we can still emit a stored block even
  81297. * when input comes from standard input. (This can also be done for
  81298. * all blocks if lit_bufsize is not greater than 32K.)
  81299. * - if compression is not successful for a file smaller than 64K, we can
  81300. * even emit a stored file instead of a stored block (saving 5 bytes).
  81301. * This is applicable only for zip (not gzip or zlib).
  81302. * - creating new Huffman trees less frequently may not provide fast
  81303. * adaptation to changes in the input data statistics. (Take for
  81304. * example a binary file with poorly compressible code followed by
  81305. * a highly compressible string table.) Smaller buffer sizes give
  81306. * fast adaptation but have of course the overhead of transmitting
  81307. * trees more frequently.
  81308. * - I can't count above 4
  81309. */
  81310. uInt last_lit; /* running index in l_buf */
  81311. ushf *d_buf;
  81312. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81313. * the same number of elements. To use different lengths, an extra flag
  81314. * array would be necessary.
  81315. */
  81316. ulg opt_len; /* bit length of current block with optimal trees */
  81317. ulg static_len; /* bit length of current block with static trees */
  81318. uInt matches; /* number of string matches in current block */
  81319. int last_eob_len; /* bit length of EOB code for last block */
  81320. #ifdef DEBUG
  81321. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81322. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81323. #endif
  81324. ush bi_buf;
  81325. /* Output buffer. bits are inserted starting at the bottom (least
  81326. * significant bits).
  81327. */
  81328. int bi_valid;
  81329. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81330. * are always zero.
  81331. */
  81332. } FAR deflate_state;
  81333. /* Output a byte on the stream.
  81334. * IN assertion: there is enough room in pending_buf.
  81335. */
  81336. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81337. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81338. /* Minimum amount of lookahead, except at the end of the input file.
  81339. * See deflate.c for comments about the MIN_MATCH+1.
  81340. */
  81341. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81342. /* In order to simplify the code, particularly on 16 bit machines, match
  81343. * distances are limited to MAX_DIST instead of WSIZE.
  81344. */
  81345. /* in trees.c */
  81346. void _tr_init OF((deflate_state *s));
  81347. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81348. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81349. int eof));
  81350. void _tr_align OF((deflate_state *s));
  81351. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81352. int eof));
  81353. #define d_code(dist) \
  81354. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81355. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81356. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81357. * used.
  81358. */
  81359. #ifndef DEBUG
  81360. /* Inline versions of _tr_tally for speed: */
  81361. #if defined(GEN_TREES_H) || !defined(STDC)
  81362. extern uch _length_code[];
  81363. extern uch _dist_code[];
  81364. #else
  81365. extern const uch _length_code[];
  81366. extern const uch _dist_code[];
  81367. #endif
  81368. # define _tr_tally_lit(s, c, flush) \
  81369. { uch cc = (c); \
  81370. s->d_buf[s->last_lit] = 0; \
  81371. s->l_buf[s->last_lit++] = cc; \
  81372. s->dyn_ltree[cc].Freq++; \
  81373. flush = (s->last_lit == s->lit_bufsize-1); \
  81374. }
  81375. # define _tr_tally_dist(s, distance, length, flush) \
  81376. { uch len = (length); \
  81377. ush dist = (distance); \
  81378. s->d_buf[s->last_lit] = dist; \
  81379. s->l_buf[s->last_lit++] = len; \
  81380. dist--; \
  81381. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81382. s->dyn_dtree[d_code(dist)].Freq++; \
  81383. flush = (s->last_lit == s->lit_bufsize-1); \
  81384. }
  81385. #else
  81386. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81387. # define _tr_tally_dist(s, distance, length, flush) \
  81388. flush = _tr_tally(s, distance, length)
  81389. #endif
  81390. #endif /* DEFLATE_H */
  81391. /*** End of inlined file: deflate.h ***/
  81392. const char deflate_copyright[] =
  81393. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81394. /*
  81395. If you use the zlib library in a product, an acknowledgment is welcome
  81396. in the documentation of your product. If for some reason you cannot
  81397. include such an acknowledgment, I would appreciate that you keep this
  81398. copyright string in the executable of your product.
  81399. */
  81400. /* ===========================================================================
  81401. * Function prototypes.
  81402. */
  81403. typedef enum {
  81404. need_more, /* block not completed, need more input or more output */
  81405. block_done, /* block flush performed */
  81406. finish_started, /* finish started, need only more output at next deflate */
  81407. finish_done /* finish done, accept no more input or output */
  81408. } block_state;
  81409. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81410. /* Compression function. Returns the block state after the call. */
  81411. local void fill_window OF((deflate_state *s));
  81412. local block_state deflate_stored OF((deflate_state *s, int flush));
  81413. local block_state deflate_fast OF((deflate_state *s, int flush));
  81414. #ifndef FASTEST
  81415. local block_state deflate_slow OF((deflate_state *s, int flush));
  81416. #endif
  81417. local void lm_init OF((deflate_state *s));
  81418. local void putShortMSB OF((deflate_state *s, uInt b));
  81419. local void flush_pending OF((z_streamp strm));
  81420. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81421. #ifndef FASTEST
  81422. #ifdef ASMV
  81423. void match_init OF((void)); /* asm code initialization */
  81424. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81425. #else
  81426. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81427. #endif
  81428. #endif
  81429. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81430. #ifdef DEBUG
  81431. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81432. int length));
  81433. #endif
  81434. /* ===========================================================================
  81435. * Local data
  81436. */
  81437. #define NIL 0
  81438. /* Tail of hash chains */
  81439. #ifndef TOO_FAR
  81440. # define TOO_FAR 4096
  81441. #endif
  81442. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81443. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81444. /* Minimum amount of lookahead, except at the end of the input file.
  81445. * See deflate.c for comments about the MIN_MATCH+1.
  81446. */
  81447. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81448. * the desired pack level (0..9). The values given below have been tuned to
  81449. * exclude worst case performance for pathological files. Better values may be
  81450. * found for specific files.
  81451. */
  81452. typedef struct config_s {
  81453. ush good_length; /* reduce lazy search above this match length */
  81454. ush max_lazy; /* do not perform lazy search above this match length */
  81455. ush nice_length; /* quit search above this match length */
  81456. ush max_chain;
  81457. compress_func func;
  81458. } config;
  81459. #ifdef FASTEST
  81460. local const config configuration_table[2] = {
  81461. /* good lazy nice chain */
  81462. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81463. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81464. #else
  81465. local const config configuration_table[10] = {
  81466. /* good lazy nice chain */
  81467. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81468. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81469. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81470. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81471. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81472. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81473. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81474. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81475. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81476. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81477. #endif
  81478. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81479. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81480. * meaning.
  81481. */
  81482. #define EQUAL 0
  81483. /* result of memcmp for equal strings */
  81484. #ifndef NO_DUMMY_DECL
  81485. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81486. #endif
  81487. /* ===========================================================================
  81488. * Update a hash value with the given input byte
  81489. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81490. * input characters, so that a running hash key can be computed from the
  81491. * previous key instead of complete recalculation each time.
  81492. */
  81493. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81494. /* ===========================================================================
  81495. * Insert string str in the dictionary and set match_head to the previous head
  81496. * of the hash chain (the most recent string with same hash key). Return
  81497. * the previous length of the hash chain.
  81498. * If this file is compiled with -DFASTEST, the compression level is forced
  81499. * to 1, and no hash chains are maintained.
  81500. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81501. * input characters and the first MIN_MATCH bytes of str are valid
  81502. * (except for the last MIN_MATCH-1 bytes of the input file).
  81503. */
  81504. #ifdef FASTEST
  81505. #define INSERT_STRING(s, str, match_head) \
  81506. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81507. match_head = s->head[s->ins_h], \
  81508. s->head[s->ins_h] = (Pos)(str))
  81509. #else
  81510. #define INSERT_STRING(s, str, match_head) \
  81511. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81512. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81513. s->head[s->ins_h] = (Pos)(str))
  81514. #endif
  81515. /* ===========================================================================
  81516. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81517. * prev[] will be initialized on the fly.
  81518. */
  81519. #define CLEAR_HASH(s) \
  81520. s->head[s->hash_size-1] = NIL; \
  81521. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81522. /* ========================================================================= */
  81523. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81524. {
  81525. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81526. Z_DEFAULT_STRATEGY, version, stream_size);
  81527. /* To do: ignore strm->next_in if we use it as window */
  81528. }
  81529. /* ========================================================================= */
  81530. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81531. {
  81532. deflate_state *s;
  81533. int wrap = 1;
  81534. static const char my_version[] = ZLIB_VERSION;
  81535. ushf *overlay;
  81536. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81537. * output size for (length,distance) codes is <= 24 bits.
  81538. */
  81539. if (version == Z_NULL || version[0] != my_version[0] ||
  81540. stream_size != sizeof(z_stream)) {
  81541. return Z_VERSION_ERROR;
  81542. }
  81543. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81544. strm->msg = Z_NULL;
  81545. if (strm->zalloc == (alloc_func)0) {
  81546. strm->zalloc = zcalloc;
  81547. strm->opaque = (voidpf)0;
  81548. }
  81549. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81550. #ifdef FASTEST
  81551. if (level != 0) level = 1;
  81552. #else
  81553. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81554. #endif
  81555. if (windowBits < 0) { /* suppress zlib wrapper */
  81556. wrap = 0;
  81557. windowBits = -windowBits;
  81558. }
  81559. #ifdef GZIP
  81560. else if (windowBits > 15) {
  81561. wrap = 2; /* write gzip wrapper instead */
  81562. windowBits -= 16;
  81563. }
  81564. #endif
  81565. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81566. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81567. strategy < 0 || strategy > Z_FIXED) {
  81568. return Z_STREAM_ERROR;
  81569. }
  81570. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81571. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81572. if (s == Z_NULL) return Z_MEM_ERROR;
  81573. strm->state = (struct internal_state FAR *)s;
  81574. s->strm = strm;
  81575. s->wrap = wrap;
  81576. s->gzhead = Z_NULL;
  81577. s->w_bits = windowBits;
  81578. s->w_size = 1 << s->w_bits;
  81579. s->w_mask = s->w_size - 1;
  81580. s->hash_bits = memLevel + 7;
  81581. s->hash_size = 1 << s->hash_bits;
  81582. s->hash_mask = s->hash_size - 1;
  81583. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81584. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81585. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81586. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81587. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81588. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81589. s->pending_buf = (uchf *) overlay;
  81590. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81591. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81592. s->pending_buf == Z_NULL) {
  81593. s->status = FINISH_STATE;
  81594. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81595. deflateEnd (strm);
  81596. return Z_MEM_ERROR;
  81597. }
  81598. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81599. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81600. s->level = level;
  81601. s->strategy = strategy;
  81602. s->method = (Byte)method;
  81603. return deflateReset(strm);
  81604. }
  81605. /* ========================================================================= */
  81606. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81607. {
  81608. deflate_state *s;
  81609. uInt length = dictLength;
  81610. uInt n;
  81611. IPos hash_head = 0;
  81612. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81613. strm->state->wrap == 2 ||
  81614. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81615. return Z_STREAM_ERROR;
  81616. s = strm->state;
  81617. if (s->wrap)
  81618. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81619. if (length < MIN_MATCH) return Z_OK;
  81620. if (length > MAX_DIST(s)) {
  81621. length = MAX_DIST(s);
  81622. dictionary += dictLength - length; /* use the tail of the dictionary */
  81623. }
  81624. zmemcpy(s->window, dictionary, length);
  81625. s->strstart = length;
  81626. s->block_start = (long)length;
  81627. /* Insert all strings in the hash table (except for the last two bytes).
  81628. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81629. * call of fill_window.
  81630. */
  81631. s->ins_h = s->window[0];
  81632. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81633. for (n = 0; n <= length - MIN_MATCH; n++) {
  81634. INSERT_STRING(s, n, hash_head);
  81635. }
  81636. if (hash_head) hash_head = 0; /* to make compiler happy */
  81637. return Z_OK;
  81638. }
  81639. /* ========================================================================= */
  81640. int ZEXPORT deflateReset (z_streamp strm)
  81641. {
  81642. deflate_state *s;
  81643. if (strm == Z_NULL || strm->state == Z_NULL ||
  81644. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81645. return Z_STREAM_ERROR;
  81646. }
  81647. strm->total_in = strm->total_out = 0;
  81648. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81649. strm->data_type = Z_UNKNOWN;
  81650. s = (deflate_state *)strm->state;
  81651. s->pending = 0;
  81652. s->pending_out = s->pending_buf;
  81653. if (s->wrap < 0) {
  81654. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81655. }
  81656. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81657. strm->adler =
  81658. #ifdef GZIP
  81659. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81660. #endif
  81661. adler32(0L, Z_NULL, 0);
  81662. s->last_flush = Z_NO_FLUSH;
  81663. _tr_init(s);
  81664. lm_init(s);
  81665. return Z_OK;
  81666. }
  81667. /* ========================================================================= */
  81668. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81669. {
  81670. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81671. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81672. strm->state->gzhead = head;
  81673. return Z_OK;
  81674. }
  81675. /* ========================================================================= */
  81676. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81677. {
  81678. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81679. strm->state->bi_valid = bits;
  81680. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81681. return Z_OK;
  81682. }
  81683. /* ========================================================================= */
  81684. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81685. {
  81686. deflate_state *s;
  81687. compress_func func;
  81688. int err = Z_OK;
  81689. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81690. s = strm->state;
  81691. #ifdef FASTEST
  81692. if (level != 0) level = 1;
  81693. #else
  81694. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81695. #endif
  81696. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81697. return Z_STREAM_ERROR;
  81698. }
  81699. func = configuration_table[s->level].func;
  81700. if (func != configuration_table[level].func && strm->total_in != 0) {
  81701. /* Flush the last buffer: */
  81702. err = deflate(strm, Z_PARTIAL_FLUSH);
  81703. }
  81704. if (s->level != level) {
  81705. s->level = level;
  81706. s->max_lazy_match = configuration_table[level].max_lazy;
  81707. s->good_match = configuration_table[level].good_length;
  81708. s->nice_match = configuration_table[level].nice_length;
  81709. s->max_chain_length = configuration_table[level].max_chain;
  81710. }
  81711. s->strategy = strategy;
  81712. return err;
  81713. }
  81714. /* ========================================================================= */
  81715. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81716. {
  81717. deflate_state *s;
  81718. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81719. s = strm->state;
  81720. s->good_match = good_length;
  81721. s->max_lazy_match = max_lazy;
  81722. s->nice_match = nice_length;
  81723. s->max_chain_length = max_chain;
  81724. return Z_OK;
  81725. }
  81726. /* =========================================================================
  81727. * For the default windowBits of 15 and memLevel of 8, this function returns
  81728. * a close to exact, as well as small, upper bound on the compressed size.
  81729. * They are coded as constants here for a reason--if the #define's are
  81730. * changed, then this function needs to be changed as well. The return
  81731. * value for 15 and 8 only works for those exact settings.
  81732. *
  81733. * For any setting other than those defaults for windowBits and memLevel,
  81734. * the value returned is a conservative worst case for the maximum expansion
  81735. * resulting from using fixed blocks instead of stored blocks, which deflate
  81736. * can emit on compressed data for some combinations of the parameters.
  81737. *
  81738. * This function could be more sophisticated to provide closer upper bounds
  81739. * for every combination of windowBits and memLevel, as well as wrap.
  81740. * But even the conservative upper bound of about 14% expansion does not
  81741. * seem onerous for output buffer allocation.
  81742. */
  81743. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81744. {
  81745. deflate_state *s;
  81746. uLong destLen;
  81747. /* conservative upper bound */
  81748. destLen = sourceLen +
  81749. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81750. /* if can't get parameters, return conservative bound */
  81751. if (strm == Z_NULL || strm->state == Z_NULL)
  81752. return destLen;
  81753. /* if not default parameters, return conservative bound */
  81754. s = strm->state;
  81755. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81756. return destLen;
  81757. /* default settings: return tight bound for that case */
  81758. return compressBound(sourceLen);
  81759. }
  81760. /* =========================================================================
  81761. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81762. * IN assertion: the stream state is correct and there is enough room in
  81763. * pending_buf.
  81764. */
  81765. local void putShortMSB (deflate_state *s, uInt b)
  81766. {
  81767. put_byte(s, (Byte)(b >> 8));
  81768. put_byte(s, (Byte)(b & 0xff));
  81769. }
  81770. /* =========================================================================
  81771. * Flush as much pending output as possible. All deflate() output goes
  81772. * through this function so some applications may wish to modify it
  81773. * to avoid allocating a large strm->next_out buffer and copying into it.
  81774. * (See also read_buf()).
  81775. */
  81776. local void flush_pending (z_streamp strm)
  81777. {
  81778. unsigned len = strm->state->pending;
  81779. if (len > strm->avail_out) len = strm->avail_out;
  81780. if (len == 0) return;
  81781. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81782. strm->next_out += len;
  81783. strm->state->pending_out += len;
  81784. strm->total_out += len;
  81785. strm->avail_out -= len;
  81786. strm->state->pending -= len;
  81787. if (strm->state->pending == 0) {
  81788. strm->state->pending_out = strm->state->pending_buf;
  81789. }
  81790. }
  81791. /* ========================================================================= */
  81792. int ZEXPORT deflate (z_streamp strm, int flush)
  81793. {
  81794. int old_flush; /* value of flush param for previous deflate call */
  81795. deflate_state *s;
  81796. if (strm == Z_NULL || strm->state == Z_NULL ||
  81797. flush > Z_FINISH || flush < 0) {
  81798. return Z_STREAM_ERROR;
  81799. }
  81800. s = strm->state;
  81801. if (strm->next_out == Z_NULL ||
  81802. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81803. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81804. ERR_RETURN(strm, Z_STREAM_ERROR);
  81805. }
  81806. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81807. s->strm = strm; /* just in case */
  81808. old_flush = s->last_flush;
  81809. s->last_flush = flush;
  81810. /* Write the header */
  81811. if (s->status == INIT_STATE) {
  81812. #ifdef GZIP
  81813. if (s->wrap == 2) {
  81814. strm->adler = crc32(0L, Z_NULL, 0);
  81815. put_byte(s, 31);
  81816. put_byte(s, 139);
  81817. put_byte(s, 8);
  81818. if (s->gzhead == NULL) {
  81819. put_byte(s, 0);
  81820. put_byte(s, 0);
  81821. put_byte(s, 0);
  81822. put_byte(s, 0);
  81823. put_byte(s, 0);
  81824. put_byte(s, s->level == 9 ? 2 :
  81825. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81826. 4 : 0));
  81827. put_byte(s, OS_CODE);
  81828. s->status = BUSY_STATE;
  81829. }
  81830. else {
  81831. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81832. (s->gzhead->hcrc ? 2 : 0) +
  81833. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81834. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81835. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81836. );
  81837. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81838. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81839. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81840. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81841. put_byte(s, s->level == 9 ? 2 :
  81842. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81843. 4 : 0));
  81844. put_byte(s, s->gzhead->os & 0xff);
  81845. if (s->gzhead->extra != NULL) {
  81846. put_byte(s, s->gzhead->extra_len & 0xff);
  81847. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81848. }
  81849. if (s->gzhead->hcrc)
  81850. strm->adler = crc32(strm->adler, s->pending_buf,
  81851. s->pending);
  81852. s->gzindex = 0;
  81853. s->status = EXTRA_STATE;
  81854. }
  81855. }
  81856. else
  81857. #endif
  81858. {
  81859. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81860. uInt level_flags;
  81861. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81862. level_flags = 0;
  81863. else if (s->level < 6)
  81864. level_flags = 1;
  81865. else if (s->level == 6)
  81866. level_flags = 2;
  81867. else
  81868. level_flags = 3;
  81869. header |= (level_flags << 6);
  81870. if (s->strstart != 0) header |= PRESET_DICT;
  81871. header += 31 - (header % 31);
  81872. s->status = BUSY_STATE;
  81873. putShortMSB(s, header);
  81874. /* Save the adler32 of the preset dictionary: */
  81875. if (s->strstart != 0) {
  81876. putShortMSB(s, (uInt)(strm->adler >> 16));
  81877. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81878. }
  81879. strm->adler = adler32(0L, Z_NULL, 0);
  81880. }
  81881. }
  81882. #ifdef GZIP
  81883. if (s->status == EXTRA_STATE) {
  81884. if (s->gzhead->extra != NULL) {
  81885. uInt beg = s->pending; /* start of bytes to update crc */
  81886. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81887. if (s->pending == s->pending_buf_size) {
  81888. if (s->gzhead->hcrc && s->pending > beg)
  81889. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81890. s->pending - beg);
  81891. flush_pending(strm);
  81892. beg = s->pending;
  81893. if (s->pending == s->pending_buf_size)
  81894. break;
  81895. }
  81896. put_byte(s, s->gzhead->extra[s->gzindex]);
  81897. s->gzindex++;
  81898. }
  81899. if (s->gzhead->hcrc && s->pending > beg)
  81900. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81901. s->pending - beg);
  81902. if (s->gzindex == s->gzhead->extra_len) {
  81903. s->gzindex = 0;
  81904. s->status = NAME_STATE;
  81905. }
  81906. }
  81907. else
  81908. s->status = NAME_STATE;
  81909. }
  81910. if (s->status == NAME_STATE) {
  81911. if (s->gzhead->name != NULL) {
  81912. uInt beg = s->pending; /* start of bytes to update crc */
  81913. int val;
  81914. do {
  81915. if (s->pending == s->pending_buf_size) {
  81916. if (s->gzhead->hcrc && s->pending > beg)
  81917. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81918. s->pending - beg);
  81919. flush_pending(strm);
  81920. beg = s->pending;
  81921. if (s->pending == s->pending_buf_size) {
  81922. val = 1;
  81923. break;
  81924. }
  81925. }
  81926. val = s->gzhead->name[s->gzindex++];
  81927. put_byte(s, val);
  81928. } while (val != 0);
  81929. if (s->gzhead->hcrc && s->pending > beg)
  81930. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81931. s->pending - beg);
  81932. if (val == 0) {
  81933. s->gzindex = 0;
  81934. s->status = COMMENT_STATE;
  81935. }
  81936. }
  81937. else
  81938. s->status = COMMENT_STATE;
  81939. }
  81940. if (s->status == COMMENT_STATE) {
  81941. if (s->gzhead->comment != NULL) {
  81942. uInt beg = s->pending; /* start of bytes to update crc */
  81943. int val;
  81944. do {
  81945. if (s->pending == s->pending_buf_size) {
  81946. if (s->gzhead->hcrc && s->pending > beg)
  81947. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81948. s->pending - beg);
  81949. flush_pending(strm);
  81950. beg = s->pending;
  81951. if (s->pending == s->pending_buf_size) {
  81952. val = 1;
  81953. break;
  81954. }
  81955. }
  81956. val = s->gzhead->comment[s->gzindex++];
  81957. put_byte(s, val);
  81958. } while (val != 0);
  81959. if (s->gzhead->hcrc && s->pending > beg)
  81960. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81961. s->pending - beg);
  81962. if (val == 0)
  81963. s->status = HCRC_STATE;
  81964. }
  81965. else
  81966. s->status = HCRC_STATE;
  81967. }
  81968. if (s->status == HCRC_STATE) {
  81969. if (s->gzhead->hcrc) {
  81970. if (s->pending + 2 > s->pending_buf_size)
  81971. flush_pending(strm);
  81972. if (s->pending + 2 <= s->pending_buf_size) {
  81973. put_byte(s, (Byte)(strm->adler & 0xff));
  81974. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81975. strm->adler = crc32(0L, Z_NULL, 0);
  81976. s->status = BUSY_STATE;
  81977. }
  81978. }
  81979. else
  81980. s->status = BUSY_STATE;
  81981. }
  81982. #endif
  81983. /* Flush as much pending output as possible */
  81984. if (s->pending != 0) {
  81985. flush_pending(strm);
  81986. if (strm->avail_out == 0) {
  81987. /* Since avail_out is 0, deflate will be called again with
  81988. * more output space, but possibly with both pending and
  81989. * avail_in equal to zero. There won't be anything to do,
  81990. * but this is not an error situation so make sure we
  81991. * return OK instead of BUF_ERROR at next call of deflate:
  81992. */
  81993. s->last_flush = -1;
  81994. return Z_OK;
  81995. }
  81996. /* Make sure there is something to do and avoid duplicate consecutive
  81997. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81998. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81999. */
  82000. } else if (strm->avail_in == 0 && flush <= old_flush &&
  82001. flush != Z_FINISH) {
  82002. ERR_RETURN(strm, Z_BUF_ERROR);
  82003. }
  82004. /* User must not provide more input after the first FINISH: */
  82005. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  82006. ERR_RETURN(strm, Z_BUF_ERROR);
  82007. }
  82008. /* Start a new block or continue the current one.
  82009. */
  82010. if (strm->avail_in != 0 || s->lookahead != 0 ||
  82011. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  82012. block_state bstate;
  82013. bstate = (*(configuration_table[s->level].func))(s, flush);
  82014. if (bstate == finish_started || bstate == finish_done) {
  82015. s->status = FINISH_STATE;
  82016. }
  82017. if (bstate == need_more || bstate == finish_started) {
  82018. if (strm->avail_out == 0) {
  82019. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82020. }
  82021. return Z_OK;
  82022. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82023. * of deflate should use the same flush parameter to make sure
  82024. * that the flush is complete. So we don't have to output an
  82025. * empty block here, this will be done at next call. This also
  82026. * ensures that for a very small output buffer, we emit at most
  82027. * one empty block.
  82028. */
  82029. }
  82030. if (bstate == block_done) {
  82031. if (flush == Z_PARTIAL_FLUSH) {
  82032. _tr_align(s);
  82033. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82034. _tr_stored_block(s, (char*)0, 0L, 0);
  82035. /* For a full flush, this empty block will be recognized
  82036. * as a special marker by inflate_sync().
  82037. */
  82038. if (flush == Z_FULL_FLUSH) {
  82039. CLEAR_HASH(s); /* forget history */
  82040. }
  82041. }
  82042. flush_pending(strm);
  82043. if (strm->avail_out == 0) {
  82044. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82045. return Z_OK;
  82046. }
  82047. }
  82048. }
  82049. Assert(strm->avail_out > 0, "bug2");
  82050. if (flush != Z_FINISH) return Z_OK;
  82051. if (s->wrap <= 0) return Z_STREAM_END;
  82052. /* Write the trailer */
  82053. #ifdef GZIP
  82054. if (s->wrap == 2) {
  82055. put_byte(s, (Byte)(strm->adler & 0xff));
  82056. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82057. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82058. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82059. put_byte(s, (Byte)(strm->total_in & 0xff));
  82060. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82061. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82062. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82063. }
  82064. else
  82065. #endif
  82066. {
  82067. putShortMSB(s, (uInt)(strm->adler >> 16));
  82068. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82069. }
  82070. flush_pending(strm);
  82071. /* If avail_out is zero, the application will call deflate again
  82072. * to flush the rest.
  82073. */
  82074. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82075. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82076. }
  82077. /* ========================================================================= */
  82078. int ZEXPORT deflateEnd (z_streamp strm)
  82079. {
  82080. int status;
  82081. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82082. status = strm->state->status;
  82083. if (status != INIT_STATE &&
  82084. status != EXTRA_STATE &&
  82085. status != NAME_STATE &&
  82086. status != COMMENT_STATE &&
  82087. status != HCRC_STATE &&
  82088. status != BUSY_STATE &&
  82089. status != FINISH_STATE) {
  82090. return Z_STREAM_ERROR;
  82091. }
  82092. /* Deallocate in reverse order of allocations: */
  82093. TRY_FREE(strm, strm->state->pending_buf);
  82094. TRY_FREE(strm, strm->state->head);
  82095. TRY_FREE(strm, strm->state->prev);
  82096. TRY_FREE(strm, strm->state->window);
  82097. ZFREE(strm, strm->state);
  82098. strm->state = Z_NULL;
  82099. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82100. }
  82101. /* =========================================================================
  82102. * Copy the source state to the destination state.
  82103. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82104. * doesn't have enough memory anyway to duplicate compression states).
  82105. */
  82106. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82107. {
  82108. #ifdef MAXSEG_64K
  82109. return Z_STREAM_ERROR;
  82110. #else
  82111. deflate_state *ds;
  82112. deflate_state *ss;
  82113. ushf *overlay;
  82114. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82115. return Z_STREAM_ERROR;
  82116. }
  82117. ss = source->state;
  82118. zmemcpy(dest, source, sizeof(z_stream));
  82119. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82120. if (ds == Z_NULL) return Z_MEM_ERROR;
  82121. dest->state = (struct internal_state FAR *) ds;
  82122. zmemcpy(ds, ss, sizeof(deflate_state));
  82123. ds->strm = dest;
  82124. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82125. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82126. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82127. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82128. ds->pending_buf = (uchf *) overlay;
  82129. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82130. ds->pending_buf == Z_NULL) {
  82131. deflateEnd (dest);
  82132. return Z_MEM_ERROR;
  82133. }
  82134. /* following zmemcpy do not work for 16-bit MSDOS */
  82135. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82136. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82137. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82138. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82139. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82140. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82141. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82142. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82143. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82144. ds->bl_desc.dyn_tree = ds->bl_tree;
  82145. return Z_OK;
  82146. #endif /* MAXSEG_64K */
  82147. }
  82148. /* ===========================================================================
  82149. * Read a new buffer from the current input stream, update the adler32
  82150. * and total number of bytes read. All deflate() input goes through
  82151. * this function so some applications may wish to modify it to avoid
  82152. * allocating a large strm->next_in buffer and copying from it.
  82153. * (See also flush_pending()).
  82154. */
  82155. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82156. {
  82157. unsigned len = strm->avail_in;
  82158. if (len > size) len = size;
  82159. if (len == 0) return 0;
  82160. strm->avail_in -= len;
  82161. if (strm->state->wrap == 1) {
  82162. strm->adler = adler32(strm->adler, strm->next_in, len);
  82163. }
  82164. #ifdef GZIP
  82165. else if (strm->state->wrap == 2) {
  82166. strm->adler = crc32(strm->adler, strm->next_in, len);
  82167. }
  82168. #endif
  82169. zmemcpy(buf, strm->next_in, len);
  82170. strm->next_in += len;
  82171. strm->total_in += len;
  82172. return (int)len;
  82173. }
  82174. /* ===========================================================================
  82175. * Initialize the "longest match" routines for a new zlib stream
  82176. */
  82177. local void lm_init (deflate_state *s)
  82178. {
  82179. s->window_size = (ulg)2L*s->w_size;
  82180. CLEAR_HASH(s);
  82181. /* Set the default configuration parameters:
  82182. */
  82183. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82184. s->good_match = configuration_table[s->level].good_length;
  82185. s->nice_match = configuration_table[s->level].nice_length;
  82186. s->max_chain_length = configuration_table[s->level].max_chain;
  82187. s->strstart = 0;
  82188. s->block_start = 0L;
  82189. s->lookahead = 0;
  82190. s->match_length = s->prev_length = MIN_MATCH-1;
  82191. s->match_available = 0;
  82192. s->ins_h = 0;
  82193. #ifndef FASTEST
  82194. #ifdef ASMV
  82195. match_init(); /* initialize the asm code */
  82196. #endif
  82197. #endif
  82198. }
  82199. #ifndef FASTEST
  82200. /* ===========================================================================
  82201. * Set match_start to the longest match starting at the given string and
  82202. * return its length. Matches shorter or equal to prev_length are discarded,
  82203. * in which case the result is equal to prev_length and match_start is
  82204. * garbage.
  82205. * IN assertions: cur_match is the head of the hash chain for the current
  82206. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82207. * OUT assertion: the match length is not greater than s->lookahead.
  82208. */
  82209. #ifndef ASMV
  82210. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82211. * match.S. The code will be functionally equivalent.
  82212. */
  82213. local uInt longest_match(deflate_state *s, IPos cur_match)
  82214. {
  82215. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82216. register Bytef *scan = s->window + s->strstart; /* current string */
  82217. register Bytef *match; /* matched string */
  82218. register int len; /* length of current match */
  82219. int best_len = s->prev_length; /* best match length so far */
  82220. int nice_match = s->nice_match; /* stop if match long enough */
  82221. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82222. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82223. /* Stop when cur_match becomes <= limit. To simplify the code,
  82224. * we prevent matches with the string of window index 0.
  82225. */
  82226. Posf *prev = s->prev;
  82227. uInt wmask = s->w_mask;
  82228. #ifdef UNALIGNED_OK
  82229. /* Compare two bytes at a time. Note: this is not always beneficial.
  82230. * Try with and without -DUNALIGNED_OK to check.
  82231. */
  82232. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82233. register ush scan_start = *(ushf*)scan;
  82234. register ush scan_end = *(ushf*)(scan+best_len-1);
  82235. #else
  82236. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82237. register Byte scan_end1 = scan[best_len-1];
  82238. register Byte scan_end = scan[best_len];
  82239. #endif
  82240. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82241. * It is easy to get rid of this optimization if necessary.
  82242. */
  82243. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82244. /* Do not waste too much time if we already have a good match: */
  82245. if (s->prev_length >= s->good_match) {
  82246. chain_length >>= 2;
  82247. }
  82248. /* Do not look for matches beyond the end of the input. This is necessary
  82249. * to make deflate deterministic.
  82250. */
  82251. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82252. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82253. do {
  82254. Assert(cur_match < s->strstart, "no future");
  82255. match = s->window + cur_match;
  82256. /* Skip to next match if the match length cannot increase
  82257. * or if the match length is less than 2. Note that the checks below
  82258. * for insufficient lookahead only occur occasionally for performance
  82259. * reasons. Therefore uninitialized memory will be accessed, and
  82260. * conditional jumps will be made that depend on those values.
  82261. * However the length of the match is limited to the lookahead, so
  82262. * the output of deflate is not affected by the uninitialized values.
  82263. */
  82264. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82265. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82266. * UNALIGNED_OK if your compiler uses a different size.
  82267. */
  82268. if (*(ushf*)(match+best_len-1) != scan_end ||
  82269. *(ushf*)match != scan_start) continue;
  82270. /* It is not necessary to compare scan[2] and match[2] since they are
  82271. * always equal when the other bytes match, given that the hash keys
  82272. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82273. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82274. * lookahead only every 4th comparison; the 128th check will be made
  82275. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82276. * necessary to put more guard bytes at the end of the window, or
  82277. * to check more often for insufficient lookahead.
  82278. */
  82279. Assert(scan[2] == match[2], "scan[2]?");
  82280. scan++, match++;
  82281. do {
  82282. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82283. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82284. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82285. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82286. scan < strend);
  82287. /* The funny "do {}" generates better code on most compilers */
  82288. /* Here, scan <= window+strstart+257 */
  82289. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82290. if (*scan == *match) scan++;
  82291. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82292. scan = strend - (MAX_MATCH-1);
  82293. #else /* UNALIGNED_OK */
  82294. if (match[best_len] != scan_end ||
  82295. match[best_len-1] != scan_end1 ||
  82296. *match != *scan ||
  82297. *++match != scan[1]) continue;
  82298. /* The check at best_len-1 can be removed because it will be made
  82299. * again later. (This heuristic is not always a win.)
  82300. * It is not necessary to compare scan[2] and match[2] since they
  82301. * are always equal when the other bytes match, given that
  82302. * the hash keys are equal and that HASH_BITS >= 8.
  82303. */
  82304. scan += 2, match++;
  82305. Assert(*scan == *match, "match[2]?");
  82306. /* We check for insufficient lookahead only every 8th comparison;
  82307. * the 256th check will be made at strstart+258.
  82308. */
  82309. do {
  82310. } while (*++scan == *++match && *++scan == *++match &&
  82311. *++scan == *++match && *++scan == *++match &&
  82312. *++scan == *++match && *++scan == *++match &&
  82313. *++scan == *++match && *++scan == *++match &&
  82314. scan < strend);
  82315. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82316. len = MAX_MATCH - (int)(strend - scan);
  82317. scan = strend - MAX_MATCH;
  82318. #endif /* UNALIGNED_OK */
  82319. if (len > best_len) {
  82320. s->match_start = cur_match;
  82321. best_len = len;
  82322. if (len >= nice_match) break;
  82323. #ifdef UNALIGNED_OK
  82324. scan_end = *(ushf*)(scan+best_len-1);
  82325. #else
  82326. scan_end1 = scan[best_len-1];
  82327. scan_end = scan[best_len];
  82328. #endif
  82329. }
  82330. } while ((cur_match = prev[cur_match & wmask]) > limit
  82331. && --chain_length != 0);
  82332. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82333. return s->lookahead;
  82334. }
  82335. #endif /* ASMV */
  82336. #endif /* FASTEST */
  82337. /* ---------------------------------------------------------------------------
  82338. * Optimized version for level == 1 or strategy == Z_RLE only
  82339. */
  82340. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82341. {
  82342. register Bytef *scan = s->window + s->strstart; /* current string */
  82343. register Bytef *match; /* matched string */
  82344. register int len; /* length of current match */
  82345. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82346. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82347. * It is easy to get rid of this optimization if necessary.
  82348. */
  82349. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82350. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82351. Assert(cur_match < s->strstart, "no future");
  82352. match = s->window + cur_match;
  82353. /* Return failure if the match length is less than 2:
  82354. */
  82355. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82356. /* The check at best_len-1 can be removed because it will be made
  82357. * again later. (This heuristic is not always a win.)
  82358. * It is not necessary to compare scan[2] and match[2] since they
  82359. * are always equal when the other bytes match, given that
  82360. * the hash keys are equal and that HASH_BITS >= 8.
  82361. */
  82362. scan += 2, match += 2;
  82363. Assert(*scan == *match, "match[2]?");
  82364. /* We check for insufficient lookahead only every 8th comparison;
  82365. * the 256th check will be made at strstart+258.
  82366. */
  82367. do {
  82368. } while (*++scan == *++match && *++scan == *++match &&
  82369. *++scan == *++match && *++scan == *++match &&
  82370. *++scan == *++match && *++scan == *++match &&
  82371. *++scan == *++match && *++scan == *++match &&
  82372. scan < strend);
  82373. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82374. len = MAX_MATCH - (int)(strend - scan);
  82375. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82376. s->match_start = cur_match;
  82377. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82378. }
  82379. #ifdef DEBUG
  82380. /* ===========================================================================
  82381. * Check that the match at match_start is indeed a match.
  82382. */
  82383. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82384. {
  82385. /* check that the match is indeed a match */
  82386. if (zmemcmp(s->window + match,
  82387. s->window + start, length) != EQUAL) {
  82388. fprintf(stderr, " start %u, match %u, length %d\n",
  82389. start, match, length);
  82390. do {
  82391. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82392. } while (--length != 0);
  82393. z_error("invalid match");
  82394. }
  82395. if (z_verbose > 1) {
  82396. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82397. do { putc(s->window[start++], stderr); } while (--length != 0);
  82398. }
  82399. }
  82400. #else
  82401. # define check_match(s, start, match, length)
  82402. #endif /* DEBUG */
  82403. /* ===========================================================================
  82404. * Fill the window when the lookahead becomes insufficient.
  82405. * Updates strstart and lookahead.
  82406. *
  82407. * IN assertion: lookahead < MIN_LOOKAHEAD
  82408. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82409. * At least one byte has been read, or avail_in == 0; reads are
  82410. * performed for at least two bytes (required for the zip translate_eol
  82411. * option -- not supported here).
  82412. */
  82413. local void fill_window (deflate_state *s)
  82414. {
  82415. register unsigned n, m;
  82416. register Posf *p;
  82417. unsigned more; /* Amount of free space at the end of the window. */
  82418. uInt wsize = s->w_size;
  82419. do {
  82420. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82421. /* Deal with !@#$% 64K limit: */
  82422. if (sizeof(int) <= 2) {
  82423. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82424. more = wsize;
  82425. } else if (more == (unsigned)(-1)) {
  82426. /* Very unlikely, but possible on 16 bit machine if
  82427. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82428. */
  82429. more--;
  82430. }
  82431. }
  82432. /* If the window is almost full and there is insufficient lookahead,
  82433. * move the upper half to the lower one to make room in the upper half.
  82434. */
  82435. if (s->strstart >= wsize+MAX_DIST(s)) {
  82436. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82437. s->match_start -= wsize;
  82438. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82439. s->block_start -= (long) wsize;
  82440. /* Slide the hash table (could be avoided with 32 bit values
  82441. at the expense of memory usage). We slide even when level == 0
  82442. to keep the hash table consistent if we switch back to level > 0
  82443. later. (Using level 0 permanently is not an optimal usage of
  82444. zlib, so we don't care about this pathological case.)
  82445. */
  82446. /* %%% avoid this when Z_RLE */
  82447. n = s->hash_size;
  82448. p = &s->head[n];
  82449. do {
  82450. m = *--p;
  82451. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82452. } while (--n);
  82453. n = wsize;
  82454. #ifndef FASTEST
  82455. p = &s->prev[n];
  82456. do {
  82457. m = *--p;
  82458. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82459. /* If n is not on any hash chain, prev[n] is garbage but
  82460. * its value will never be used.
  82461. */
  82462. } while (--n);
  82463. #endif
  82464. more += wsize;
  82465. }
  82466. if (s->strm->avail_in == 0) return;
  82467. /* If there was no sliding:
  82468. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82469. * more == window_size - lookahead - strstart
  82470. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82471. * => more >= window_size - 2*WSIZE + 2
  82472. * In the BIG_MEM or MMAP case (not yet supported),
  82473. * window_size == input_size + MIN_LOOKAHEAD &&
  82474. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82475. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82476. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82477. */
  82478. Assert(more >= 2, "more < 2");
  82479. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82480. s->lookahead += n;
  82481. /* Initialize the hash value now that we have some input: */
  82482. if (s->lookahead >= MIN_MATCH) {
  82483. s->ins_h = s->window[s->strstart];
  82484. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82485. #if MIN_MATCH != 3
  82486. Call UPDATE_HASH() MIN_MATCH-3 more times
  82487. #endif
  82488. }
  82489. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82490. * but this is not important since only literal bytes will be emitted.
  82491. */
  82492. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82493. }
  82494. /* ===========================================================================
  82495. * Flush the current block, with given end-of-file flag.
  82496. * IN assertion: strstart is set to the end of the current match.
  82497. */
  82498. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82499. _tr_flush_block(s, (s->block_start >= 0L ? \
  82500. (charf *)&s->window[(unsigned)s->block_start] : \
  82501. (charf *)Z_NULL), \
  82502. (ulg)((long)s->strstart - s->block_start), \
  82503. (eof)); \
  82504. s->block_start = s->strstart; \
  82505. flush_pending(s->strm); \
  82506. Tracev((stderr,"[FLUSH]")); \
  82507. }
  82508. /* Same but force premature exit if necessary. */
  82509. #define FLUSH_BLOCK(s, eof) { \
  82510. FLUSH_BLOCK_ONLY(s, eof); \
  82511. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82512. }
  82513. /* ===========================================================================
  82514. * Copy without compression as much as possible from the input stream, return
  82515. * the current block state.
  82516. * This function does not insert new strings in the dictionary since
  82517. * uncompressible data is probably not useful. This function is used
  82518. * only for the level=0 compression option.
  82519. * NOTE: this function should be optimized to avoid extra copying from
  82520. * window to pending_buf.
  82521. */
  82522. local block_state deflate_stored(deflate_state *s, int flush)
  82523. {
  82524. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82525. * to pending_buf_size, and each stored block has a 5 byte header:
  82526. */
  82527. ulg max_block_size = 0xffff;
  82528. ulg max_start;
  82529. if (max_block_size > s->pending_buf_size - 5) {
  82530. max_block_size = s->pending_buf_size - 5;
  82531. }
  82532. /* Copy as much as possible from input to output: */
  82533. for (;;) {
  82534. /* Fill the window as much as possible: */
  82535. if (s->lookahead <= 1) {
  82536. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82537. s->block_start >= (long)s->w_size, "slide too late");
  82538. fill_window(s);
  82539. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82540. if (s->lookahead == 0) break; /* flush the current block */
  82541. }
  82542. Assert(s->block_start >= 0L, "block gone");
  82543. s->strstart += s->lookahead;
  82544. s->lookahead = 0;
  82545. /* Emit a stored block if pending_buf will be full: */
  82546. max_start = s->block_start + max_block_size;
  82547. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82548. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82549. s->lookahead = (uInt)(s->strstart - max_start);
  82550. s->strstart = (uInt)max_start;
  82551. FLUSH_BLOCK(s, 0);
  82552. }
  82553. /* Flush if we may have to slide, otherwise block_start may become
  82554. * negative and the data will be gone:
  82555. */
  82556. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82557. FLUSH_BLOCK(s, 0);
  82558. }
  82559. }
  82560. FLUSH_BLOCK(s, flush == Z_FINISH);
  82561. return flush == Z_FINISH ? finish_done : block_done;
  82562. }
  82563. /* ===========================================================================
  82564. * Compress as much as possible from the input stream, return the current
  82565. * block state.
  82566. * This function does not perform lazy evaluation of matches and inserts
  82567. * new strings in the dictionary only for unmatched strings or for short
  82568. * matches. It is used only for the fast compression options.
  82569. */
  82570. local block_state deflate_fast(deflate_state *s, int flush)
  82571. {
  82572. IPos hash_head = NIL; /* head of the hash chain */
  82573. int bflush; /* set if current block must be flushed */
  82574. for (;;) {
  82575. /* Make sure that we always have enough lookahead, except
  82576. * at the end of the input file. We need MAX_MATCH bytes
  82577. * for the next match, plus MIN_MATCH bytes to insert the
  82578. * string following the next match.
  82579. */
  82580. if (s->lookahead < MIN_LOOKAHEAD) {
  82581. fill_window(s);
  82582. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82583. return need_more;
  82584. }
  82585. if (s->lookahead == 0) break; /* flush the current block */
  82586. }
  82587. /* Insert the string window[strstart .. strstart+2] in the
  82588. * dictionary, and set hash_head to the head of the hash chain:
  82589. */
  82590. if (s->lookahead >= MIN_MATCH) {
  82591. INSERT_STRING(s, s->strstart, hash_head);
  82592. }
  82593. /* Find the longest match, discarding those <= prev_length.
  82594. * At this point we have always match_length < MIN_MATCH
  82595. */
  82596. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82597. /* To simplify the code, we prevent matches with the string
  82598. * of window index 0 (in particular we have to avoid a match
  82599. * of the string with itself at the start of the input file).
  82600. */
  82601. #ifdef FASTEST
  82602. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82603. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82604. s->match_length = longest_match_fast (s, hash_head);
  82605. }
  82606. #else
  82607. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82608. s->match_length = longest_match (s, hash_head);
  82609. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82610. s->match_length = longest_match_fast (s, hash_head);
  82611. }
  82612. #endif
  82613. /* longest_match() or longest_match_fast() sets match_start */
  82614. }
  82615. if (s->match_length >= MIN_MATCH) {
  82616. check_match(s, s->strstart, s->match_start, s->match_length);
  82617. _tr_tally_dist(s, s->strstart - s->match_start,
  82618. s->match_length - MIN_MATCH, bflush);
  82619. s->lookahead -= s->match_length;
  82620. /* Insert new strings in the hash table only if the match length
  82621. * is not too large. This saves time but degrades compression.
  82622. */
  82623. #ifndef FASTEST
  82624. if (s->match_length <= s->max_insert_length &&
  82625. s->lookahead >= MIN_MATCH) {
  82626. s->match_length--; /* string at strstart already in table */
  82627. do {
  82628. s->strstart++;
  82629. INSERT_STRING(s, s->strstart, hash_head);
  82630. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82631. * always MIN_MATCH bytes ahead.
  82632. */
  82633. } while (--s->match_length != 0);
  82634. s->strstart++;
  82635. } else
  82636. #endif
  82637. {
  82638. s->strstart += s->match_length;
  82639. s->match_length = 0;
  82640. s->ins_h = s->window[s->strstart];
  82641. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82642. #if MIN_MATCH != 3
  82643. Call UPDATE_HASH() MIN_MATCH-3 more times
  82644. #endif
  82645. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82646. * matter since it will be recomputed at next deflate call.
  82647. */
  82648. }
  82649. } else {
  82650. /* No match, output a literal byte */
  82651. Tracevv((stderr,"%c", s->window[s->strstart]));
  82652. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82653. s->lookahead--;
  82654. s->strstart++;
  82655. }
  82656. if (bflush) FLUSH_BLOCK(s, 0);
  82657. }
  82658. FLUSH_BLOCK(s, flush == Z_FINISH);
  82659. return flush == Z_FINISH ? finish_done : block_done;
  82660. }
  82661. #ifndef FASTEST
  82662. /* ===========================================================================
  82663. * Same as above, but achieves better compression. We use a lazy
  82664. * evaluation for matches: a match is finally adopted only if there is
  82665. * no better match at the next window position.
  82666. */
  82667. local block_state deflate_slow(deflate_state *s, int flush)
  82668. {
  82669. IPos hash_head = NIL; /* head of hash chain */
  82670. int bflush; /* set if current block must be flushed */
  82671. /* Process the input block. */
  82672. for (;;) {
  82673. /* Make sure that we always have enough lookahead, except
  82674. * at the end of the input file. We need MAX_MATCH bytes
  82675. * for the next match, plus MIN_MATCH bytes to insert the
  82676. * string following the next match.
  82677. */
  82678. if (s->lookahead < MIN_LOOKAHEAD) {
  82679. fill_window(s);
  82680. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82681. return need_more;
  82682. }
  82683. if (s->lookahead == 0) break; /* flush the current block */
  82684. }
  82685. /* Insert the string window[strstart .. strstart+2] in the
  82686. * dictionary, and set hash_head to the head of the hash chain:
  82687. */
  82688. if (s->lookahead >= MIN_MATCH) {
  82689. INSERT_STRING(s, s->strstart, hash_head);
  82690. }
  82691. /* Find the longest match, discarding those <= prev_length.
  82692. */
  82693. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82694. s->match_length = MIN_MATCH-1;
  82695. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82696. s->strstart - hash_head <= MAX_DIST(s)) {
  82697. /* To simplify the code, we prevent matches with the string
  82698. * of window index 0 (in particular we have to avoid a match
  82699. * of the string with itself at the start of the input file).
  82700. */
  82701. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82702. s->match_length = longest_match (s, hash_head);
  82703. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82704. s->match_length = longest_match_fast (s, hash_head);
  82705. }
  82706. /* longest_match() or longest_match_fast() sets match_start */
  82707. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82708. #if TOO_FAR <= 32767
  82709. || (s->match_length == MIN_MATCH &&
  82710. s->strstart - s->match_start > TOO_FAR)
  82711. #endif
  82712. )) {
  82713. /* If prev_match is also MIN_MATCH, match_start is garbage
  82714. * but we will ignore the current match anyway.
  82715. */
  82716. s->match_length = MIN_MATCH-1;
  82717. }
  82718. }
  82719. /* If there was a match at the previous step and the current
  82720. * match is not better, output the previous match:
  82721. */
  82722. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82723. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82724. /* Do not insert strings in hash table beyond this. */
  82725. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82726. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82727. s->prev_length - MIN_MATCH, bflush);
  82728. /* Insert in hash table all strings up to the end of the match.
  82729. * strstart-1 and strstart are already inserted. If there is not
  82730. * enough lookahead, the last two strings are not inserted in
  82731. * the hash table.
  82732. */
  82733. s->lookahead -= s->prev_length-1;
  82734. s->prev_length -= 2;
  82735. do {
  82736. if (++s->strstart <= max_insert) {
  82737. INSERT_STRING(s, s->strstart, hash_head);
  82738. }
  82739. } while (--s->prev_length != 0);
  82740. s->match_available = 0;
  82741. s->match_length = MIN_MATCH-1;
  82742. s->strstart++;
  82743. if (bflush) FLUSH_BLOCK(s, 0);
  82744. } else if (s->match_available) {
  82745. /* If there was no match at the previous position, output a
  82746. * single literal. If there was a match but the current match
  82747. * is longer, truncate the previous match to a single literal.
  82748. */
  82749. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82750. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82751. if (bflush) {
  82752. FLUSH_BLOCK_ONLY(s, 0);
  82753. }
  82754. s->strstart++;
  82755. s->lookahead--;
  82756. if (s->strm->avail_out == 0) return need_more;
  82757. } else {
  82758. /* There is no previous match to compare with, wait for
  82759. * the next step to decide.
  82760. */
  82761. s->match_available = 1;
  82762. s->strstart++;
  82763. s->lookahead--;
  82764. }
  82765. }
  82766. Assert (flush != Z_NO_FLUSH, "no flush?");
  82767. if (s->match_available) {
  82768. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82769. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82770. s->match_available = 0;
  82771. }
  82772. FLUSH_BLOCK(s, flush == Z_FINISH);
  82773. return flush == Z_FINISH ? finish_done : block_done;
  82774. }
  82775. #endif /* FASTEST */
  82776. #if 0
  82777. /* ===========================================================================
  82778. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82779. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82780. * deflate switches away from Z_RLE.)
  82781. */
  82782. local block_state deflate_rle(s, flush)
  82783. deflate_state *s;
  82784. int flush;
  82785. {
  82786. int bflush; /* set if current block must be flushed */
  82787. uInt run; /* length of run */
  82788. uInt max; /* maximum length of run */
  82789. uInt prev; /* byte at distance one to match */
  82790. Bytef *scan; /* scan for end of run */
  82791. for (;;) {
  82792. /* Make sure that we always have enough lookahead, except
  82793. * at the end of the input file. We need MAX_MATCH bytes
  82794. * for the longest encodable run.
  82795. */
  82796. if (s->lookahead < MAX_MATCH) {
  82797. fill_window(s);
  82798. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82799. return need_more;
  82800. }
  82801. if (s->lookahead == 0) break; /* flush the current block */
  82802. }
  82803. /* See how many times the previous byte repeats */
  82804. run = 0;
  82805. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82806. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82807. scan = s->window + s->strstart - 1;
  82808. prev = *scan++;
  82809. do {
  82810. if (*scan++ != prev)
  82811. break;
  82812. } while (++run < max);
  82813. }
  82814. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82815. if (run >= MIN_MATCH) {
  82816. check_match(s, s->strstart, s->strstart - 1, run);
  82817. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82818. s->lookahead -= run;
  82819. s->strstart += run;
  82820. } else {
  82821. /* No match, output a literal byte */
  82822. Tracevv((stderr,"%c", s->window[s->strstart]));
  82823. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82824. s->lookahead--;
  82825. s->strstart++;
  82826. }
  82827. if (bflush) FLUSH_BLOCK(s, 0);
  82828. }
  82829. FLUSH_BLOCK(s, flush == Z_FINISH);
  82830. return flush == Z_FINISH ? finish_done : block_done;
  82831. }
  82832. #endif
  82833. /*** End of inlined file: deflate.c ***/
  82834. /*** Start of inlined file: inffast.c ***/
  82835. /*** Start of inlined file: inftrees.h ***/
  82836. /* WARNING: this file should *not* be used by applications. It is
  82837. part of the implementation of the compression library and is
  82838. subject to change. Applications should only use zlib.h.
  82839. */
  82840. #ifndef _INFTREES_H_
  82841. #define _INFTREES_H_
  82842. /* Structure for decoding tables. Each entry provides either the
  82843. information needed to do the operation requested by the code that
  82844. indexed that table entry, or it provides a pointer to another
  82845. table that indexes more bits of the code. op indicates whether
  82846. the entry is a pointer to another table, a literal, a length or
  82847. distance, an end-of-block, or an invalid code. For a table
  82848. pointer, the low four bits of op is the number of index bits of
  82849. that table. For a length or distance, the low four bits of op
  82850. is the number of extra bits to get after the code. bits is
  82851. the number of bits in this code or part of the code to drop off
  82852. of the bit buffer. val is the actual byte to output in the case
  82853. of a literal, the base length or distance, or the offset from
  82854. the current table to the next table. Each entry is four bytes. */
  82855. typedef struct {
  82856. unsigned char op; /* operation, extra bits, table bits */
  82857. unsigned char bits; /* bits in this part of the code */
  82858. unsigned short val; /* offset in table or code value */
  82859. } code;
  82860. /* op values as set by inflate_table():
  82861. 00000000 - literal
  82862. 0000tttt - table link, tttt != 0 is the number of table index bits
  82863. 0001eeee - length or distance, eeee is the number of extra bits
  82864. 01100000 - end of block
  82865. 01000000 - invalid code
  82866. */
  82867. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82868. exhaustive search was 1444 code structures (852 for length/literals
  82869. and 592 for distances, the latter actually the result of an
  82870. exhaustive search). The true maximum is not known, but the value
  82871. below is more than safe. */
  82872. #define ENOUGH 2048
  82873. #define MAXD 592
  82874. /* Type of code to build for inftable() */
  82875. typedef enum {
  82876. CODES,
  82877. LENS,
  82878. DISTS
  82879. } codetype;
  82880. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82881. unsigned codes, code FAR * FAR *table,
  82882. unsigned FAR *bits, unsigned short FAR *work));
  82883. #endif
  82884. /*** End of inlined file: inftrees.h ***/
  82885. /*** Start of inlined file: inflate.h ***/
  82886. /* WARNING: this file should *not* be used by applications. It is
  82887. part of the implementation of the compression library and is
  82888. subject to change. Applications should only use zlib.h.
  82889. */
  82890. #ifndef _INFLATE_H_
  82891. #define _INFLATE_H_
  82892. /* define NO_GZIP when compiling if you want to disable gzip header and
  82893. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82894. the crc code when it is not needed. For shared libraries, gzip decoding
  82895. should be left enabled. */
  82896. #ifndef NO_GZIP
  82897. # define GUNZIP
  82898. #endif
  82899. /* Possible inflate modes between inflate() calls */
  82900. typedef enum {
  82901. HEAD, /* i: waiting for magic header */
  82902. FLAGS, /* i: waiting for method and flags (gzip) */
  82903. TIME, /* i: waiting for modification time (gzip) */
  82904. OS, /* i: waiting for extra flags and operating system (gzip) */
  82905. EXLEN, /* i: waiting for extra length (gzip) */
  82906. EXTRA, /* i: waiting for extra bytes (gzip) */
  82907. NAME, /* i: waiting for end of file name (gzip) */
  82908. COMMENT, /* i: waiting for end of comment (gzip) */
  82909. HCRC, /* i: waiting for header crc (gzip) */
  82910. DICTID, /* i: waiting for dictionary check value */
  82911. DICT, /* waiting for inflateSetDictionary() call */
  82912. TYPE, /* i: waiting for type bits, including last-flag bit */
  82913. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82914. STORED, /* i: waiting for stored size (length and complement) */
  82915. COPY, /* i/o: waiting for input or output to copy stored block */
  82916. TABLE, /* i: waiting for dynamic block table lengths */
  82917. LENLENS, /* i: waiting for code length code lengths */
  82918. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82919. LEN, /* i: waiting for length/lit code */
  82920. LENEXT, /* i: waiting for length extra bits */
  82921. DIST, /* i: waiting for distance code */
  82922. DISTEXT, /* i: waiting for distance extra bits */
  82923. MATCH, /* o: waiting for output space to copy string */
  82924. LIT, /* o: waiting for output space to write literal */
  82925. CHECK, /* i: waiting for 32-bit check value */
  82926. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82927. DONE, /* finished check, done -- remain here until reset */
  82928. BAD, /* got a data error -- remain here until reset */
  82929. MEM, /* got an inflate() memory error -- remain here until reset */
  82930. SYNC /* looking for synchronization bytes to restart inflate() */
  82931. } inflate_mode;
  82932. /*
  82933. State transitions between above modes -
  82934. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82935. Process header:
  82936. HEAD -> (gzip) or (zlib)
  82937. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82938. NAME -> COMMENT -> HCRC -> TYPE
  82939. (zlib) -> DICTID or TYPE
  82940. DICTID -> DICT -> TYPE
  82941. Read deflate blocks:
  82942. TYPE -> STORED or TABLE or LEN or CHECK
  82943. STORED -> COPY -> TYPE
  82944. TABLE -> LENLENS -> CODELENS -> LEN
  82945. Read deflate codes:
  82946. LEN -> LENEXT or LIT or TYPE
  82947. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82948. LIT -> LEN
  82949. Process trailer:
  82950. CHECK -> LENGTH -> DONE
  82951. */
  82952. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82953. struct inflate_state {
  82954. inflate_mode mode; /* current inflate mode */
  82955. int last; /* true if processing last block */
  82956. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82957. int havedict; /* true if dictionary provided */
  82958. int flags; /* gzip header method and flags (0 if zlib) */
  82959. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82960. unsigned long check; /* protected copy of check value */
  82961. unsigned long total; /* protected copy of output count */
  82962. gz_headerp head; /* where to save gzip header information */
  82963. /* sliding window */
  82964. unsigned wbits; /* log base 2 of requested window size */
  82965. unsigned wsize; /* window size or zero if not using window */
  82966. unsigned whave; /* valid bytes in the window */
  82967. unsigned write; /* window write index */
  82968. unsigned char FAR *window; /* allocated sliding window, if needed */
  82969. /* bit accumulator */
  82970. unsigned long hold; /* input bit accumulator */
  82971. unsigned bits; /* number of bits in "in" */
  82972. /* for string and stored block copying */
  82973. unsigned length; /* literal or length of data to copy */
  82974. unsigned offset; /* distance back to copy string from */
  82975. /* for table and code decoding */
  82976. unsigned extra; /* extra bits needed */
  82977. /* fixed and dynamic code tables */
  82978. code const FAR *lencode; /* starting table for length/literal codes */
  82979. code const FAR *distcode; /* starting table for distance codes */
  82980. unsigned lenbits; /* index bits for lencode */
  82981. unsigned distbits; /* index bits for distcode */
  82982. /* dynamic table building */
  82983. unsigned ncode; /* number of code length code lengths */
  82984. unsigned nlen; /* number of length code lengths */
  82985. unsigned ndist; /* number of distance code lengths */
  82986. unsigned have; /* number of code lengths in lens[] */
  82987. code FAR *next; /* next available space in codes[] */
  82988. unsigned short lens[320]; /* temporary storage for code lengths */
  82989. unsigned short work[288]; /* work area for code table building */
  82990. code codes[ENOUGH]; /* space for code tables */
  82991. };
  82992. #endif
  82993. /*** End of inlined file: inflate.h ***/
  82994. /*** Start of inlined file: inffast.h ***/
  82995. /* WARNING: this file should *not* be used by applications. It is
  82996. part of the implementation of the compression library and is
  82997. subject to change. Applications should only use zlib.h.
  82998. */
  82999. void inflate_fast OF((z_streamp strm, unsigned start));
  83000. /*** End of inlined file: inffast.h ***/
  83001. #ifndef ASMINF
  83002. /* Allow machine dependent optimization for post-increment or pre-increment.
  83003. Based on testing to date,
  83004. Pre-increment preferred for:
  83005. - PowerPC G3 (Adler)
  83006. - MIPS R5000 (Randers-Pehrson)
  83007. Post-increment preferred for:
  83008. - none
  83009. No measurable difference:
  83010. - Pentium III (Anderson)
  83011. - M68060 (Nikl)
  83012. */
  83013. #ifdef POSTINC
  83014. # define OFF 0
  83015. # define PUP(a) *(a)++
  83016. #else
  83017. # define OFF 1
  83018. # define PUP(a) *++(a)
  83019. #endif
  83020. /*
  83021. Decode literal, length, and distance codes and write out the resulting
  83022. literal and match bytes until either not enough input or output is
  83023. available, an end-of-block is encountered, or a data error is encountered.
  83024. When large enough input and output buffers are supplied to inflate(), for
  83025. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83026. inflate execution time is spent in this routine.
  83027. Entry assumptions:
  83028. state->mode == LEN
  83029. strm->avail_in >= 6
  83030. strm->avail_out >= 258
  83031. start >= strm->avail_out
  83032. state->bits < 8
  83033. On return, state->mode is one of:
  83034. LEN -- ran out of enough output space or enough available input
  83035. TYPE -- reached end of block code, inflate() to interpret next block
  83036. BAD -- error in block data
  83037. Notes:
  83038. - The maximum input bits used by a length/distance pair is 15 bits for the
  83039. length code, 5 bits for the length extra, 15 bits for the distance code,
  83040. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83041. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83042. checking for available input while decoding.
  83043. - The maximum bytes that a single length/distance pair can output is 258
  83044. bytes, which is the maximum length that can be coded. inflate_fast()
  83045. requires strm->avail_out >= 258 for each loop to avoid checking for
  83046. output space.
  83047. */
  83048. void inflate_fast (z_streamp strm, unsigned start)
  83049. {
  83050. struct inflate_state FAR *state;
  83051. unsigned char FAR *in; /* local strm->next_in */
  83052. unsigned char FAR *last; /* while in < last, enough input available */
  83053. unsigned char FAR *out; /* local strm->next_out */
  83054. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83055. unsigned char FAR *end; /* while out < end, enough space available */
  83056. #ifdef INFLATE_STRICT
  83057. unsigned dmax; /* maximum distance from zlib header */
  83058. #endif
  83059. unsigned wsize; /* window size or zero if not using window */
  83060. unsigned whave; /* valid bytes in the window */
  83061. unsigned write; /* window write index */
  83062. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83063. unsigned long hold; /* local strm->hold */
  83064. unsigned bits; /* local strm->bits */
  83065. code const FAR *lcode; /* local strm->lencode */
  83066. code const FAR *dcode; /* local strm->distcode */
  83067. unsigned lmask; /* mask for first level of length codes */
  83068. unsigned dmask; /* mask for first level of distance codes */
  83069. code thisx; /* retrieved table entry */
  83070. unsigned op; /* code bits, operation, extra bits, or */
  83071. /* window position, window bytes to copy */
  83072. unsigned len; /* match length, unused bytes */
  83073. unsigned dist; /* match distance */
  83074. unsigned char FAR *from; /* where to copy match from */
  83075. /* copy state to local variables */
  83076. state = (struct inflate_state FAR *)strm->state;
  83077. in = strm->next_in - OFF;
  83078. last = in + (strm->avail_in - 5);
  83079. out = strm->next_out - OFF;
  83080. beg = out - (start - strm->avail_out);
  83081. end = out + (strm->avail_out - 257);
  83082. #ifdef INFLATE_STRICT
  83083. dmax = state->dmax;
  83084. #endif
  83085. wsize = state->wsize;
  83086. whave = state->whave;
  83087. write = state->write;
  83088. window = state->window;
  83089. hold = state->hold;
  83090. bits = state->bits;
  83091. lcode = state->lencode;
  83092. dcode = state->distcode;
  83093. lmask = (1U << state->lenbits) - 1;
  83094. dmask = (1U << state->distbits) - 1;
  83095. /* decode literals and length/distances until end-of-block or not enough
  83096. input data or output space */
  83097. do {
  83098. if (bits < 15) {
  83099. hold += (unsigned long)(PUP(in)) << bits;
  83100. bits += 8;
  83101. hold += (unsigned long)(PUP(in)) << bits;
  83102. bits += 8;
  83103. }
  83104. thisx = lcode[hold & lmask];
  83105. dolen:
  83106. op = (unsigned)(thisx.bits);
  83107. hold >>= op;
  83108. bits -= op;
  83109. op = (unsigned)(thisx.op);
  83110. if (op == 0) { /* literal */
  83111. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83112. "inflate: literal '%c'\n" :
  83113. "inflate: literal 0x%02x\n", thisx.val));
  83114. PUP(out) = (unsigned char)(thisx.val);
  83115. }
  83116. else if (op & 16) { /* length base */
  83117. len = (unsigned)(thisx.val);
  83118. op &= 15; /* number of extra bits */
  83119. if (op) {
  83120. if (bits < op) {
  83121. hold += (unsigned long)(PUP(in)) << bits;
  83122. bits += 8;
  83123. }
  83124. len += (unsigned)hold & ((1U << op) - 1);
  83125. hold >>= op;
  83126. bits -= op;
  83127. }
  83128. Tracevv((stderr, "inflate: length %u\n", len));
  83129. if (bits < 15) {
  83130. hold += (unsigned long)(PUP(in)) << bits;
  83131. bits += 8;
  83132. hold += (unsigned long)(PUP(in)) << bits;
  83133. bits += 8;
  83134. }
  83135. thisx = dcode[hold & dmask];
  83136. dodist:
  83137. op = (unsigned)(thisx.bits);
  83138. hold >>= op;
  83139. bits -= op;
  83140. op = (unsigned)(thisx.op);
  83141. if (op & 16) { /* distance base */
  83142. dist = (unsigned)(thisx.val);
  83143. op &= 15; /* number of extra bits */
  83144. if (bits < op) {
  83145. hold += (unsigned long)(PUP(in)) << bits;
  83146. bits += 8;
  83147. if (bits < op) {
  83148. hold += (unsigned long)(PUP(in)) << bits;
  83149. bits += 8;
  83150. }
  83151. }
  83152. dist += (unsigned)hold & ((1U << op) - 1);
  83153. #ifdef INFLATE_STRICT
  83154. if (dist > dmax) {
  83155. strm->msg = (char *)"invalid distance too far back";
  83156. state->mode = BAD;
  83157. break;
  83158. }
  83159. #endif
  83160. hold >>= op;
  83161. bits -= op;
  83162. Tracevv((stderr, "inflate: distance %u\n", dist));
  83163. op = (unsigned)(out - beg); /* max distance in output */
  83164. if (dist > op) { /* see if copy from window */
  83165. op = dist - op; /* distance back in window */
  83166. if (op > whave) {
  83167. strm->msg = (char *)"invalid distance too far back";
  83168. state->mode = BAD;
  83169. break;
  83170. }
  83171. from = window - OFF;
  83172. if (write == 0) { /* very common case */
  83173. from += wsize - op;
  83174. if (op < len) { /* some from window */
  83175. len -= op;
  83176. do {
  83177. PUP(out) = PUP(from);
  83178. } while (--op);
  83179. from = out - dist; /* rest from output */
  83180. }
  83181. }
  83182. else if (write < op) { /* wrap around window */
  83183. from += wsize + write - op;
  83184. op -= write;
  83185. if (op < len) { /* some from end of window */
  83186. len -= op;
  83187. do {
  83188. PUP(out) = PUP(from);
  83189. } while (--op);
  83190. from = window - OFF;
  83191. if (write < len) { /* some from start of window */
  83192. op = write;
  83193. len -= op;
  83194. do {
  83195. PUP(out) = PUP(from);
  83196. } while (--op);
  83197. from = out - dist; /* rest from output */
  83198. }
  83199. }
  83200. }
  83201. else { /* contiguous in window */
  83202. from += write - op;
  83203. if (op < len) { /* some from window */
  83204. len -= op;
  83205. do {
  83206. PUP(out) = PUP(from);
  83207. } while (--op);
  83208. from = out - dist; /* rest from output */
  83209. }
  83210. }
  83211. while (len > 2) {
  83212. PUP(out) = PUP(from);
  83213. PUP(out) = PUP(from);
  83214. PUP(out) = PUP(from);
  83215. len -= 3;
  83216. }
  83217. if (len) {
  83218. PUP(out) = PUP(from);
  83219. if (len > 1)
  83220. PUP(out) = PUP(from);
  83221. }
  83222. }
  83223. else {
  83224. from = out - dist; /* copy direct from output */
  83225. do { /* minimum length is three */
  83226. PUP(out) = PUP(from);
  83227. PUP(out) = PUP(from);
  83228. PUP(out) = PUP(from);
  83229. len -= 3;
  83230. } while (len > 2);
  83231. if (len) {
  83232. PUP(out) = PUP(from);
  83233. if (len > 1)
  83234. PUP(out) = PUP(from);
  83235. }
  83236. }
  83237. }
  83238. else if ((op & 64) == 0) { /* 2nd level distance code */
  83239. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83240. goto dodist;
  83241. }
  83242. else {
  83243. strm->msg = (char *)"invalid distance code";
  83244. state->mode = BAD;
  83245. break;
  83246. }
  83247. }
  83248. else if ((op & 64) == 0) { /* 2nd level length code */
  83249. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83250. goto dolen;
  83251. }
  83252. else if (op & 32) { /* end-of-block */
  83253. Tracevv((stderr, "inflate: end of block\n"));
  83254. state->mode = TYPE;
  83255. break;
  83256. }
  83257. else {
  83258. strm->msg = (char *)"invalid literal/length code";
  83259. state->mode = BAD;
  83260. break;
  83261. }
  83262. } while (in < last && out < end);
  83263. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83264. len = bits >> 3;
  83265. in -= len;
  83266. bits -= len << 3;
  83267. hold &= (1U << bits) - 1;
  83268. /* update state and return */
  83269. strm->next_in = in + OFF;
  83270. strm->next_out = out + OFF;
  83271. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83272. strm->avail_out = (unsigned)(out < end ?
  83273. 257 + (end - out) : 257 - (out - end));
  83274. state->hold = hold;
  83275. state->bits = bits;
  83276. return;
  83277. }
  83278. /*
  83279. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83280. - Using bit fields for code structure
  83281. - Different op definition to avoid & for extra bits (do & for table bits)
  83282. - Three separate decoding do-loops for direct, window, and write == 0
  83283. - Special case for distance > 1 copies to do overlapped load and store copy
  83284. - Explicit branch predictions (based on measured branch probabilities)
  83285. - Deferring match copy and interspersed it with decoding subsequent codes
  83286. - Swapping literal/length else
  83287. - Swapping window/direct else
  83288. - Larger unrolled copy loops (three is about right)
  83289. - Moving len -= 3 statement into middle of loop
  83290. */
  83291. #endif /* !ASMINF */
  83292. /*** End of inlined file: inffast.c ***/
  83293. #undef PULLBYTE
  83294. #undef LOAD
  83295. #undef RESTORE
  83296. #undef INITBITS
  83297. #undef NEEDBITS
  83298. #undef DROPBITS
  83299. #undef BYTEBITS
  83300. /*** Start of inlined file: inflate.c ***/
  83301. /*
  83302. * Change history:
  83303. *
  83304. * 1.2.beta0 24 Nov 2002
  83305. * - First version -- complete rewrite of inflate to simplify code, avoid
  83306. * creation of window when not needed, minimize use of window when it is
  83307. * needed, make inffast.c even faster, implement gzip decoding, and to
  83308. * improve code readability and style over the previous zlib inflate code
  83309. *
  83310. * 1.2.beta1 25 Nov 2002
  83311. * - Use pointers for available input and output checking in inffast.c
  83312. * - Remove input and output counters in inffast.c
  83313. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83314. * - Remove unnecessary second byte pull from length extra in inffast.c
  83315. * - Unroll direct copy to three copies per loop in inffast.c
  83316. *
  83317. * 1.2.beta2 4 Dec 2002
  83318. * - Change external routine names to reduce potential conflicts
  83319. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83320. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83321. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83322. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83323. *
  83324. * 1.2.beta3 22 Dec 2002
  83325. * - Add comments on state->bits assertion in inffast.c
  83326. * - Add comments on op field in inftrees.h
  83327. * - Fix bug in reuse of allocated window after inflateReset()
  83328. * - Remove bit fields--back to byte structure for speed
  83329. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83330. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83331. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83332. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83333. * - Use local copies of stream next and avail values, as well as local bit
  83334. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83335. *
  83336. * 1.2.beta4 1 Jan 2003
  83337. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83338. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83339. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83340. * - Rearrange window copies in inflate_fast() for speed and simplification
  83341. * - Unroll last copy for window match in inflate_fast()
  83342. * - Use local copies of window variables in inflate_fast() for speed
  83343. * - Pull out common write == 0 case for speed in inflate_fast()
  83344. * - Make op and len in inflate_fast() unsigned for consistency
  83345. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83346. * - Simplified bad distance check in inflate_fast()
  83347. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83348. * source file infback.c to provide a call-back interface to inflate for
  83349. * programs like gzip and unzip -- uses window as output buffer to avoid
  83350. * window copying
  83351. *
  83352. * 1.2.beta5 1 Jan 2003
  83353. * - Improved inflateBack() interface to allow the caller to provide initial
  83354. * input in strm.
  83355. * - Fixed stored blocks bug in inflateBack()
  83356. *
  83357. * 1.2.beta6 4 Jan 2003
  83358. * - Added comments in inffast.c on effectiveness of POSTINC
  83359. * - Typecasting all around to reduce compiler warnings
  83360. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83361. * make compilers happy
  83362. * - Changed type of window in inflateBackInit() to unsigned char *
  83363. *
  83364. * 1.2.beta7 27 Jan 2003
  83365. * - Changed many types to unsigned or unsigned short to avoid warnings
  83366. * - Added inflateCopy() function
  83367. *
  83368. * 1.2.0 9 Mar 2003
  83369. * - Changed inflateBack() interface to provide separate opaque descriptors
  83370. * for the in() and out() functions
  83371. * - Changed inflateBack() argument and in_func typedef to swap the length
  83372. * and buffer address return values for the input function
  83373. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83374. *
  83375. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83376. */
  83377. /*** Start of inlined file: inffast.h ***/
  83378. /* WARNING: this file should *not* be used by applications. It is
  83379. part of the implementation of the compression library and is
  83380. subject to change. Applications should only use zlib.h.
  83381. */
  83382. void inflate_fast OF((z_streamp strm, unsigned start));
  83383. /*** End of inlined file: inffast.h ***/
  83384. #ifdef MAKEFIXED
  83385. # ifndef BUILDFIXED
  83386. # define BUILDFIXED
  83387. # endif
  83388. #endif
  83389. /* function prototypes */
  83390. local void fixedtables OF((struct inflate_state FAR *state));
  83391. local int updatewindow OF((z_streamp strm, unsigned out));
  83392. #ifdef BUILDFIXED
  83393. void makefixed OF((void));
  83394. #endif
  83395. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83396. unsigned len));
  83397. int ZEXPORT inflateReset (z_streamp strm)
  83398. {
  83399. struct inflate_state FAR *state;
  83400. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83401. state = (struct inflate_state FAR *)strm->state;
  83402. strm->total_in = strm->total_out = state->total = 0;
  83403. strm->msg = Z_NULL;
  83404. strm->adler = 1; /* to support ill-conceived Java test suite */
  83405. state->mode = HEAD;
  83406. state->last = 0;
  83407. state->havedict = 0;
  83408. state->dmax = 32768U;
  83409. state->head = Z_NULL;
  83410. state->wsize = 0;
  83411. state->whave = 0;
  83412. state->write = 0;
  83413. state->hold = 0;
  83414. state->bits = 0;
  83415. state->lencode = state->distcode = state->next = state->codes;
  83416. Tracev((stderr, "inflate: reset\n"));
  83417. return Z_OK;
  83418. }
  83419. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83420. {
  83421. struct inflate_state FAR *state;
  83422. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83423. state = (struct inflate_state FAR *)strm->state;
  83424. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83425. value &= (1L << bits) - 1;
  83426. state->hold += value << state->bits;
  83427. state->bits += bits;
  83428. return Z_OK;
  83429. }
  83430. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83431. {
  83432. struct inflate_state FAR *state;
  83433. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83434. stream_size != (int)(sizeof(z_stream)))
  83435. return Z_VERSION_ERROR;
  83436. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83437. strm->msg = Z_NULL; /* in case we return an error */
  83438. if (strm->zalloc == (alloc_func)0) {
  83439. strm->zalloc = zcalloc;
  83440. strm->opaque = (voidpf)0;
  83441. }
  83442. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83443. state = (struct inflate_state FAR *)
  83444. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83445. if (state == Z_NULL) return Z_MEM_ERROR;
  83446. Tracev((stderr, "inflate: allocated\n"));
  83447. strm->state = (struct internal_state FAR *)state;
  83448. if (windowBits < 0) {
  83449. state->wrap = 0;
  83450. windowBits = -windowBits;
  83451. }
  83452. else {
  83453. state->wrap = (windowBits >> 4) + 1;
  83454. #ifdef GUNZIP
  83455. if (windowBits < 48) windowBits &= 15;
  83456. #endif
  83457. }
  83458. if (windowBits < 8 || windowBits > 15) {
  83459. ZFREE(strm, state);
  83460. strm->state = Z_NULL;
  83461. return Z_STREAM_ERROR;
  83462. }
  83463. state->wbits = (unsigned)windowBits;
  83464. state->window = Z_NULL;
  83465. return inflateReset(strm);
  83466. }
  83467. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83468. {
  83469. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83470. }
  83471. /*
  83472. Return state with length and distance decoding tables and index sizes set to
  83473. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83474. If BUILDFIXED is defined, then instead this routine builds the tables the
  83475. first time it's called, and returns those tables the first time and
  83476. thereafter. This reduces the size of the code by about 2K bytes, in
  83477. exchange for a little execution time. However, BUILDFIXED should not be
  83478. used for threaded applications, since the rewriting of the tables and virgin
  83479. may not be thread-safe.
  83480. */
  83481. local void fixedtables (struct inflate_state FAR *state)
  83482. {
  83483. #ifdef BUILDFIXED
  83484. static int virgin = 1;
  83485. static code *lenfix, *distfix;
  83486. static code fixed[544];
  83487. /* build fixed huffman tables if first call (may not be thread safe) */
  83488. if (virgin) {
  83489. unsigned sym, bits;
  83490. static code *next;
  83491. /* literal/length table */
  83492. sym = 0;
  83493. while (sym < 144) state->lens[sym++] = 8;
  83494. while (sym < 256) state->lens[sym++] = 9;
  83495. while (sym < 280) state->lens[sym++] = 7;
  83496. while (sym < 288) state->lens[sym++] = 8;
  83497. next = fixed;
  83498. lenfix = next;
  83499. bits = 9;
  83500. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83501. /* distance table */
  83502. sym = 0;
  83503. while (sym < 32) state->lens[sym++] = 5;
  83504. distfix = next;
  83505. bits = 5;
  83506. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83507. /* do this just once */
  83508. virgin = 0;
  83509. }
  83510. #else /* !BUILDFIXED */
  83511. /*** Start of inlined file: inffixed.h ***/
  83512. /* WARNING: this file should *not* be used by applications. It
  83513. is part of the implementation of the compression library and
  83514. is subject to change. Applications should only use zlib.h.
  83515. */
  83516. static const code lenfix[512] = {
  83517. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83518. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83519. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83520. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83521. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83522. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83523. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83524. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83525. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83526. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83527. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83528. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83529. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83530. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83531. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83532. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83533. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83534. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83535. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83536. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83537. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83538. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83539. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83540. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83541. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83542. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83543. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83544. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83545. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83546. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83547. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83548. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83549. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83550. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83551. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83552. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83553. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83554. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83555. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83556. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83557. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83558. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83559. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83560. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83561. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83562. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83563. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83564. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83565. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83566. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83567. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83568. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83569. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83570. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83571. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83572. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83573. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83574. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83575. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83576. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83577. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83578. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83579. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83580. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83581. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83582. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83583. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83584. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83585. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83586. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83587. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83588. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83589. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83590. {0,9,255}
  83591. };
  83592. static const code distfix[32] = {
  83593. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83594. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83595. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83596. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83597. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83598. {22,5,193},{64,5,0}
  83599. };
  83600. /*** End of inlined file: inffixed.h ***/
  83601. #endif /* BUILDFIXED */
  83602. state->lencode = lenfix;
  83603. state->lenbits = 9;
  83604. state->distcode = distfix;
  83605. state->distbits = 5;
  83606. }
  83607. #ifdef MAKEFIXED
  83608. #include <stdio.h>
  83609. /*
  83610. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83611. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83612. those tables to stdout, which would be piped to inffixed.h. A small program
  83613. can simply call makefixed to do this:
  83614. void makefixed(void);
  83615. int main(void)
  83616. {
  83617. makefixed();
  83618. return 0;
  83619. }
  83620. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83621. a.out > inffixed.h
  83622. */
  83623. void makefixed()
  83624. {
  83625. unsigned low, size;
  83626. struct inflate_state state;
  83627. fixedtables(&state);
  83628. puts(" /* inffixed.h -- table for decoding fixed codes");
  83629. puts(" * Generated automatically by makefixed().");
  83630. puts(" */");
  83631. puts("");
  83632. puts(" /* WARNING: this file should *not* be used by applications.");
  83633. puts(" It is part of the implementation of this library and is");
  83634. puts(" subject to change. Applications should only use zlib.h.");
  83635. puts(" */");
  83636. puts("");
  83637. size = 1U << 9;
  83638. printf(" static const code lenfix[%u] = {", size);
  83639. low = 0;
  83640. for (;;) {
  83641. if ((low % 7) == 0) printf("\n ");
  83642. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83643. state.lencode[low].val);
  83644. if (++low == size) break;
  83645. putchar(',');
  83646. }
  83647. puts("\n };");
  83648. size = 1U << 5;
  83649. printf("\n static const code distfix[%u] = {", size);
  83650. low = 0;
  83651. for (;;) {
  83652. if ((low % 6) == 0) printf("\n ");
  83653. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83654. state.distcode[low].val);
  83655. if (++low == size) break;
  83656. putchar(',');
  83657. }
  83658. puts("\n };");
  83659. }
  83660. #endif /* MAKEFIXED */
  83661. /*
  83662. Update the window with the last wsize (normally 32K) bytes written before
  83663. returning. If window does not exist yet, create it. This is only called
  83664. when a window is already in use, or when output has been written during this
  83665. inflate call, but the end of the deflate stream has not been reached yet.
  83666. It is also called to create a window for dictionary data when a dictionary
  83667. is loaded.
  83668. Providing output buffers larger than 32K to inflate() should provide a speed
  83669. advantage, since only the last 32K of output is copied to the sliding window
  83670. upon return from inflate(), and since all distances after the first 32K of
  83671. output will fall in the output data, making match copies simpler and faster.
  83672. The advantage may be dependent on the size of the processor's data caches.
  83673. */
  83674. local int updatewindow (z_streamp strm, unsigned out)
  83675. {
  83676. struct inflate_state FAR *state;
  83677. unsigned copy, dist;
  83678. state = (struct inflate_state FAR *)strm->state;
  83679. /* if it hasn't been done already, allocate space for the window */
  83680. if (state->window == Z_NULL) {
  83681. state->window = (unsigned char FAR *)
  83682. ZALLOC(strm, 1U << state->wbits,
  83683. sizeof(unsigned char));
  83684. if (state->window == Z_NULL) return 1;
  83685. }
  83686. /* if window not in use yet, initialize */
  83687. if (state->wsize == 0) {
  83688. state->wsize = 1U << state->wbits;
  83689. state->write = 0;
  83690. state->whave = 0;
  83691. }
  83692. /* copy state->wsize or less output bytes into the circular window */
  83693. copy = out - strm->avail_out;
  83694. if (copy >= state->wsize) {
  83695. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83696. state->write = 0;
  83697. state->whave = state->wsize;
  83698. }
  83699. else {
  83700. dist = state->wsize - state->write;
  83701. if (dist > copy) dist = copy;
  83702. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83703. copy -= dist;
  83704. if (copy) {
  83705. zmemcpy(state->window, strm->next_out - copy, copy);
  83706. state->write = copy;
  83707. state->whave = state->wsize;
  83708. }
  83709. else {
  83710. state->write += dist;
  83711. if (state->write == state->wsize) state->write = 0;
  83712. if (state->whave < state->wsize) state->whave += dist;
  83713. }
  83714. }
  83715. return 0;
  83716. }
  83717. /* Macros for inflate(): */
  83718. /* check function to use adler32() for zlib or crc32() for gzip */
  83719. #ifdef GUNZIP
  83720. # define UPDATE(check, buf, len) \
  83721. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83722. #else
  83723. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83724. #endif
  83725. /* check macros for header crc */
  83726. #ifdef GUNZIP
  83727. # define CRC2(check, word) \
  83728. do { \
  83729. hbuf[0] = (unsigned char)(word); \
  83730. hbuf[1] = (unsigned char)((word) >> 8); \
  83731. check = crc32(check, hbuf, 2); \
  83732. } while (0)
  83733. # define CRC4(check, word) \
  83734. do { \
  83735. hbuf[0] = (unsigned char)(word); \
  83736. hbuf[1] = (unsigned char)((word) >> 8); \
  83737. hbuf[2] = (unsigned char)((word) >> 16); \
  83738. hbuf[3] = (unsigned char)((word) >> 24); \
  83739. check = crc32(check, hbuf, 4); \
  83740. } while (0)
  83741. #endif
  83742. /* Load registers with state in inflate() for speed */
  83743. #define LOAD() \
  83744. do { \
  83745. put = strm->next_out; \
  83746. left = strm->avail_out; \
  83747. next = strm->next_in; \
  83748. have = strm->avail_in; \
  83749. hold = state->hold; \
  83750. bits = state->bits; \
  83751. } while (0)
  83752. /* Restore state from registers in inflate() */
  83753. #define RESTORE() \
  83754. do { \
  83755. strm->next_out = put; \
  83756. strm->avail_out = left; \
  83757. strm->next_in = next; \
  83758. strm->avail_in = have; \
  83759. state->hold = hold; \
  83760. state->bits = bits; \
  83761. } while (0)
  83762. /* Clear the input bit accumulator */
  83763. #define INITBITS() \
  83764. do { \
  83765. hold = 0; \
  83766. bits = 0; \
  83767. } while (0)
  83768. /* Get a byte of input into the bit accumulator, or return from inflate()
  83769. if there is no input available. */
  83770. #define PULLBYTE() \
  83771. do { \
  83772. if (have == 0) goto inf_leave; \
  83773. have--; \
  83774. hold += (unsigned long)(*next++) << bits; \
  83775. bits += 8; \
  83776. } while (0)
  83777. /* Assure that there are at least n bits in the bit accumulator. If there is
  83778. not enough available input to do that, then return from inflate(). */
  83779. #define NEEDBITS(n) \
  83780. do { \
  83781. while (bits < (unsigned)(n)) \
  83782. PULLBYTE(); \
  83783. } while (0)
  83784. /* Return the low n bits of the bit accumulator (n < 16) */
  83785. #define BITS(n) \
  83786. ((unsigned)hold & ((1U << (n)) - 1))
  83787. /* Remove n bits from the bit accumulator */
  83788. #define DROPBITS(n) \
  83789. do { \
  83790. hold >>= (n); \
  83791. bits -= (unsigned)(n); \
  83792. } while (0)
  83793. /* Remove zero to seven bits as needed to go to a byte boundary */
  83794. #define BYTEBITS() \
  83795. do { \
  83796. hold >>= bits & 7; \
  83797. bits -= bits & 7; \
  83798. } while (0)
  83799. /* Reverse the bytes in a 32-bit value */
  83800. #define REVERSE(q) \
  83801. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83802. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83803. /*
  83804. inflate() uses a state machine to process as much input data and generate as
  83805. much output data as possible before returning. The state machine is
  83806. structured roughly as follows:
  83807. for (;;) switch (state) {
  83808. ...
  83809. case STATEn:
  83810. if (not enough input data or output space to make progress)
  83811. return;
  83812. ... make progress ...
  83813. state = STATEm;
  83814. break;
  83815. ...
  83816. }
  83817. so when inflate() is called again, the same case is attempted again, and
  83818. if the appropriate resources are provided, the machine proceeds to the
  83819. next state. The NEEDBITS() macro is usually the way the state evaluates
  83820. whether it can proceed or should return. NEEDBITS() does the return if
  83821. the requested bits are not available. The typical use of the BITS macros
  83822. is:
  83823. NEEDBITS(n);
  83824. ... do something with BITS(n) ...
  83825. DROPBITS(n);
  83826. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83827. input left to load n bits into the accumulator, or it continues. BITS(n)
  83828. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83829. the low n bits off the accumulator. INITBITS() clears the accumulator
  83830. and sets the number of available bits to zero. BYTEBITS() discards just
  83831. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83832. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83833. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83834. if there is no input available. The decoding of variable length codes uses
  83835. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83836. code, and no more.
  83837. Some states loop until they get enough input, making sure that enough
  83838. state information is maintained to continue the loop where it left off
  83839. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83840. would all have to actually be part of the saved state in case NEEDBITS()
  83841. returns:
  83842. case STATEw:
  83843. while (want < need) {
  83844. NEEDBITS(n);
  83845. keep[want++] = BITS(n);
  83846. DROPBITS(n);
  83847. }
  83848. state = STATEx;
  83849. case STATEx:
  83850. As shown above, if the next state is also the next case, then the break
  83851. is omitted.
  83852. A state may also return if there is not enough output space available to
  83853. complete that state. Those states are copying stored data, writing a
  83854. literal byte, and copying a matching string.
  83855. When returning, a "goto inf_leave" is used to update the total counters,
  83856. update the check value, and determine whether any progress has been made
  83857. during that inflate() call in order to return the proper return code.
  83858. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83859. When there is a window, goto inf_leave will update the window with the last
  83860. output written. If a goto inf_leave occurs in the middle of decompression
  83861. and there is no window currently, goto inf_leave will create one and copy
  83862. output to the window for the next call of inflate().
  83863. In this implementation, the flush parameter of inflate() only affects the
  83864. return code (per zlib.h). inflate() always writes as much as possible to
  83865. strm->next_out, given the space available and the provided input--the effect
  83866. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83867. the allocation of and copying into a sliding window until necessary, which
  83868. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83869. stream available. So the only thing the flush parameter actually does is:
  83870. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83871. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83872. */
  83873. int ZEXPORT inflate (z_streamp strm, int flush)
  83874. {
  83875. struct inflate_state FAR *state;
  83876. unsigned char FAR *next; /* next input */
  83877. unsigned char FAR *put; /* next output */
  83878. unsigned have, left; /* available input and output */
  83879. unsigned long hold; /* bit buffer */
  83880. unsigned bits; /* bits in bit buffer */
  83881. unsigned in, out; /* save starting available input and output */
  83882. unsigned copy; /* number of stored or match bytes to copy */
  83883. unsigned char FAR *from; /* where to copy match bytes from */
  83884. code thisx; /* current decoding table entry */
  83885. code last; /* parent table entry */
  83886. unsigned len; /* length to copy for repeats, bits to drop */
  83887. int ret; /* return code */
  83888. #ifdef GUNZIP
  83889. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83890. #endif
  83891. static const unsigned short order[19] = /* permutation of code lengths */
  83892. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83893. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83894. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83895. return Z_STREAM_ERROR;
  83896. state = (struct inflate_state FAR *)strm->state;
  83897. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83898. LOAD();
  83899. in = have;
  83900. out = left;
  83901. ret = Z_OK;
  83902. for (;;)
  83903. switch (state->mode) {
  83904. case HEAD:
  83905. if (state->wrap == 0) {
  83906. state->mode = TYPEDO;
  83907. break;
  83908. }
  83909. NEEDBITS(16);
  83910. #ifdef GUNZIP
  83911. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83912. state->check = crc32(0L, Z_NULL, 0);
  83913. CRC2(state->check, hold);
  83914. INITBITS();
  83915. state->mode = FLAGS;
  83916. break;
  83917. }
  83918. state->flags = 0; /* expect zlib header */
  83919. if (state->head != Z_NULL)
  83920. state->head->done = -1;
  83921. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83922. #else
  83923. if (
  83924. #endif
  83925. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83926. strm->msg = (char *)"incorrect header check";
  83927. state->mode = BAD;
  83928. break;
  83929. }
  83930. if (BITS(4) != Z_DEFLATED) {
  83931. strm->msg = (char *)"unknown compression method";
  83932. state->mode = BAD;
  83933. break;
  83934. }
  83935. DROPBITS(4);
  83936. len = BITS(4) + 8;
  83937. if (len > state->wbits) {
  83938. strm->msg = (char *)"invalid window size";
  83939. state->mode = BAD;
  83940. break;
  83941. }
  83942. state->dmax = 1U << len;
  83943. Tracev((stderr, "inflate: zlib header ok\n"));
  83944. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83945. state->mode = hold & 0x200 ? DICTID : TYPE;
  83946. INITBITS();
  83947. break;
  83948. #ifdef GUNZIP
  83949. case FLAGS:
  83950. NEEDBITS(16);
  83951. state->flags = (int)(hold);
  83952. if ((state->flags & 0xff) != Z_DEFLATED) {
  83953. strm->msg = (char *)"unknown compression method";
  83954. state->mode = BAD;
  83955. break;
  83956. }
  83957. if (state->flags & 0xe000) {
  83958. strm->msg = (char *)"unknown header flags set";
  83959. state->mode = BAD;
  83960. break;
  83961. }
  83962. if (state->head != Z_NULL)
  83963. state->head->text = (int)((hold >> 8) & 1);
  83964. if (state->flags & 0x0200) CRC2(state->check, hold);
  83965. INITBITS();
  83966. state->mode = TIME;
  83967. case TIME:
  83968. NEEDBITS(32);
  83969. if (state->head != Z_NULL)
  83970. state->head->time = hold;
  83971. if (state->flags & 0x0200) CRC4(state->check, hold);
  83972. INITBITS();
  83973. state->mode = OS;
  83974. case OS:
  83975. NEEDBITS(16);
  83976. if (state->head != Z_NULL) {
  83977. state->head->xflags = (int)(hold & 0xff);
  83978. state->head->os = (int)(hold >> 8);
  83979. }
  83980. if (state->flags & 0x0200) CRC2(state->check, hold);
  83981. INITBITS();
  83982. state->mode = EXLEN;
  83983. case EXLEN:
  83984. if (state->flags & 0x0400) {
  83985. NEEDBITS(16);
  83986. state->length = (unsigned)(hold);
  83987. if (state->head != Z_NULL)
  83988. state->head->extra_len = (unsigned)hold;
  83989. if (state->flags & 0x0200) CRC2(state->check, hold);
  83990. INITBITS();
  83991. }
  83992. else if (state->head != Z_NULL)
  83993. state->head->extra = Z_NULL;
  83994. state->mode = EXTRA;
  83995. case EXTRA:
  83996. if (state->flags & 0x0400) {
  83997. copy = state->length;
  83998. if (copy > have) copy = have;
  83999. if (copy) {
  84000. if (state->head != Z_NULL &&
  84001. state->head->extra != Z_NULL) {
  84002. len = state->head->extra_len - state->length;
  84003. zmemcpy(state->head->extra + len, next,
  84004. len + copy > state->head->extra_max ?
  84005. state->head->extra_max - len : copy);
  84006. }
  84007. if (state->flags & 0x0200)
  84008. state->check = crc32(state->check, next, copy);
  84009. have -= copy;
  84010. next += copy;
  84011. state->length -= copy;
  84012. }
  84013. if (state->length) goto inf_leave;
  84014. }
  84015. state->length = 0;
  84016. state->mode = NAME;
  84017. case NAME:
  84018. if (state->flags & 0x0800) {
  84019. if (have == 0) goto inf_leave;
  84020. copy = 0;
  84021. do {
  84022. len = (unsigned)(next[copy++]);
  84023. if (state->head != Z_NULL &&
  84024. state->head->name != Z_NULL &&
  84025. state->length < state->head->name_max)
  84026. state->head->name[state->length++] = len;
  84027. } while (len && copy < have);
  84028. if (state->flags & 0x0200)
  84029. state->check = crc32(state->check, next, copy);
  84030. have -= copy;
  84031. next += copy;
  84032. if (len) goto inf_leave;
  84033. }
  84034. else if (state->head != Z_NULL)
  84035. state->head->name = Z_NULL;
  84036. state->length = 0;
  84037. state->mode = COMMENT;
  84038. case COMMENT:
  84039. if (state->flags & 0x1000) {
  84040. if (have == 0) goto inf_leave;
  84041. copy = 0;
  84042. do {
  84043. len = (unsigned)(next[copy++]);
  84044. if (state->head != Z_NULL &&
  84045. state->head->comment != Z_NULL &&
  84046. state->length < state->head->comm_max)
  84047. state->head->comment[state->length++] = len;
  84048. } while (len && copy < have);
  84049. if (state->flags & 0x0200)
  84050. state->check = crc32(state->check, next, copy);
  84051. have -= copy;
  84052. next += copy;
  84053. if (len) goto inf_leave;
  84054. }
  84055. else if (state->head != Z_NULL)
  84056. state->head->comment = Z_NULL;
  84057. state->mode = HCRC;
  84058. case HCRC:
  84059. if (state->flags & 0x0200) {
  84060. NEEDBITS(16);
  84061. if (hold != (state->check & 0xffff)) {
  84062. strm->msg = (char *)"header crc mismatch";
  84063. state->mode = BAD;
  84064. break;
  84065. }
  84066. INITBITS();
  84067. }
  84068. if (state->head != Z_NULL) {
  84069. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84070. state->head->done = 1;
  84071. }
  84072. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84073. state->mode = TYPE;
  84074. break;
  84075. #endif
  84076. case DICTID:
  84077. NEEDBITS(32);
  84078. strm->adler = state->check = REVERSE(hold);
  84079. INITBITS();
  84080. state->mode = DICT;
  84081. case DICT:
  84082. if (state->havedict == 0) {
  84083. RESTORE();
  84084. return Z_NEED_DICT;
  84085. }
  84086. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84087. state->mode = TYPE;
  84088. case TYPE:
  84089. if (flush == Z_BLOCK) goto inf_leave;
  84090. case TYPEDO:
  84091. if (state->last) {
  84092. BYTEBITS();
  84093. state->mode = CHECK;
  84094. break;
  84095. }
  84096. NEEDBITS(3);
  84097. state->last = BITS(1);
  84098. DROPBITS(1);
  84099. switch (BITS(2)) {
  84100. case 0: /* stored block */
  84101. Tracev((stderr, "inflate: stored block%s\n",
  84102. state->last ? " (last)" : ""));
  84103. state->mode = STORED;
  84104. break;
  84105. case 1: /* fixed block */
  84106. fixedtables(state);
  84107. Tracev((stderr, "inflate: fixed codes block%s\n",
  84108. state->last ? " (last)" : ""));
  84109. state->mode = LEN; /* decode codes */
  84110. break;
  84111. case 2: /* dynamic block */
  84112. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84113. state->last ? " (last)" : ""));
  84114. state->mode = TABLE;
  84115. break;
  84116. case 3:
  84117. strm->msg = (char *)"invalid block type";
  84118. state->mode = BAD;
  84119. }
  84120. DROPBITS(2);
  84121. break;
  84122. case STORED:
  84123. BYTEBITS(); /* go to byte boundary */
  84124. NEEDBITS(32);
  84125. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84126. strm->msg = (char *)"invalid stored block lengths";
  84127. state->mode = BAD;
  84128. break;
  84129. }
  84130. state->length = (unsigned)hold & 0xffff;
  84131. Tracev((stderr, "inflate: stored length %u\n",
  84132. state->length));
  84133. INITBITS();
  84134. state->mode = COPY;
  84135. case COPY:
  84136. copy = state->length;
  84137. if (copy) {
  84138. if (copy > have) copy = have;
  84139. if (copy > left) copy = left;
  84140. if (copy == 0) goto inf_leave;
  84141. zmemcpy(put, next, copy);
  84142. have -= copy;
  84143. next += copy;
  84144. left -= copy;
  84145. put += copy;
  84146. state->length -= copy;
  84147. break;
  84148. }
  84149. Tracev((stderr, "inflate: stored end\n"));
  84150. state->mode = TYPE;
  84151. break;
  84152. case TABLE:
  84153. NEEDBITS(14);
  84154. state->nlen = BITS(5) + 257;
  84155. DROPBITS(5);
  84156. state->ndist = BITS(5) + 1;
  84157. DROPBITS(5);
  84158. state->ncode = BITS(4) + 4;
  84159. DROPBITS(4);
  84160. #ifndef PKZIP_BUG_WORKAROUND
  84161. if (state->nlen > 286 || state->ndist > 30) {
  84162. strm->msg = (char *)"too many length or distance symbols";
  84163. state->mode = BAD;
  84164. break;
  84165. }
  84166. #endif
  84167. Tracev((stderr, "inflate: table sizes ok\n"));
  84168. state->have = 0;
  84169. state->mode = LENLENS;
  84170. case LENLENS:
  84171. while (state->have < state->ncode) {
  84172. NEEDBITS(3);
  84173. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84174. DROPBITS(3);
  84175. }
  84176. while (state->have < 19)
  84177. state->lens[order[state->have++]] = 0;
  84178. state->next = state->codes;
  84179. state->lencode = (code const FAR *)(state->next);
  84180. state->lenbits = 7;
  84181. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84182. &(state->lenbits), state->work);
  84183. if (ret) {
  84184. strm->msg = (char *)"invalid code lengths set";
  84185. state->mode = BAD;
  84186. break;
  84187. }
  84188. Tracev((stderr, "inflate: code lengths ok\n"));
  84189. state->have = 0;
  84190. state->mode = CODELENS;
  84191. case CODELENS:
  84192. while (state->have < state->nlen + state->ndist) {
  84193. for (;;) {
  84194. thisx = state->lencode[BITS(state->lenbits)];
  84195. if ((unsigned)(thisx.bits) <= bits) break;
  84196. PULLBYTE();
  84197. }
  84198. if (thisx.val < 16) {
  84199. NEEDBITS(thisx.bits);
  84200. DROPBITS(thisx.bits);
  84201. state->lens[state->have++] = thisx.val;
  84202. }
  84203. else {
  84204. if (thisx.val == 16) {
  84205. NEEDBITS(thisx.bits + 2);
  84206. DROPBITS(thisx.bits);
  84207. if (state->have == 0) {
  84208. strm->msg = (char *)"invalid bit length repeat";
  84209. state->mode = BAD;
  84210. break;
  84211. }
  84212. len = state->lens[state->have - 1];
  84213. copy = 3 + BITS(2);
  84214. DROPBITS(2);
  84215. }
  84216. else if (thisx.val == 17) {
  84217. NEEDBITS(thisx.bits + 3);
  84218. DROPBITS(thisx.bits);
  84219. len = 0;
  84220. copy = 3 + BITS(3);
  84221. DROPBITS(3);
  84222. }
  84223. else {
  84224. NEEDBITS(thisx.bits + 7);
  84225. DROPBITS(thisx.bits);
  84226. len = 0;
  84227. copy = 11 + BITS(7);
  84228. DROPBITS(7);
  84229. }
  84230. if (state->have + copy > state->nlen + state->ndist) {
  84231. strm->msg = (char *)"invalid bit length repeat";
  84232. state->mode = BAD;
  84233. break;
  84234. }
  84235. while (copy--)
  84236. state->lens[state->have++] = (unsigned short)len;
  84237. }
  84238. }
  84239. /* handle error breaks in while */
  84240. if (state->mode == BAD) break;
  84241. /* build code tables */
  84242. state->next = state->codes;
  84243. state->lencode = (code const FAR *)(state->next);
  84244. state->lenbits = 9;
  84245. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84246. &(state->lenbits), state->work);
  84247. if (ret) {
  84248. strm->msg = (char *)"invalid literal/lengths set";
  84249. state->mode = BAD;
  84250. break;
  84251. }
  84252. state->distcode = (code const FAR *)(state->next);
  84253. state->distbits = 6;
  84254. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84255. &(state->next), &(state->distbits), state->work);
  84256. if (ret) {
  84257. strm->msg = (char *)"invalid distances set";
  84258. state->mode = BAD;
  84259. break;
  84260. }
  84261. Tracev((stderr, "inflate: codes ok\n"));
  84262. state->mode = LEN;
  84263. case LEN:
  84264. if (have >= 6 && left >= 258) {
  84265. RESTORE();
  84266. inflate_fast(strm, out);
  84267. LOAD();
  84268. break;
  84269. }
  84270. for (;;) {
  84271. thisx = state->lencode[BITS(state->lenbits)];
  84272. if ((unsigned)(thisx.bits) <= bits) break;
  84273. PULLBYTE();
  84274. }
  84275. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84276. last = thisx;
  84277. for (;;) {
  84278. thisx = state->lencode[last.val +
  84279. (BITS(last.bits + last.op) >> last.bits)];
  84280. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84281. PULLBYTE();
  84282. }
  84283. DROPBITS(last.bits);
  84284. }
  84285. DROPBITS(thisx.bits);
  84286. state->length = (unsigned)thisx.val;
  84287. if ((int)(thisx.op) == 0) {
  84288. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84289. "inflate: literal '%c'\n" :
  84290. "inflate: literal 0x%02x\n", thisx.val));
  84291. state->mode = LIT;
  84292. break;
  84293. }
  84294. if (thisx.op & 32) {
  84295. Tracevv((stderr, "inflate: end of block\n"));
  84296. state->mode = TYPE;
  84297. break;
  84298. }
  84299. if (thisx.op & 64) {
  84300. strm->msg = (char *)"invalid literal/length code";
  84301. state->mode = BAD;
  84302. break;
  84303. }
  84304. state->extra = (unsigned)(thisx.op) & 15;
  84305. state->mode = LENEXT;
  84306. case LENEXT:
  84307. if (state->extra) {
  84308. NEEDBITS(state->extra);
  84309. state->length += BITS(state->extra);
  84310. DROPBITS(state->extra);
  84311. }
  84312. Tracevv((stderr, "inflate: length %u\n", state->length));
  84313. state->mode = DIST;
  84314. case DIST:
  84315. for (;;) {
  84316. thisx = state->distcode[BITS(state->distbits)];
  84317. if ((unsigned)(thisx.bits) <= bits) break;
  84318. PULLBYTE();
  84319. }
  84320. if ((thisx.op & 0xf0) == 0) {
  84321. last = thisx;
  84322. for (;;) {
  84323. thisx = state->distcode[last.val +
  84324. (BITS(last.bits + last.op) >> last.bits)];
  84325. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84326. PULLBYTE();
  84327. }
  84328. DROPBITS(last.bits);
  84329. }
  84330. DROPBITS(thisx.bits);
  84331. if (thisx.op & 64) {
  84332. strm->msg = (char *)"invalid distance code";
  84333. state->mode = BAD;
  84334. break;
  84335. }
  84336. state->offset = (unsigned)thisx.val;
  84337. state->extra = (unsigned)(thisx.op) & 15;
  84338. state->mode = DISTEXT;
  84339. case DISTEXT:
  84340. if (state->extra) {
  84341. NEEDBITS(state->extra);
  84342. state->offset += BITS(state->extra);
  84343. DROPBITS(state->extra);
  84344. }
  84345. #ifdef INFLATE_STRICT
  84346. if (state->offset > state->dmax) {
  84347. strm->msg = (char *)"invalid distance too far back";
  84348. state->mode = BAD;
  84349. break;
  84350. }
  84351. #endif
  84352. if (state->offset > state->whave + out - left) {
  84353. strm->msg = (char *)"invalid distance too far back";
  84354. state->mode = BAD;
  84355. break;
  84356. }
  84357. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84358. state->mode = MATCH;
  84359. case MATCH:
  84360. if (left == 0) goto inf_leave;
  84361. copy = out - left;
  84362. if (state->offset > copy) { /* copy from window */
  84363. copy = state->offset - copy;
  84364. if (copy > state->write) {
  84365. copy -= state->write;
  84366. from = state->window + (state->wsize - copy);
  84367. }
  84368. else
  84369. from = state->window + (state->write - copy);
  84370. if (copy > state->length) copy = state->length;
  84371. }
  84372. else { /* copy from output */
  84373. from = put - state->offset;
  84374. copy = state->length;
  84375. }
  84376. if (copy > left) copy = left;
  84377. left -= copy;
  84378. state->length -= copy;
  84379. do {
  84380. *put++ = *from++;
  84381. } while (--copy);
  84382. if (state->length == 0) state->mode = LEN;
  84383. break;
  84384. case LIT:
  84385. if (left == 0) goto inf_leave;
  84386. *put++ = (unsigned char)(state->length);
  84387. left--;
  84388. state->mode = LEN;
  84389. break;
  84390. case CHECK:
  84391. if (state->wrap) {
  84392. NEEDBITS(32);
  84393. out -= left;
  84394. strm->total_out += out;
  84395. state->total += out;
  84396. if (out)
  84397. strm->adler = state->check =
  84398. UPDATE(state->check, put - out, out);
  84399. out = left;
  84400. if ((
  84401. #ifdef GUNZIP
  84402. state->flags ? hold :
  84403. #endif
  84404. REVERSE(hold)) != state->check) {
  84405. strm->msg = (char *)"incorrect data check";
  84406. state->mode = BAD;
  84407. break;
  84408. }
  84409. INITBITS();
  84410. Tracev((stderr, "inflate: check matches trailer\n"));
  84411. }
  84412. #ifdef GUNZIP
  84413. state->mode = LENGTH;
  84414. case LENGTH:
  84415. if (state->wrap && state->flags) {
  84416. NEEDBITS(32);
  84417. if (hold != (state->total & 0xffffffffUL)) {
  84418. strm->msg = (char *)"incorrect length check";
  84419. state->mode = BAD;
  84420. break;
  84421. }
  84422. INITBITS();
  84423. Tracev((stderr, "inflate: length matches trailer\n"));
  84424. }
  84425. #endif
  84426. state->mode = DONE;
  84427. case DONE:
  84428. ret = Z_STREAM_END;
  84429. goto inf_leave;
  84430. case BAD:
  84431. ret = Z_DATA_ERROR;
  84432. goto inf_leave;
  84433. case MEM:
  84434. return Z_MEM_ERROR;
  84435. case SYNC:
  84436. default:
  84437. return Z_STREAM_ERROR;
  84438. }
  84439. /*
  84440. Return from inflate(), updating the total counts and the check value.
  84441. If there was no progress during the inflate() call, return a buffer
  84442. error. Call updatewindow() to create and/or update the window state.
  84443. Note: a memory error from inflate() is non-recoverable.
  84444. */
  84445. inf_leave:
  84446. RESTORE();
  84447. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84448. if (updatewindow(strm, out)) {
  84449. state->mode = MEM;
  84450. return Z_MEM_ERROR;
  84451. }
  84452. in -= strm->avail_in;
  84453. out -= strm->avail_out;
  84454. strm->total_in += in;
  84455. strm->total_out += out;
  84456. state->total += out;
  84457. if (state->wrap && out)
  84458. strm->adler = state->check =
  84459. UPDATE(state->check, strm->next_out - out, out);
  84460. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84461. (state->mode == TYPE ? 128 : 0);
  84462. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84463. ret = Z_BUF_ERROR;
  84464. return ret;
  84465. }
  84466. int ZEXPORT inflateEnd (z_streamp strm)
  84467. {
  84468. struct inflate_state FAR *state;
  84469. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84470. return Z_STREAM_ERROR;
  84471. state = (struct inflate_state FAR *)strm->state;
  84472. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84473. ZFREE(strm, strm->state);
  84474. strm->state = Z_NULL;
  84475. Tracev((stderr, "inflate: end\n"));
  84476. return Z_OK;
  84477. }
  84478. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84479. {
  84480. struct inflate_state FAR *state;
  84481. unsigned long id_;
  84482. /* check state */
  84483. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84484. state = (struct inflate_state FAR *)strm->state;
  84485. if (state->wrap != 0 && state->mode != DICT)
  84486. return Z_STREAM_ERROR;
  84487. /* check for correct dictionary id */
  84488. if (state->mode == DICT) {
  84489. id_ = adler32(0L, Z_NULL, 0);
  84490. id_ = adler32(id_, dictionary, dictLength);
  84491. if (id_ != state->check)
  84492. return Z_DATA_ERROR;
  84493. }
  84494. /* copy dictionary to window */
  84495. if (updatewindow(strm, strm->avail_out)) {
  84496. state->mode = MEM;
  84497. return Z_MEM_ERROR;
  84498. }
  84499. if (dictLength > state->wsize) {
  84500. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84501. state->wsize);
  84502. state->whave = state->wsize;
  84503. }
  84504. else {
  84505. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84506. dictLength);
  84507. state->whave = dictLength;
  84508. }
  84509. state->havedict = 1;
  84510. Tracev((stderr, "inflate: dictionary set\n"));
  84511. return Z_OK;
  84512. }
  84513. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84514. {
  84515. struct inflate_state FAR *state;
  84516. /* check state */
  84517. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84518. state = (struct inflate_state FAR *)strm->state;
  84519. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84520. /* save header structure */
  84521. state->head = head;
  84522. head->done = 0;
  84523. return Z_OK;
  84524. }
  84525. /*
  84526. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84527. or when out of input. When called, *have is the number of pattern bytes
  84528. found in order so far, in 0..3. On return *have is updated to the new
  84529. state. If on return *have equals four, then the pattern was found and the
  84530. return value is how many bytes were read including the last byte of the
  84531. pattern. If *have is less than four, then the pattern has not been found
  84532. yet and the return value is len. In the latter case, syncsearch() can be
  84533. called again with more data and the *have state. *have is initialized to
  84534. zero for the first call.
  84535. */
  84536. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84537. {
  84538. unsigned got;
  84539. unsigned next;
  84540. got = *have;
  84541. next = 0;
  84542. while (next < len && got < 4) {
  84543. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84544. got++;
  84545. else if (buf[next])
  84546. got = 0;
  84547. else
  84548. got = 4 - got;
  84549. next++;
  84550. }
  84551. *have = got;
  84552. return next;
  84553. }
  84554. int ZEXPORT inflateSync (z_streamp strm)
  84555. {
  84556. unsigned len; /* number of bytes to look at or looked at */
  84557. unsigned long in, out; /* temporary to save total_in and total_out */
  84558. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84559. struct inflate_state FAR *state;
  84560. /* check parameters */
  84561. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84562. state = (struct inflate_state FAR *)strm->state;
  84563. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84564. /* if first time, start search in bit buffer */
  84565. if (state->mode != SYNC) {
  84566. state->mode = SYNC;
  84567. state->hold <<= state->bits & 7;
  84568. state->bits -= state->bits & 7;
  84569. len = 0;
  84570. while (state->bits >= 8) {
  84571. buf[len++] = (unsigned char)(state->hold);
  84572. state->hold >>= 8;
  84573. state->bits -= 8;
  84574. }
  84575. state->have = 0;
  84576. syncsearch(&(state->have), buf, len);
  84577. }
  84578. /* search available input */
  84579. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84580. strm->avail_in -= len;
  84581. strm->next_in += len;
  84582. strm->total_in += len;
  84583. /* return no joy or set up to restart inflate() on a new block */
  84584. if (state->have != 4) return Z_DATA_ERROR;
  84585. in = strm->total_in; out = strm->total_out;
  84586. inflateReset(strm);
  84587. strm->total_in = in; strm->total_out = out;
  84588. state->mode = TYPE;
  84589. return Z_OK;
  84590. }
  84591. /*
  84592. Returns true if inflate is currently at the end of a block generated by
  84593. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84594. implementation to provide an additional safety check. PPP uses
  84595. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84596. block. When decompressing, PPP checks that at the end of input packet,
  84597. inflate is waiting for these length bytes.
  84598. */
  84599. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84600. {
  84601. struct inflate_state FAR *state;
  84602. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84603. state = (struct inflate_state FAR *)strm->state;
  84604. return state->mode == STORED && state->bits == 0;
  84605. }
  84606. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84607. {
  84608. struct inflate_state FAR *state;
  84609. struct inflate_state FAR *copy;
  84610. unsigned char FAR *window;
  84611. unsigned wsize;
  84612. /* check input */
  84613. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84614. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84615. return Z_STREAM_ERROR;
  84616. state = (struct inflate_state FAR *)source->state;
  84617. /* allocate space */
  84618. copy = (struct inflate_state FAR *)
  84619. ZALLOC(source, 1, sizeof(struct inflate_state));
  84620. if (copy == Z_NULL) return Z_MEM_ERROR;
  84621. window = Z_NULL;
  84622. if (state->window != Z_NULL) {
  84623. window = (unsigned char FAR *)
  84624. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84625. if (window == Z_NULL) {
  84626. ZFREE(source, copy);
  84627. return Z_MEM_ERROR;
  84628. }
  84629. }
  84630. /* copy state */
  84631. zmemcpy(dest, source, sizeof(z_stream));
  84632. zmemcpy(copy, state, sizeof(struct inflate_state));
  84633. if (state->lencode >= state->codes &&
  84634. state->lencode <= state->codes + ENOUGH - 1) {
  84635. copy->lencode = copy->codes + (state->lencode - state->codes);
  84636. copy->distcode = copy->codes + (state->distcode - state->codes);
  84637. }
  84638. copy->next = copy->codes + (state->next - state->codes);
  84639. if (window != Z_NULL) {
  84640. wsize = 1U << state->wbits;
  84641. zmemcpy(window, state->window, wsize);
  84642. }
  84643. copy->window = window;
  84644. dest->state = (struct internal_state FAR *)copy;
  84645. return Z_OK;
  84646. }
  84647. /*** End of inlined file: inflate.c ***/
  84648. /*** Start of inlined file: inftrees.c ***/
  84649. #define MAXBITS 15
  84650. const char inflate_copyright[] =
  84651. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84652. /*
  84653. If you use the zlib library in a product, an acknowledgment is welcome
  84654. in the documentation of your product. If for some reason you cannot
  84655. include such an acknowledgment, I would appreciate that you keep this
  84656. copyright string in the executable of your product.
  84657. */
  84658. /*
  84659. Build a set of tables to decode the provided canonical Huffman code.
  84660. The code lengths are lens[0..codes-1]. The result starts at *table,
  84661. whose indices are 0..2^bits-1. work is a writable array of at least
  84662. lens shorts, which is used as a work area. type is the type of code
  84663. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84664. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84665. on return points to the next available entry's address. bits is the
  84666. requested root table index bits, and on return it is the actual root
  84667. table index bits. It will differ if the request is greater than the
  84668. longest code or if it is less than the shortest code.
  84669. */
  84670. int inflate_table (codetype type,
  84671. unsigned short FAR *lens,
  84672. unsigned codes,
  84673. code FAR * FAR *table,
  84674. unsigned FAR *bits,
  84675. unsigned short FAR *work)
  84676. {
  84677. unsigned len; /* a code's length in bits */
  84678. unsigned sym; /* index of code symbols */
  84679. unsigned min, max; /* minimum and maximum code lengths */
  84680. unsigned root; /* number of index bits for root table */
  84681. unsigned curr; /* number of index bits for current table */
  84682. unsigned drop; /* code bits to drop for sub-table */
  84683. int left; /* number of prefix codes available */
  84684. unsigned used; /* code entries in table used */
  84685. unsigned huff; /* Huffman code */
  84686. unsigned incr; /* for incrementing code, index */
  84687. unsigned fill; /* index for replicating entries */
  84688. unsigned low; /* low bits for current root entry */
  84689. unsigned mask; /* mask for low root bits */
  84690. code thisx; /* table entry for duplication */
  84691. code FAR *next; /* next available space in table */
  84692. const unsigned short FAR *base; /* base value table to use */
  84693. const unsigned short FAR *extra; /* extra bits table to use */
  84694. int end; /* use base and extra for symbol > end */
  84695. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84696. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84697. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84698. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84699. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84700. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84701. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84702. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84703. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84704. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84705. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84706. 8193, 12289, 16385, 24577, 0, 0};
  84707. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84708. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84709. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84710. 28, 28, 29, 29, 64, 64};
  84711. /*
  84712. Process a set of code lengths to create a canonical Huffman code. The
  84713. code lengths are lens[0..codes-1]. Each length corresponds to the
  84714. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84715. symbols by length from short to long, and retaining the symbol order
  84716. for codes with equal lengths. Then the code starts with all zero bits
  84717. for the first code of the shortest length, and the codes are integer
  84718. increments for the same length, and zeros are appended as the length
  84719. increases. For the deflate format, these bits are stored backwards
  84720. from their more natural integer increment ordering, and so when the
  84721. decoding tables are built in the large loop below, the integer codes
  84722. are incremented backwards.
  84723. This routine assumes, but does not check, that all of the entries in
  84724. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84725. 1..MAXBITS is interpreted as that code length. zero means that that
  84726. symbol does not occur in this code.
  84727. The codes are sorted by computing a count of codes for each length,
  84728. creating from that a table of starting indices for each length in the
  84729. sorted table, and then entering the symbols in order in the sorted
  84730. table. The sorted table is work[], with that space being provided by
  84731. the caller.
  84732. The length counts are used for other purposes as well, i.e. finding
  84733. the minimum and maximum length codes, determining if there are any
  84734. codes at all, checking for a valid set of lengths, and looking ahead
  84735. at length counts to determine sub-table sizes when building the
  84736. decoding tables.
  84737. */
  84738. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84739. for (len = 0; len <= MAXBITS; len++)
  84740. count[len] = 0;
  84741. for (sym = 0; sym < codes; sym++)
  84742. count[lens[sym]]++;
  84743. /* bound code lengths, force root to be within code lengths */
  84744. root = *bits;
  84745. for (max = MAXBITS; max >= 1; max--)
  84746. if (count[max] != 0) break;
  84747. if (root > max) root = max;
  84748. if (max == 0) { /* no symbols to code at all */
  84749. thisx.op = (unsigned char)64; /* invalid code marker */
  84750. thisx.bits = (unsigned char)1;
  84751. thisx.val = (unsigned short)0;
  84752. *(*table)++ = thisx; /* make a table to force an error */
  84753. *(*table)++ = thisx;
  84754. *bits = 1;
  84755. return 0; /* no symbols, but wait for decoding to report error */
  84756. }
  84757. for (min = 1; min <= MAXBITS; min++)
  84758. if (count[min] != 0) break;
  84759. if (root < min) root = min;
  84760. /* check for an over-subscribed or incomplete set of lengths */
  84761. left = 1;
  84762. for (len = 1; len <= MAXBITS; len++) {
  84763. left <<= 1;
  84764. left -= count[len];
  84765. if (left < 0) return -1; /* over-subscribed */
  84766. }
  84767. if (left > 0 && (type == CODES || max != 1))
  84768. return -1; /* incomplete set */
  84769. /* generate offsets into symbol table for each length for sorting */
  84770. offs[1] = 0;
  84771. for (len = 1; len < MAXBITS; len++)
  84772. offs[len + 1] = offs[len] + count[len];
  84773. /* sort symbols by length, by symbol order within each length */
  84774. for (sym = 0; sym < codes; sym++)
  84775. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84776. /*
  84777. Create and fill in decoding tables. In this loop, the table being
  84778. filled is at next and has curr index bits. The code being used is huff
  84779. with length len. That code is converted to an index by dropping drop
  84780. bits off of the bottom. For codes where len is less than drop + curr,
  84781. those top drop + curr - len bits are incremented through all values to
  84782. fill the table with replicated entries.
  84783. root is the number of index bits for the root table. When len exceeds
  84784. root, sub-tables are created pointed to by the root entry with an index
  84785. of the low root bits of huff. This is saved in low to check for when a
  84786. new sub-table should be started. drop is zero when the root table is
  84787. being filled, and drop is root when sub-tables are being filled.
  84788. When a new sub-table is needed, it is necessary to look ahead in the
  84789. code lengths to determine what size sub-table is needed. The length
  84790. counts are used for this, and so count[] is decremented as codes are
  84791. entered in the tables.
  84792. used keeps track of how many table entries have been allocated from the
  84793. provided *table space. It is checked when a LENS table is being made
  84794. against the space in *table, ENOUGH, minus the maximum space needed by
  84795. the worst case distance code, MAXD. This should never happen, but the
  84796. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84797. This assumes that when type == LENS, bits == 9.
  84798. sym increments through all symbols, and the loop terminates when
  84799. all codes of length max, i.e. all codes, have been processed. This
  84800. routine permits incomplete codes, so another loop after this one fills
  84801. in the rest of the decoding tables with invalid code markers.
  84802. */
  84803. /* set up for code type */
  84804. switch (type) {
  84805. case CODES:
  84806. base = extra = work; /* dummy value--not used */
  84807. end = 19;
  84808. break;
  84809. case LENS:
  84810. base = lbase;
  84811. base -= 257;
  84812. extra = lext;
  84813. extra -= 257;
  84814. end = 256;
  84815. break;
  84816. default: /* DISTS */
  84817. base = dbase;
  84818. extra = dext;
  84819. end = -1;
  84820. }
  84821. /* initialize state for loop */
  84822. huff = 0; /* starting code */
  84823. sym = 0; /* starting code symbol */
  84824. len = min; /* starting code length */
  84825. next = *table; /* current table to fill in */
  84826. curr = root; /* current table index bits */
  84827. drop = 0; /* current bits to drop from code for index */
  84828. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84829. used = 1U << root; /* use root table entries */
  84830. mask = used - 1; /* mask for comparing low */
  84831. /* check available table space */
  84832. if (type == LENS && used >= ENOUGH - MAXD)
  84833. return 1;
  84834. /* process all codes and make table entries */
  84835. for (;;) {
  84836. /* create table entry */
  84837. thisx.bits = (unsigned char)(len - drop);
  84838. if ((int)(work[sym]) < end) {
  84839. thisx.op = (unsigned char)0;
  84840. thisx.val = work[sym];
  84841. }
  84842. else if ((int)(work[sym]) > end) {
  84843. thisx.op = (unsigned char)(extra[work[sym]]);
  84844. thisx.val = base[work[sym]];
  84845. }
  84846. else {
  84847. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84848. thisx.val = 0;
  84849. }
  84850. /* replicate for those indices with low len bits equal to huff */
  84851. incr = 1U << (len - drop);
  84852. fill = 1U << curr;
  84853. min = fill; /* save offset to next table */
  84854. do {
  84855. fill -= incr;
  84856. next[(huff >> drop) + fill] = thisx;
  84857. } while (fill != 0);
  84858. /* backwards increment the len-bit code huff */
  84859. incr = 1U << (len - 1);
  84860. while (huff & incr)
  84861. incr >>= 1;
  84862. if (incr != 0) {
  84863. huff &= incr - 1;
  84864. huff += incr;
  84865. }
  84866. else
  84867. huff = 0;
  84868. /* go to next symbol, update count, len */
  84869. sym++;
  84870. if (--(count[len]) == 0) {
  84871. if (len == max) break;
  84872. len = lens[work[sym]];
  84873. }
  84874. /* create new sub-table if needed */
  84875. if (len > root && (huff & mask) != low) {
  84876. /* if first time, transition to sub-tables */
  84877. if (drop == 0)
  84878. drop = root;
  84879. /* increment past last table */
  84880. next += min; /* here min is 1 << curr */
  84881. /* determine length of next table */
  84882. curr = len - drop;
  84883. left = (int)(1 << curr);
  84884. while (curr + drop < max) {
  84885. left -= count[curr + drop];
  84886. if (left <= 0) break;
  84887. curr++;
  84888. left <<= 1;
  84889. }
  84890. /* check for enough space */
  84891. used += 1U << curr;
  84892. if (type == LENS && used >= ENOUGH - MAXD)
  84893. return 1;
  84894. /* point entry in root table to sub-table */
  84895. low = huff & mask;
  84896. (*table)[low].op = (unsigned char)curr;
  84897. (*table)[low].bits = (unsigned char)root;
  84898. (*table)[low].val = (unsigned short)(next - *table);
  84899. }
  84900. }
  84901. /*
  84902. Fill in rest of table for incomplete codes. This loop is similar to the
  84903. loop above in incrementing huff for table indices. It is assumed that
  84904. len is equal to curr + drop, so there is no loop needed to increment
  84905. through high index bits. When the current sub-table is filled, the loop
  84906. drops back to the root table to fill in any remaining entries there.
  84907. */
  84908. thisx.op = (unsigned char)64; /* invalid code marker */
  84909. thisx.bits = (unsigned char)(len - drop);
  84910. thisx.val = (unsigned short)0;
  84911. while (huff != 0) {
  84912. /* when done with sub-table, drop back to root table */
  84913. if (drop != 0 && (huff & mask) != low) {
  84914. drop = 0;
  84915. len = root;
  84916. next = *table;
  84917. thisx.bits = (unsigned char)len;
  84918. }
  84919. /* put invalid code marker in table */
  84920. next[huff >> drop] = thisx;
  84921. /* backwards increment the len-bit code huff */
  84922. incr = 1U << (len - 1);
  84923. while (huff & incr)
  84924. incr >>= 1;
  84925. if (incr != 0) {
  84926. huff &= incr - 1;
  84927. huff += incr;
  84928. }
  84929. else
  84930. huff = 0;
  84931. }
  84932. /* set return parameters */
  84933. *table += used;
  84934. *bits = root;
  84935. return 0;
  84936. }
  84937. /*** End of inlined file: inftrees.c ***/
  84938. /*** Start of inlined file: trees.c ***/
  84939. /*
  84940. * ALGORITHM
  84941. *
  84942. * The "deflation" process uses several Huffman trees. The more
  84943. * common source values are represented by shorter bit sequences.
  84944. *
  84945. * Each code tree is stored in a compressed form which is itself
  84946. * a Huffman encoding of the lengths of all the code strings (in
  84947. * ascending order by source values). The actual code strings are
  84948. * reconstructed from the lengths in the inflate process, as described
  84949. * in the deflate specification.
  84950. *
  84951. * REFERENCES
  84952. *
  84953. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84954. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84955. *
  84956. * Storer, James A.
  84957. * Data Compression: Methods and Theory, pp. 49-50.
  84958. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84959. *
  84960. * Sedgewick, R.
  84961. * Algorithms, p290.
  84962. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84963. */
  84964. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84965. /* #define GEN_TREES_H */
  84966. #ifdef DEBUG
  84967. # include <ctype.h>
  84968. #endif
  84969. /* ===========================================================================
  84970. * Constants
  84971. */
  84972. #define MAX_BL_BITS 7
  84973. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84974. #define END_BLOCK 256
  84975. /* end of block literal code */
  84976. #define REP_3_6 16
  84977. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84978. #define REPZ_3_10 17
  84979. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84980. #define REPZ_11_138 18
  84981. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84982. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84983. = {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};
  84984. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84985. = {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};
  84986. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84987. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84988. local const uch bl_order[BL_CODES]
  84989. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84990. /* The lengths of the bit length codes are sent in order of decreasing
  84991. * probability, to avoid transmitting the lengths for unused bit length codes.
  84992. */
  84993. #define Buf_size (8 * 2*sizeof(char))
  84994. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84995. * more than 16 bits on some systems.)
  84996. */
  84997. /* ===========================================================================
  84998. * Local data. These are initialized only once.
  84999. */
  85000. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  85001. #if defined(GEN_TREES_H) || !defined(STDC)
  85002. /* non ANSI compilers may not accept trees.h */
  85003. local ct_data static_ltree[L_CODES+2];
  85004. /* The static literal tree. Since the bit lengths are imposed, there is no
  85005. * need for the L_CODES extra codes used during heap construction. However
  85006. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  85007. * below).
  85008. */
  85009. local ct_data static_dtree[D_CODES];
  85010. /* The static distance tree. (Actually a trivial tree since all codes use
  85011. * 5 bits.)
  85012. */
  85013. uch _dist_code[DIST_CODE_LEN];
  85014. /* Distance codes. The first 256 values correspond to the distances
  85015. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85016. * the 15 bit distances.
  85017. */
  85018. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85019. /* length code for each normalized match length (0 == MIN_MATCH) */
  85020. local int base_length[LENGTH_CODES];
  85021. /* First normalized length for each code (0 = MIN_MATCH) */
  85022. local int base_dist[D_CODES];
  85023. /* First normalized distance for each code (0 = distance of 1) */
  85024. #else
  85025. /*** Start of inlined file: trees.h ***/
  85026. local const ct_data static_ltree[L_CODES+2] = {
  85027. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85028. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85029. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85030. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85031. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85032. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85033. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85034. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85035. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85036. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85037. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85038. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85039. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85040. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85041. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85042. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85043. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85044. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85045. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85046. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85047. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85048. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85049. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85050. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85051. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85052. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85053. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85054. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85055. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85056. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85057. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85058. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85059. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85060. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85061. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85062. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85063. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85064. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85065. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85066. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85067. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85068. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85069. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85070. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85071. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85072. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85073. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85074. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85075. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85076. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85077. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85078. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85079. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85080. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85081. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85082. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85083. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85084. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85085. };
  85086. local const ct_data static_dtree[D_CODES] = {
  85087. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85088. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85089. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85090. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85091. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85092. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85093. };
  85094. const uch _dist_code[DIST_CODE_LEN] = {
  85095. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85096. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85097. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85098. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85099. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85100. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85101. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85102. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85103. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85104. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85105. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85106. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85107. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85108. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85109. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85110. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85111. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85112. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85113. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85114. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85115. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85116. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85117. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85118. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85119. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85120. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85121. };
  85122. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85123. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85124. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85125. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85126. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85127. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85128. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85129. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85130. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85131. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85132. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85133. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85134. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85135. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85136. };
  85137. local const int base_length[LENGTH_CODES] = {
  85138. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85139. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85140. };
  85141. local const int base_dist[D_CODES] = {
  85142. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85143. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85144. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85145. };
  85146. /*** End of inlined file: trees.h ***/
  85147. #endif /* GEN_TREES_H */
  85148. struct static_tree_desc_s {
  85149. const ct_data *static_tree; /* static tree or NULL */
  85150. const intf *extra_bits; /* extra bits for each code or NULL */
  85151. int extra_base; /* base index for extra_bits */
  85152. int elems; /* max number of elements in the tree */
  85153. int max_length; /* max bit length for the codes */
  85154. };
  85155. local static_tree_desc static_l_desc =
  85156. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85157. local static_tree_desc static_d_desc =
  85158. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85159. local static_tree_desc static_bl_desc =
  85160. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85161. /* ===========================================================================
  85162. * Local (static) routines in this file.
  85163. */
  85164. local void tr_static_init OF((void));
  85165. local void init_block OF((deflate_state *s));
  85166. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85167. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85168. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85169. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85170. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85171. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85172. local int build_bl_tree OF((deflate_state *s));
  85173. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85174. int blcodes));
  85175. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85176. ct_data *dtree));
  85177. local void set_data_type OF((deflate_state *s));
  85178. local unsigned bi_reverse OF((unsigned value, int length));
  85179. local void bi_windup OF((deflate_state *s));
  85180. local void bi_flush OF((deflate_state *s));
  85181. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85182. int header));
  85183. #ifdef GEN_TREES_H
  85184. local void gen_trees_header OF((void));
  85185. #endif
  85186. #ifndef DEBUG
  85187. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85188. /* Send a code of the given tree. c and tree must not have side effects */
  85189. #else /* DEBUG */
  85190. # define send_code(s, c, tree) \
  85191. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85192. send_bits(s, tree[c].Code, tree[c].Len); }
  85193. #endif
  85194. /* ===========================================================================
  85195. * Output a short LSB first on the stream.
  85196. * IN assertion: there is enough room in pendingBuf.
  85197. */
  85198. #define put_short(s, w) { \
  85199. put_byte(s, (uch)((w) & 0xff)); \
  85200. put_byte(s, (uch)((ush)(w) >> 8)); \
  85201. }
  85202. /* ===========================================================================
  85203. * Send a value on a given number of bits.
  85204. * IN assertion: length <= 16 and value fits in length bits.
  85205. */
  85206. #ifdef DEBUG
  85207. local void send_bits OF((deflate_state *s, int value, int length));
  85208. local void send_bits (deflate_state *s, int value, int length)
  85209. {
  85210. Tracevv((stderr," l %2d v %4x ", length, value));
  85211. Assert(length > 0 && length <= 15, "invalid length");
  85212. s->bits_sent += (ulg)length;
  85213. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85214. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85215. * unused bits in value.
  85216. */
  85217. if (s->bi_valid > (int)Buf_size - length) {
  85218. s->bi_buf |= (value << s->bi_valid);
  85219. put_short(s, s->bi_buf);
  85220. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85221. s->bi_valid += length - Buf_size;
  85222. } else {
  85223. s->bi_buf |= value << s->bi_valid;
  85224. s->bi_valid += length;
  85225. }
  85226. }
  85227. #else /* !DEBUG */
  85228. #define send_bits(s, value, length) \
  85229. { int len = length;\
  85230. if (s->bi_valid > (int)Buf_size - len) {\
  85231. int val = value;\
  85232. s->bi_buf |= (val << s->bi_valid);\
  85233. put_short(s, s->bi_buf);\
  85234. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85235. s->bi_valid += len - Buf_size;\
  85236. } else {\
  85237. s->bi_buf |= (value) << s->bi_valid;\
  85238. s->bi_valid += len;\
  85239. }\
  85240. }
  85241. #endif /* DEBUG */
  85242. /* the arguments must not have side effects */
  85243. /* ===========================================================================
  85244. * Initialize the various 'constant' tables.
  85245. */
  85246. local void tr_static_init()
  85247. {
  85248. #if defined(GEN_TREES_H) || !defined(STDC)
  85249. static int static_init_done = 0;
  85250. int n; /* iterates over tree elements */
  85251. int bits; /* bit counter */
  85252. int length; /* length value */
  85253. int code; /* code value */
  85254. int dist; /* distance index */
  85255. ush bl_count[MAX_BITS+1];
  85256. /* number of codes at each bit length for an optimal tree */
  85257. if (static_init_done) return;
  85258. /* For some embedded targets, global variables are not initialized: */
  85259. static_l_desc.static_tree = static_ltree;
  85260. static_l_desc.extra_bits = extra_lbits;
  85261. static_d_desc.static_tree = static_dtree;
  85262. static_d_desc.extra_bits = extra_dbits;
  85263. static_bl_desc.extra_bits = extra_blbits;
  85264. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85265. length = 0;
  85266. for (code = 0; code < LENGTH_CODES-1; code++) {
  85267. base_length[code] = length;
  85268. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85269. _length_code[length++] = (uch)code;
  85270. }
  85271. }
  85272. Assert (length == 256, "tr_static_init: length != 256");
  85273. /* Note that the length 255 (match length 258) can be represented
  85274. * in two different ways: code 284 + 5 bits or code 285, so we
  85275. * overwrite length_code[255] to use the best encoding:
  85276. */
  85277. _length_code[length-1] = (uch)code;
  85278. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85279. dist = 0;
  85280. for (code = 0 ; code < 16; code++) {
  85281. base_dist[code] = dist;
  85282. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85283. _dist_code[dist++] = (uch)code;
  85284. }
  85285. }
  85286. Assert (dist == 256, "tr_static_init: dist != 256");
  85287. dist >>= 7; /* from now on, all distances are divided by 128 */
  85288. for ( ; code < D_CODES; code++) {
  85289. base_dist[code] = dist << 7;
  85290. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85291. _dist_code[256 + dist++] = (uch)code;
  85292. }
  85293. }
  85294. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85295. /* Construct the codes of the static literal tree */
  85296. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85297. n = 0;
  85298. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85299. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85300. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85301. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85302. /* Codes 286 and 287 do not exist, but we must include them in the
  85303. * tree construction to get a canonical Huffman tree (longest code
  85304. * all ones)
  85305. */
  85306. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85307. /* The static distance tree is trivial: */
  85308. for (n = 0; n < D_CODES; n++) {
  85309. static_dtree[n].Len = 5;
  85310. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85311. }
  85312. static_init_done = 1;
  85313. # ifdef GEN_TREES_H
  85314. gen_trees_header();
  85315. # endif
  85316. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85317. }
  85318. /* ===========================================================================
  85319. * Genererate the file trees.h describing the static trees.
  85320. */
  85321. #ifdef GEN_TREES_H
  85322. # ifndef DEBUG
  85323. # include <stdio.h>
  85324. # endif
  85325. # define SEPARATOR(i, last, width) \
  85326. ((i) == (last)? "\n};\n\n" : \
  85327. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85328. void gen_trees_header()
  85329. {
  85330. FILE *header = fopen("trees.h", "w");
  85331. int i;
  85332. Assert (header != NULL, "Can't open trees.h");
  85333. fprintf(header,
  85334. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85335. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85336. for (i = 0; i < L_CODES+2; i++) {
  85337. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85338. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85339. }
  85340. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85341. for (i = 0; i < D_CODES; i++) {
  85342. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85343. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85344. }
  85345. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85346. for (i = 0; i < DIST_CODE_LEN; i++) {
  85347. fprintf(header, "%2u%s", _dist_code[i],
  85348. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85349. }
  85350. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85351. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85352. fprintf(header, "%2u%s", _length_code[i],
  85353. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85354. }
  85355. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85356. for (i = 0; i < LENGTH_CODES; i++) {
  85357. fprintf(header, "%1u%s", base_length[i],
  85358. SEPARATOR(i, LENGTH_CODES-1, 20));
  85359. }
  85360. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85361. for (i = 0; i < D_CODES; i++) {
  85362. fprintf(header, "%5u%s", base_dist[i],
  85363. SEPARATOR(i, D_CODES-1, 10));
  85364. }
  85365. fclose(header);
  85366. }
  85367. #endif /* GEN_TREES_H */
  85368. /* ===========================================================================
  85369. * Initialize the tree data structures for a new zlib stream.
  85370. */
  85371. void _tr_init(deflate_state *s)
  85372. {
  85373. tr_static_init();
  85374. s->l_desc.dyn_tree = s->dyn_ltree;
  85375. s->l_desc.stat_desc = &static_l_desc;
  85376. s->d_desc.dyn_tree = s->dyn_dtree;
  85377. s->d_desc.stat_desc = &static_d_desc;
  85378. s->bl_desc.dyn_tree = s->bl_tree;
  85379. s->bl_desc.stat_desc = &static_bl_desc;
  85380. s->bi_buf = 0;
  85381. s->bi_valid = 0;
  85382. s->last_eob_len = 8; /* enough lookahead for inflate */
  85383. #ifdef DEBUG
  85384. s->compressed_len = 0L;
  85385. s->bits_sent = 0L;
  85386. #endif
  85387. /* Initialize the first block of the first file: */
  85388. init_block(s);
  85389. }
  85390. /* ===========================================================================
  85391. * Initialize a new block.
  85392. */
  85393. local void init_block (deflate_state *s)
  85394. {
  85395. int n; /* iterates over tree elements */
  85396. /* Initialize the trees. */
  85397. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85398. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85399. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85400. s->dyn_ltree[END_BLOCK].Freq = 1;
  85401. s->opt_len = s->static_len = 0L;
  85402. s->last_lit = s->matches = 0;
  85403. }
  85404. #define SMALLEST 1
  85405. /* Index within the heap array of least frequent node in the Huffman tree */
  85406. /* ===========================================================================
  85407. * Remove the smallest element from the heap and recreate the heap with
  85408. * one less element. Updates heap and heap_len.
  85409. */
  85410. #define pqremove(s, tree, top) \
  85411. {\
  85412. top = s->heap[SMALLEST]; \
  85413. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85414. pqdownheap(s, tree, SMALLEST); \
  85415. }
  85416. /* ===========================================================================
  85417. * Compares to subtrees, using the tree depth as tie breaker when
  85418. * the subtrees have equal frequency. This minimizes the worst case length.
  85419. */
  85420. #define smaller(tree, n, m, depth) \
  85421. (tree[n].Freq < tree[m].Freq || \
  85422. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85423. /* ===========================================================================
  85424. * Restore the heap property by moving down the tree starting at node k,
  85425. * exchanging a node with the smallest of its two sons if necessary, stopping
  85426. * when the heap property is re-established (each father smaller than its
  85427. * two sons).
  85428. */
  85429. local void pqdownheap (deflate_state *s,
  85430. ct_data *tree, /* the tree to restore */
  85431. int k) /* node to move down */
  85432. {
  85433. int v = s->heap[k];
  85434. int j = k << 1; /* left son of k */
  85435. while (j <= s->heap_len) {
  85436. /* Set j to the smallest of the two sons: */
  85437. if (j < s->heap_len &&
  85438. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85439. j++;
  85440. }
  85441. /* Exit if v is smaller than both sons */
  85442. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85443. /* Exchange v with the smallest son */
  85444. s->heap[k] = s->heap[j]; k = j;
  85445. /* And continue down the tree, setting j to the left son of k */
  85446. j <<= 1;
  85447. }
  85448. s->heap[k] = v;
  85449. }
  85450. /* ===========================================================================
  85451. * Compute the optimal bit lengths for a tree and update the total bit length
  85452. * for the current block.
  85453. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85454. * above are the tree nodes sorted by increasing frequency.
  85455. * OUT assertions: the field len is set to the optimal bit length, the
  85456. * array bl_count contains the frequencies for each bit length.
  85457. * The length opt_len is updated; static_len is also updated if stree is
  85458. * not null.
  85459. */
  85460. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85461. {
  85462. ct_data *tree = desc->dyn_tree;
  85463. int max_code = desc->max_code;
  85464. const ct_data *stree = desc->stat_desc->static_tree;
  85465. const intf *extra = desc->stat_desc->extra_bits;
  85466. int base = desc->stat_desc->extra_base;
  85467. int max_length = desc->stat_desc->max_length;
  85468. int h; /* heap index */
  85469. int n, m; /* iterate over the tree elements */
  85470. int bits; /* bit length */
  85471. int xbits; /* extra bits */
  85472. ush f; /* frequency */
  85473. int overflow = 0; /* number of elements with bit length too large */
  85474. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85475. /* In a first pass, compute the optimal bit lengths (which may
  85476. * overflow in the case of the bit length tree).
  85477. */
  85478. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85479. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85480. n = s->heap[h];
  85481. bits = tree[tree[n].Dad].Len + 1;
  85482. if (bits > max_length) bits = max_length, overflow++;
  85483. tree[n].Len = (ush)bits;
  85484. /* We overwrite tree[n].Dad which is no longer needed */
  85485. if (n > max_code) continue; /* not a leaf node */
  85486. s->bl_count[bits]++;
  85487. xbits = 0;
  85488. if (n >= base) xbits = extra[n-base];
  85489. f = tree[n].Freq;
  85490. s->opt_len += (ulg)f * (bits + xbits);
  85491. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85492. }
  85493. if (overflow == 0) return;
  85494. Trace((stderr,"\nbit length overflow\n"));
  85495. /* This happens for example on obj2 and pic of the Calgary corpus */
  85496. /* Find the first bit length which could increase: */
  85497. do {
  85498. bits = max_length-1;
  85499. while (s->bl_count[bits] == 0) bits--;
  85500. s->bl_count[bits]--; /* move one leaf down the tree */
  85501. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85502. s->bl_count[max_length]--;
  85503. /* The brother of the overflow item also moves one step up,
  85504. * but this does not affect bl_count[max_length]
  85505. */
  85506. overflow -= 2;
  85507. } while (overflow > 0);
  85508. /* Now recompute all bit lengths, scanning in increasing frequency.
  85509. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85510. * lengths instead of fixing only the wrong ones. This idea is taken
  85511. * from 'ar' written by Haruhiko Okumura.)
  85512. */
  85513. for (bits = max_length; bits != 0; bits--) {
  85514. n = s->bl_count[bits];
  85515. while (n != 0) {
  85516. m = s->heap[--h];
  85517. if (m > max_code) continue;
  85518. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85519. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85520. s->opt_len += ((long)bits - (long)tree[m].Len)
  85521. *(long)tree[m].Freq;
  85522. tree[m].Len = (ush)bits;
  85523. }
  85524. n--;
  85525. }
  85526. }
  85527. }
  85528. /* ===========================================================================
  85529. * Generate the codes for a given tree and bit counts (which need not be
  85530. * optimal).
  85531. * IN assertion: the array bl_count contains the bit length statistics for
  85532. * the given tree and the field len is set for all tree elements.
  85533. * OUT assertion: the field code is set for all tree elements of non
  85534. * zero code length.
  85535. */
  85536. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85537. int max_code, /* largest code with non zero frequency */
  85538. ushf *bl_count) /* number of codes at each bit length */
  85539. {
  85540. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85541. ush code = 0; /* running code value */
  85542. int bits; /* bit index */
  85543. int n; /* code index */
  85544. /* The distribution counts are first used to generate the code values
  85545. * without bit reversal.
  85546. */
  85547. for (bits = 1; bits <= MAX_BITS; bits++) {
  85548. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85549. }
  85550. /* Check that the bit counts in bl_count are consistent. The last code
  85551. * must be all ones.
  85552. */
  85553. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85554. "inconsistent bit counts");
  85555. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85556. for (n = 0; n <= max_code; n++) {
  85557. int len = tree[n].Len;
  85558. if (len == 0) continue;
  85559. /* Now reverse the bits */
  85560. tree[n].Code = bi_reverse(next_code[len]++, len);
  85561. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85562. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85563. }
  85564. }
  85565. /* ===========================================================================
  85566. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85567. * Update the total bit length for the current block.
  85568. * IN assertion: the field freq is set for all tree elements.
  85569. * OUT assertions: the fields len and code are set to the optimal bit length
  85570. * and corresponding code. The length opt_len is updated; static_len is
  85571. * also updated if stree is not null. The field max_code is set.
  85572. */
  85573. local void build_tree (deflate_state *s,
  85574. tree_desc *desc) /* the tree descriptor */
  85575. {
  85576. ct_data *tree = desc->dyn_tree;
  85577. const ct_data *stree = desc->stat_desc->static_tree;
  85578. int elems = desc->stat_desc->elems;
  85579. int n, m; /* iterate over heap elements */
  85580. int max_code = -1; /* largest code with non zero frequency */
  85581. int node; /* new node being created */
  85582. /* Construct the initial heap, with least frequent element in
  85583. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85584. * heap[0] is not used.
  85585. */
  85586. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85587. for (n = 0; n < elems; n++) {
  85588. if (tree[n].Freq != 0) {
  85589. s->heap[++(s->heap_len)] = max_code = n;
  85590. s->depth[n] = 0;
  85591. } else {
  85592. tree[n].Len = 0;
  85593. }
  85594. }
  85595. /* The pkzip format requires that at least one distance code exists,
  85596. * and that at least one bit should be sent even if there is only one
  85597. * possible code. So to avoid special checks later on we force at least
  85598. * two codes of non zero frequency.
  85599. */
  85600. while (s->heap_len < 2) {
  85601. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85602. tree[node].Freq = 1;
  85603. s->depth[node] = 0;
  85604. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85605. /* node is 0 or 1 so it does not have extra bits */
  85606. }
  85607. desc->max_code = max_code;
  85608. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85609. * establish sub-heaps of increasing lengths:
  85610. */
  85611. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85612. /* Construct the Huffman tree by repeatedly combining the least two
  85613. * frequent nodes.
  85614. */
  85615. node = elems; /* next internal node of the tree */
  85616. do {
  85617. pqremove(s, tree, n); /* n = node of least frequency */
  85618. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85619. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85620. s->heap[--(s->heap_max)] = m;
  85621. /* Create a new node father of n and m */
  85622. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85623. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85624. s->depth[n] : s->depth[m]) + 1);
  85625. tree[n].Dad = tree[m].Dad = (ush)node;
  85626. #ifdef DUMP_BL_TREE
  85627. if (tree == s->bl_tree) {
  85628. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85629. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85630. }
  85631. #endif
  85632. /* and insert the new node in the heap */
  85633. s->heap[SMALLEST] = node++;
  85634. pqdownheap(s, tree, SMALLEST);
  85635. } while (s->heap_len >= 2);
  85636. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85637. /* At this point, the fields freq and dad are set. We can now
  85638. * generate the bit lengths.
  85639. */
  85640. gen_bitlen(s, (tree_desc *)desc);
  85641. /* The field len is now set, we can generate the bit codes */
  85642. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85643. }
  85644. /* ===========================================================================
  85645. * Scan a literal or distance tree to determine the frequencies of the codes
  85646. * in the bit length tree.
  85647. */
  85648. local void scan_tree (deflate_state *s,
  85649. ct_data *tree, /* the tree to be scanned */
  85650. int max_code) /* and its largest code of non zero frequency */
  85651. {
  85652. int n; /* iterates over all tree elements */
  85653. int prevlen = -1; /* last emitted length */
  85654. int curlen; /* length of current code */
  85655. int nextlen = tree[0].Len; /* length of next code */
  85656. int count = 0; /* repeat count of the current code */
  85657. int max_count = 7; /* max repeat count */
  85658. int min_count = 4; /* min repeat count */
  85659. if (nextlen == 0) max_count = 138, min_count = 3;
  85660. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85661. for (n = 0; n <= max_code; n++) {
  85662. curlen = nextlen; nextlen = tree[n+1].Len;
  85663. if (++count < max_count && curlen == nextlen) {
  85664. continue;
  85665. } else if (count < min_count) {
  85666. s->bl_tree[curlen].Freq += count;
  85667. } else if (curlen != 0) {
  85668. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85669. s->bl_tree[REP_3_6].Freq++;
  85670. } else if (count <= 10) {
  85671. s->bl_tree[REPZ_3_10].Freq++;
  85672. } else {
  85673. s->bl_tree[REPZ_11_138].Freq++;
  85674. }
  85675. count = 0; prevlen = curlen;
  85676. if (nextlen == 0) {
  85677. max_count = 138, min_count = 3;
  85678. } else if (curlen == nextlen) {
  85679. max_count = 6, min_count = 3;
  85680. } else {
  85681. max_count = 7, min_count = 4;
  85682. }
  85683. }
  85684. }
  85685. /* ===========================================================================
  85686. * Send a literal or distance tree in compressed form, using the codes in
  85687. * bl_tree.
  85688. */
  85689. local void send_tree (deflate_state *s,
  85690. ct_data *tree, /* the tree to be scanned */
  85691. int max_code) /* and its largest code of non zero frequency */
  85692. {
  85693. int n; /* iterates over all tree elements */
  85694. int prevlen = -1; /* last emitted length */
  85695. int curlen; /* length of current code */
  85696. int nextlen = tree[0].Len; /* length of next code */
  85697. int count = 0; /* repeat count of the current code */
  85698. int max_count = 7; /* max repeat count */
  85699. int min_count = 4; /* min repeat count */
  85700. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85701. if (nextlen == 0) max_count = 138, min_count = 3;
  85702. for (n = 0; n <= max_code; n++) {
  85703. curlen = nextlen; nextlen = tree[n+1].Len;
  85704. if (++count < max_count && curlen == nextlen) {
  85705. continue;
  85706. } else if (count < min_count) {
  85707. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85708. } else if (curlen != 0) {
  85709. if (curlen != prevlen) {
  85710. send_code(s, curlen, s->bl_tree); count--;
  85711. }
  85712. Assert(count >= 3 && count <= 6, " 3_6?");
  85713. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85714. } else if (count <= 10) {
  85715. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85716. } else {
  85717. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85718. }
  85719. count = 0; prevlen = curlen;
  85720. if (nextlen == 0) {
  85721. max_count = 138, min_count = 3;
  85722. } else if (curlen == nextlen) {
  85723. max_count = 6, min_count = 3;
  85724. } else {
  85725. max_count = 7, min_count = 4;
  85726. }
  85727. }
  85728. }
  85729. /* ===========================================================================
  85730. * Construct the Huffman tree for the bit lengths and return the index in
  85731. * bl_order of the last bit length code to send.
  85732. */
  85733. local int build_bl_tree (deflate_state *s)
  85734. {
  85735. int max_blindex; /* index of last bit length code of non zero freq */
  85736. /* Determine the bit length frequencies for literal and distance trees */
  85737. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85738. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85739. /* Build the bit length tree: */
  85740. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85741. /* opt_len now includes the length of the tree representations, except
  85742. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85743. */
  85744. /* Determine the number of bit length codes to send. The pkzip format
  85745. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85746. * 3 but the actual value used is 4.)
  85747. */
  85748. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85749. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85750. }
  85751. /* Update opt_len to include the bit length tree and counts */
  85752. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85753. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85754. s->opt_len, s->static_len));
  85755. return max_blindex;
  85756. }
  85757. /* ===========================================================================
  85758. * Send the header for a block using dynamic Huffman trees: the counts, the
  85759. * lengths of the bit length codes, the literal tree and the distance tree.
  85760. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85761. */
  85762. local void send_all_trees (deflate_state *s,
  85763. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85764. {
  85765. int rank; /* index in bl_order */
  85766. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85767. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85768. "too many codes");
  85769. Tracev((stderr, "\nbl counts: "));
  85770. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85771. send_bits(s, dcodes-1, 5);
  85772. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85773. for (rank = 0; rank < blcodes; rank++) {
  85774. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85775. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85776. }
  85777. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85778. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85779. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85780. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85781. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85782. }
  85783. /* ===========================================================================
  85784. * Send a stored block
  85785. */
  85786. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85787. {
  85788. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85789. #ifdef DEBUG
  85790. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85791. s->compressed_len += (stored_len + 4) << 3;
  85792. #endif
  85793. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85794. }
  85795. /* ===========================================================================
  85796. * Send one empty static block to give enough lookahead for inflate.
  85797. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85798. * The current inflate code requires 9 bits of lookahead. If the
  85799. * last two codes for the previous block (real code plus EOB) were coded
  85800. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85801. * the last real code. In this case we send two empty static blocks instead
  85802. * of one. (There are no problems if the previous block is stored or fixed.)
  85803. * To simplify the code, we assume the worst case of last real code encoded
  85804. * on one bit only.
  85805. */
  85806. void _tr_align (deflate_state *s)
  85807. {
  85808. send_bits(s, STATIC_TREES<<1, 3);
  85809. send_code(s, END_BLOCK, static_ltree);
  85810. #ifdef DEBUG
  85811. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85812. #endif
  85813. bi_flush(s);
  85814. /* Of the 10 bits for the empty block, we have already sent
  85815. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85816. * the EOB of the previous block) was thus at least one plus the length
  85817. * of the EOB plus what we have just sent of the empty static block.
  85818. */
  85819. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85820. send_bits(s, STATIC_TREES<<1, 3);
  85821. send_code(s, END_BLOCK, static_ltree);
  85822. #ifdef DEBUG
  85823. s->compressed_len += 10L;
  85824. #endif
  85825. bi_flush(s);
  85826. }
  85827. s->last_eob_len = 7;
  85828. }
  85829. /* ===========================================================================
  85830. * Determine the best encoding for the current block: dynamic trees, static
  85831. * trees or store, and output the encoded block to the zip file.
  85832. */
  85833. void _tr_flush_block (deflate_state *s,
  85834. charf *buf, /* input block, or NULL if too old */
  85835. ulg stored_len, /* length of input block */
  85836. int eof) /* true if this is the last block for a file */
  85837. {
  85838. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85839. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85840. /* Build the Huffman trees unless a stored block is forced */
  85841. if (s->level > 0) {
  85842. /* Check if the file is binary or text */
  85843. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85844. set_data_type(s);
  85845. /* Construct the literal and distance trees */
  85846. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85847. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85848. s->static_len));
  85849. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85850. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85851. s->static_len));
  85852. /* At this point, opt_len and static_len are the total bit lengths of
  85853. * the compressed block data, excluding the tree representations.
  85854. */
  85855. /* Build the bit length tree for the above two trees, and get the index
  85856. * in bl_order of the last bit length code to send.
  85857. */
  85858. max_blindex = build_bl_tree(s);
  85859. /* Determine the best encoding. Compute the block lengths in bytes. */
  85860. opt_lenb = (s->opt_len+3+7)>>3;
  85861. static_lenb = (s->static_len+3+7)>>3;
  85862. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85863. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85864. s->last_lit));
  85865. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85866. } else {
  85867. Assert(buf != (char*)0, "lost buf");
  85868. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85869. }
  85870. #ifdef FORCE_STORED
  85871. if (buf != (char*)0) { /* force stored block */
  85872. #else
  85873. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85874. /* 4: two words for the lengths */
  85875. #endif
  85876. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85877. * Otherwise we can't have processed more than WSIZE input bytes since
  85878. * the last block flush, because compression would have been
  85879. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85880. * transform a block into a stored block.
  85881. */
  85882. _tr_stored_block(s, buf, stored_len, eof);
  85883. #ifdef FORCE_STATIC
  85884. } else if (static_lenb >= 0) { /* force static trees */
  85885. #else
  85886. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85887. #endif
  85888. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85889. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85890. #ifdef DEBUG
  85891. s->compressed_len += 3 + s->static_len;
  85892. #endif
  85893. } else {
  85894. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85895. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85896. max_blindex+1);
  85897. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85898. #ifdef DEBUG
  85899. s->compressed_len += 3 + s->opt_len;
  85900. #endif
  85901. }
  85902. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85903. /* The above check is made mod 2^32, for files larger than 512 MB
  85904. * and uLong implemented on 32 bits.
  85905. */
  85906. init_block(s);
  85907. if (eof) {
  85908. bi_windup(s);
  85909. #ifdef DEBUG
  85910. s->compressed_len += 7; /* align on byte boundary */
  85911. #endif
  85912. }
  85913. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85914. s->compressed_len-7*eof));
  85915. }
  85916. /* ===========================================================================
  85917. * Save the match info and tally the frequency counts. Return true if
  85918. * the current block must be flushed.
  85919. */
  85920. int _tr_tally (deflate_state *s,
  85921. unsigned dist, /* distance of matched string */
  85922. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85923. {
  85924. s->d_buf[s->last_lit] = (ush)dist;
  85925. s->l_buf[s->last_lit++] = (uch)lc;
  85926. if (dist == 0) {
  85927. /* lc is the unmatched char */
  85928. s->dyn_ltree[lc].Freq++;
  85929. } else {
  85930. s->matches++;
  85931. /* Here, lc is the match length - MIN_MATCH */
  85932. dist--; /* dist = match distance - 1 */
  85933. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85934. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85935. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85936. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85937. s->dyn_dtree[d_code(dist)].Freq++;
  85938. }
  85939. #ifdef TRUNCATE_BLOCK
  85940. /* Try to guess if it is profitable to stop the current block here */
  85941. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85942. /* Compute an upper bound for the compressed length */
  85943. ulg out_length = (ulg)s->last_lit*8L;
  85944. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85945. int dcode;
  85946. for (dcode = 0; dcode < D_CODES; dcode++) {
  85947. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85948. (5L+extra_dbits[dcode]);
  85949. }
  85950. out_length >>= 3;
  85951. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85952. s->last_lit, in_length, out_length,
  85953. 100L - out_length*100L/in_length));
  85954. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85955. }
  85956. #endif
  85957. return (s->last_lit == s->lit_bufsize-1);
  85958. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85959. * on 16 bit machines and because stored blocks are restricted to
  85960. * 64K-1 bytes.
  85961. */
  85962. }
  85963. /* ===========================================================================
  85964. * Send the block data compressed using the given Huffman trees
  85965. */
  85966. local void compress_block (deflate_state *s,
  85967. ct_data *ltree, /* literal tree */
  85968. ct_data *dtree) /* distance tree */
  85969. {
  85970. unsigned dist; /* distance of matched string */
  85971. int lc; /* match length or unmatched char (if dist == 0) */
  85972. unsigned lx = 0; /* running index in l_buf */
  85973. unsigned code; /* the code to send */
  85974. int extra; /* number of extra bits to send */
  85975. if (s->last_lit != 0) do {
  85976. dist = s->d_buf[lx];
  85977. lc = s->l_buf[lx++];
  85978. if (dist == 0) {
  85979. send_code(s, lc, ltree); /* send a literal byte */
  85980. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85981. } else {
  85982. /* Here, lc is the match length - MIN_MATCH */
  85983. code = _length_code[lc];
  85984. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85985. extra = extra_lbits[code];
  85986. if (extra != 0) {
  85987. lc -= base_length[code];
  85988. send_bits(s, lc, extra); /* send the extra length bits */
  85989. }
  85990. dist--; /* dist is now the match distance - 1 */
  85991. code = d_code(dist);
  85992. Assert (code < D_CODES, "bad d_code");
  85993. send_code(s, code, dtree); /* send the distance code */
  85994. extra = extra_dbits[code];
  85995. if (extra != 0) {
  85996. dist -= base_dist[code];
  85997. send_bits(s, dist, extra); /* send the extra distance bits */
  85998. }
  85999. } /* literal or match pair ? */
  86000. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  86001. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  86002. "pendingBuf overflow");
  86003. } while (lx < s->last_lit);
  86004. send_code(s, END_BLOCK, ltree);
  86005. s->last_eob_len = ltree[END_BLOCK].Len;
  86006. }
  86007. /* ===========================================================================
  86008. * Set the data type to BINARY or TEXT, using a crude approximation:
  86009. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  86010. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  86011. * IN assertion: the fields Freq of dyn_ltree are set.
  86012. */
  86013. local void set_data_type (deflate_state *s)
  86014. {
  86015. int n;
  86016. for (n = 0; n < 9; n++)
  86017. if (s->dyn_ltree[n].Freq != 0)
  86018. break;
  86019. if (n == 9)
  86020. for (n = 14; n < 32; n++)
  86021. if (s->dyn_ltree[n].Freq != 0)
  86022. break;
  86023. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86024. }
  86025. /* ===========================================================================
  86026. * Reverse the first len bits of a code, using straightforward code (a faster
  86027. * method would use a table)
  86028. * IN assertion: 1 <= len <= 15
  86029. */
  86030. local unsigned bi_reverse (unsigned code, int len)
  86031. {
  86032. register unsigned res = 0;
  86033. do {
  86034. res |= code & 1;
  86035. code >>= 1, res <<= 1;
  86036. } while (--len > 0);
  86037. return res >> 1;
  86038. }
  86039. /* ===========================================================================
  86040. * Flush the bit buffer, keeping at most 7 bits in it.
  86041. */
  86042. local void bi_flush (deflate_state *s)
  86043. {
  86044. if (s->bi_valid == 16) {
  86045. put_short(s, s->bi_buf);
  86046. s->bi_buf = 0;
  86047. s->bi_valid = 0;
  86048. } else if (s->bi_valid >= 8) {
  86049. put_byte(s, (Byte)s->bi_buf);
  86050. s->bi_buf >>= 8;
  86051. s->bi_valid -= 8;
  86052. }
  86053. }
  86054. /* ===========================================================================
  86055. * Flush the bit buffer and align the output on a byte boundary
  86056. */
  86057. local void bi_windup (deflate_state *s)
  86058. {
  86059. if (s->bi_valid > 8) {
  86060. put_short(s, s->bi_buf);
  86061. } else if (s->bi_valid > 0) {
  86062. put_byte(s, (Byte)s->bi_buf);
  86063. }
  86064. s->bi_buf = 0;
  86065. s->bi_valid = 0;
  86066. #ifdef DEBUG
  86067. s->bits_sent = (s->bits_sent+7) & ~7;
  86068. #endif
  86069. }
  86070. /* ===========================================================================
  86071. * Copy a stored block, storing first the length and its
  86072. * one's complement if requested.
  86073. */
  86074. local void copy_block(deflate_state *s,
  86075. charf *buf, /* the input data */
  86076. unsigned len, /* its length */
  86077. int header) /* true if block header must be written */
  86078. {
  86079. bi_windup(s); /* align on byte boundary */
  86080. s->last_eob_len = 8; /* enough lookahead for inflate */
  86081. if (header) {
  86082. put_short(s, (ush)len);
  86083. put_short(s, (ush)~len);
  86084. #ifdef DEBUG
  86085. s->bits_sent += 2*16;
  86086. #endif
  86087. }
  86088. #ifdef DEBUG
  86089. s->bits_sent += (ulg)len<<3;
  86090. #endif
  86091. while (len--) {
  86092. put_byte(s, *buf++);
  86093. }
  86094. }
  86095. /*** End of inlined file: trees.c ***/
  86096. /*** Start of inlined file: zutil.c ***/
  86097. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86098. #ifndef NO_DUMMY_DECL
  86099. struct internal_state {int dummy;}; /* for buggy compilers */
  86100. #endif
  86101. const char * const z_errmsg[10] = {
  86102. "need dictionary", /* Z_NEED_DICT 2 */
  86103. "stream end", /* Z_STREAM_END 1 */
  86104. "", /* Z_OK 0 */
  86105. "file error", /* Z_ERRNO (-1) */
  86106. "stream error", /* Z_STREAM_ERROR (-2) */
  86107. "data error", /* Z_DATA_ERROR (-3) */
  86108. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86109. "buffer error", /* Z_BUF_ERROR (-5) */
  86110. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86111. ""};
  86112. /*const char * ZEXPORT zlibVersion()
  86113. {
  86114. return ZLIB_VERSION;
  86115. }
  86116. uLong ZEXPORT zlibCompileFlags()
  86117. {
  86118. uLong flags;
  86119. flags = 0;
  86120. switch (sizeof(uInt)) {
  86121. case 2: break;
  86122. case 4: flags += 1; break;
  86123. case 8: flags += 2; break;
  86124. default: flags += 3;
  86125. }
  86126. switch (sizeof(uLong)) {
  86127. case 2: break;
  86128. case 4: flags += 1 << 2; break;
  86129. case 8: flags += 2 << 2; break;
  86130. default: flags += 3 << 2;
  86131. }
  86132. switch (sizeof(voidpf)) {
  86133. case 2: break;
  86134. case 4: flags += 1 << 4; break;
  86135. case 8: flags += 2 << 4; break;
  86136. default: flags += 3 << 4;
  86137. }
  86138. switch (sizeof(z_off_t)) {
  86139. case 2: break;
  86140. case 4: flags += 1 << 6; break;
  86141. case 8: flags += 2 << 6; break;
  86142. default: flags += 3 << 6;
  86143. }
  86144. #ifdef DEBUG
  86145. flags += 1 << 8;
  86146. #endif
  86147. #if defined(ASMV) || defined(ASMINF)
  86148. flags += 1 << 9;
  86149. #endif
  86150. #ifdef ZLIB_WINAPI
  86151. flags += 1 << 10;
  86152. #endif
  86153. #ifdef BUILDFIXED
  86154. flags += 1 << 12;
  86155. #endif
  86156. #ifdef DYNAMIC_CRC_TABLE
  86157. flags += 1 << 13;
  86158. #endif
  86159. #ifdef NO_GZCOMPRESS
  86160. flags += 1L << 16;
  86161. #endif
  86162. #ifdef NO_GZIP
  86163. flags += 1L << 17;
  86164. #endif
  86165. #ifdef PKZIP_BUG_WORKAROUND
  86166. flags += 1L << 20;
  86167. #endif
  86168. #ifdef FASTEST
  86169. flags += 1L << 21;
  86170. #endif
  86171. #ifdef STDC
  86172. # ifdef NO_vsnprintf
  86173. flags += 1L << 25;
  86174. # ifdef HAS_vsprintf_void
  86175. flags += 1L << 26;
  86176. # endif
  86177. # else
  86178. # ifdef HAS_vsnprintf_void
  86179. flags += 1L << 26;
  86180. # endif
  86181. # endif
  86182. #else
  86183. flags += 1L << 24;
  86184. # ifdef NO_snprintf
  86185. flags += 1L << 25;
  86186. # ifdef HAS_sprintf_void
  86187. flags += 1L << 26;
  86188. # endif
  86189. # else
  86190. # ifdef HAS_snprintf_void
  86191. flags += 1L << 26;
  86192. # endif
  86193. # endif
  86194. #endif
  86195. return flags;
  86196. }*/
  86197. #ifdef DEBUG
  86198. # ifndef verbose
  86199. # define verbose 0
  86200. # endif
  86201. int z_verbose = verbose;
  86202. void z_error (const char *m)
  86203. {
  86204. fprintf(stderr, "%s\n", m);
  86205. exit(1);
  86206. }
  86207. #endif
  86208. /* exported to allow conversion of error code to string for compress() and
  86209. * uncompress()
  86210. */
  86211. const char * ZEXPORT zError(int err)
  86212. {
  86213. return ERR_MSG(err);
  86214. }
  86215. #if defined(_WIN32_WCE)
  86216. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86217. * errno. We define it as a global variable to simplify porting.
  86218. * Its value is always 0 and should not be used.
  86219. */
  86220. int errno = 0;
  86221. #endif
  86222. #ifndef HAVE_MEMCPY
  86223. void zmemcpy(dest, source, len)
  86224. Bytef* dest;
  86225. const Bytef* source;
  86226. uInt len;
  86227. {
  86228. if (len == 0) return;
  86229. do {
  86230. *dest++ = *source++; /* ??? to be unrolled */
  86231. } while (--len != 0);
  86232. }
  86233. int zmemcmp(s1, s2, len)
  86234. const Bytef* s1;
  86235. const Bytef* s2;
  86236. uInt len;
  86237. {
  86238. uInt j;
  86239. for (j = 0; j < len; j++) {
  86240. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86241. }
  86242. return 0;
  86243. }
  86244. void zmemzero(dest, len)
  86245. Bytef* dest;
  86246. uInt len;
  86247. {
  86248. if (len == 0) return;
  86249. do {
  86250. *dest++ = 0; /* ??? to be unrolled */
  86251. } while (--len != 0);
  86252. }
  86253. #endif
  86254. #ifdef SYS16BIT
  86255. #ifdef __TURBOC__
  86256. /* Turbo C in 16-bit mode */
  86257. # define MY_ZCALLOC
  86258. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86259. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86260. * must fix the pointer. Warning: the pointer must be put back to its
  86261. * original form in order to free it, use zcfree().
  86262. */
  86263. #define MAX_PTR 10
  86264. /* 10*64K = 640K */
  86265. local int next_ptr = 0;
  86266. typedef struct ptr_table_s {
  86267. voidpf org_ptr;
  86268. voidpf new_ptr;
  86269. } ptr_table;
  86270. local ptr_table table[MAX_PTR];
  86271. /* This table is used to remember the original form of pointers
  86272. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86273. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86274. * protected from concurrent access. This hack doesn't work anyway on
  86275. * a protected system like OS/2. Use Microsoft C instead.
  86276. */
  86277. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86278. {
  86279. voidpf buf = opaque; /* just to make some compilers happy */
  86280. ulg bsize = (ulg)items*size;
  86281. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86282. * will return a usable pointer which doesn't have to be normalized.
  86283. */
  86284. if (bsize < 65520L) {
  86285. buf = farmalloc(bsize);
  86286. if (*(ush*)&buf != 0) return buf;
  86287. } else {
  86288. buf = farmalloc(bsize + 16L);
  86289. }
  86290. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86291. table[next_ptr].org_ptr = buf;
  86292. /* Normalize the pointer to seg:0 */
  86293. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86294. *(ush*)&buf = 0;
  86295. table[next_ptr++].new_ptr = buf;
  86296. return buf;
  86297. }
  86298. void zcfree (voidpf opaque, voidpf ptr)
  86299. {
  86300. int n;
  86301. if (*(ush*)&ptr != 0) { /* object < 64K */
  86302. farfree(ptr);
  86303. return;
  86304. }
  86305. /* Find the original pointer */
  86306. for (n = 0; n < next_ptr; n++) {
  86307. if (ptr != table[n].new_ptr) continue;
  86308. farfree(table[n].org_ptr);
  86309. while (++n < next_ptr) {
  86310. table[n-1] = table[n];
  86311. }
  86312. next_ptr--;
  86313. return;
  86314. }
  86315. ptr = opaque; /* just to make some compilers happy */
  86316. Assert(0, "zcfree: ptr not found");
  86317. }
  86318. #endif /* __TURBOC__ */
  86319. #ifdef M_I86
  86320. /* Microsoft C in 16-bit mode */
  86321. # define MY_ZCALLOC
  86322. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86323. # define _halloc halloc
  86324. # define _hfree hfree
  86325. #endif
  86326. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86327. {
  86328. if (opaque) opaque = 0; /* to make compiler happy */
  86329. return _halloc((long)items, size);
  86330. }
  86331. void zcfree (voidpf opaque, voidpf ptr)
  86332. {
  86333. if (opaque) opaque = 0; /* to make compiler happy */
  86334. _hfree(ptr);
  86335. }
  86336. #endif /* M_I86 */
  86337. #endif /* SYS16BIT */
  86338. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86339. #ifndef STDC
  86340. extern voidp malloc OF((uInt size));
  86341. extern voidp calloc OF((uInt items, uInt size));
  86342. extern void free OF((voidpf ptr));
  86343. #endif
  86344. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86345. {
  86346. if (opaque) items += size - size; /* make compiler happy */
  86347. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86348. (voidpf)calloc(items, size);
  86349. }
  86350. void zcfree (voidpf opaque, voidpf ptr)
  86351. {
  86352. free(ptr);
  86353. if (opaque) return; /* make compiler happy */
  86354. }
  86355. #endif /* MY_ZCALLOC */
  86356. /*** End of inlined file: zutil.c ***/
  86357. #undef Byte
  86358. #else
  86359. #include <zlib.h>
  86360. #endif
  86361. }
  86362. #if JUCE_MSVC
  86363. #pragma warning (pop)
  86364. #endif
  86365. BEGIN_JUCE_NAMESPACE
  86366. // internal helper object that holds the zlib structures so they don't have to be
  86367. // included publicly.
  86368. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86369. {
  86370. public:
  86371. GZIPDecompressHelper (const bool noWrap)
  86372. : finished (true),
  86373. needsDictionary (false),
  86374. error (true),
  86375. streamIsValid (false),
  86376. data (0),
  86377. dataSize (0)
  86378. {
  86379. using namespace zlibNamespace;
  86380. zerostruct (stream);
  86381. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86382. finished = error = ! streamIsValid;
  86383. }
  86384. ~GZIPDecompressHelper()
  86385. {
  86386. using namespace zlibNamespace;
  86387. if (streamIsValid)
  86388. inflateEnd (&stream);
  86389. }
  86390. bool needsInput() const throw() { return dataSize <= 0; }
  86391. void setInput (uint8* const data_, const int size) throw()
  86392. {
  86393. data = data_;
  86394. dataSize = size;
  86395. }
  86396. int doNextBlock (uint8* const dest, const int destSize)
  86397. {
  86398. using namespace zlibNamespace;
  86399. if (streamIsValid && data != 0 && ! finished)
  86400. {
  86401. stream.next_in = data;
  86402. stream.next_out = dest;
  86403. stream.avail_in = dataSize;
  86404. stream.avail_out = destSize;
  86405. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86406. {
  86407. case Z_STREAM_END:
  86408. finished = true;
  86409. // deliberate fall-through
  86410. case Z_OK:
  86411. data += dataSize - stream.avail_in;
  86412. dataSize = stream.avail_in;
  86413. return destSize - stream.avail_out;
  86414. case Z_NEED_DICT:
  86415. needsDictionary = true;
  86416. data += dataSize - stream.avail_in;
  86417. dataSize = stream.avail_in;
  86418. break;
  86419. case Z_DATA_ERROR:
  86420. case Z_MEM_ERROR:
  86421. error = true;
  86422. default:
  86423. break;
  86424. }
  86425. }
  86426. return 0;
  86427. }
  86428. bool finished, needsDictionary, error, streamIsValid;
  86429. enum { gzipDecompBufferSize = 32768 };
  86430. private:
  86431. zlibNamespace::z_stream stream;
  86432. uint8* data;
  86433. int dataSize;
  86434. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  86435. };
  86436. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86437. const bool deleteSourceWhenDestroyed,
  86438. const bool noWrap_,
  86439. const int64 uncompressedStreamLength_)
  86440. : sourceStream (sourceStream_),
  86441. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86442. uncompressedStreamLength (uncompressedStreamLength_),
  86443. noWrap (noWrap_),
  86444. isEof (false),
  86445. activeBufferSize (0),
  86446. originalSourcePos (sourceStream_->getPosition()),
  86447. currentPos (0),
  86448. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86449. helper (new GZIPDecompressHelper (noWrap_))
  86450. {
  86451. }
  86452. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86453. : sourceStream (&sourceStream_),
  86454. uncompressedStreamLength (-1),
  86455. noWrap (false),
  86456. isEof (false),
  86457. activeBufferSize (0),
  86458. originalSourcePos (sourceStream_.getPosition()),
  86459. currentPos (0),
  86460. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86461. helper (new GZIPDecompressHelper (false))
  86462. {
  86463. }
  86464. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86465. {
  86466. }
  86467. int64 GZIPDecompressorInputStream::getTotalLength()
  86468. {
  86469. return uncompressedStreamLength;
  86470. }
  86471. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86472. {
  86473. if ((howMany > 0) && ! isEof)
  86474. {
  86475. jassert (destBuffer != 0);
  86476. if (destBuffer != 0)
  86477. {
  86478. int numRead = 0;
  86479. uint8* d = static_cast <uint8*> (destBuffer);
  86480. while (! helper->error)
  86481. {
  86482. const int n = helper->doNextBlock (d, howMany);
  86483. currentPos += n;
  86484. if (n == 0)
  86485. {
  86486. if (helper->finished || helper->needsDictionary)
  86487. {
  86488. isEof = true;
  86489. return numRead;
  86490. }
  86491. if (helper->needsInput())
  86492. {
  86493. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86494. if (activeBufferSize > 0)
  86495. {
  86496. helper->setInput (buffer, activeBufferSize);
  86497. }
  86498. else
  86499. {
  86500. isEof = true;
  86501. return numRead;
  86502. }
  86503. }
  86504. }
  86505. else
  86506. {
  86507. numRead += n;
  86508. howMany -= n;
  86509. d += n;
  86510. if (howMany <= 0)
  86511. return numRead;
  86512. }
  86513. }
  86514. }
  86515. }
  86516. return 0;
  86517. }
  86518. bool GZIPDecompressorInputStream::isExhausted()
  86519. {
  86520. return helper->error || isEof;
  86521. }
  86522. int64 GZIPDecompressorInputStream::getPosition()
  86523. {
  86524. return currentPos;
  86525. }
  86526. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86527. {
  86528. if (newPos < currentPos)
  86529. {
  86530. // to go backwards, reset the stream and start again..
  86531. isEof = false;
  86532. activeBufferSize = 0;
  86533. currentPos = 0;
  86534. helper = new GZIPDecompressHelper (noWrap);
  86535. sourceStream->setPosition (originalSourcePos);
  86536. }
  86537. skipNextBytes (newPos - currentPos);
  86538. return true;
  86539. }
  86540. END_JUCE_NAMESPACE
  86541. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86542. #endif
  86543. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86544. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86545. #if JUCE_USE_FLAC
  86546. #if JUCE_WINDOWS
  86547. #include <windows.h>
  86548. #endif
  86549. namespace FlacNamespace
  86550. {
  86551. #if JUCE_INCLUDE_FLAC_CODE
  86552. #if JUCE_MSVC
  86553. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86554. #endif
  86555. #define FLAC__NO_DLL 1
  86556. #if ! defined (SIZE_MAX)
  86557. #define SIZE_MAX 0xffffffff
  86558. #endif
  86559. #define __STDC_LIMIT_MACROS 1
  86560. /*** Start of inlined file: all.h ***/
  86561. #ifndef FLAC__ALL_H
  86562. #define FLAC__ALL_H
  86563. /*** Start of inlined file: export.h ***/
  86564. #ifndef FLAC__EXPORT_H
  86565. #define FLAC__EXPORT_H
  86566. /** \file include/FLAC/export.h
  86567. *
  86568. * \brief
  86569. * This module contains #defines and symbols for exporting function
  86570. * calls, and providing version information and compiled-in features.
  86571. *
  86572. * See the \link flac_export export \endlink module.
  86573. */
  86574. /** \defgroup flac_export FLAC/export.h: export symbols
  86575. * \ingroup flac
  86576. *
  86577. * \brief
  86578. * This module contains #defines and symbols for exporting function
  86579. * calls, and providing version information and compiled-in features.
  86580. *
  86581. * If you are compiling with MSVC and will link to the static library
  86582. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86583. * make sure the symbols are exported properly.
  86584. *
  86585. * \{
  86586. */
  86587. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86588. #define FLAC_API
  86589. #else
  86590. #ifdef FLAC_API_EXPORTS
  86591. #define FLAC_API _declspec(dllexport)
  86592. #else
  86593. #define FLAC_API _declspec(dllimport)
  86594. #endif
  86595. #endif
  86596. /** These #defines will mirror the libtool-based library version number, see
  86597. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86598. */
  86599. #define FLAC_API_VERSION_CURRENT 10
  86600. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86601. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86602. #ifdef __cplusplus
  86603. extern "C" {
  86604. #endif
  86605. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86606. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86607. #ifdef __cplusplus
  86608. }
  86609. #endif
  86610. /* \} */
  86611. #endif
  86612. /*** End of inlined file: export.h ***/
  86613. /*** Start of inlined file: assert.h ***/
  86614. #ifndef FLAC__ASSERT_H
  86615. #define FLAC__ASSERT_H
  86616. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86617. #ifdef DEBUG
  86618. #include <assert.h>
  86619. #define FLAC__ASSERT(x) assert(x)
  86620. #define FLAC__ASSERT_DECLARATION(x) x
  86621. #else
  86622. #define FLAC__ASSERT(x)
  86623. #define FLAC__ASSERT_DECLARATION(x)
  86624. #endif
  86625. #endif
  86626. /*** End of inlined file: assert.h ***/
  86627. /*** Start of inlined file: callback.h ***/
  86628. #ifndef FLAC__CALLBACK_H
  86629. #define FLAC__CALLBACK_H
  86630. /*** Start of inlined file: ordinals.h ***/
  86631. #ifndef FLAC__ORDINALS_H
  86632. #define FLAC__ORDINALS_H
  86633. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86634. #include <inttypes.h>
  86635. #endif
  86636. typedef signed char FLAC__int8;
  86637. typedef unsigned char FLAC__uint8;
  86638. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86639. typedef __int16 FLAC__int16;
  86640. typedef __int32 FLAC__int32;
  86641. typedef __int64 FLAC__int64;
  86642. typedef unsigned __int16 FLAC__uint16;
  86643. typedef unsigned __int32 FLAC__uint32;
  86644. typedef unsigned __int64 FLAC__uint64;
  86645. #elif defined(__EMX__)
  86646. typedef short FLAC__int16;
  86647. typedef long FLAC__int32;
  86648. typedef long long FLAC__int64;
  86649. typedef unsigned short FLAC__uint16;
  86650. typedef unsigned long FLAC__uint32;
  86651. typedef unsigned long long FLAC__uint64;
  86652. #else
  86653. typedef int16_t FLAC__int16;
  86654. typedef int32_t FLAC__int32;
  86655. typedef int64_t FLAC__int64;
  86656. typedef uint16_t FLAC__uint16;
  86657. typedef uint32_t FLAC__uint32;
  86658. typedef uint64_t FLAC__uint64;
  86659. #endif
  86660. typedef int FLAC__bool;
  86661. typedef FLAC__uint8 FLAC__byte;
  86662. #ifdef true
  86663. #undef true
  86664. #endif
  86665. #ifdef false
  86666. #undef false
  86667. #endif
  86668. #ifndef __cplusplus
  86669. #define true 1
  86670. #define false 0
  86671. #endif
  86672. #endif
  86673. /*** End of inlined file: ordinals.h ***/
  86674. #include <stdlib.h> /* for size_t */
  86675. /** \file include/FLAC/callback.h
  86676. *
  86677. * \brief
  86678. * This module defines the structures for describing I/O callbacks
  86679. * to the other FLAC interfaces.
  86680. *
  86681. * See the detailed documentation for callbacks in the
  86682. * \link flac_callbacks callbacks \endlink module.
  86683. */
  86684. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86685. * \ingroup flac
  86686. *
  86687. * \brief
  86688. * This module defines the structures for describing I/O callbacks
  86689. * to the other FLAC interfaces.
  86690. *
  86691. * The purpose of the I/O callback functions is to create a common way
  86692. * for the metadata interfaces to handle I/O.
  86693. *
  86694. * Originally the metadata interfaces required filenames as the way of
  86695. * specifying FLAC files to operate on. This is problematic in some
  86696. * environments so there is an additional option to specify a set of
  86697. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86698. *
  86699. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86700. * opaque structure for a data source.
  86701. *
  86702. * The callback function prototypes are similar (but not identical) to the
  86703. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86704. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86705. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86706. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86707. * is required. \warning You generally CANNOT directly use fseek or ftell
  86708. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86709. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86710. * large files. You will have to find an equivalent function (e.g. ftello),
  86711. * or write a wrapper. The same is true for feof() since this is usually
  86712. * implemented as a macro, not as a function whose address can be taken.
  86713. *
  86714. * \{
  86715. */
  86716. #ifdef __cplusplus
  86717. extern "C" {
  86718. #endif
  86719. /** This is the opaque handle type used by the callbacks. Typically
  86720. * this is a \c FILE* or address of a file descriptor.
  86721. */
  86722. typedef void* FLAC__IOHandle;
  86723. /** Signature for the read callback.
  86724. * The signature and semantics match POSIX fread() implementations
  86725. * and can generally be used interchangeably.
  86726. *
  86727. * \param ptr The address of the read buffer.
  86728. * \param size The size of the records to be read.
  86729. * \param nmemb The number of records to be read.
  86730. * \param handle The handle to the data source.
  86731. * \retval size_t
  86732. * The number of records read.
  86733. */
  86734. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86735. /** Signature for the write callback.
  86736. * The signature and semantics match POSIX fwrite() implementations
  86737. * and can generally be used interchangeably.
  86738. *
  86739. * \param ptr The address of the write buffer.
  86740. * \param size The size of the records to be written.
  86741. * \param nmemb The number of records to be written.
  86742. * \param handle The handle to the data source.
  86743. * \retval size_t
  86744. * The number of records written.
  86745. */
  86746. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86747. /** Signature for the seek callback.
  86748. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86749. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86750. * and 32-bits wide.
  86751. *
  86752. * \param handle The handle to the data source.
  86753. * \param offset The new position, relative to \a whence
  86754. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86755. * \retval int
  86756. * \c 0 on success, \c -1 on error.
  86757. */
  86758. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86759. /** Signature for the tell callback.
  86760. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86761. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86762. * and 32-bits wide.
  86763. *
  86764. * \param handle The handle to the data source.
  86765. * \retval FLAC__int64
  86766. * The current position on success, \c -1 on error.
  86767. */
  86768. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86769. /** Signature for the EOF callback.
  86770. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86771. * on many systems, feof() is a macro, so in this case a wrapper function
  86772. * must be provided instead.
  86773. *
  86774. * \param handle The handle to the data source.
  86775. * \retval int
  86776. * \c 0 if not at end of file, nonzero if at end of file.
  86777. */
  86778. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86779. /** Signature for the close callback.
  86780. * The signature and semantics match POSIX fclose() implementations
  86781. * and can generally be used interchangeably.
  86782. *
  86783. * \param handle The handle to the data source.
  86784. * \retval int
  86785. * \c 0 on success, \c EOF on error.
  86786. */
  86787. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86788. /** A structure for holding a set of callbacks.
  86789. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86790. * describe which of the callbacks are required. The ones that are not
  86791. * required may be set to NULL.
  86792. *
  86793. * If the seek requirement for an interface is optional, you can signify that
  86794. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86795. */
  86796. typedef struct {
  86797. FLAC__IOCallback_Read read;
  86798. FLAC__IOCallback_Write write;
  86799. FLAC__IOCallback_Seek seek;
  86800. FLAC__IOCallback_Tell tell;
  86801. FLAC__IOCallback_Eof eof;
  86802. FLAC__IOCallback_Close close;
  86803. } FLAC__IOCallbacks;
  86804. /* \} */
  86805. #ifdef __cplusplus
  86806. }
  86807. #endif
  86808. #endif
  86809. /*** End of inlined file: callback.h ***/
  86810. /*** Start of inlined file: format.h ***/
  86811. #ifndef FLAC__FORMAT_H
  86812. #define FLAC__FORMAT_H
  86813. #ifdef __cplusplus
  86814. extern "C" {
  86815. #endif
  86816. /** \file include/FLAC/format.h
  86817. *
  86818. * \brief
  86819. * This module contains structure definitions for the representation
  86820. * of FLAC format components in memory. These are the basic
  86821. * structures used by the rest of the interfaces.
  86822. *
  86823. * See the detailed documentation in the
  86824. * \link flac_format format \endlink module.
  86825. */
  86826. /** \defgroup flac_format FLAC/format.h: format components
  86827. * \ingroup flac
  86828. *
  86829. * \brief
  86830. * This module contains structure definitions for the representation
  86831. * of FLAC format components in memory. These are the basic
  86832. * structures used by the rest of the interfaces.
  86833. *
  86834. * First, you should be familiar with the
  86835. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86836. * follow directly from the specification. As a user of libFLAC, the
  86837. * interesting parts really are the structures that describe the frame
  86838. * header and metadata blocks.
  86839. *
  86840. * The format structures here are very primitive, designed to store
  86841. * information in an efficient way. Reading information from the
  86842. * structures is easy but creating or modifying them directly is
  86843. * more complex. For the most part, as a user of a library, editing
  86844. * is not necessary; however, for metadata blocks it is, so there are
  86845. * convenience functions provided in the \link flac_metadata metadata
  86846. * module \endlink to simplify the manipulation of metadata blocks.
  86847. *
  86848. * \note
  86849. * It's not the best convention, but symbols ending in _LEN are in bits
  86850. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86851. * global variables because they are usually used when declaring byte
  86852. * arrays and some compilers require compile-time knowledge of array
  86853. * sizes when declared on the stack.
  86854. *
  86855. * \{
  86856. */
  86857. /*
  86858. Most of the values described in this file are defined by the FLAC
  86859. format specification. There is nothing to tune here.
  86860. */
  86861. /** The largest legal metadata type code. */
  86862. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86863. /** The minimum block size, in samples, permitted by the format. */
  86864. #define FLAC__MIN_BLOCK_SIZE (16u)
  86865. /** The maximum block size, in samples, permitted by the format. */
  86866. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86867. /** The maximum block size, in samples, permitted by the FLAC subset for
  86868. * sample rates up to 48kHz. */
  86869. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86870. /** The maximum number of channels permitted by the format. */
  86871. #define FLAC__MAX_CHANNELS (8u)
  86872. /** The minimum sample resolution permitted by the format. */
  86873. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86874. /** The maximum sample resolution permitted by the format. */
  86875. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86876. /** The maximum sample resolution permitted by libFLAC.
  86877. *
  86878. * \warning
  86879. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86880. * the reference encoder/decoder is currently limited to 24 bits because
  86881. * of prevalent 32-bit math, so make sure and use this value when
  86882. * appropriate.
  86883. */
  86884. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86885. /** The maximum sample rate permitted by the format. The value is
  86886. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86887. * as to why.
  86888. */
  86889. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86890. /** The maximum LPC order permitted by the format. */
  86891. #define FLAC__MAX_LPC_ORDER (32u)
  86892. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86893. * up to 48kHz. */
  86894. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86895. /** The minimum quantized linear predictor coefficient precision
  86896. * permitted by the format.
  86897. */
  86898. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86899. /** The maximum quantized linear predictor coefficient precision
  86900. * permitted by the format.
  86901. */
  86902. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86903. /** The maximum order of the fixed predictors permitted by the format. */
  86904. #define FLAC__MAX_FIXED_ORDER (4u)
  86905. /** The maximum Rice partition order permitted by the format. */
  86906. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86907. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86908. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86909. /** The version string of the release, stamped onto the libraries and binaries.
  86910. *
  86911. * \note
  86912. * This does not correspond to the shared library version number, which
  86913. * is used to determine binary compatibility.
  86914. */
  86915. extern FLAC_API const char *FLAC__VERSION_STRING;
  86916. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86917. * This is a NUL-terminated ASCII string; when inserted into the
  86918. * VORBIS_COMMENT the trailing null is stripped.
  86919. */
  86920. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86921. /** The byte string representation of the beginning of a FLAC stream. */
  86922. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86923. /** The 32-bit integer big-endian representation of the beginning of
  86924. * a FLAC stream.
  86925. */
  86926. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86927. /** The length of the FLAC signature in bits. */
  86928. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86929. /** The length of the FLAC signature in bytes. */
  86930. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86931. /*****************************************************************************
  86932. *
  86933. * Subframe structures
  86934. *
  86935. *****************************************************************************/
  86936. /*****************************************************************************/
  86937. /** An enumeration of the available entropy coding methods. */
  86938. typedef enum {
  86939. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86940. /**< Residual is coded by partitioning into contexts, each with it's own
  86941. * 4-bit Rice parameter. */
  86942. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86943. /**< Residual is coded by partitioning into contexts, each with it's own
  86944. * 5-bit Rice parameter. */
  86945. } FLAC__EntropyCodingMethodType;
  86946. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86947. *
  86948. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86949. * give the string equivalent. The contents should not be modified.
  86950. */
  86951. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86952. /** Contents of a Rice partitioned residual
  86953. */
  86954. typedef struct {
  86955. unsigned *parameters;
  86956. /**< The Rice parameters for each context. */
  86957. unsigned *raw_bits;
  86958. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86959. * partitions and zero for unescaped partitions.
  86960. */
  86961. unsigned capacity_by_order;
  86962. /**< The capacity of the \a parameters and \a raw_bits arrays
  86963. * specified as an order, i.e. the number of array elements
  86964. * allocated is 2 ^ \a capacity_by_order.
  86965. */
  86966. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86967. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86968. */
  86969. typedef struct {
  86970. unsigned order;
  86971. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86972. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86973. /**< The context's Rice parameters and/or raw bits. */
  86974. } FLAC__EntropyCodingMethod_PartitionedRice;
  86975. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86976. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86977. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86978. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86979. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86980. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86981. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86982. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86983. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86984. */
  86985. typedef struct {
  86986. FLAC__EntropyCodingMethodType type;
  86987. union {
  86988. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86989. } data;
  86990. } FLAC__EntropyCodingMethod;
  86991. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86992. /*****************************************************************************/
  86993. /** An enumeration of the available subframe types. */
  86994. typedef enum {
  86995. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86996. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86997. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86998. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86999. } FLAC__SubframeType;
  87000. /** Maps a FLAC__SubframeType to a C string.
  87001. *
  87002. * Using a FLAC__SubframeType as the index to this array will
  87003. * give the string equivalent. The contents should not be modified.
  87004. */
  87005. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  87006. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  87007. */
  87008. typedef struct {
  87009. FLAC__int32 value; /**< The constant signal value. */
  87010. } FLAC__Subframe_Constant;
  87011. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  87012. */
  87013. typedef struct {
  87014. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  87015. } FLAC__Subframe_Verbatim;
  87016. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  87017. */
  87018. typedef struct {
  87019. FLAC__EntropyCodingMethod entropy_coding_method;
  87020. /**< The residual coding method. */
  87021. unsigned order;
  87022. /**< The polynomial order. */
  87023. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  87024. /**< Warmup samples to prime the predictor, length == order. */
  87025. const FLAC__int32 *residual;
  87026. /**< The residual signal, length == (blocksize minus order) samples. */
  87027. } FLAC__Subframe_Fixed;
  87028. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87029. */
  87030. typedef struct {
  87031. FLAC__EntropyCodingMethod entropy_coding_method;
  87032. /**< The residual coding method. */
  87033. unsigned order;
  87034. /**< The FIR order. */
  87035. unsigned qlp_coeff_precision;
  87036. /**< Quantized FIR filter coefficient precision in bits. */
  87037. int quantization_level;
  87038. /**< The qlp coeff shift needed. */
  87039. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87040. /**< FIR filter coefficients. */
  87041. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87042. /**< Warmup samples to prime the predictor, length == order. */
  87043. const FLAC__int32 *residual;
  87044. /**< The residual signal, length == (blocksize minus order) samples. */
  87045. } FLAC__Subframe_LPC;
  87046. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87047. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87048. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87049. */
  87050. typedef struct {
  87051. FLAC__SubframeType type;
  87052. union {
  87053. FLAC__Subframe_Constant constant;
  87054. FLAC__Subframe_Fixed fixed;
  87055. FLAC__Subframe_LPC lpc;
  87056. FLAC__Subframe_Verbatim verbatim;
  87057. } data;
  87058. unsigned wasted_bits;
  87059. } FLAC__Subframe;
  87060. /** == 1 (bit)
  87061. *
  87062. * This used to be a zero-padding bit (hence the name
  87063. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87064. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87065. * to mean something else.
  87066. */
  87067. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87068. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87069. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87070. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87071. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87072. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87073. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87074. /*****************************************************************************/
  87075. /*****************************************************************************
  87076. *
  87077. * Frame structures
  87078. *
  87079. *****************************************************************************/
  87080. /** An enumeration of the available channel assignments. */
  87081. typedef enum {
  87082. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87083. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87084. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87085. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87086. } FLAC__ChannelAssignment;
  87087. /** Maps a FLAC__ChannelAssignment to a C string.
  87088. *
  87089. * Using a FLAC__ChannelAssignment as the index to this array will
  87090. * give the string equivalent. The contents should not be modified.
  87091. */
  87092. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87093. /** An enumeration of the possible frame numbering methods. */
  87094. typedef enum {
  87095. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87096. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87097. } FLAC__FrameNumberType;
  87098. /** Maps a FLAC__FrameNumberType to a C string.
  87099. *
  87100. * Using a FLAC__FrameNumberType as the index to this array will
  87101. * give the string equivalent. The contents should not be modified.
  87102. */
  87103. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87104. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87105. */
  87106. typedef struct {
  87107. unsigned blocksize;
  87108. /**< The number of samples per subframe. */
  87109. unsigned sample_rate;
  87110. /**< The sample rate in Hz. */
  87111. unsigned channels;
  87112. /**< The number of channels (== number of subframes). */
  87113. FLAC__ChannelAssignment channel_assignment;
  87114. /**< The channel assignment for the frame. */
  87115. unsigned bits_per_sample;
  87116. /**< The sample resolution. */
  87117. FLAC__FrameNumberType number_type;
  87118. /**< The numbering scheme used for the frame. As a convenience, the
  87119. * decoder will always convert a frame number to a sample number because
  87120. * the rules are complex. */
  87121. union {
  87122. FLAC__uint32 frame_number;
  87123. FLAC__uint64 sample_number;
  87124. } number;
  87125. /**< The frame number or sample number of first sample in frame;
  87126. * use the \a number_type value to determine which to use. */
  87127. FLAC__uint8 crc;
  87128. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87129. * of the raw frame header bytes, meaning everything before the CRC byte
  87130. * including the sync code.
  87131. */
  87132. } FLAC__FrameHeader;
  87133. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87134. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87135. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87136. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87137. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87138. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87139. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87140. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87141. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87142. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87143. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87144. */
  87145. typedef struct {
  87146. FLAC__uint16 crc;
  87147. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87148. * 0) of the bytes before the crc, back to and including the frame header
  87149. * sync code.
  87150. */
  87151. } FLAC__FrameFooter;
  87152. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87153. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87154. */
  87155. typedef struct {
  87156. FLAC__FrameHeader header;
  87157. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87158. FLAC__FrameFooter footer;
  87159. } FLAC__Frame;
  87160. /*****************************************************************************/
  87161. /*****************************************************************************
  87162. *
  87163. * Meta-data structures
  87164. *
  87165. *****************************************************************************/
  87166. /** An enumeration of the available metadata block types. */
  87167. typedef enum {
  87168. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87169. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87170. FLAC__METADATA_TYPE_PADDING = 1,
  87171. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87172. FLAC__METADATA_TYPE_APPLICATION = 2,
  87173. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87174. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87175. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87176. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87177. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87178. FLAC__METADATA_TYPE_CUESHEET = 5,
  87179. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87180. FLAC__METADATA_TYPE_PICTURE = 6,
  87181. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87182. FLAC__METADATA_TYPE_UNDEFINED = 7
  87183. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87184. } FLAC__MetadataType;
  87185. /** Maps a FLAC__MetadataType to a C string.
  87186. *
  87187. * Using a FLAC__MetadataType as the index to this array will
  87188. * give the string equivalent. The contents should not be modified.
  87189. */
  87190. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87191. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87192. */
  87193. typedef struct {
  87194. unsigned min_blocksize, max_blocksize;
  87195. unsigned min_framesize, max_framesize;
  87196. unsigned sample_rate;
  87197. unsigned channels;
  87198. unsigned bits_per_sample;
  87199. FLAC__uint64 total_samples;
  87200. FLAC__byte md5sum[16];
  87201. } FLAC__StreamMetadata_StreamInfo;
  87202. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87203. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87204. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87205. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87206. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87207. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87208. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87209. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87210. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87211. /** The total stream length of the STREAMINFO block in bytes. */
  87212. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87213. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87214. */
  87215. typedef struct {
  87216. int dummy;
  87217. /**< Conceptually this is an empty struct since we don't store the
  87218. * padding bytes. Empty structs are not allowed by some C compilers,
  87219. * hence the dummy.
  87220. */
  87221. } FLAC__StreamMetadata_Padding;
  87222. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87223. */
  87224. typedef struct {
  87225. FLAC__byte id[4];
  87226. FLAC__byte *data;
  87227. } FLAC__StreamMetadata_Application;
  87228. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87229. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87230. */
  87231. typedef struct {
  87232. FLAC__uint64 sample_number;
  87233. /**< The sample number of the target frame. */
  87234. FLAC__uint64 stream_offset;
  87235. /**< The offset, in bytes, of the target frame with respect to
  87236. * beginning of the first frame. */
  87237. unsigned frame_samples;
  87238. /**< The number of samples in the target frame. */
  87239. } FLAC__StreamMetadata_SeekPoint;
  87240. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87241. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87242. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87243. /** The total stream length of a seek point in bytes. */
  87244. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87245. /** The value used in the \a sample_number field of
  87246. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87247. * point (== 0xffffffffffffffff).
  87248. */
  87249. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87250. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87251. *
  87252. * \note From the format specification:
  87253. * - The seek points must be sorted by ascending sample number.
  87254. * - Each seek point's sample number must be the first sample of the
  87255. * target frame.
  87256. * - Each seek point's sample number must be unique within the table.
  87257. * - Existence of a SEEKTABLE block implies a correct setting of
  87258. * total_samples in the stream_info block.
  87259. * - Behavior is undefined when more than one SEEKTABLE block is
  87260. * present in a stream.
  87261. */
  87262. typedef struct {
  87263. unsigned num_points;
  87264. FLAC__StreamMetadata_SeekPoint *points;
  87265. } FLAC__StreamMetadata_SeekTable;
  87266. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87267. *
  87268. * For convenience, the APIs maintain a trailing NUL character at the end of
  87269. * \a entry which is not counted toward \a length, i.e.
  87270. * \code strlen(entry) == length \endcode
  87271. */
  87272. typedef struct {
  87273. FLAC__uint32 length;
  87274. FLAC__byte *entry;
  87275. } FLAC__StreamMetadata_VorbisComment_Entry;
  87276. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87277. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87278. */
  87279. typedef struct {
  87280. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87281. FLAC__uint32 num_comments;
  87282. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87283. } FLAC__StreamMetadata_VorbisComment;
  87284. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87285. /** FLAC CUESHEET track index structure. (See the
  87286. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87287. * the full description of each field.)
  87288. */
  87289. typedef struct {
  87290. FLAC__uint64 offset;
  87291. /**< Offset in samples, relative to the track offset, of the index
  87292. * point.
  87293. */
  87294. FLAC__byte number;
  87295. /**< The index point number. */
  87296. } FLAC__StreamMetadata_CueSheet_Index;
  87297. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87298. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87299. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87300. /** FLAC CUESHEET track structure. (See the
  87301. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87302. * the full description of each field.)
  87303. */
  87304. typedef struct {
  87305. FLAC__uint64 offset;
  87306. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87307. FLAC__byte number;
  87308. /**< The track number. */
  87309. char isrc[13];
  87310. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87311. unsigned type:1;
  87312. /**< The track type: 0 for audio, 1 for non-audio. */
  87313. unsigned pre_emphasis:1;
  87314. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87315. FLAC__byte num_indices;
  87316. /**< The number of track index points. */
  87317. FLAC__StreamMetadata_CueSheet_Index *indices;
  87318. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87319. } FLAC__StreamMetadata_CueSheet_Track;
  87320. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87321. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87322. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87323. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87324. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87325. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87326. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87327. /** FLAC CUESHEET structure. (See the
  87328. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87329. * for the full description of each field.)
  87330. */
  87331. typedef struct {
  87332. char media_catalog_number[129];
  87333. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87334. * general, the media catalog number may be 0 to 128 bytes long; any
  87335. * unused characters should be right-padded with NUL characters.
  87336. */
  87337. FLAC__uint64 lead_in;
  87338. /**< The number of lead-in samples. */
  87339. FLAC__bool is_cd;
  87340. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87341. unsigned num_tracks;
  87342. /**< The number of tracks. */
  87343. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87344. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87345. } FLAC__StreamMetadata_CueSheet;
  87346. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87347. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87348. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87349. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87350. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87351. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87352. typedef enum {
  87353. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87354. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87355. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87356. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87357. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87358. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87359. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87360. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87361. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87362. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87363. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87364. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87365. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87366. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87367. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87368. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87369. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87370. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87371. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87372. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87373. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87374. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87375. } FLAC__StreamMetadata_Picture_Type;
  87376. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87377. *
  87378. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87379. * will give the string equivalent. The contents should not be
  87380. * modified.
  87381. */
  87382. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87383. /** FLAC PICTURE structure. (See the
  87384. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87385. * for the full description of each field.)
  87386. */
  87387. typedef struct {
  87388. FLAC__StreamMetadata_Picture_Type type;
  87389. /**< The kind of picture stored. */
  87390. char *mime_type;
  87391. /**< Picture data's MIME type, in ASCII printable characters
  87392. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87393. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87394. * MIME type of '-->' is also allowed, in which case the picture
  87395. * data should be a complete URL. In file storage, the MIME type is
  87396. * stored as a 32-bit length followed by the ASCII string with no NUL
  87397. * terminator, but is converted to a plain C string in this structure
  87398. * for convenience.
  87399. */
  87400. FLAC__byte *description;
  87401. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87402. * the description is stored as a 32-bit length followed by the UTF-8
  87403. * string with no NUL terminator, but is converted to a plain C string
  87404. * in this structure for convenience.
  87405. */
  87406. FLAC__uint32 width;
  87407. /**< Picture's width in pixels. */
  87408. FLAC__uint32 height;
  87409. /**< Picture's height in pixels. */
  87410. FLAC__uint32 depth;
  87411. /**< Picture's color depth in bits-per-pixel. */
  87412. FLAC__uint32 colors;
  87413. /**< For indexed palettes (like GIF), picture's number of colors (the
  87414. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87415. */
  87416. FLAC__uint32 data_length;
  87417. /**< Length of binary picture data in bytes. */
  87418. FLAC__byte *data;
  87419. /**< Binary picture data. */
  87420. } FLAC__StreamMetadata_Picture;
  87421. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87422. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87423. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87424. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87425. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87426. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87427. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87428. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87429. /** Structure that is used when a metadata block of unknown type is loaded.
  87430. * The contents are opaque. The structure is used only internally to
  87431. * correctly handle unknown metadata.
  87432. */
  87433. typedef struct {
  87434. FLAC__byte *data;
  87435. } FLAC__StreamMetadata_Unknown;
  87436. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87437. */
  87438. typedef struct {
  87439. FLAC__MetadataType type;
  87440. /**< The type of the metadata block; used determine which member of the
  87441. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87442. * then \a data.unknown must be used. */
  87443. FLAC__bool is_last;
  87444. /**< \c true if this metadata block is the last, else \a false */
  87445. unsigned length;
  87446. /**< Length, in bytes, of the block data as it appears in the stream. */
  87447. union {
  87448. FLAC__StreamMetadata_StreamInfo stream_info;
  87449. FLAC__StreamMetadata_Padding padding;
  87450. FLAC__StreamMetadata_Application application;
  87451. FLAC__StreamMetadata_SeekTable seek_table;
  87452. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87453. FLAC__StreamMetadata_CueSheet cue_sheet;
  87454. FLAC__StreamMetadata_Picture picture;
  87455. FLAC__StreamMetadata_Unknown unknown;
  87456. } data;
  87457. /**< Polymorphic block data; use the \a type value to determine which
  87458. * to use. */
  87459. } FLAC__StreamMetadata;
  87460. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87461. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87462. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87463. /** The total stream length of a metadata block header in bytes. */
  87464. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87465. /*****************************************************************************/
  87466. /*****************************************************************************
  87467. *
  87468. * Utility functions
  87469. *
  87470. *****************************************************************************/
  87471. /** Tests that a sample rate is valid for FLAC.
  87472. *
  87473. * \param sample_rate The sample rate to test for compliance.
  87474. * \retval FLAC__bool
  87475. * \c true if the given sample rate conforms to the specification, else
  87476. * \c false.
  87477. */
  87478. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87479. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87480. * for valid sample rates are slightly more complex since the rate has to
  87481. * be expressible completely in the frame header.
  87482. *
  87483. * \param sample_rate The sample rate to test for compliance.
  87484. * \retval FLAC__bool
  87485. * \c true if the given sample rate conforms to the specification for the
  87486. * subset, else \c false.
  87487. */
  87488. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87489. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87490. * comment specification.
  87491. *
  87492. * Vorbis comment names must be composed only of characters from
  87493. * [0x20-0x3C,0x3E-0x7D].
  87494. *
  87495. * \param name A NUL-terminated string to be checked.
  87496. * \assert
  87497. * \code name != NULL \endcode
  87498. * \retval FLAC__bool
  87499. * \c false if entry name is illegal, else \c true.
  87500. */
  87501. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87502. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87503. * comment specification.
  87504. *
  87505. * Vorbis comment values must be valid UTF-8 sequences.
  87506. *
  87507. * \param value A string to be checked.
  87508. * \param length A the length of \a value in bytes. May be
  87509. * \c (unsigned)(-1) to indicate that \a value is a plain
  87510. * UTF-8 NUL-terminated string.
  87511. * \assert
  87512. * \code value != NULL \endcode
  87513. * \retval FLAC__bool
  87514. * \c false if entry name is illegal, else \c true.
  87515. */
  87516. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87517. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87518. * comment specification.
  87519. *
  87520. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87521. * 'value' must be legal according to
  87522. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87523. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87524. *
  87525. * \param entry An entry to be checked.
  87526. * \param length The length of \a entry in bytes.
  87527. * \assert
  87528. * \code value != NULL \endcode
  87529. * \retval FLAC__bool
  87530. * \c false if entry name is illegal, else \c true.
  87531. */
  87532. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87533. /** Check a seek table to see if it conforms to the FLAC specification.
  87534. * See the format specification for limits on the contents of the
  87535. * seek table.
  87536. *
  87537. * \param seek_table A pointer to a seek table to be checked.
  87538. * \assert
  87539. * \code seek_table != NULL \endcode
  87540. * \retval FLAC__bool
  87541. * \c false if seek table is illegal, else \c true.
  87542. */
  87543. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87544. /** Sort a seek table's seek points according to the format specification.
  87545. * This includes a "unique-ification" step to remove duplicates, i.e.
  87546. * seek points with identical \a sample_number values. Duplicate seek
  87547. * points are converted into placeholder points and sorted to the end of
  87548. * the table.
  87549. *
  87550. * \param seek_table A pointer to a seek table to be sorted.
  87551. * \assert
  87552. * \code seek_table != NULL \endcode
  87553. * \retval unsigned
  87554. * The number of duplicate seek points converted into placeholders.
  87555. */
  87556. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87557. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87558. * See the format specification for limits on the contents of the
  87559. * cue sheet.
  87560. *
  87561. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87562. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87563. * stringent requirements for a CD-DA (audio) disc.
  87564. * \param violation Address of a pointer to a string. If there is a
  87565. * violation, a pointer to a string explanation of the
  87566. * violation will be returned here. \a violation may be
  87567. * \c NULL if you don't need the returned string. Do not
  87568. * free the returned string; it will always point to static
  87569. * data.
  87570. * \assert
  87571. * \code cue_sheet != NULL \endcode
  87572. * \retval FLAC__bool
  87573. * \c false if cue sheet is illegal, else \c true.
  87574. */
  87575. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87576. /** Check picture data to see if it conforms to the FLAC specification.
  87577. * See the format specification for limits on the contents of the
  87578. * PICTURE block.
  87579. *
  87580. * \param picture A pointer to existing picture data to be checked.
  87581. * \param violation Address of a pointer to a string. If there is a
  87582. * violation, a pointer to a string explanation of the
  87583. * violation will be returned here. \a violation may be
  87584. * \c NULL if you don't need the returned string. Do not
  87585. * free the returned string; it will always point to static
  87586. * data.
  87587. * \assert
  87588. * \code picture != NULL \endcode
  87589. * \retval FLAC__bool
  87590. * \c false if picture data is illegal, else \c true.
  87591. */
  87592. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87593. /* \} */
  87594. #ifdef __cplusplus
  87595. }
  87596. #endif
  87597. #endif
  87598. /*** End of inlined file: format.h ***/
  87599. /*** Start of inlined file: metadata.h ***/
  87600. #ifndef FLAC__METADATA_H
  87601. #define FLAC__METADATA_H
  87602. #include <sys/types.h> /* for off_t */
  87603. /* --------------------------------------------------------------------
  87604. (For an example of how all these routines are used, see the source
  87605. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87606. metaflac in src/metaflac/)
  87607. ------------------------------------------------------------------*/
  87608. /** \file include/FLAC/metadata.h
  87609. *
  87610. * \brief
  87611. * This module provides functions for creating and manipulating FLAC
  87612. * metadata blocks in memory, and three progressively more powerful
  87613. * interfaces for traversing and editing metadata in FLAC files.
  87614. *
  87615. * See the detailed documentation for each interface in the
  87616. * \link flac_metadata metadata \endlink module.
  87617. */
  87618. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87619. * \ingroup flac
  87620. *
  87621. * \brief
  87622. * This module provides functions for creating and manipulating FLAC
  87623. * metadata blocks in memory, and three progressively more powerful
  87624. * interfaces for traversing and editing metadata in native FLAC files.
  87625. * Note that currently only the Chain interface (level 2) supports Ogg
  87626. * FLAC files, and it is read-only i.e. no writing back changed
  87627. * metadata to file.
  87628. *
  87629. * There are three metadata interfaces of increasing complexity:
  87630. *
  87631. * Level 0:
  87632. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87633. * PICTURE blocks.
  87634. *
  87635. * Level 1:
  87636. * Read-write access to all metadata blocks. This level is write-
  87637. * efficient in most cases (more on this below), and uses less memory
  87638. * than level 2.
  87639. *
  87640. * Level 2:
  87641. * Read-write access to all metadata blocks. This level is write-
  87642. * efficient in all cases, but uses more memory since all metadata for
  87643. * the whole file is read into memory and manipulated before writing
  87644. * out again.
  87645. *
  87646. * What do we mean by efficient? Since FLAC metadata appears at the
  87647. * beginning of the file, when writing metadata back to a FLAC file
  87648. * it is possible to grow or shrink the metadata such that the entire
  87649. * file must be rewritten. However, if the size remains the same during
  87650. * changes or PADDING blocks are utilized, only the metadata needs to be
  87651. * overwritten, which is much faster.
  87652. *
  87653. * Efficient means the whole file is rewritten at most one time, and only
  87654. * when necessary. Level 1 is not efficient only in the case that you
  87655. * cause more than one metadata block to grow or shrink beyond what can
  87656. * be accomodated by padding. In this case you should probably use level
  87657. * 2, which allows you to edit all the metadata for a file in memory and
  87658. * write it out all at once.
  87659. *
  87660. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87661. * front of the file.
  87662. *
  87663. * All levels access files via their filenames. In addition, level 2
  87664. * has additional alternative read and write functions that take an I/O
  87665. * handle and callbacks, for situations where access by filename is not
  87666. * possible.
  87667. *
  87668. * In addition to the three interfaces, this module defines functions for
  87669. * creating and manipulating various metadata objects in memory. As we see
  87670. * from the Format module, FLAC metadata blocks in memory are very primitive
  87671. * structures for storing information in an efficient way. Reading
  87672. * information from the structures is easy but creating or modifying them
  87673. * directly is more complex. The metadata object routines here facilitate
  87674. * this by taking care of the consistency and memory management drudgery.
  87675. *
  87676. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87677. * metadata however, you will not probably not need these.
  87678. *
  87679. * From a dependency standpoint, none of the encoders or decoders require
  87680. * the metadata module. This is so that embedded users can strip out the
  87681. * metadata module from libFLAC to reduce the size and complexity.
  87682. */
  87683. #ifdef __cplusplus
  87684. extern "C" {
  87685. #endif
  87686. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87687. * \ingroup flac_metadata
  87688. *
  87689. * \brief
  87690. * The level 0 interface consists of individual routines to read the
  87691. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87692. * only a filename.
  87693. *
  87694. * They try to skip any ID3v2 tag at the head of the file.
  87695. *
  87696. * \{
  87697. */
  87698. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87699. * will try to skip any ID3v2 tag at the head of the file.
  87700. *
  87701. * \param filename The path to the FLAC file to read.
  87702. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87703. * FLAC__StreamMetadata is a simple structure with no
  87704. * memory allocation involved, you pass the address of
  87705. * an existing structure. It need not be initialized.
  87706. * \assert
  87707. * \code filename != NULL \endcode
  87708. * \code streaminfo != NULL \endcode
  87709. * \retval FLAC__bool
  87710. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87711. * \c false if there was a memory allocation error, a file decoder error,
  87712. * or the file contained no STREAMINFO block. (A memory allocation error
  87713. * is possible because this function must set up a file decoder.)
  87714. */
  87715. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87716. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87717. * function will try to skip any ID3v2 tag at the head of the file.
  87718. *
  87719. * \param filename The path to the FLAC file to read.
  87720. * \param tags The address where the returned pointer will be
  87721. * stored. The \a tags object must be deleted by
  87722. * the caller using FLAC__metadata_object_delete().
  87723. * \assert
  87724. * \code filename != NULL \endcode
  87725. * \code tags != NULL \endcode
  87726. * \retval FLAC__bool
  87727. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87728. * and \a *tags will be set to the address of the metadata structure.
  87729. * Returns \c false if there was a memory allocation error, a file
  87730. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87731. * \a *tags will be set to \c NULL.
  87732. */
  87733. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87734. /** Read the CUESHEET metadata block of the given FLAC file. This
  87735. * function will try to skip any ID3v2 tag at the head of the file.
  87736. *
  87737. * \param filename The path to the FLAC file to read.
  87738. * \param cuesheet The address where the returned pointer will be
  87739. * stored. The \a cuesheet object must be deleted by
  87740. * the caller using FLAC__metadata_object_delete().
  87741. * \assert
  87742. * \code filename != NULL \endcode
  87743. * \code cuesheet != NULL \endcode
  87744. * \retval FLAC__bool
  87745. * \c true if a valid CUESHEET block was read from \a filename,
  87746. * and \a *cuesheet will be set to the address of the metadata
  87747. * structure. Returns \c false if there was a memory allocation
  87748. * error, a file decoder error, or the file contained no CUESHEET
  87749. * block, and \a *cuesheet will be set to \c NULL.
  87750. */
  87751. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87752. /** Read a PICTURE metadata block of the given FLAC file. This
  87753. * function will try to skip any ID3v2 tag at the head of the file.
  87754. * Since there can be more than one PICTURE block in a file, this
  87755. * function takes a number of parameters that act as constraints to
  87756. * the search. The PICTURE block with the largest area matching all
  87757. * the constraints will be returned, or \a *picture will be set to
  87758. * \c NULL if there was no such block.
  87759. *
  87760. * \param filename The path to the FLAC file to read.
  87761. * \param picture The address where the returned pointer will be
  87762. * stored. The \a picture object must be deleted by
  87763. * the caller using FLAC__metadata_object_delete().
  87764. * \param type The desired picture type. Use \c -1 to mean
  87765. * "any type".
  87766. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87767. * string will be matched exactly. Use \c NULL to
  87768. * mean "any MIME type".
  87769. * \param description The desired description. The string will be
  87770. * matched exactly. Use \c NULL to mean "any
  87771. * description".
  87772. * \param max_width The maximum width in pixels desired. Use
  87773. * \c (unsigned)(-1) to mean "any width".
  87774. * \param max_height The maximum height in pixels desired. Use
  87775. * \c (unsigned)(-1) to mean "any height".
  87776. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87777. * Use \c (unsigned)(-1) to mean "any depth".
  87778. * \param max_colors The maximum number of colors desired. Use
  87779. * \c (unsigned)(-1) to mean "any number of colors".
  87780. * \assert
  87781. * \code filename != NULL \endcode
  87782. * \code picture != NULL \endcode
  87783. * \retval FLAC__bool
  87784. * \c true if a valid PICTURE block was read from \a filename,
  87785. * and \a *picture will be set to the address of the metadata
  87786. * structure. Returns \c false if there was a memory allocation
  87787. * error, a file decoder error, or the file contained no PICTURE
  87788. * block, and \a *picture will be set to \c NULL.
  87789. */
  87790. 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);
  87791. /* \} */
  87792. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87793. * \ingroup flac_metadata
  87794. *
  87795. * \brief
  87796. * The level 1 interface provides read-write access to FLAC file metadata and
  87797. * operates directly on the FLAC file.
  87798. *
  87799. * The general usage of this interface is:
  87800. *
  87801. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87802. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87803. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87804. * see if the file is writable, or only read access is allowed.
  87805. * - Use FLAC__metadata_simple_iterator_next() and
  87806. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87807. * This is does not read the actual blocks themselves.
  87808. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87809. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87810. * forward from the front of the file.
  87811. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87812. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87813. * the current iterator position. The returned object is yours to modify
  87814. * and free.
  87815. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87816. * back. You must have write permission to the original file. Make sure to
  87817. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87818. * below.
  87819. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87820. * Use the object creation functions from
  87821. * \link flac_metadata_object here \endlink to generate new objects.
  87822. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87823. * currently referred to by the iterator, or replace it with padding.
  87824. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87825. * finished.
  87826. *
  87827. * \note
  87828. * The FLAC file remains open the whole time between
  87829. * FLAC__metadata_simple_iterator_init() and
  87830. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87831. * the file during this time.
  87832. *
  87833. * \note
  87834. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87835. * FLAC__StreamMetadata objects. These are managed automatically.
  87836. *
  87837. * \note
  87838. * If any of the modification functions
  87839. * (FLAC__metadata_simple_iterator_set_block(),
  87840. * FLAC__metadata_simple_iterator_delete_block(),
  87841. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87842. * you should delete the iterator as it may no longer be valid.
  87843. *
  87844. * \{
  87845. */
  87846. struct FLAC__Metadata_SimpleIterator;
  87847. /** The opaque structure definition for the level 1 iterator type.
  87848. * See the
  87849. * \link flac_metadata_level1 metadata level 1 module \endlink
  87850. * for a detailed description.
  87851. */
  87852. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87853. /** Status type for FLAC__Metadata_SimpleIterator.
  87854. *
  87855. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87856. */
  87857. typedef enum {
  87858. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87859. /**< The iterator is in the normal OK state */
  87860. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87861. /**< The data passed into a function violated the function's usage criteria */
  87862. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87863. /**< The iterator could not open the target file */
  87864. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87865. /**< The iterator could not find the FLAC signature at the start of the file */
  87866. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87867. /**< The iterator tried to write to a file that was not writable */
  87868. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87869. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87870. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87871. /**< The iterator encountered an error while reading the FLAC file */
  87872. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87873. /**< The iterator encountered an error while seeking in the FLAC file */
  87874. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87875. /**< The iterator encountered an error while writing the FLAC file */
  87876. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87877. /**< The iterator encountered an error renaming the FLAC file */
  87878. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87879. /**< The iterator encountered an error removing the temporary file */
  87880. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87881. /**< Memory allocation failed */
  87882. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87883. /**< The caller violated an assertion or an unexpected error occurred */
  87884. } FLAC__Metadata_SimpleIteratorStatus;
  87885. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87886. *
  87887. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87888. * will give the string equivalent. The contents should not be modified.
  87889. */
  87890. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87891. /** Create a new iterator instance.
  87892. *
  87893. * \retval FLAC__Metadata_SimpleIterator*
  87894. * \c NULL if there was an error allocating memory, else the new instance.
  87895. */
  87896. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87897. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87898. *
  87899. * \param iterator A pointer to an existing iterator.
  87900. * \assert
  87901. * \code iterator != NULL \endcode
  87902. */
  87903. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87904. /** Get the current status of the iterator. Call this after a function
  87905. * returns \c false to get the reason for the error. Also resets the status
  87906. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87907. *
  87908. * \param iterator A pointer to an existing iterator.
  87909. * \assert
  87910. * \code iterator != NULL \endcode
  87911. * \retval FLAC__Metadata_SimpleIteratorStatus
  87912. * The current status of the iterator.
  87913. */
  87914. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87915. /** Initialize the iterator to point to the first metadata block in the
  87916. * given FLAC file.
  87917. *
  87918. * \param iterator A pointer to an existing iterator.
  87919. * \param filename The path to the FLAC file.
  87920. * \param read_only If \c true, the FLAC file will be opened
  87921. * in read-only mode; if \c false, the FLAC
  87922. * file will be opened for edit even if no
  87923. * edits are performed.
  87924. * \param preserve_file_stats If \c true, the owner and modification
  87925. * time will be preserved even if the FLAC
  87926. * file is written to.
  87927. * \assert
  87928. * \code iterator != NULL \endcode
  87929. * \code filename != NULL \endcode
  87930. * \retval FLAC__bool
  87931. * \c false if a memory allocation error occurs, the file can't be
  87932. * opened, or another error occurs, else \c true.
  87933. */
  87934. 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);
  87935. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87936. * FLAC__metadata_simple_iterator_set_block() and
  87937. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87938. *
  87939. * \param iterator A pointer to an existing iterator.
  87940. * \assert
  87941. * \code iterator != NULL \endcode
  87942. * \retval FLAC__bool
  87943. * See above.
  87944. */
  87945. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87946. /** Moves the iterator forward one metadata block, returning \c false if
  87947. * already at the end.
  87948. *
  87949. * \param iterator A pointer to an existing initialized iterator.
  87950. * \assert
  87951. * \code iterator != NULL \endcode
  87952. * \a iterator has been successfully initialized with
  87953. * FLAC__metadata_simple_iterator_init()
  87954. * \retval FLAC__bool
  87955. * \c false if already at the last metadata block of the chain, else
  87956. * \c true.
  87957. */
  87958. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87959. /** Moves the iterator backward one metadata block, returning \c false if
  87960. * already at the beginning.
  87961. *
  87962. * \param iterator A pointer to an existing initialized iterator.
  87963. * \assert
  87964. * \code iterator != NULL \endcode
  87965. * \a iterator has been successfully initialized with
  87966. * FLAC__metadata_simple_iterator_init()
  87967. * \retval FLAC__bool
  87968. * \c false if already at the first metadata block of the chain, else
  87969. * \c true.
  87970. */
  87971. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87972. /** Returns a flag telling if the current metadata block is the last.
  87973. *
  87974. * \param iterator A pointer to an existing initialized iterator.
  87975. * \assert
  87976. * \code iterator != NULL \endcode
  87977. * \a iterator has been successfully initialized with
  87978. * FLAC__metadata_simple_iterator_init()
  87979. * \retval FLAC__bool
  87980. * \c true if the current metadata block is the last in the file,
  87981. * else \c false.
  87982. */
  87983. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87984. /** Get the offset of the metadata block at the current position. This
  87985. * avoids reading the actual block data which can save time for large
  87986. * blocks.
  87987. *
  87988. * \param iterator A pointer to an existing initialized iterator.
  87989. * \assert
  87990. * \code iterator != NULL \endcode
  87991. * \a iterator has been successfully initialized with
  87992. * FLAC__metadata_simple_iterator_init()
  87993. * \retval off_t
  87994. * The offset of the metadata block at the current iterator position.
  87995. * This is the byte offset relative to the beginning of the file of
  87996. * the current metadata block's header.
  87997. */
  87998. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87999. /** Get the type of the metadata block at the current position. This
  88000. * avoids reading the actual block data which can save time for large
  88001. * blocks.
  88002. *
  88003. * \param iterator A pointer to an existing initialized iterator.
  88004. * \assert
  88005. * \code iterator != NULL \endcode
  88006. * \a iterator has been successfully initialized with
  88007. * FLAC__metadata_simple_iterator_init()
  88008. * \retval FLAC__MetadataType
  88009. * The type of the metadata block at the current iterator position.
  88010. */
  88011. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  88012. /** Get the length of the metadata block at the current position. This
  88013. * avoids reading the actual block data which can save time for large
  88014. * blocks.
  88015. *
  88016. * \param iterator A pointer to an existing initialized iterator.
  88017. * \assert
  88018. * \code iterator != NULL \endcode
  88019. * \a iterator has been successfully initialized with
  88020. * FLAC__metadata_simple_iterator_init()
  88021. * \retval unsigned
  88022. * The length of the metadata block at the current iterator position.
  88023. * The is same length as that in the
  88024. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88025. * i.e. the length of the metadata body that follows the header.
  88026. */
  88027. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88028. /** Get the application ID of the \c APPLICATION block at the current
  88029. * position. This avoids reading the actual block data which can save
  88030. * time for large blocks.
  88031. *
  88032. * \param iterator A pointer to an existing initialized iterator.
  88033. * \param id A pointer to a buffer of at least \c 4 bytes where
  88034. * the ID will be stored.
  88035. * \assert
  88036. * \code iterator != NULL \endcode
  88037. * \code id != NULL \endcode
  88038. * \a iterator has been successfully initialized with
  88039. * FLAC__metadata_simple_iterator_init()
  88040. * \retval FLAC__bool
  88041. * \c true if the ID was successfully read, else \c false, in which
  88042. * case you should check FLAC__metadata_simple_iterator_status() to
  88043. * find out why. If the status is
  88044. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88045. * current metadata block is not an \c APPLICATION block. Otherwise
  88046. * if the status is
  88047. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88048. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88049. * occurred and the iterator can no longer be used.
  88050. */
  88051. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88052. /** Get the metadata block at the current position. You can modify the
  88053. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88054. * write it back to the FLAC file.
  88055. *
  88056. * You must call FLAC__metadata_object_delete() on the returned object
  88057. * when you are finished with it.
  88058. *
  88059. * \param iterator A pointer to an existing initialized iterator.
  88060. * \assert
  88061. * \code iterator != NULL \endcode
  88062. * \a iterator has been successfully initialized with
  88063. * FLAC__metadata_simple_iterator_init()
  88064. * \retval FLAC__StreamMetadata*
  88065. * The current metadata block, or \c NULL if there was a memory
  88066. * allocation error.
  88067. */
  88068. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88069. /** Write a block back to the FLAC file. This function tries to be
  88070. * as efficient as possible; how the block is actually written is
  88071. * shown by the following:
  88072. *
  88073. * Existing block is a STREAMINFO block and the new block is a
  88074. * STREAMINFO block: the new block is written in place. Make sure
  88075. * you know what you're doing when changing the values of a
  88076. * STREAMINFO block.
  88077. *
  88078. * Existing block is a STREAMINFO block and the new block is a
  88079. * not a STREAMINFO block: this is an error since the first block
  88080. * must be a STREAMINFO block. Returns \c false without altering the
  88081. * file.
  88082. *
  88083. * Existing block is not a STREAMINFO block and the new block is a
  88084. * STREAMINFO block: this is an error since there may be only one
  88085. * STREAMINFO block. Returns \c false without altering the file.
  88086. *
  88087. * Existing block and new block are the same length: the existing
  88088. * block will be replaced by the new block, written in place.
  88089. *
  88090. * Existing block is longer than new block: if use_padding is \c true,
  88091. * the existing block will be overwritten in place with the new
  88092. * block followed by a PADDING block, if possible, to make the total
  88093. * size the same as the existing block. Remember that a padding
  88094. * block requires at least four bytes so if the difference in size
  88095. * between the new block and existing block is less than that, the
  88096. * entire file will have to be rewritten, using the new block's
  88097. * exact size. If use_padding is \c false, the entire file will be
  88098. * rewritten, replacing the existing block by the new block.
  88099. *
  88100. * Existing block is shorter than new block: if use_padding is \c true,
  88101. * the function will try and expand the new block into the following
  88102. * PADDING block, if it exists and doing so won't shrink the PADDING
  88103. * block to less than 4 bytes. If there is no following PADDING
  88104. * block, or it will shrink to less than 4 bytes, or use_padding is
  88105. * \c false, the entire file is rewritten, replacing the existing block
  88106. * with the new block. Note that in this case any following PADDING
  88107. * block is preserved as is.
  88108. *
  88109. * After writing the block, the iterator will remain in the same
  88110. * place, i.e. pointing to the new block.
  88111. *
  88112. * \param iterator A pointer to an existing initialized iterator.
  88113. * \param block The block to set.
  88114. * \param use_padding See above.
  88115. * \assert
  88116. * \code iterator != NULL \endcode
  88117. * \a iterator has been successfully initialized with
  88118. * FLAC__metadata_simple_iterator_init()
  88119. * \code block != NULL \endcode
  88120. * \retval FLAC__bool
  88121. * \c true if successful, else \c false.
  88122. */
  88123. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88124. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88125. * except that instead of writing over an existing block, it appends
  88126. * a block after the existing block. \a use_padding is again used to
  88127. * tell the function to try an expand into following padding in an
  88128. * attempt to avoid rewriting the entire file.
  88129. *
  88130. * This function will fail and return \c false if given a STREAMINFO
  88131. * block.
  88132. *
  88133. * After writing the block, the iterator will be pointing to the
  88134. * new block.
  88135. *
  88136. * \param iterator A pointer to an existing initialized iterator.
  88137. * \param block The block to set.
  88138. * \param use_padding See above.
  88139. * \assert
  88140. * \code iterator != NULL \endcode
  88141. * \a iterator has been successfully initialized with
  88142. * FLAC__metadata_simple_iterator_init()
  88143. * \code block != NULL \endcode
  88144. * \retval FLAC__bool
  88145. * \c true if successful, else \c false.
  88146. */
  88147. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88148. /** Deletes the block at the current position. This will cause the
  88149. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88150. * in which case the block will be replaced by an equal-sized PADDING
  88151. * block. The iterator will be left pointing to the block before the
  88152. * one just deleted.
  88153. *
  88154. * You may not delete the STREAMINFO block.
  88155. *
  88156. * \param iterator A pointer to an existing initialized iterator.
  88157. * \param use_padding See above.
  88158. * \assert
  88159. * \code iterator != NULL \endcode
  88160. * \a iterator has been successfully initialized with
  88161. * FLAC__metadata_simple_iterator_init()
  88162. * \retval FLAC__bool
  88163. * \c true if successful, else \c false.
  88164. */
  88165. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88166. /* \} */
  88167. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88168. * \ingroup flac_metadata
  88169. *
  88170. * \brief
  88171. * The level 2 interface provides read-write access to FLAC file metadata;
  88172. * all metadata is read into memory, operated on in memory, and then written
  88173. * to file, which is more efficient than level 1 when editing multiple blocks.
  88174. *
  88175. * Currently Ogg FLAC is supported for read only, via
  88176. * FLAC__metadata_chain_read_ogg() but a subsequent
  88177. * FLAC__metadata_chain_write() will fail.
  88178. *
  88179. * The general usage of this interface is:
  88180. *
  88181. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88182. * linked list of FLAC metadata blocks.
  88183. * - Read all metadata into the the chain from a FLAC file using
  88184. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88185. * check the status.
  88186. * - Optionally, consolidate the padding using
  88187. * FLAC__metadata_chain_merge_padding() or
  88188. * FLAC__metadata_chain_sort_padding().
  88189. * - Create a new iterator using FLAC__metadata_iterator_new()
  88190. * - Initialize the iterator to point to the first element in the chain
  88191. * using FLAC__metadata_iterator_init()
  88192. * - Traverse the chain using FLAC__metadata_iterator_next and
  88193. * FLAC__metadata_iterator_prev().
  88194. * - Get a block for reading or modification using
  88195. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88196. * inside the chain is returned, so the block is yours to modify.
  88197. * Changes will be reflected in the FLAC file when you write the
  88198. * chain. You can also add and delete blocks (see functions below).
  88199. * - When done, write out the chain using FLAC__metadata_chain_write().
  88200. * Make sure to read the whole comment to the function below.
  88201. * - Delete the chain using FLAC__metadata_chain_delete().
  88202. *
  88203. * \note
  88204. * Even though the FLAC file is not open while the chain is being
  88205. * manipulated, you must not alter the file externally during
  88206. * this time. The chain assumes the FLAC file will not change
  88207. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88208. * and FLAC__metadata_chain_write().
  88209. *
  88210. * \note
  88211. * Do not modify the is_last, length, or type fields of returned
  88212. * FLAC__StreamMetadata objects. These are managed automatically.
  88213. *
  88214. * \note
  88215. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88216. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88217. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88218. * become owned by the chain and they will be deleted when the chain is
  88219. * deleted.
  88220. *
  88221. * \{
  88222. */
  88223. struct FLAC__Metadata_Chain;
  88224. /** The opaque structure definition for the level 2 chain type.
  88225. */
  88226. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88227. struct FLAC__Metadata_Iterator;
  88228. /** The opaque structure definition for the level 2 iterator type.
  88229. */
  88230. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88231. typedef enum {
  88232. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88233. /**< The chain is in the normal OK state */
  88234. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88235. /**< The data passed into a function violated the function's usage criteria */
  88236. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88237. /**< The chain could not open the target file */
  88238. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88239. /**< The chain could not find the FLAC signature at the start of the file */
  88240. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88241. /**< The chain tried to write to a file that was not writable */
  88242. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88243. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88244. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88245. /**< The chain encountered an error while reading the FLAC file */
  88246. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88247. /**< The chain encountered an error while seeking in the FLAC file */
  88248. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88249. /**< The chain encountered an error while writing the FLAC file */
  88250. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88251. /**< The chain encountered an error renaming the FLAC file */
  88252. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88253. /**< The chain encountered an error removing the temporary file */
  88254. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88255. /**< Memory allocation failed */
  88256. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88257. /**< The caller violated an assertion or an unexpected error occurred */
  88258. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88259. /**< One or more of the required callbacks was NULL */
  88260. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88261. /**< FLAC__metadata_chain_write() was called on a chain read by
  88262. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88263. * or
  88264. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88265. * was called on a chain read by
  88266. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88267. * Matching read/write methods must always be used. */
  88268. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88269. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88270. * chain write requires a tempfile; use
  88271. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88272. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88273. * called when the chain write does not require a tempfile; use
  88274. * FLAC__metadata_chain_write_with_callbacks() instead.
  88275. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88276. * before writing via callbacks. */
  88277. } FLAC__Metadata_ChainStatus;
  88278. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88279. *
  88280. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88281. * will give the string equivalent. The contents should not be modified.
  88282. */
  88283. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88284. /*********** FLAC__Metadata_Chain ***********/
  88285. /** Create a new chain instance.
  88286. *
  88287. * \retval FLAC__Metadata_Chain*
  88288. * \c NULL if there was an error allocating memory, else the new instance.
  88289. */
  88290. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88291. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88292. *
  88293. * \param chain A pointer to an existing chain.
  88294. * \assert
  88295. * \code chain != NULL \endcode
  88296. */
  88297. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88298. /** Get the current status of the chain. Call this after a function
  88299. * returns \c false to get the reason for the error. Also resets the
  88300. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88301. *
  88302. * \param chain A pointer to an existing chain.
  88303. * \assert
  88304. * \code chain != NULL \endcode
  88305. * \retval FLAC__Metadata_ChainStatus
  88306. * The current status of the chain.
  88307. */
  88308. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88309. /** Read all metadata from a FLAC file into the chain.
  88310. *
  88311. * \param chain A pointer to an existing chain.
  88312. * \param filename The path to the FLAC file to read.
  88313. * \assert
  88314. * \code chain != NULL \endcode
  88315. * \code filename != NULL \endcode
  88316. * \retval FLAC__bool
  88317. * \c true if a valid list of metadata blocks was read from
  88318. * \a filename, else \c false. On failure, check the status with
  88319. * FLAC__metadata_chain_status().
  88320. */
  88321. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88322. /** Read all metadata from an Ogg FLAC file into the chain.
  88323. *
  88324. * \note Ogg FLAC metadata data writing is not supported yet and
  88325. * FLAC__metadata_chain_write() will fail.
  88326. *
  88327. * \param chain A pointer to an existing chain.
  88328. * \param filename The path to the Ogg FLAC file to read.
  88329. * \assert
  88330. * \code chain != NULL \endcode
  88331. * \code filename != NULL \endcode
  88332. * \retval FLAC__bool
  88333. * \c true if a valid list of metadata blocks was read from
  88334. * \a filename, else \c false. On failure, check the status with
  88335. * FLAC__metadata_chain_status().
  88336. */
  88337. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88338. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88339. *
  88340. * The \a handle need only be open for reading, but must be seekable.
  88341. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88342. * for Windows).
  88343. *
  88344. * \param chain A pointer to an existing chain.
  88345. * \param handle The I/O handle of the FLAC stream to read. The
  88346. * handle will NOT be closed after the metadata is read;
  88347. * that is the duty of the caller.
  88348. * \param callbacks
  88349. * A set of callbacks to use for I/O. The mandatory
  88350. * callbacks are \a read, \a seek, and \a tell.
  88351. * \assert
  88352. * \code chain != NULL \endcode
  88353. * \retval FLAC__bool
  88354. * \c true if a valid list of metadata blocks was read from
  88355. * \a handle, else \c false. On failure, check the status with
  88356. * FLAC__metadata_chain_status().
  88357. */
  88358. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88359. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88360. *
  88361. * The \a handle need only be open for reading, but must be seekable.
  88362. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88363. * for Windows).
  88364. *
  88365. * \note Ogg FLAC metadata data writing is not supported yet and
  88366. * FLAC__metadata_chain_write() will fail.
  88367. *
  88368. * \param chain A pointer to an existing chain.
  88369. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88370. * handle will NOT be closed after the metadata is read;
  88371. * that is the duty of the caller.
  88372. * \param callbacks
  88373. * A set of callbacks to use for I/O. The mandatory
  88374. * callbacks are \a read, \a seek, and \a tell.
  88375. * \assert
  88376. * \code chain != NULL \endcode
  88377. * \retval FLAC__bool
  88378. * \c true if a valid list of metadata blocks was read from
  88379. * \a handle, else \c false. On failure, check the status with
  88380. * FLAC__metadata_chain_status().
  88381. */
  88382. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88383. /** Checks if writing the given chain would require the use of a
  88384. * temporary file, or if it could be written in place.
  88385. *
  88386. * Under certain conditions, padding can be utilized so that writing
  88387. * edited metadata back to the FLAC file does not require rewriting the
  88388. * entire file. If rewriting is required, then a temporary workfile is
  88389. * required. When writing metadata using callbacks, you must check
  88390. * this function to know whether to call
  88391. * FLAC__metadata_chain_write_with_callbacks() or
  88392. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88393. * writing with FLAC__metadata_chain_write(), the temporary file is
  88394. * handled internally.
  88395. *
  88396. * \param chain A pointer to an existing chain.
  88397. * \param use_padding
  88398. * Whether or not padding will be allowed to be used
  88399. * during the write. The value of \a use_padding given
  88400. * here must match the value later passed to
  88401. * FLAC__metadata_chain_write_with_callbacks() or
  88402. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88403. * \assert
  88404. * \code chain != NULL \endcode
  88405. * \retval FLAC__bool
  88406. * \c true if writing the current chain would require a tempfile, or
  88407. * \c false if metadata can be written in place.
  88408. */
  88409. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88410. /** Write all metadata out to the FLAC file. This function tries to be as
  88411. * efficient as possible; how the metadata is actually written is shown by
  88412. * the following:
  88413. *
  88414. * If the current chain is the same size as the existing metadata, the new
  88415. * data is written in place.
  88416. *
  88417. * If the current chain is longer than the existing metadata, and
  88418. * \a use_padding is \c true, and the last block is a PADDING block of
  88419. * sufficient length, the function will truncate the final padding block
  88420. * so that the overall size of the metadata is the same as the existing
  88421. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88422. * the above conditions are met, the entire FLAC file must be rewritten.
  88423. * If you want to use padding this way it is a good idea to call
  88424. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88425. * amount of padding to work with, unless you need to preserve ordering
  88426. * of the PADDING blocks for some reason.
  88427. *
  88428. * If the current chain is shorter than the existing metadata, and
  88429. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88430. * is extended to make the overall size the same as the existing data. If
  88431. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88432. * PADDING block is added to the end of the new data to make it the same
  88433. * size as the existing data (if possible, see the note to
  88434. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88435. * and the new data is written in place. If none of the above apply or
  88436. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88437. *
  88438. * If \a preserve_file_stats is \c true, the owner and modification time will
  88439. * be preserved even if the FLAC file is written.
  88440. *
  88441. * For this write function to be used, the chain must have been read with
  88442. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88443. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88444. *
  88445. * \param chain A pointer to an existing chain.
  88446. * \param use_padding See above.
  88447. * \param preserve_file_stats See above.
  88448. * \assert
  88449. * \code chain != NULL \endcode
  88450. * \retval FLAC__bool
  88451. * \c true if the write succeeded, else \c false. On failure,
  88452. * check the status with FLAC__metadata_chain_status().
  88453. */
  88454. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88455. /** Write all metadata out to a FLAC stream via callbacks.
  88456. *
  88457. * (See FLAC__metadata_chain_write() for the details on how padding is
  88458. * used to write metadata in place if possible.)
  88459. *
  88460. * The \a handle must be open for updating and be seekable. The
  88461. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88462. * for Windows).
  88463. *
  88464. * For this write function to be used, the chain must have been read with
  88465. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88466. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88467. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88468. * \c false.
  88469. *
  88470. * \param chain A pointer to an existing chain.
  88471. * \param use_padding See FLAC__metadata_chain_write()
  88472. * \param handle The I/O handle of the FLAC stream to write. The
  88473. * handle will NOT be closed after the metadata is
  88474. * written; that is the duty of the caller.
  88475. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88476. * callbacks are \a write and \a seek.
  88477. * \assert
  88478. * \code chain != NULL \endcode
  88479. * \retval FLAC__bool
  88480. * \c true if the write succeeded, else \c false. On failure,
  88481. * check the status with FLAC__metadata_chain_status().
  88482. */
  88483. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88484. /** Write all metadata out to a FLAC stream via callbacks.
  88485. *
  88486. * (See FLAC__metadata_chain_write() for the details on how padding is
  88487. * used to write metadata in place if possible.)
  88488. *
  88489. * This version of the write-with-callbacks function must be used when
  88490. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88491. * this function, you must supply an I/O handle corresponding to the
  88492. * FLAC file to edit, and a temporary handle to which the new FLAC
  88493. * file will be written. It is the caller's job to move this temporary
  88494. * FLAC file on top of the original FLAC file to complete the metadata
  88495. * edit.
  88496. *
  88497. * The \a handle must be open for reading and be seekable. The
  88498. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88499. * for Windows).
  88500. *
  88501. * The \a temp_handle must be open for writing. The
  88502. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88503. * for Windows). It should be an empty stream, or at least positioned
  88504. * at the start-of-file (in which case it is the caller's duty to
  88505. * truncate it on return).
  88506. *
  88507. * For this write function to be used, the chain must have been read with
  88508. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88509. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88510. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88511. * \c true.
  88512. *
  88513. * \param chain A pointer to an existing chain.
  88514. * \param use_padding See FLAC__metadata_chain_write()
  88515. * \param handle The I/O handle of the original FLAC stream to read.
  88516. * The handle will NOT be closed after the metadata is
  88517. * written; that is the duty of the caller.
  88518. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88519. * The mandatory callbacks are \a read, \a seek, and
  88520. * \a eof.
  88521. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88522. * handle will NOT be closed after the metadata is
  88523. * written; that is the duty of the caller.
  88524. * \param temp_callbacks
  88525. * A set of callbacks to use for I/O on temp_handle.
  88526. * The only mandatory callback is \a write.
  88527. * \assert
  88528. * \code chain != NULL \endcode
  88529. * \retval FLAC__bool
  88530. * \c true if the write succeeded, else \c false. On failure,
  88531. * check the status with FLAC__metadata_chain_status().
  88532. */
  88533. 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);
  88534. /** Merge adjacent PADDING blocks into a single block.
  88535. *
  88536. * \note This function does not write to the FLAC file, it only
  88537. * modifies the chain.
  88538. *
  88539. * \warning Any iterator on the current chain will become invalid after this
  88540. * call. You should delete the iterator and get a new one.
  88541. *
  88542. * \param chain A pointer to an existing chain.
  88543. * \assert
  88544. * \code chain != NULL \endcode
  88545. */
  88546. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88547. /** This function will move all PADDING blocks to the end on the metadata,
  88548. * then merge them into a single block.
  88549. *
  88550. * \note This function does not write to the FLAC file, it only
  88551. * modifies the chain.
  88552. *
  88553. * \warning Any iterator on the current chain will become invalid after this
  88554. * call. You should delete the iterator and get a new one.
  88555. *
  88556. * \param chain A pointer to an existing chain.
  88557. * \assert
  88558. * \code chain != NULL \endcode
  88559. */
  88560. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88561. /*********** FLAC__Metadata_Iterator ***********/
  88562. /** Create a new iterator instance.
  88563. *
  88564. * \retval FLAC__Metadata_Iterator*
  88565. * \c NULL if there was an error allocating memory, else the new instance.
  88566. */
  88567. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88568. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88569. *
  88570. * \param iterator A pointer to an existing iterator.
  88571. * \assert
  88572. * \code iterator != NULL \endcode
  88573. */
  88574. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88575. /** Initialize the iterator to point to the first metadata block in the
  88576. * given chain.
  88577. *
  88578. * \param iterator A pointer to an existing iterator.
  88579. * \param chain A pointer to an existing and initialized (read) chain.
  88580. * \assert
  88581. * \code iterator != NULL \endcode
  88582. * \code chain != NULL \endcode
  88583. */
  88584. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88585. /** Moves the iterator forward one metadata block, returning \c false if
  88586. * already at the end.
  88587. *
  88588. * \param iterator A pointer to an existing initialized iterator.
  88589. * \assert
  88590. * \code iterator != NULL \endcode
  88591. * \a iterator has been successfully initialized with
  88592. * FLAC__metadata_iterator_init()
  88593. * \retval FLAC__bool
  88594. * \c false if already at the last metadata block of the chain, else
  88595. * \c true.
  88596. */
  88597. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88598. /** Moves the iterator backward one metadata block, returning \c false if
  88599. * already at the beginning.
  88600. *
  88601. * \param iterator A pointer to an existing initialized iterator.
  88602. * \assert
  88603. * \code iterator != NULL \endcode
  88604. * \a iterator has been successfully initialized with
  88605. * FLAC__metadata_iterator_init()
  88606. * \retval FLAC__bool
  88607. * \c false if already at the first metadata block of the chain, else
  88608. * \c true.
  88609. */
  88610. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88611. /** Get the type of the metadata block at the current position.
  88612. *
  88613. * \param iterator A pointer to an existing initialized iterator.
  88614. * \assert
  88615. * \code iterator != NULL \endcode
  88616. * \a iterator has been successfully initialized with
  88617. * FLAC__metadata_iterator_init()
  88618. * \retval FLAC__MetadataType
  88619. * The type of the metadata block at the current iterator position.
  88620. */
  88621. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88622. /** Get the metadata block at the current position. You can modify
  88623. * the block in place but must write the chain before the changes
  88624. * are reflected to the FLAC file. You do not need to call
  88625. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88626. * the pointer returned by FLAC__metadata_iterator_get_block()
  88627. * points directly into the chain.
  88628. *
  88629. * \warning
  88630. * Do not call FLAC__metadata_object_delete() on the returned object;
  88631. * to delete a block use FLAC__metadata_iterator_delete_block().
  88632. *
  88633. * \param iterator A pointer to an existing initialized iterator.
  88634. * \assert
  88635. * \code iterator != NULL \endcode
  88636. * \a iterator has been successfully initialized with
  88637. * FLAC__metadata_iterator_init()
  88638. * \retval FLAC__StreamMetadata*
  88639. * The current metadata block.
  88640. */
  88641. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88642. /** Set the metadata block at the current position, replacing the existing
  88643. * block. The new block passed in becomes owned by the chain and it will be
  88644. * deleted when the chain is deleted.
  88645. *
  88646. * \param iterator A pointer to an existing initialized iterator.
  88647. * \param block A pointer to a metadata block.
  88648. * \assert
  88649. * \code iterator != NULL \endcode
  88650. * \a iterator has been successfully initialized with
  88651. * FLAC__metadata_iterator_init()
  88652. * \code block != NULL \endcode
  88653. * \retval FLAC__bool
  88654. * \c false if the conditions in the above description are not met, or
  88655. * a memory allocation error occurs, otherwise \c true.
  88656. */
  88657. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88658. /** Removes the current block from the chain. If \a replace_with_padding is
  88659. * \c true, the block will instead be replaced with a padding block of equal
  88660. * size. You can not delete the STREAMINFO block. The iterator will be
  88661. * left pointing to the block before the one just "deleted", even if
  88662. * \a replace_with_padding is \c true.
  88663. *
  88664. * \param iterator A pointer to an existing initialized iterator.
  88665. * \param replace_with_padding See above.
  88666. * \assert
  88667. * \code iterator != NULL \endcode
  88668. * \a iterator has been successfully initialized with
  88669. * FLAC__metadata_iterator_init()
  88670. * \retval FLAC__bool
  88671. * \c false if the conditions in the above description are not met,
  88672. * otherwise \c true.
  88673. */
  88674. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88675. /** Insert a new block before the current block. You cannot insert a block
  88676. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88677. * as there can be only one, the one that already exists at the head when you
  88678. * read in a chain. The chain takes ownership of the new block and it will be
  88679. * deleted when the chain is deleted. The iterator will be left pointing to
  88680. * the new block.
  88681. *
  88682. * \param iterator A pointer to an existing initialized iterator.
  88683. * \param block A pointer to a metadata block to insert.
  88684. * \assert
  88685. * \code iterator != NULL \endcode
  88686. * \a iterator has been successfully initialized with
  88687. * FLAC__metadata_iterator_init()
  88688. * \retval FLAC__bool
  88689. * \c false if the conditions in the above description are not met, or
  88690. * a memory allocation error occurs, otherwise \c true.
  88691. */
  88692. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88693. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88694. * block as there can be only one, the one that already exists at the head when
  88695. * you read in a chain. The chain takes ownership of the new block and it will
  88696. * be deleted when the chain is deleted. The iterator will be left pointing to
  88697. * the new block.
  88698. *
  88699. * \param iterator A pointer to an existing initialized iterator.
  88700. * \param block A pointer to a metadata block to insert.
  88701. * \assert
  88702. * \code iterator != NULL \endcode
  88703. * \a iterator has been successfully initialized with
  88704. * FLAC__metadata_iterator_init()
  88705. * \retval FLAC__bool
  88706. * \c false if the conditions in the above description are not met, or
  88707. * a memory allocation error occurs, otherwise \c true.
  88708. */
  88709. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88710. /* \} */
  88711. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88712. * \ingroup flac_metadata
  88713. *
  88714. * \brief
  88715. * This module contains methods for manipulating FLAC metadata objects.
  88716. *
  88717. * Since many are variable length we have to be careful about the memory
  88718. * management. We decree that all pointers to data in the object are
  88719. * owned by the object and memory-managed by the object.
  88720. *
  88721. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88722. * functions to create all instances. When using the
  88723. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88724. * \a copy to \c true to have the function make it's own copy of the data, or
  88725. * to \c false to give the object ownership of your data. In the latter case
  88726. * your pointer must be freeable by free() and will be free()d when the object
  88727. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88728. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88729. * the length argument is 0 and the \a copy argument is \c false.
  88730. *
  88731. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88732. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88733. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88734. * case of a memory allocation error.
  88735. *
  88736. * We don't have the convenience of C++ here, so note that the library relies
  88737. * on you to keep the types straight. In other words, if you pass, for
  88738. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88739. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88740. * failure.
  88741. *
  88742. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88743. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88744. * toward the length or stored in the stream, but it can make working with plain
  88745. * comments (those that don't contain embedded-NULs in the value) easier.
  88746. * Entries passed into these functions have trailing NULs added if missing, and
  88747. * returned entries are guaranteed to have a trailing NUL.
  88748. *
  88749. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88750. * comment entry/name/value will first validate that it complies with the Vorbis
  88751. * comment specification and return false if it does not.
  88752. *
  88753. * There is no need to recalculate the length field on metadata blocks you
  88754. * have modified. They will be calculated automatically before they are
  88755. * written back to a file.
  88756. *
  88757. * \{
  88758. */
  88759. /** Create a new metadata object instance of the given type.
  88760. *
  88761. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88762. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88763. * the vendor string set (but zero comments).
  88764. *
  88765. * Do not pass in a value greater than or equal to
  88766. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88767. * doing.
  88768. *
  88769. * \param type Type of object to create
  88770. * \retval FLAC__StreamMetadata*
  88771. * \c NULL if there was an error allocating memory or the type code is
  88772. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88773. */
  88774. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88775. /** Create a copy of an existing metadata object.
  88776. *
  88777. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88778. * object is also copied. The caller takes ownership of the new block and
  88779. * is responsible for freeing it with FLAC__metadata_object_delete().
  88780. *
  88781. * \param object Pointer to object to copy.
  88782. * \assert
  88783. * \code object != NULL \endcode
  88784. * \retval FLAC__StreamMetadata*
  88785. * \c NULL if there was an error allocating memory, else the new instance.
  88786. */
  88787. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88788. /** Free a metadata object. Deletes the object pointed to by \a object.
  88789. *
  88790. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88791. * object is also deleted.
  88792. *
  88793. * \param object A pointer to an existing object.
  88794. * \assert
  88795. * \code object != NULL \endcode
  88796. */
  88797. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88798. /** Compares two metadata objects.
  88799. *
  88800. * The compare is "deep", i.e. dynamically allocated data within the
  88801. * object is also compared.
  88802. *
  88803. * \param block1 A pointer to an existing object.
  88804. * \param block2 A pointer to an existing object.
  88805. * \assert
  88806. * \code block1 != NULL \endcode
  88807. * \code block2 != NULL \endcode
  88808. * \retval FLAC__bool
  88809. * \c true if objects are identical, else \c false.
  88810. */
  88811. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88812. /** Sets the application data of an APPLICATION block.
  88813. *
  88814. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88815. * takes ownership of the pointer. The existing data will be freed if this
  88816. * function is successful, otherwise the original data will remain if \a copy
  88817. * is \c true and malloc() fails.
  88818. *
  88819. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88820. *
  88821. * \param object A pointer to an existing APPLICATION object.
  88822. * \param data A pointer to the data to set.
  88823. * \param length The length of \a data in bytes.
  88824. * \param copy See above.
  88825. * \assert
  88826. * \code object != NULL \endcode
  88827. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88828. * \code (data != NULL && length > 0) ||
  88829. * (data == NULL && length == 0 && copy == false) \endcode
  88830. * \retval FLAC__bool
  88831. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88832. */
  88833. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88834. /** Resize the seekpoint array.
  88835. *
  88836. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88837. * points will be added to the end.
  88838. *
  88839. * \param object A pointer to an existing SEEKTABLE object.
  88840. * \param new_num_points The desired length of the array; may be \c 0.
  88841. * \assert
  88842. * \code object != NULL \endcode
  88843. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88844. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88845. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88846. * \retval FLAC__bool
  88847. * \c false if memory allocation error, else \c true.
  88848. */
  88849. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88850. /** Set a seekpoint in a seektable.
  88851. *
  88852. * \param object A pointer to an existing SEEKTABLE object.
  88853. * \param point_num Index into seekpoint array to set.
  88854. * \param point The point to set.
  88855. * \assert
  88856. * \code object != NULL \endcode
  88857. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88858. * \code object->data.seek_table.num_points > point_num \endcode
  88859. */
  88860. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88861. /** Insert a seekpoint into a seektable.
  88862. *
  88863. * \param object A pointer to an existing SEEKTABLE object.
  88864. * \param point_num Index into seekpoint array to set.
  88865. * \param point The point to set.
  88866. * \assert
  88867. * \code object != NULL \endcode
  88868. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88869. * \code object->data.seek_table.num_points >= point_num \endcode
  88870. * \retval FLAC__bool
  88871. * \c false if memory allocation error, else \c true.
  88872. */
  88873. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88874. /** Delete a seekpoint from a seektable.
  88875. *
  88876. * \param object A pointer to an existing SEEKTABLE object.
  88877. * \param point_num Index into seekpoint array to set.
  88878. * \assert
  88879. * \code object != NULL \endcode
  88880. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88881. * \code object->data.seek_table.num_points > point_num \endcode
  88882. * \retval FLAC__bool
  88883. * \c false if memory allocation error, else \c true.
  88884. */
  88885. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88886. /** Check a seektable to see if it conforms to the FLAC specification.
  88887. * See the format specification for limits on the contents of the
  88888. * seektable.
  88889. *
  88890. * \param object A pointer to an existing SEEKTABLE object.
  88891. * \assert
  88892. * \code object != NULL \endcode
  88893. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88894. * \retval FLAC__bool
  88895. * \c false if seek table is illegal, else \c true.
  88896. */
  88897. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88898. /** Append a number of placeholder points to the end of a seek table.
  88899. *
  88900. * \note
  88901. * As with the other ..._seektable_template_... functions, you should
  88902. * call FLAC__metadata_object_seektable_template_sort() when finished
  88903. * to make the seek table legal.
  88904. *
  88905. * \param object A pointer to an existing SEEKTABLE object.
  88906. * \param num The number of placeholder points to append.
  88907. * \assert
  88908. * \code object != NULL \endcode
  88909. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88910. * \retval FLAC__bool
  88911. * \c false if memory allocation fails, else \c true.
  88912. */
  88913. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88914. /** Append a specific seek point template to the end of a seek table.
  88915. *
  88916. * \note
  88917. * As with the other ..._seektable_template_... functions, you should
  88918. * call FLAC__metadata_object_seektable_template_sort() when finished
  88919. * to make the seek table legal.
  88920. *
  88921. * \param object A pointer to an existing SEEKTABLE object.
  88922. * \param sample_number The sample number of the seek point template.
  88923. * \assert
  88924. * \code object != NULL \endcode
  88925. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88926. * \retval FLAC__bool
  88927. * \c false if memory allocation fails, else \c true.
  88928. */
  88929. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88930. /** Append specific seek point templates to the end of a seek table.
  88931. *
  88932. * \note
  88933. * As with the other ..._seektable_template_... functions, you should
  88934. * call FLAC__metadata_object_seektable_template_sort() when finished
  88935. * to make the seek table legal.
  88936. *
  88937. * \param object A pointer to an existing SEEKTABLE object.
  88938. * \param sample_numbers An array of sample numbers for the seek points.
  88939. * \param num The number of seek point templates to append.
  88940. * \assert
  88941. * \code object != NULL \endcode
  88942. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88943. * \retval FLAC__bool
  88944. * \c false if memory allocation fails, else \c true.
  88945. */
  88946. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88947. /** Append a set of evenly-spaced seek point templates to the end of a
  88948. * seek table.
  88949. *
  88950. * \note
  88951. * As with the other ..._seektable_template_... functions, you should
  88952. * call FLAC__metadata_object_seektable_template_sort() when finished
  88953. * to make the seek table legal.
  88954. *
  88955. * \param object A pointer to an existing SEEKTABLE object.
  88956. * \param num The number of placeholder points to append.
  88957. * \param total_samples The total number of samples to be encoded;
  88958. * the seekpoints will be spaced approximately
  88959. * \a total_samples / \a num samples apart.
  88960. * \assert
  88961. * \code object != NULL \endcode
  88962. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88963. * \code total_samples > 0 \endcode
  88964. * \retval FLAC__bool
  88965. * \c false if memory allocation fails, else \c true.
  88966. */
  88967. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88968. /** Append a set of evenly-spaced seek point templates to the end of a
  88969. * seek table.
  88970. *
  88971. * \note
  88972. * As with the other ..._seektable_template_... functions, you should
  88973. * call FLAC__metadata_object_seektable_template_sort() when finished
  88974. * to make the seek table legal.
  88975. *
  88976. * \param object A pointer to an existing SEEKTABLE object.
  88977. * \param samples The number of samples apart to space the placeholder
  88978. * points. The first point will be at sample \c 0, the
  88979. * second at sample \a samples, then 2*\a samples, and
  88980. * so on. As long as \a samples and \a total_samples
  88981. * are greater than \c 0, there will always be at least
  88982. * one seekpoint at sample \c 0.
  88983. * \param total_samples The total number of samples to be encoded;
  88984. * the seekpoints will be spaced
  88985. * \a samples samples apart.
  88986. * \assert
  88987. * \code object != NULL \endcode
  88988. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88989. * \code samples > 0 \endcode
  88990. * \code total_samples > 0 \endcode
  88991. * \retval FLAC__bool
  88992. * \c false if memory allocation fails, else \c true.
  88993. */
  88994. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88995. /** Sort a seek table's seek points according to the format specification,
  88996. * removing duplicates.
  88997. *
  88998. * \param object A pointer to a seek table to be sorted.
  88999. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  89000. * If \c true, duplicates are deleted and the seek table is
  89001. * shrunk appropriately; the number of placeholder points
  89002. * present in the seek table will be the same after the call
  89003. * as before.
  89004. * \assert
  89005. * \code object != NULL \endcode
  89006. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89007. * \retval FLAC__bool
  89008. * \c false if realloc() fails, else \c true.
  89009. */
  89010. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  89011. /** Sets the vendor string in a VORBIS_COMMENT block.
  89012. *
  89013. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89014. * one already.
  89015. *
  89016. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89017. * takes ownership of the \c entry.entry pointer.
  89018. *
  89019. * \note If this function returns \c false, the caller still owns the
  89020. * pointer.
  89021. *
  89022. * \param object A pointer to an existing VORBIS_COMMENT object.
  89023. * \param entry The entry to set the vendor string to.
  89024. * \param copy See above.
  89025. * \assert
  89026. * \code object != NULL \endcode
  89027. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89028. * \code (entry.entry != NULL && entry.length > 0) ||
  89029. * (entry.entry == NULL && entry.length == 0) \endcode
  89030. * \retval FLAC__bool
  89031. * \c false if memory allocation fails or \a entry does not comply with the
  89032. * Vorbis comment specification, else \c true.
  89033. */
  89034. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89035. /** Resize the comment array.
  89036. *
  89037. * If the size shrinks, elements will truncated; if it grows, new empty
  89038. * fields will be added to the end.
  89039. *
  89040. * \param object A pointer to an existing VORBIS_COMMENT object.
  89041. * \param new_num_comments The desired length of the array; may be \c 0.
  89042. * \assert
  89043. * \code object != NULL \endcode
  89044. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89045. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89046. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89047. * \retval FLAC__bool
  89048. * \c false if memory allocation fails, else \c true.
  89049. */
  89050. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89051. /** Sets a comment in a VORBIS_COMMENT block.
  89052. *
  89053. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89054. * one already.
  89055. *
  89056. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89057. * takes ownership of the \c entry.entry pointer.
  89058. *
  89059. * \note If this function returns \c false, the caller still owns the
  89060. * pointer.
  89061. *
  89062. * \param object A pointer to an existing VORBIS_COMMENT object.
  89063. * \param comment_num Index into comment array to set.
  89064. * \param entry The entry to set the comment to.
  89065. * \param copy See above.
  89066. * \assert
  89067. * \code object != NULL \endcode
  89068. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89069. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89070. * \code (entry.entry != NULL && entry.length > 0) ||
  89071. * (entry.entry == NULL && entry.length == 0) \endcode
  89072. * \retval FLAC__bool
  89073. * \c false if memory allocation fails or \a entry does not comply with the
  89074. * Vorbis comment specification, else \c true.
  89075. */
  89076. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89077. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89078. *
  89079. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89080. * one already.
  89081. *
  89082. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89083. * takes ownership of the \c entry.entry pointer.
  89084. *
  89085. * \note If this function returns \c false, the caller still owns the
  89086. * pointer.
  89087. *
  89088. * \param object A pointer to an existing VORBIS_COMMENT object.
  89089. * \param comment_num The index at which to insert the comment. The comments
  89090. * at and after \a comment_num move right one position.
  89091. * To append a comment to the end, set \a comment_num to
  89092. * \c object->data.vorbis_comment.num_comments .
  89093. * \param entry The comment to insert.
  89094. * \param copy See above.
  89095. * \assert
  89096. * \code object != NULL \endcode
  89097. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89098. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89099. * \code (entry.entry != NULL && entry.length > 0) ||
  89100. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89101. * \retval FLAC__bool
  89102. * \c false if memory allocation fails or \a entry does not comply with the
  89103. * Vorbis comment specification, else \c true.
  89104. */
  89105. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89106. /** Appends a comment to a VORBIS_COMMENT block.
  89107. *
  89108. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89109. * one already.
  89110. *
  89111. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89112. * takes ownership of the \c entry.entry pointer.
  89113. *
  89114. * \note If this function returns \c false, the caller still owns the
  89115. * pointer.
  89116. *
  89117. * \param object A pointer to an existing VORBIS_COMMENT object.
  89118. * \param entry The comment to insert.
  89119. * \param copy See above.
  89120. * \assert
  89121. * \code object != NULL \endcode
  89122. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89123. * \code (entry.entry != NULL && entry.length > 0) ||
  89124. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89125. * \retval FLAC__bool
  89126. * \c false if memory allocation fails or \a entry does not comply with the
  89127. * Vorbis comment specification, else \c true.
  89128. */
  89129. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89130. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89131. *
  89132. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89133. * one already.
  89134. *
  89135. * Depending on the the value of \a all, either all or just the first comment
  89136. * whose field name(s) match the given entry's name will be replaced by the
  89137. * given entry. If no comments match, \a entry will simply be appended.
  89138. *
  89139. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89140. * takes ownership of the \c entry.entry pointer.
  89141. *
  89142. * \note If this function returns \c false, the caller still owns the
  89143. * pointer.
  89144. *
  89145. * \param object A pointer to an existing VORBIS_COMMENT object.
  89146. * \param entry The comment to insert.
  89147. * \param all If \c true, all comments whose field name matches
  89148. * \a entry's field name will be removed, and \a entry will
  89149. * be inserted at the position of the first matching
  89150. * comment. If \c false, only the first comment whose
  89151. * field name matches \a entry's field name will be
  89152. * replaced with \a entry.
  89153. * \param copy See above.
  89154. * \assert
  89155. * \code object != NULL \endcode
  89156. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89157. * \code (entry.entry != NULL && entry.length > 0) ||
  89158. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89159. * \retval FLAC__bool
  89160. * \c false if memory allocation fails or \a entry does not comply with the
  89161. * Vorbis comment specification, else \c true.
  89162. */
  89163. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89164. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89165. *
  89166. * \param object A pointer to an existing VORBIS_COMMENT object.
  89167. * \param comment_num The index of the comment to delete.
  89168. * \assert
  89169. * \code object != NULL \endcode
  89170. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89171. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89172. * \retval FLAC__bool
  89173. * \c false if realloc() fails, else \c true.
  89174. */
  89175. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89176. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89177. *
  89178. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89179. * memory and shall be owned by the caller. For convenience the entry will
  89180. * have a terminating NUL.
  89181. *
  89182. * \param entry A pointer to a Vorbis comment entry. The entry's
  89183. * \c entry pointer should not point to allocated
  89184. * memory as it will be overwritten.
  89185. * \param field_name The field name in ASCII, \c NUL terminated.
  89186. * \param field_value The field value in UTF-8, \c NUL terminated.
  89187. * \assert
  89188. * \code entry != NULL \endcode
  89189. * \code field_name != NULL \endcode
  89190. * \code field_value != NULL \endcode
  89191. * \retval FLAC__bool
  89192. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89193. * not comply with the Vorbis comment specification, else \c true.
  89194. */
  89195. 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);
  89196. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89197. *
  89198. * The returned pointers to name and value will be allocated by malloc()
  89199. * and shall be owned by the caller.
  89200. *
  89201. * \param entry An existing Vorbis comment entry.
  89202. * \param field_name The address of where the returned pointer to the
  89203. * field name will be stored.
  89204. * \param field_value The address of where the returned pointer to the
  89205. * field value will be stored.
  89206. * \assert
  89207. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89208. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89209. * \code field_name != NULL \endcode
  89210. * \code field_value != NULL \endcode
  89211. * \retval FLAC__bool
  89212. * \c false if memory allocation fails or \a entry does not comply with the
  89213. * Vorbis comment specification, else \c true.
  89214. */
  89215. 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);
  89216. /** Check if the given Vorbis comment entry's field name matches the given
  89217. * field name.
  89218. *
  89219. * \param entry An existing Vorbis comment entry.
  89220. * \param field_name The field name to check.
  89221. * \param field_name_length The length of \a field_name, not including the
  89222. * terminating \c NUL.
  89223. * \assert
  89224. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89225. * \retval FLAC__bool
  89226. * \c true if the field names match, else \c false
  89227. */
  89228. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89229. /** Find a Vorbis comment with the given field name.
  89230. *
  89231. * The search begins at entry number \a offset; use an offset of 0 to
  89232. * search from the beginning of the comment array.
  89233. *
  89234. * \param object A pointer to an existing VORBIS_COMMENT object.
  89235. * \param offset The offset into the comment array from where to start
  89236. * the search.
  89237. * \param field_name The field name of the comment to find.
  89238. * \assert
  89239. * \code object != NULL \endcode
  89240. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89241. * \code field_name != NULL \endcode
  89242. * \retval int
  89243. * The offset in the comment array of the first comment whose field
  89244. * name matches \a field_name, or \c -1 if no match was found.
  89245. */
  89246. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89247. /** Remove first Vorbis comment matching the given field name.
  89248. *
  89249. * \param object A pointer to an existing VORBIS_COMMENT object.
  89250. * \param field_name The field name of comment to delete.
  89251. * \assert
  89252. * \code object != NULL \endcode
  89253. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89254. * \retval int
  89255. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89256. * \c 1 for one matching entry deleted.
  89257. */
  89258. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89259. /** Remove all Vorbis comments matching the given field name.
  89260. *
  89261. * \param object A pointer to an existing VORBIS_COMMENT object.
  89262. * \param field_name The field name of comments to delete.
  89263. * \assert
  89264. * \code object != NULL \endcode
  89265. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89266. * \retval int
  89267. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89268. * else the number of matching entries deleted.
  89269. */
  89270. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89271. /** Create a new CUESHEET track instance.
  89272. *
  89273. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89274. *
  89275. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89276. * \c NULL if there was an error allocating memory, else the new instance.
  89277. */
  89278. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89279. /** Create a copy of an existing CUESHEET track object.
  89280. *
  89281. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89282. * object is also copied. The caller takes ownership of the new object and
  89283. * is responsible for freeing it with
  89284. * FLAC__metadata_object_cuesheet_track_delete().
  89285. *
  89286. * \param object Pointer to object to copy.
  89287. * \assert
  89288. * \code object != NULL \endcode
  89289. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89290. * \c NULL if there was an error allocating memory, else the new instance.
  89291. */
  89292. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89293. /** Delete a CUESHEET track object
  89294. *
  89295. * \param object A pointer to an existing CUESHEET track object.
  89296. * \assert
  89297. * \code object != NULL \endcode
  89298. */
  89299. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89300. /** Resize a track's index point array.
  89301. *
  89302. * If the size shrinks, elements will truncated; if it grows, new blank
  89303. * indices will be added to the end.
  89304. *
  89305. * \param object A pointer to an existing CUESHEET object.
  89306. * \param track_num The index of the track to modify. NOTE: this is not
  89307. * necessarily the same as the track's \a number field.
  89308. * \param new_num_indices The desired length of the array; may be \c 0.
  89309. * \assert
  89310. * \code object != NULL \endcode
  89311. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89312. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89313. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89314. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89315. * \retval FLAC__bool
  89316. * \c false if memory allocation error, else \c true.
  89317. */
  89318. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89319. /** Insert an index point in a CUESHEET track at the given index.
  89320. *
  89321. * \param object A pointer to an existing CUESHEET object.
  89322. * \param track_num The index of the track to modify. NOTE: this is not
  89323. * necessarily the same as the track's \a number field.
  89324. * \param index_num The index into the track's index array at which to
  89325. * insert the index point. NOTE: this is not necessarily
  89326. * the same as the index point's \a number field. The
  89327. * indices at and after \a index_num move right one
  89328. * position. To append an index point to the end, set
  89329. * \a index_num to
  89330. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89331. * \param index The index point to insert.
  89332. * \assert
  89333. * \code object != NULL \endcode
  89334. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89335. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89336. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89337. * \retval FLAC__bool
  89338. * \c false if realloc() fails, else \c true.
  89339. */
  89340. 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);
  89341. /** Insert a blank index point in a CUESHEET track at the given index.
  89342. *
  89343. * A blank index point is one in which all field values are zero.
  89344. *
  89345. * \param object A pointer to an existing CUESHEET object.
  89346. * \param track_num The index of the track to modify. NOTE: this is not
  89347. * necessarily the same as the track's \a number field.
  89348. * \param index_num The index into the track's index array at which to
  89349. * insert the index point. NOTE: this is not necessarily
  89350. * the same as the index point's \a number field. The
  89351. * indices at and after \a index_num move right one
  89352. * position. To append an index point to the end, set
  89353. * \a index_num to
  89354. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89355. * \assert
  89356. * \code object != NULL \endcode
  89357. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89358. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89359. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89360. * \retval FLAC__bool
  89361. * \c false if realloc() fails, else \c true.
  89362. */
  89363. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89364. /** Delete an index point in a CUESHEET track at the given index.
  89365. *
  89366. * \param object A pointer to an existing CUESHEET object.
  89367. * \param track_num The index into the track array of the track to
  89368. * modify. NOTE: this is not necessarily the same
  89369. * as the track's \a number field.
  89370. * \param index_num The index into the track's index array of the index
  89371. * to delete. NOTE: this is not necessarily the same
  89372. * as the index's \a number field.
  89373. * \assert
  89374. * \code object != NULL \endcode
  89375. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89376. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89377. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89378. * \retval FLAC__bool
  89379. * \c false if realloc() fails, else \c true.
  89380. */
  89381. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89382. /** Resize the track array.
  89383. *
  89384. * If the size shrinks, elements will truncated; if it grows, new blank
  89385. * tracks will be added to the end.
  89386. *
  89387. * \param object A pointer to an existing CUESHEET object.
  89388. * \param new_num_tracks The desired length of the array; may be \c 0.
  89389. * \assert
  89390. * \code object != NULL \endcode
  89391. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89392. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89393. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89394. * \retval FLAC__bool
  89395. * \c false if memory allocation error, else \c true.
  89396. */
  89397. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89398. /** Sets a track in a CUESHEET block.
  89399. *
  89400. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89401. * takes ownership of the \a track pointer.
  89402. *
  89403. * \param object A pointer to an existing CUESHEET object.
  89404. * \param track_num Index into track array to set. NOTE: this is not
  89405. * necessarily the same as the track's \a number field.
  89406. * \param track The track to set the track to. You may safely pass in
  89407. * a const pointer if \a copy is \c true.
  89408. * \param copy See above.
  89409. * \assert
  89410. * \code object != NULL \endcode
  89411. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89412. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89413. * \code (track->indices != NULL && track->num_indices > 0) ||
  89414. * (track->indices == NULL && track->num_indices == 0)
  89415. * \retval FLAC__bool
  89416. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89417. */
  89418. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89419. /** Insert a track in a CUESHEET block at the given index.
  89420. *
  89421. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89422. * takes ownership of the \a track pointer.
  89423. *
  89424. * \param object A pointer to an existing CUESHEET object.
  89425. * \param track_num The index at which to insert the track. NOTE: this
  89426. * is not necessarily the same as the track's \a number
  89427. * field. The tracks at and after \a track_num move right
  89428. * one position. To append a track to the end, set
  89429. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89430. * \param track The track to insert. You may safely pass in a const
  89431. * pointer if \a copy is \c true.
  89432. * \param copy See above.
  89433. * \assert
  89434. * \code object != NULL \endcode
  89435. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89436. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89437. * \retval FLAC__bool
  89438. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89439. */
  89440. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89441. /** Insert a blank track in a CUESHEET block at the given index.
  89442. *
  89443. * A blank track is one in which all field values are zero.
  89444. *
  89445. * \param object A pointer to an existing CUESHEET object.
  89446. * \param track_num The index at which to insert the track. NOTE: this
  89447. * is not necessarily the same as the track's \a number
  89448. * field. The tracks at and after \a track_num move right
  89449. * one position. To append a track to the end, set
  89450. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89451. * \assert
  89452. * \code object != NULL \endcode
  89453. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89454. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89455. * \retval FLAC__bool
  89456. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89457. */
  89458. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89459. /** Delete a track in a CUESHEET block at the given index.
  89460. *
  89461. * \param object A pointer to an existing CUESHEET object.
  89462. * \param track_num The index into the track array of the track to
  89463. * delete. NOTE: this is not necessarily the same
  89464. * as the track's \a number field.
  89465. * \assert
  89466. * \code object != NULL \endcode
  89467. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89468. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89469. * \retval FLAC__bool
  89470. * \c false if realloc() fails, else \c true.
  89471. */
  89472. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89473. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89474. * See the format specification for limits on the contents of the
  89475. * cue sheet.
  89476. *
  89477. * \param object A pointer to an existing CUESHEET object.
  89478. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89479. * stringent requirements for a CD-DA (audio) disc.
  89480. * \param violation Address of a pointer to a string. If there is a
  89481. * violation, a pointer to a string explanation of the
  89482. * violation will be returned here. \a violation may be
  89483. * \c NULL if you don't need the returned string. Do not
  89484. * free the returned string; it will always point to static
  89485. * data.
  89486. * \assert
  89487. * \code object != NULL \endcode
  89488. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89489. * \retval FLAC__bool
  89490. * \c false if cue sheet is illegal, else \c true.
  89491. */
  89492. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89493. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89494. * assumes the cue sheet corresponds to a CD; the result is undefined
  89495. * if the cuesheet's is_cd bit is not set.
  89496. *
  89497. * \param object A pointer to an existing CUESHEET object.
  89498. * \assert
  89499. * \code object != NULL \endcode
  89500. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89501. * \retval FLAC__uint32
  89502. * The unsigned integer representation of the CDDB/freedb ID
  89503. */
  89504. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89505. /** Sets the MIME type of a PICTURE block.
  89506. *
  89507. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89508. * takes ownership of the pointer. The existing string will be freed if this
  89509. * function is successful, otherwise the original string will remain if \a copy
  89510. * is \c true and malloc() fails.
  89511. *
  89512. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89513. *
  89514. * \param object A pointer to an existing PICTURE object.
  89515. * \param mime_type A pointer to the MIME type string. The string must be
  89516. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89517. * is done.
  89518. * \param copy See above.
  89519. * \assert
  89520. * \code object != NULL \endcode
  89521. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89522. * \code (mime_type != NULL) \endcode
  89523. * \retval FLAC__bool
  89524. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89525. */
  89526. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89527. /** Sets the description of a PICTURE block.
  89528. *
  89529. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89530. * takes ownership of the pointer. The existing string will be freed if this
  89531. * function is successful, otherwise the original string will remain if \a copy
  89532. * is \c true and malloc() fails.
  89533. *
  89534. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89535. *
  89536. * \param object A pointer to an existing PICTURE object.
  89537. * \param description A pointer to the description string. The string must be
  89538. * valid UTF-8, NUL-terminated. No validation is done.
  89539. * \param copy See above.
  89540. * \assert
  89541. * \code object != NULL \endcode
  89542. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89543. * \code (description != NULL) \endcode
  89544. * \retval FLAC__bool
  89545. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89546. */
  89547. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89548. /** Sets the picture data of a PICTURE block.
  89549. *
  89550. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89551. * takes ownership of the pointer. Also sets the \a data_length field of the
  89552. * metadata object to what is passed in as the \a length parameter. The
  89553. * existing data will be freed if this function is successful, otherwise the
  89554. * original data and data_length will remain if \a copy is \c true and
  89555. * malloc() fails.
  89556. *
  89557. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89558. *
  89559. * \param object A pointer to an existing PICTURE object.
  89560. * \param data A pointer to the data to set.
  89561. * \param length The length of \a data in bytes.
  89562. * \param copy See above.
  89563. * \assert
  89564. * \code object != NULL \endcode
  89565. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89566. * \code (data != NULL && length > 0) ||
  89567. * (data == NULL && length == 0 && copy == false) \endcode
  89568. * \retval FLAC__bool
  89569. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89570. */
  89571. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89572. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89573. * See the format specification for limits on the contents of the
  89574. * PICTURE block.
  89575. *
  89576. * \param object A pointer to existing PICTURE block to be checked.
  89577. * \param violation Address of a pointer to a string. If there is a
  89578. * violation, a pointer to a string explanation of the
  89579. * violation will be returned here. \a violation may be
  89580. * \c NULL if you don't need the returned string. Do not
  89581. * free the returned string; it will always point to static
  89582. * data.
  89583. * \assert
  89584. * \code object != NULL \endcode
  89585. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89586. * \retval FLAC__bool
  89587. * \c false if PICTURE block is illegal, else \c true.
  89588. */
  89589. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89590. /* \} */
  89591. #ifdef __cplusplus
  89592. }
  89593. #endif
  89594. #endif
  89595. /*** End of inlined file: metadata.h ***/
  89596. /*** Start of inlined file: stream_decoder.h ***/
  89597. #ifndef FLAC__STREAM_DECODER_H
  89598. #define FLAC__STREAM_DECODER_H
  89599. #include <stdio.h> /* for FILE */
  89600. #ifdef __cplusplus
  89601. extern "C" {
  89602. #endif
  89603. /** \file include/FLAC/stream_decoder.h
  89604. *
  89605. * \brief
  89606. * This module contains the functions which implement the stream
  89607. * decoder.
  89608. *
  89609. * See the detailed documentation in the
  89610. * \link flac_stream_decoder stream decoder \endlink module.
  89611. */
  89612. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89613. * \ingroup flac
  89614. *
  89615. * \brief
  89616. * This module describes the decoder layers provided by libFLAC.
  89617. *
  89618. * The stream decoder can be used to decode complete streams either from
  89619. * the client via callbacks, or directly from a file, depending on how
  89620. * it is initialized. When decoding via callbacks, the client provides
  89621. * callbacks for reading FLAC data and writing decoded samples, and
  89622. * handling metadata and errors. If the client also supplies seek-related
  89623. * callback, the decoder function for sample-accurate seeking within the
  89624. * FLAC input is also available. When decoding from a file, the client
  89625. * needs only supply a filename or open \c FILE* and write/metadata/error
  89626. * callbacks; the rest of the callbacks are supplied internally. For more
  89627. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89628. */
  89629. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89630. * \ingroup flac_decoder
  89631. *
  89632. * \brief
  89633. * This module contains the functions which implement the stream
  89634. * decoder.
  89635. *
  89636. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89637. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89638. *
  89639. * The basic usage of this decoder is as follows:
  89640. * - The program creates an instance of a decoder using
  89641. * FLAC__stream_decoder_new().
  89642. * - The program overrides the default settings using
  89643. * FLAC__stream_decoder_set_*() functions.
  89644. * - The program initializes the instance to validate the settings and
  89645. * prepare for decoding using
  89646. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89647. * or FLAC__stream_decoder_init_file() for native FLAC,
  89648. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89649. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89650. * - The program calls the FLAC__stream_decoder_process_*() functions
  89651. * to decode data, which subsequently calls the callbacks.
  89652. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89653. * which flushes the input and output and resets the decoder to the
  89654. * uninitialized state.
  89655. * - The instance may be used again or deleted with
  89656. * FLAC__stream_decoder_delete().
  89657. *
  89658. * In more detail, the program will create a new instance by calling
  89659. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89660. * functions to override the default decoder options, and call
  89661. * one of the FLAC__stream_decoder_init_*() functions.
  89662. *
  89663. * There are three initialization functions for native FLAC, one for
  89664. * setting up the decoder to decode FLAC data from the client via
  89665. * callbacks, and two for decoding directly from a FLAC file.
  89666. *
  89667. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89668. * You must also supply several callbacks for handling I/O. Some (like
  89669. * seeking) are optional, depending on the capabilities of the input.
  89670. *
  89671. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89672. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89673. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89674. * the other callbacks internally.
  89675. *
  89676. * There are three similarly-named init functions for decoding from Ogg
  89677. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89678. * library has been built with Ogg support.
  89679. *
  89680. * Once the decoder is initialized, your program will call one of several
  89681. * functions to start the decoding process:
  89682. *
  89683. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89684. * most one metadata block or audio frame and return, calling either the
  89685. * metadata callback or write callback, respectively, once. If the decoder
  89686. * loses sync it will return with only the error callback being called.
  89687. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89688. * to process the stream from the current location and stop upon reaching
  89689. * the first audio frame. The client will get one metadata, write, or error
  89690. * callback per metadata block, audio frame, or sync error, respectively.
  89691. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89692. * to process the stream from the current location until the read callback
  89693. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89694. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89695. * write, or error callback per metadata block, audio frame, or sync error,
  89696. * respectively.
  89697. *
  89698. * When the decoder has finished decoding (normally or through an abort),
  89699. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89700. * ensures the decoder is in the correct state and frees memory. Then the
  89701. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89702. * again to decode another stream.
  89703. *
  89704. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89705. * At any point after the stream decoder has been initialized, the client can
  89706. * call this function to seek to an exact sample within the stream.
  89707. * Subsequently, the first time the write callback is called it will be
  89708. * passed a (possibly partial) block starting at that sample.
  89709. *
  89710. * If the client cannot seek via the callback interface provided, but still
  89711. * has another way of seeking, it can flush the decoder using
  89712. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89713. * through the read callback.
  89714. *
  89715. * The stream decoder also provides MD5 signature checking. If this is
  89716. * turned on before initialization, FLAC__stream_decoder_finish() will
  89717. * report when the decoded MD5 signature does not match the one stored
  89718. * in the STREAMINFO block. MD5 checking is automatically turned off
  89719. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89720. * in the STREAMINFO block or when a seek is attempted.
  89721. *
  89722. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89723. * attention. By default, the decoder only calls the metadata_callback for
  89724. * the STREAMINFO block. These functions allow you to tell the decoder
  89725. * explicitly which blocks to parse and return via the metadata_callback
  89726. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89727. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89728. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89729. * which blocks to return. Remember that metadata blocks can potentially
  89730. * be big (for example, cover art) so filtering out the ones you don't
  89731. * use can reduce the memory requirements of the decoder. Also note the
  89732. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89733. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89734. * filtering APPLICATION blocks based on the application ID.
  89735. *
  89736. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89737. * they still can legally be filtered from the metadata_callback.
  89738. *
  89739. * \note
  89740. * The "set" functions may only be called when the decoder is in the
  89741. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89742. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89743. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89744. * return \c true, otherwise \c false.
  89745. *
  89746. * \note
  89747. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89748. * defaults, including the callbacks.
  89749. *
  89750. * \{
  89751. */
  89752. /** State values for a FLAC__StreamDecoder
  89753. *
  89754. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89755. */
  89756. typedef enum {
  89757. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89758. /**< The decoder is ready to search for metadata. */
  89759. FLAC__STREAM_DECODER_READ_METADATA,
  89760. /**< The decoder is ready to or is in the process of reading metadata. */
  89761. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89762. /**< The decoder is ready to or is in the process of searching for the
  89763. * frame sync code.
  89764. */
  89765. FLAC__STREAM_DECODER_READ_FRAME,
  89766. /**< The decoder is ready to or is in the process of reading a frame. */
  89767. FLAC__STREAM_DECODER_END_OF_STREAM,
  89768. /**< The decoder has reached the end of the stream. */
  89769. FLAC__STREAM_DECODER_OGG_ERROR,
  89770. /**< An error occurred in the underlying Ogg layer. */
  89771. FLAC__STREAM_DECODER_SEEK_ERROR,
  89772. /**< An error occurred while seeking. The decoder must be flushed
  89773. * with FLAC__stream_decoder_flush() or reset with
  89774. * FLAC__stream_decoder_reset() before decoding can continue.
  89775. */
  89776. FLAC__STREAM_DECODER_ABORTED,
  89777. /**< The decoder was aborted by the read callback. */
  89778. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89779. /**< An error occurred allocating memory. The decoder is in an invalid
  89780. * state and can no longer be used.
  89781. */
  89782. FLAC__STREAM_DECODER_UNINITIALIZED
  89783. /**< The decoder is in the uninitialized state; one of the
  89784. * FLAC__stream_decoder_init_*() functions must be called before samples
  89785. * can be processed.
  89786. */
  89787. } FLAC__StreamDecoderState;
  89788. /** Maps a FLAC__StreamDecoderState to a C string.
  89789. *
  89790. * Using a FLAC__StreamDecoderState as the index to this array
  89791. * will give the string equivalent. The contents should not be modified.
  89792. */
  89793. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89794. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89795. */
  89796. typedef enum {
  89797. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89798. /**< Initialization was successful. */
  89799. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89800. /**< The library was not compiled with support for the given container
  89801. * format.
  89802. */
  89803. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89804. /**< A required callback was not supplied. */
  89805. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89806. /**< An error occurred allocating memory. */
  89807. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89808. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89809. * FLAC__stream_decoder_init_ogg_file(). */
  89810. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89811. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89812. * already initialized, usually because
  89813. * FLAC__stream_decoder_finish() was not called.
  89814. */
  89815. } FLAC__StreamDecoderInitStatus;
  89816. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89817. *
  89818. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89819. * will give the string equivalent. The contents should not be modified.
  89820. */
  89821. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89822. /** Return values for the FLAC__StreamDecoder read callback.
  89823. */
  89824. typedef enum {
  89825. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89826. /**< The read was OK and decoding can continue. */
  89827. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89828. /**< The read was attempted while at the end of the stream. Note that
  89829. * the client must only return this value when the read callback was
  89830. * called when already at the end of the stream. Otherwise, if the read
  89831. * itself moves to the end of the stream, the client should still return
  89832. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89833. * the next read callback it should return
  89834. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89835. * of \c 0.
  89836. */
  89837. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89838. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89839. } FLAC__StreamDecoderReadStatus;
  89840. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89841. *
  89842. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89843. * will give the string equivalent. The contents should not be modified.
  89844. */
  89845. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89846. /** Return values for the FLAC__StreamDecoder seek callback.
  89847. */
  89848. typedef enum {
  89849. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89850. /**< The seek was OK and decoding can continue. */
  89851. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89852. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89853. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89854. /**< Client does not support seeking. */
  89855. } FLAC__StreamDecoderSeekStatus;
  89856. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89857. *
  89858. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89859. * will give the string equivalent. The contents should not be modified.
  89860. */
  89861. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89862. /** Return values for the FLAC__StreamDecoder tell callback.
  89863. */
  89864. typedef enum {
  89865. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89866. /**< The tell was OK and decoding can continue. */
  89867. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89868. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89869. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89870. /**< Client does not support telling the position. */
  89871. } FLAC__StreamDecoderTellStatus;
  89872. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89873. *
  89874. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89875. * will give the string equivalent. The contents should not be modified.
  89876. */
  89877. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89878. /** Return values for the FLAC__StreamDecoder length callback.
  89879. */
  89880. typedef enum {
  89881. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89882. /**< The length call was OK and decoding can continue. */
  89883. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89884. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89885. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89886. /**< Client does not support reporting the length. */
  89887. } FLAC__StreamDecoderLengthStatus;
  89888. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89889. *
  89890. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89891. * will give the string equivalent. The contents should not be modified.
  89892. */
  89893. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89894. /** Return values for the FLAC__StreamDecoder write callback.
  89895. */
  89896. typedef enum {
  89897. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89898. /**< The write was OK and decoding can continue. */
  89899. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89900. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89901. } FLAC__StreamDecoderWriteStatus;
  89902. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89903. *
  89904. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89905. * will give the string equivalent. The contents should not be modified.
  89906. */
  89907. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89908. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89909. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89910. * all. The rest could be caused by bad sync (false synchronization on
  89911. * data that is not the start of a frame) or corrupted data. The error
  89912. * itself is the decoder's best guess at what happened assuming a correct
  89913. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89914. * could be caused by a correct sync on the start of a frame, but some
  89915. * data in the frame header was corrupted. Or it could be the result of
  89916. * syncing on a point the stream that looked like the starting of a frame
  89917. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89918. * could be because the decoder encountered a valid frame made by a future
  89919. * version of the encoder which it cannot parse, or because of a false
  89920. * sync making it appear as though an encountered frame was generated by
  89921. * a future encoder.
  89922. */
  89923. typedef enum {
  89924. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89925. /**< An error in the stream caused the decoder to lose synchronization. */
  89926. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89927. /**< The decoder encountered a corrupted frame header. */
  89928. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89929. /**< The frame's data did not match the CRC in the footer. */
  89930. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89931. /**< The decoder encountered reserved fields in use in the stream. */
  89932. } FLAC__StreamDecoderErrorStatus;
  89933. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89934. *
  89935. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89936. * will give the string equivalent. The contents should not be modified.
  89937. */
  89938. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89939. /***********************************************************************
  89940. *
  89941. * class FLAC__StreamDecoder
  89942. *
  89943. ***********************************************************************/
  89944. struct FLAC__StreamDecoderProtected;
  89945. struct FLAC__StreamDecoderPrivate;
  89946. /** The opaque structure definition for the stream decoder type.
  89947. * See the \link flac_stream_decoder stream decoder module \endlink
  89948. * for a detailed description.
  89949. */
  89950. typedef struct {
  89951. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89952. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89953. } FLAC__StreamDecoder;
  89954. /** Signature for the read callback.
  89955. *
  89956. * A function pointer matching this signature must be passed to
  89957. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89958. * called when the decoder needs more input data. The address of the
  89959. * buffer to be filled is supplied, along with the number of bytes the
  89960. * buffer can hold. The callback may choose to supply less data and
  89961. * modify the byte count but must be careful not to overflow the buffer.
  89962. * The callback then returns a status code chosen from
  89963. * FLAC__StreamDecoderReadStatus.
  89964. *
  89965. * Here is an example of a read callback for stdio streams:
  89966. * \code
  89967. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89968. * {
  89969. * FILE *file = ((MyClientData*)client_data)->file;
  89970. * if(*bytes > 0) {
  89971. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89972. * if(ferror(file))
  89973. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89974. * else if(*bytes == 0)
  89975. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89976. * else
  89977. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89978. * }
  89979. * else
  89980. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89981. * }
  89982. * \endcode
  89983. *
  89984. * \note In general, FLAC__StreamDecoder functions which change the
  89985. * state should not be called on the \a decoder while in the callback.
  89986. *
  89987. * \param decoder The decoder instance calling the callback.
  89988. * \param buffer A pointer to a location for the callee to store
  89989. * data to be decoded.
  89990. * \param bytes A pointer to the size of the buffer. On entry
  89991. * to the callback, it contains the maximum number
  89992. * of bytes that may be stored in \a buffer. The
  89993. * callee must set it to the actual number of bytes
  89994. * stored (0 in case of error or end-of-stream) before
  89995. * returning.
  89996. * \param client_data The callee's client data set through
  89997. * FLAC__stream_decoder_init_*().
  89998. * \retval FLAC__StreamDecoderReadStatus
  89999. * The callee's return status. Note that the callback should return
  90000. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  90001. * zero bytes were read and there is no more data to be read.
  90002. */
  90003. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90004. /** Signature for the seek callback.
  90005. *
  90006. * A function pointer matching this signature may be passed to
  90007. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90008. * called when the decoder needs to seek the input stream. The decoder
  90009. * will pass the absolute byte offset to seek to, 0 meaning the
  90010. * beginning of the stream.
  90011. *
  90012. * Here is an example of a seek callback for stdio streams:
  90013. * \code
  90014. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90015. * {
  90016. * FILE *file = ((MyClientData*)client_data)->file;
  90017. * if(file == stdin)
  90018. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  90019. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90020. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  90021. * else
  90022. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  90023. * }
  90024. * \endcode
  90025. *
  90026. * \note In general, FLAC__StreamDecoder functions which change the
  90027. * state should not be called on the \a decoder while in the callback.
  90028. *
  90029. * \param decoder The decoder instance calling the callback.
  90030. * \param absolute_byte_offset The offset from the beginning of the stream
  90031. * to seek to.
  90032. * \param client_data The callee's client data set through
  90033. * FLAC__stream_decoder_init_*().
  90034. * \retval FLAC__StreamDecoderSeekStatus
  90035. * The callee's return status.
  90036. */
  90037. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90038. /** Signature for the tell callback.
  90039. *
  90040. * A function pointer matching this signature may be passed to
  90041. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90042. * called when the decoder wants to know the current position of the
  90043. * stream. The callback should return the byte offset from the
  90044. * beginning of the stream.
  90045. *
  90046. * Here is an example of a tell callback for stdio streams:
  90047. * \code
  90048. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90049. * {
  90050. * FILE *file = ((MyClientData*)client_data)->file;
  90051. * off_t pos;
  90052. * if(file == stdin)
  90053. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90054. * else if((pos = ftello(file)) < 0)
  90055. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90056. * else {
  90057. * *absolute_byte_offset = (FLAC__uint64)pos;
  90058. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90059. * }
  90060. * }
  90061. * \endcode
  90062. *
  90063. * \note In general, FLAC__StreamDecoder functions which change the
  90064. * state should not be called on the \a decoder while in the callback.
  90065. *
  90066. * \param decoder The decoder instance calling the callback.
  90067. * \param absolute_byte_offset A pointer to storage for the current offset
  90068. * from the beginning of the stream.
  90069. * \param client_data The callee's client data set through
  90070. * FLAC__stream_decoder_init_*().
  90071. * \retval FLAC__StreamDecoderTellStatus
  90072. * The callee's return status.
  90073. */
  90074. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90075. /** Signature for the length callback.
  90076. *
  90077. * A function pointer matching this signature may be passed to
  90078. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90079. * called when the decoder wants to know the total length of the stream
  90080. * in bytes.
  90081. *
  90082. * Here is an example of a length callback for stdio streams:
  90083. * \code
  90084. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90085. * {
  90086. * FILE *file = ((MyClientData*)client_data)->file;
  90087. * struct stat filestats;
  90088. *
  90089. * if(file == stdin)
  90090. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90091. * else if(fstat(fileno(file), &filestats) != 0)
  90092. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90093. * else {
  90094. * *stream_length = (FLAC__uint64)filestats.st_size;
  90095. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90096. * }
  90097. * }
  90098. * \endcode
  90099. *
  90100. * \note In general, FLAC__StreamDecoder functions which change the
  90101. * state should not be called on the \a decoder while in the callback.
  90102. *
  90103. * \param decoder The decoder instance calling the callback.
  90104. * \param stream_length A pointer to storage for the length of the stream
  90105. * in bytes.
  90106. * \param client_data The callee's client data set through
  90107. * FLAC__stream_decoder_init_*().
  90108. * \retval FLAC__StreamDecoderLengthStatus
  90109. * The callee's return status.
  90110. */
  90111. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90112. /** Signature for the EOF callback.
  90113. *
  90114. * A function pointer matching this signature may be passed to
  90115. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90116. * called when the decoder needs to know if the end of the stream has
  90117. * been reached.
  90118. *
  90119. * Here is an example of a EOF callback for stdio streams:
  90120. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90121. * \code
  90122. * {
  90123. * FILE *file = ((MyClientData*)client_data)->file;
  90124. * return feof(file)? true : false;
  90125. * }
  90126. * \endcode
  90127. *
  90128. * \note In general, FLAC__StreamDecoder functions which change the
  90129. * state should not be called on the \a decoder while in the callback.
  90130. *
  90131. * \param decoder The decoder instance calling the callback.
  90132. * \param client_data The callee's client data set through
  90133. * FLAC__stream_decoder_init_*().
  90134. * \retval FLAC__bool
  90135. * \c true if the currently at the end of the stream, else \c false.
  90136. */
  90137. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90138. /** Signature for the write callback.
  90139. *
  90140. * A function pointer matching this signature must be passed to one of
  90141. * the FLAC__stream_decoder_init_*() functions.
  90142. * The supplied function will be called when the decoder has decoded a
  90143. * single audio frame. The decoder will pass the frame metadata as well
  90144. * as an array of pointers (one for each channel) pointing to the
  90145. * decoded audio.
  90146. *
  90147. * \note In general, FLAC__StreamDecoder functions which change the
  90148. * state should not be called on the \a decoder while in the callback.
  90149. *
  90150. * \param decoder The decoder instance calling the callback.
  90151. * \param frame The description of the decoded frame. See
  90152. * FLAC__Frame.
  90153. * \param buffer An array of pointers to decoded channels of data.
  90154. * Each pointer will point to an array of signed
  90155. * samples of length \a frame->header.blocksize.
  90156. * Channels will be ordered according to the FLAC
  90157. * specification; see the documentation for the
  90158. * <A HREF="../format.html#frame_header">frame header</A>.
  90159. * \param client_data The callee's client data set through
  90160. * FLAC__stream_decoder_init_*().
  90161. * \retval FLAC__StreamDecoderWriteStatus
  90162. * The callee's return status.
  90163. */
  90164. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90165. /** Signature for the metadata callback.
  90166. *
  90167. * A function pointer matching this signature must be passed to one of
  90168. * the FLAC__stream_decoder_init_*() functions.
  90169. * The supplied function will be called when the decoder has decoded a
  90170. * metadata block. In a valid FLAC file there will always be one
  90171. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90172. * These will be supplied by the decoder in the same order as they
  90173. * appear in the stream and always before the first audio frame (i.e.
  90174. * write callback). The metadata block that is passed in must not be
  90175. * modified, and it doesn't live beyond the callback, so you should make
  90176. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90177. * elsewhere. Since metadata blocks can potentially be large, by
  90178. * default the decoder only calls the metadata callback for the
  90179. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90180. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90181. *
  90182. * \note In general, FLAC__StreamDecoder functions which change the
  90183. * state should not be called on the \a decoder while in the callback.
  90184. *
  90185. * \param decoder The decoder instance calling the callback.
  90186. * \param metadata The decoded metadata block.
  90187. * \param client_data The callee's client data set through
  90188. * FLAC__stream_decoder_init_*().
  90189. */
  90190. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90191. /** Signature for the error callback.
  90192. *
  90193. * A function pointer matching this signature must be passed to one of
  90194. * the FLAC__stream_decoder_init_*() functions.
  90195. * The supplied function will be called whenever an error occurs during
  90196. * decoding.
  90197. *
  90198. * \note In general, FLAC__StreamDecoder functions which change the
  90199. * state should not be called on the \a decoder while in the callback.
  90200. *
  90201. * \param decoder The decoder instance calling the callback.
  90202. * \param status The error encountered by the decoder.
  90203. * \param client_data The callee's client data set through
  90204. * FLAC__stream_decoder_init_*().
  90205. */
  90206. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90207. /***********************************************************************
  90208. *
  90209. * Class constructor/destructor
  90210. *
  90211. ***********************************************************************/
  90212. /** Create a new stream decoder instance. The instance is created with
  90213. * default settings; see the individual FLAC__stream_decoder_set_*()
  90214. * functions for each setting's default.
  90215. *
  90216. * \retval FLAC__StreamDecoder*
  90217. * \c NULL if there was an error allocating memory, else the new instance.
  90218. */
  90219. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90220. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90221. *
  90222. * \param decoder A pointer to an existing decoder.
  90223. * \assert
  90224. * \code decoder != NULL \endcode
  90225. */
  90226. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90227. /***********************************************************************
  90228. *
  90229. * Public class method prototypes
  90230. *
  90231. ***********************************************************************/
  90232. /** Set the serial number for the FLAC stream within the Ogg container.
  90233. * The default behavior is to use the serial number of the first Ogg
  90234. * page. Setting a serial number here will explicitly specify which
  90235. * stream is to be decoded.
  90236. *
  90237. * \note
  90238. * This does not need to be set for native FLAC decoding.
  90239. *
  90240. * \default \c use serial number of first page
  90241. * \param decoder A decoder instance to set.
  90242. * \param serial_number See above.
  90243. * \assert
  90244. * \code decoder != NULL \endcode
  90245. * \retval FLAC__bool
  90246. * \c false if the decoder is already initialized, else \c true.
  90247. */
  90248. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90249. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90250. * compute the MD5 signature of the unencoded audio data while decoding
  90251. * and compare it to the signature from the STREAMINFO block, if it
  90252. * exists, during FLAC__stream_decoder_finish().
  90253. *
  90254. * MD5 signature checking will be turned off (until the next
  90255. * FLAC__stream_decoder_reset()) if there is no signature in the
  90256. * STREAMINFO block or when a seek is attempted.
  90257. *
  90258. * Clients that do not use the MD5 check should leave this off to speed
  90259. * up decoding.
  90260. *
  90261. * \default \c false
  90262. * \param decoder A decoder instance to set.
  90263. * \param value Flag value (see above).
  90264. * \assert
  90265. * \code decoder != NULL \endcode
  90266. * \retval FLAC__bool
  90267. * \c false if the decoder is already initialized, else \c true.
  90268. */
  90269. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90270. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90271. *
  90272. * \default By default, only the \c STREAMINFO block is returned via the
  90273. * metadata callback.
  90274. * \param decoder A decoder instance to set.
  90275. * \param type See above.
  90276. * \assert
  90277. * \code decoder != NULL \endcode
  90278. * \a type is valid
  90279. * \retval FLAC__bool
  90280. * \c false if the decoder is already initialized, else \c true.
  90281. */
  90282. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90283. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90284. * given \a id.
  90285. *
  90286. * \default By default, only the \c STREAMINFO block is returned via the
  90287. * metadata callback.
  90288. * \param decoder A decoder instance to set.
  90289. * \param id See above.
  90290. * \assert
  90291. * \code decoder != NULL \endcode
  90292. * \code id != NULL \endcode
  90293. * \retval FLAC__bool
  90294. * \c false if the decoder is already initialized, else \c true.
  90295. */
  90296. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90297. /** Direct the decoder to pass on all metadata blocks of any type.
  90298. *
  90299. * \default By default, only the \c STREAMINFO block is returned via the
  90300. * metadata callback.
  90301. * \param decoder A decoder instance to set.
  90302. * \assert
  90303. * \code decoder != NULL \endcode
  90304. * \retval FLAC__bool
  90305. * \c false if the decoder is already initialized, else \c true.
  90306. */
  90307. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90308. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90309. *
  90310. * \default By default, only the \c STREAMINFO block is returned via the
  90311. * metadata callback.
  90312. * \param decoder A decoder instance to set.
  90313. * \param type See above.
  90314. * \assert
  90315. * \code decoder != NULL \endcode
  90316. * \a type is valid
  90317. * \retval FLAC__bool
  90318. * \c false if the decoder is already initialized, else \c true.
  90319. */
  90320. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90321. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90322. * the given \a id.
  90323. *
  90324. * \default By default, only the \c STREAMINFO block is returned via the
  90325. * metadata callback.
  90326. * \param decoder A decoder instance to set.
  90327. * \param id See above.
  90328. * \assert
  90329. * \code decoder != NULL \endcode
  90330. * \code id != NULL \endcode
  90331. * \retval FLAC__bool
  90332. * \c false if the decoder is already initialized, else \c true.
  90333. */
  90334. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90335. /** Direct the decoder to filter out all metadata blocks of any type.
  90336. *
  90337. * \default By default, only the \c STREAMINFO block is returned via the
  90338. * metadata callback.
  90339. * \param decoder A decoder instance to set.
  90340. * \assert
  90341. * \code decoder != NULL \endcode
  90342. * \retval FLAC__bool
  90343. * \c false if the decoder is already initialized, else \c true.
  90344. */
  90345. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90346. /** Get the current decoder state.
  90347. *
  90348. * \param decoder A decoder instance to query.
  90349. * \assert
  90350. * \code decoder != NULL \endcode
  90351. * \retval FLAC__StreamDecoderState
  90352. * The current decoder state.
  90353. */
  90354. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90355. /** Get the current decoder state as a C string.
  90356. *
  90357. * \param decoder A decoder instance to query.
  90358. * \assert
  90359. * \code decoder != NULL \endcode
  90360. * \retval const char *
  90361. * The decoder state as a C string. Do not modify the contents.
  90362. */
  90363. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90364. /** Get the "MD5 signature checking" flag.
  90365. * This is the value of the setting, not whether or not the decoder is
  90366. * currently checking the MD5 (remember, it can be turned off automatically
  90367. * by a seek). When the decoder is reset the flag will be restored to the
  90368. * value returned by this function.
  90369. *
  90370. * \param decoder A decoder instance to query.
  90371. * \assert
  90372. * \code decoder != NULL \endcode
  90373. * \retval FLAC__bool
  90374. * See above.
  90375. */
  90376. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90377. /** Get the total number of samples in the stream being decoded.
  90378. * Will only be valid after decoding has started and will contain the
  90379. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90380. *
  90381. * \param decoder A decoder instance to query.
  90382. * \assert
  90383. * \code decoder != NULL \endcode
  90384. * \retval unsigned
  90385. * See above.
  90386. */
  90387. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90388. /** Get the current number of channels in the stream being decoded.
  90389. * Will only be valid after decoding has started and will contain the
  90390. * value from the most recently decoded frame header.
  90391. *
  90392. * \param decoder A decoder instance to query.
  90393. * \assert
  90394. * \code decoder != NULL \endcode
  90395. * \retval unsigned
  90396. * See above.
  90397. */
  90398. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90399. /** Get the current channel assignment in the stream being decoded.
  90400. * Will only be valid after decoding has started and will contain the
  90401. * value from the most recently decoded frame header.
  90402. *
  90403. * \param decoder A decoder instance to query.
  90404. * \assert
  90405. * \code decoder != NULL \endcode
  90406. * \retval FLAC__ChannelAssignment
  90407. * See above.
  90408. */
  90409. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90410. /** Get the current sample resolution in the stream being decoded.
  90411. * Will only be valid after decoding has started and will contain the
  90412. * value from the most recently decoded frame header.
  90413. *
  90414. * \param decoder A decoder instance to query.
  90415. * \assert
  90416. * \code decoder != NULL \endcode
  90417. * \retval unsigned
  90418. * See above.
  90419. */
  90420. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90421. /** Get the current sample rate in Hz of the stream being decoded.
  90422. * Will only be valid after decoding has started and will contain the
  90423. * value from the most recently decoded frame header.
  90424. *
  90425. * \param decoder A decoder instance to query.
  90426. * \assert
  90427. * \code decoder != NULL \endcode
  90428. * \retval unsigned
  90429. * See above.
  90430. */
  90431. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90432. /** Get the current blocksize of the stream being decoded.
  90433. * Will only be valid after decoding has started and will contain the
  90434. * value from the most recently decoded frame header.
  90435. *
  90436. * \param decoder A decoder instance to query.
  90437. * \assert
  90438. * \code decoder != NULL \endcode
  90439. * \retval unsigned
  90440. * See above.
  90441. */
  90442. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90443. /** Returns the decoder's current read position within the stream.
  90444. * The position is the byte offset from the start of the stream.
  90445. * Bytes before this position have been fully decoded. Note that
  90446. * there may still be undecoded bytes in the decoder's read FIFO.
  90447. * The returned position is correct even after a seek.
  90448. *
  90449. * \warning This function currently only works for native FLAC,
  90450. * not Ogg FLAC streams.
  90451. *
  90452. * \param decoder A decoder instance to query.
  90453. * \param position Address at which to return the desired position.
  90454. * \assert
  90455. * \code decoder != NULL \endcode
  90456. * \code position != NULL \endcode
  90457. * \retval FLAC__bool
  90458. * \c true if successful, \c false if the stream is not native FLAC,
  90459. * or there was an error from the 'tell' callback or it returned
  90460. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90461. */
  90462. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90463. /** Initialize the decoder instance to decode native FLAC streams.
  90464. *
  90465. * This flavor of initialization sets up the decoder to decode from a
  90466. * native FLAC stream. I/O is performed via callbacks to the client.
  90467. * For decoding from a plain file via filename or open FILE*,
  90468. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90469. * provide a simpler interface.
  90470. *
  90471. * This function should be called after FLAC__stream_decoder_new() and
  90472. * FLAC__stream_decoder_set_*() but before any of the
  90473. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90474. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90475. * if initialization succeeded.
  90476. *
  90477. * \param decoder An uninitialized decoder instance.
  90478. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90479. * pointer must not be \c NULL.
  90480. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90481. * pointer may be \c NULL if seeking is not
  90482. * supported. If \a seek_callback is not \c NULL then a
  90483. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90484. * Alternatively, a dummy seek callback that just
  90485. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90486. * may also be supplied, all though this is slightly
  90487. * less efficient for the decoder.
  90488. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90489. * pointer may be \c NULL if not supported by the client. If
  90490. * \a seek_callback is not \c NULL then a
  90491. * \a tell_callback must also be supplied.
  90492. * Alternatively, a dummy tell callback that just
  90493. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90494. * may also be supplied, all though this is slightly
  90495. * less efficient for the decoder.
  90496. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90497. * pointer may be \c NULL if not supported by the client. If
  90498. * \a seek_callback is not \c NULL then a
  90499. * \a length_callback must also be supplied.
  90500. * Alternatively, a dummy length callback that just
  90501. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90502. * may also be supplied, all though this is slightly
  90503. * less efficient for the decoder.
  90504. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90505. * pointer may be \c NULL if not supported by the client. If
  90506. * \a seek_callback is not \c NULL then a
  90507. * \a eof_callback must also be supplied.
  90508. * Alternatively, a dummy length callback that just
  90509. * returns \c false
  90510. * may also be supplied, all though this is slightly
  90511. * less efficient for the decoder.
  90512. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90513. * pointer must not be \c NULL.
  90514. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90515. * pointer may be \c NULL if the callback is not
  90516. * desired.
  90517. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90518. * pointer must not be \c NULL.
  90519. * \param client_data This value will be supplied to callbacks in their
  90520. * \a client_data argument.
  90521. * \assert
  90522. * \code decoder != NULL \endcode
  90523. * \retval FLAC__StreamDecoderInitStatus
  90524. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90525. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90526. */
  90527. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90528. FLAC__StreamDecoder *decoder,
  90529. FLAC__StreamDecoderReadCallback read_callback,
  90530. FLAC__StreamDecoderSeekCallback seek_callback,
  90531. FLAC__StreamDecoderTellCallback tell_callback,
  90532. FLAC__StreamDecoderLengthCallback length_callback,
  90533. FLAC__StreamDecoderEofCallback eof_callback,
  90534. FLAC__StreamDecoderWriteCallback write_callback,
  90535. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90536. FLAC__StreamDecoderErrorCallback error_callback,
  90537. void *client_data
  90538. );
  90539. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90540. *
  90541. * This flavor of initialization sets up the decoder to decode from a
  90542. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90543. * client. For decoding from a plain file via filename or open FILE*,
  90544. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90545. * provide a simpler interface.
  90546. *
  90547. * This function should be called after FLAC__stream_decoder_new() and
  90548. * FLAC__stream_decoder_set_*() but before any of the
  90549. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90550. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90551. * if initialization succeeded.
  90552. *
  90553. * \note Support for Ogg FLAC in the library is optional. If this
  90554. * library has been built without support for Ogg FLAC, this function
  90555. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90556. *
  90557. * \param decoder An uninitialized decoder instance.
  90558. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90559. * pointer must not be \c NULL.
  90560. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90561. * pointer may be \c NULL if seeking is not
  90562. * supported. If \a seek_callback is not \c NULL then a
  90563. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90564. * Alternatively, a dummy seek callback that just
  90565. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90566. * may also be supplied, all though this is slightly
  90567. * less efficient for the decoder.
  90568. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90569. * pointer may be \c NULL if not supported by the client. If
  90570. * \a seek_callback is not \c NULL then a
  90571. * \a tell_callback must also be supplied.
  90572. * Alternatively, a dummy tell callback that just
  90573. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90574. * may also be supplied, all though this is slightly
  90575. * less efficient for the decoder.
  90576. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90577. * pointer may be \c NULL if not supported by the client. If
  90578. * \a seek_callback is not \c NULL then a
  90579. * \a length_callback must also be supplied.
  90580. * Alternatively, a dummy length callback that just
  90581. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90582. * may also be supplied, all though this is slightly
  90583. * less efficient for the decoder.
  90584. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90585. * pointer may be \c NULL if not supported by the client. If
  90586. * \a seek_callback is not \c NULL then a
  90587. * \a eof_callback must also be supplied.
  90588. * Alternatively, a dummy length callback that just
  90589. * returns \c false
  90590. * may also be supplied, all though this is slightly
  90591. * less efficient for the decoder.
  90592. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90593. * pointer must not be \c NULL.
  90594. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90595. * pointer may be \c NULL if the callback is not
  90596. * desired.
  90597. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90598. * pointer must not be \c NULL.
  90599. * \param client_data This value will be supplied to callbacks in their
  90600. * \a client_data argument.
  90601. * \assert
  90602. * \code decoder != NULL \endcode
  90603. * \retval FLAC__StreamDecoderInitStatus
  90604. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90605. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90606. */
  90607. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90608. FLAC__StreamDecoder *decoder,
  90609. FLAC__StreamDecoderReadCallback read_callback,
  90610. FLAC__StreamDecoderSeekCallback seek_callback,
  90611. FLAC__StreamDecoderTellCallback tell_callback,
  90612. FLAC__StreamDecoderLengthCallback length_callback,
  90613. FLAC__StreamDecoderEofCallback eof_callback,
  90614. FLAC__StreamDecoderWriteCallback write_callback,
  90615. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90616. FLAC__StreamDecoderErrorCallback error_callback,
  90617. void *client_data
  90618. );
  90619. /** Initialize the decoder instance to decode native FLAC files.
  90620. *
  90621. * This flavor of initialization sets up the decoder to decode from a
  90622. * plain native FLAC file. For non-stdio streams, you must use
  90623. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90624. *
  90625. * This function should be called after FLAC__stream_decoder_new() and
  90626. * FLAC__stream_decoder_set_*() but before any of the
  90627. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90628. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90629. * if initialization succeeded.
  90630. *
  90631. * \param decoder An uninitialized decoder instance.
  90632. * \param file An open FLAC file. The file should have been
  90633. * opened with mode \c "rb" and rewound. The file
  90634. * becomes owned by the decoder and should not be
  90635. * manipulated by the client while decoding.
  90636. * Unless \a file is \c stdin, it will be closed
  90637. * when FLAC__stream_decoder_finish() is called.
  90638. * Note however that seeking will not work when
  90639. * decoding from \c stdout since it is not seekable.
  90640. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90641. * pointer must not be \c NULL.
  90642. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90643. * pointer may be \c NULL if the callback is not
  90644. * desired.
  90645. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90646. * pointer must not be \c NULL.
  90647. * \param client_data This value will be supplied to callbacks in their
  90648. * \a client_data argument.
  90649. * \assert
  90650. * \code decoder != NULL \endcode
  90651. * \code file != NULL \endcode
  90652. * \retval FLAC__StreamDecoderInitStatus
  90653. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90654. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90655. */
  90656. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90657. FLAC__StreamDecoder *decoder,
  90658. FILE *file,
  90659. FLAC__StreamDecoderWriteCallback write_callback,
  90660. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90661. FLAC__StreamDecoderErrorCallback error_callback,
  90662. void *client_data
  90663. );
  90664. /** Initialize the decoder instance to decode Ogg FLAC files.
  90665. *
  90666. * This flavor of initialization sets up the decoder to decode from a
  90667. * plain Ogg FLAC file. For non-stdio streams, you must use
  90668. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90669. *
  90670. * This function should be called after FLAC__stream_decoder_new() and
  90671. * FLAC__stream_decoder_set_*() but before any of the
  90672. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90673. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90674. * if initialization succeeded.
  90675. *
  90676. * \note Support for Ogg FLAC in the library is optional. If this
  90677. * library has been built without support for Ogg FLAC, this function
  90678. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90679. *
  90680. * \param decoder An uninitialized decoder instance.
  90681. * \param file An open FLAC file. The file should have been
  90682. * opened with mode \c "rb" and rewound. The file
  90683. * becomes owned by the decoder and should not be
  90684. * manipulated by the client while decoding.
  90685. * Unless \a file is \c stdin, it will be closed
  90686. * when FLAC__stream_decoder_finish() is called.
  90687. * Note however that seeking will not work when
  90688. * decoding from \c stdout since it is not seekable.
  90689. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90690. * pointer must not be \c NULL.
  90691. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90692. * pointer may be \c NULL if the callback is not
  90693. * desired.
  90694. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90695. * pointer must not be \c NULL.
  90696. * \param client_data This value will be supplied to callbacks in their
  90697. * \a client_data argument.
  90698. * \assert
  90699. * \code decoder != NULL \endcode
  90700. * \code file != NULL \endcode
  90701. * \retval FLAC__StreamDecoderInitStatus
  90702. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90703. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90704. */
  90705. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90706. FLAC__StreamDecoder *decoder,
  90707. FILE *file,
  90708. FLAC__StreamDecoderWriteCallback write_callback,
  90709. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90710. FLAC__StreamDecoderErrorCallback error_callback,
  90711. void *client_data
  90712. );
  90713. /** Initialize the decoder instance to decode native FLAC files.
  90714. *
  90715. * This flavor of initialization sets up the decoder to decode from a plain
  90716. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90717. * example, with Unicode filenames on Windows), you must use
  90718. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90719. * and provide callbacks for the I/O.
  90720. *
  90721. * This function should be called after FLAC__stream_decoder_new() and
  90722. * FLAC__stream_decoder_set_*() but before any of the
  90723. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90724. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90725. * if initialization succeeded.
  90726. *
  90727. * \param decoder An uninitialized decoder instance.
  90728. * \param filename The name of the file to decode from. The file will
  90729. * be opened with fopen(). Use \c NULL to decode from
  90730. * \c stdin. Note that \c stdin is not seekable.
  90731. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90732. * pointer must not be \c NULL.
  90733. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90734. * pointer may be \c NULL if the callback is not
  90735. * desired.
  90736. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90737. * pointer must not be \c NULL.
  90738. * \param client_data This value will be supplied to callbacks in their
  90739. * \a client_data argument.
  90740. * \assert
  90741. * \code decoder != NULL \endcode
  90742. * \retval FLAC__StreamDecoderInitStatus
  90743. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90744. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90745. */
  90746. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90747. FLAC__StreamDecoder *decoder,
  90748. const char *filename,
  90749. FLAC__StreamDecoderWriteCallback write_callback,
  90750. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90751. FLAC__StreamDecoderErrorCallback error_callback,
  90752. void *client_data
  90753. );
  90754. /** Initialize the decoder instance to decode Ogg FLAC files.
  90755. *
  90756. * This flavor of initialization sets up the decoder to decode from a plain
  90757. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90758. * example, with Unicode filenames on Windows), you must use
  90759. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90760. * and provide callbacks for the I/O.
  90761. *
  90762. * This function should be called after FLAC__stream_decoder_new() and
  90763. * FLAC__stream_decoder_set_*() but before any of the
  90764. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90765. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90766. * if initialization succeeded.
  90767. *
  90768. * \note Support for Ogg FLAC in the library is optional. If this
  90769. * library has been built without support for Ogg FLAC, this function
  90770. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90771. *
  90772. * \param decoder An uninitialized decoder instance.
  90773. * \param filename The name of the file to decode from. The file will
  90774. * be opened with fopen(). Use \c NULL to decode from
  90775. * \c stdin. Note that \c stdin is not seekable.
  90776. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90777. * pointer must not be \c NULL.
  90778. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90779. * pointer may be \c NULL if the callback is not
  90780. * desired.
  90781. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90782. * pointer must not be \c NULL.
  90783. * \param client_data This value will be supplied to callbacks in their
  90784. * \a client_data argument.
  90785. * \assert
  90786. * \code decoder != NULL \endcode
  90787. * \retval FLAC__StreamDecoderInitStatus
  90788. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90789. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90790. */
  90791. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90792. FLAC__StreamDecoder *decoder,
  90793. const char *filename,
  90794. FLAC__StreamDecoderWriteCallback write_callback,
  90795. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90796. FLAC__StreamDecoderErrorCallback error_callback,
  90797. void *client_data
  90798. );
  90799. /** Finish the decoding process.
  90800. * Flushes the decoding buffer, releases resources, resets the decoder
  90801. * settings to their defaults, and returns the decoder state to
  90802. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90803. *
  90804. * In the event of a prematurely-terminated decode, it is not strictly
  90805. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90806. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90807. * with a FLAC__stream_decoder_finish().
  90808. *
  90809. * \param decoder An uninitialized decoder instance.
  90810. * \assert
  90811. * \code decoder != NULL \endcode
  90812. * \retval FLAC__bool
  90813. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90814. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90815. * signature does not match the one computed by the decoder; else
  90816. * \c true.
  90817. */
  90818. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90819. /** Flush the stream input.
  90820. * The decoder's input buffer will be cleared and the state set to
  90821. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90822. * off MD5 checking.
  90823. *
  90824. * \param decoder A decoder instance.
  90825. * \assert
  90826. * \code decoder != NULL \endcode
  90827. * \retval FLAC__bool
  90828. * \c true if successful, else \c false if a memory allocation
  90829. * error occurs (in which case the state will be set to
  90830. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90831. */
  90832. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90833. /** Reset the decoding process.
  90834. * The decoder's input buffer will be cleared and the state set to
  90835. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90836. * FLAC__stream_decoder_finish() except that the settings are
  90837. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90838. * before decoding again. MD5 checking will be restored to its original
  90839. * setting.
  90840. *
  90841. * If the decoder is seekable, or was initialized with
  90842. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90843. * the decoder will also attempt to seek to the beginning of the file.
  90844. * If this rewind fails, this function will return \c false. It follows
  90845. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90846. * \c stdin.
  90847. *
  90848. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90849. * and is not seekable (i.e. no seek callback was provided or the seek
  90850. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90851. * is the duty of the client to start feeding data from the beginning of
  90852. * the stream on the next FLAC__stream_decoder_process() or
  90853. * FLAC__stream_decoder_process_interleaved() call.
  90854. *
  90855. * \param decoder A decoder instance.
  90856. * \assert
  90857. * \code decoder != NULL \endcode
  90858. * \retval FLAC__bool
  90859. * \c true if successful, else \c false if a memory allocation occurs
  90860. * (in which case the state will be set to
  90861. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90862. * occurs (the state will be unchanged).
  90863. */
  90864. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90865. /** Decode one metadata block or audio frame.
  90866. * This version instructs the decoder to decode a either a single metadata
  90867. * block or a single frame and stop, unless the callbacks return a fatal
  90868. * error or the read callback returns
  90869. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90870. *
  90871. * As the decoder needs more input it will call the read callback.
  90872. * Depending on what was decoded, the metadata or write callback will be
  90873. * called with the decoded metadata block or audio frame.
  90874. *
  90875. * Unless there is a fatal read error or end of stream, this function
  90876. * will return once one whole frame is decoded. In other words, if the
  90877. * stream is not synchronized or points to a corrupt frame header, the
  90878. * decoder will continue to try and resync until it gets to a valid
  90879. * frame, then decode one frame, then return. If the decoder points to
  90880. * a frame whose frame CRC in the frame footer does not match the
  90881. * computed frame CRC, this function will issue a
  90882. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90883. * error callback, and return, having decoded one complete, although
  90884. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90885. * correct length to the write callback.)
  90886. *
  90887. * \param decoder An initialized decoder instance.
  90888. * \assert
  90889. * \code decoder != NULL \endcode
  90890. * \retval FLAC__bool
  90891. * \c false if any fatal read, write, or memory allocation error
  90892. * occurred (meaning decoding must stop), else \c true; for more
  90893. * information about the decoder, check the decoder state with
  90894. * FLAC__stream_decoder_get_state().
  90895. */
  90896. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90897. /** Decode until the end of the metadata.
  90898. * This version instructs the decoder to decode from the current position
  90899. * and continue until all the metadata has been read, or until the
  90900. * callbacks return a fatal error or the read callback returns
  90901. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90902. *
  90903. * As the decoder needs more input it will call the read callback.
  90904. * As each metadata block is decoded, the metadata callback will be called
  90905. * with the decoded metadata.
  90906. *
  90907. * \param decoder An initialized decoder instance.
  90908. * \assert
  90909. * \code decoder != NULL \endcode
  90910. * \retval FLAC__bool
  90911. * \c false if any fatal read, write, or memory allocation error
  90912. * occurred (meaning decoding must stop), else \c true; for more
  90913. * information about the decoder, check the decoder state with
  90914. * FLAC__stream_decoder_get_state().
  90915. */
  90916. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90917. /** Decode until the end of the stream.
  90918. * This version instructs the decoder to decode from the current position
  90919. * and continue until the end of stream (the read callback returns
  90920. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90921. * callbacks return a fatal error.
  90922. *
  90923. * As the decoder needs more input it will call the read callback.
  90924. * As each metadata block and frame is decoded, the metadata or write
  90925. * callback will be called with the decoded metadata or frame.
  90926. *
  90927. * \param decoder An initialized decoder instance.
  90928. * \assert
  90929. * \code decoder != NULL \endcode
  90930. * \retval FLAC__bool
  90931. * \c false if any fatal read, write, or memory allocation error
  90932. * occurred (meaning decoding must stop), else \c true; for more
  90933. * information about the decoder, check the decoder state with
  90934. * FLAC__stream_decoder_get_state().
  90935. */
  90936. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90937. /** Skip one audio frame.
  90938. * This version instructs the decoder to 'skip' a single frame and stop,
  90939. * unless the callbacks return a fatal error or the read callback returns
  90940. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90941. *
  90942. * The decoding flow is the same as what occurs when
  90943. * FLAC__stream_decoder_process_single() is called to process an audio
  90944. * frame, except that this function does not decode the parsed data into
  90945. * PCM or call the write callback. The integrity of the frame is still
  90946. * checked the same way as in the other process functions.
  90947. *
  90948. * This function will return once one whole frame is skipped, in the
  90949. * same way that FLAC__stream_decoder_process_single() will return once
  90950. * one whole frame is decoded.
  90951. *
  90952. * This function can be used in more quickly determining FLAC frame
  90953. * boundaries when decoding of the actual data is not needed, for
  90954. * example when an application is separating a FLAC stream into frames
  90955. * for editing or storing in a container. To do this, the application
  90956. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90957. * to the next frame, then use
  90958. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90959. * boundary.
  90960. *
  90961. * This function should only be called when the stream has advanced
  90962. * past all the metadata, otherwise it will return \c false.
  90963. *
  90964. * \param decoder An initialized decoder instance not in a metadata
  90965. * state.
  90966. * \assert
  90967. * \code decoder != NULL \endcode
  90968. * \retval FLAC__bool
  90969. * \c false if any fatal read, write, or memory allocation error
  90970. * occurred (meaning decoding must stop), or if the decoder
  90971. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90972. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90973. * information about the decoder, check the decoder state with
  90974. * FLAC__stream_decoder_get_state().
  90975. */
  90976. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90977. /** Flush the input and seek to an absolute sample.
  90978. * Decoding will resume at the given sample. Note that because of
  90979. * this, the next write callback may contain a partial block. The
  90980. * client must support seeking the input or this function will fail
  90981. * and return \c false. Furthermore, if the decoder state is
  90982. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90983. * with FLAC__stream_decoder_flush() or reset with
  90984. * FLAC__stream_decoder_reset() before decoding can continue.
  90985. *
  90986. * \param decoder A decoder instance.
  90987. * \param sample The target sample number to seek to.
  90988. * \assert
  90989. * \code decoder != NULL \endcode
  90990. * \retval FLAC__bool
  90991. * \c true if successful, else \c false.
  90992. */
  90993. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90994. /* \} */
  90995. #ifdef __cplusplus
  90996. }
  90997. #endif
  90998. #endif
  90999. /*** End of inlined file: stream_decoder.h ***/
  91000. /*** Start of inlined file: stream_encoder.h ***/
  91001. #ifndef FLAC__STREAM_ENCODER_H
  91002. #define FLAC__STREAM_ENCODER_H
  91003. #include <stdio.h> /* for FILE */
  91004. #ifdef __cplusplus
  91005. extern "C" {
  91006. #endif
  91007. /** \file include/FLAC/stream_encoder.h
  91008. *
  91009. * \brief
  91010. * This module contains the functions which implement the stream
  91011. * encoder.
  91012. *
  91013. * See the detailed documentation in the
  91014. * \link flac_stream_encoder stream encoder \endlink module.
  91015. */
  91016. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  91017. * \ingroup flac
  91018. *
  91019. * \brief
  91020. * This module describes the encoder layers provided by libFLAC.
  91021. *
  91022. * The stream encoder can be used to encode complete streams either to the
  91023. * client via callbacks, or directly to a file, depending on how it is
  91024. * initialized. When encoding via callbacks, the client provides a write
  91025. * callback which will be called whenever FLAC data is ready to be written.
  91026. * If the client also supplies a seek callback, the encoder will also
  91027. * automatically handle the writing back of metadata discovered while
  91028. * encoding, like stream info, seek points offsets, etc. When encoding to
  91029. * a file, the client needs only supply a filename or open \c FILE* and an
  91030. * optional progress callback for periodic notification of progress; the
  91031. * write and seek callbacks are supplied internally. For more info see the
  91032. * \link flac_stream_encoder stream encoder \endlink module.
  91033. */
  91034. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91035. * \ingroup flac_encoder
  91036. *
  91037. * \brief
  91038. * This module contains the functions which implement the stream
  91039. * encoder.
  91040. *
  91041. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91042. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91043. *
  91044. * The basic usage of this encoder is as follows:
  91045. * - The program creates an instance of an encoder using
  91046. * FLAC__stream_encoder_new().
  91047. * - The program overrides the default settings using
  91048. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91049. * functions should be called:
  91050. * - FLAC__stream_encoder_set_channels()
  91051. * - FLAC__stream_encoder_set_bits_per_sample()
  91052. * - FLAC__stream_encoder_set_sample_rate()
  91053. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91054. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91055. * - If the application wants to control the compression level or set its own
  91056. * metadata, then the following should also be called:
  91057. * - FLAC__stream_encoder_set_compression_level()
  91058. * - FLAC__stream_encoder_set_verify()
  91059. * - FLAC__stream_encoder_set_metadata()
  91060. * - The rest of the set functions should only be called if the client needs
  91061. * exact control over how the audio is compressed; thorough understanding
  91062. * of the FLAC format is necessary to achieve good results.
  91063. * - The program initializes the instance to validate the settings and
  91064. * prepare for encoding using
  91065. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91066. * or FLAC__stream_encoder_init_file() for native FLAC
  91067. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91068. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91069. * - The program calls FLAC__stream_encoder_process() or
  91070. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91071. * subsequently calls the callbacks when there is encoder data ready
  91072. * to be written.
  91073. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91074. * which causes the encoder to encode any data still in its input pipe,
  91075. * update the metadata with the final encoding statistics if output
  91076. * seeking is possible, and finally reset the encoder to the
  91077. * uninitialized state.
  91078. * - The instance may be used again or deleted with
  91079. * FLAC__stream_encoder_delete().
  91080. *
  91081. * In more detail, the stream encoder functions similarly to the
  91082. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91083. * callbacks and more options. Typically the client will create a new
  91084. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91085. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91086. * calling one of the FLAC__stream_encoder_init_*() functions.
  91087. *
  91088. * Unlike the decoders, the stream encoder has many options that can
  91089. * affect the speed and compression ratio. When setting these parameters
  91090. * you should have some basic knowledge of the format (see the
  91091. * <A HREF="../documentation.html#format">user-level documentation</A>
  91092. * or the <A HREF="../format.html">formal description</A>). The
  91093. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91094. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91095. * functions will do this, so make sure to pay attention to the state
  91096. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91097. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91098. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91099. * the constructor.
  91100. *
  91101. * There are three initialization functions for native FLAC, one for
  91102. * setting up the encoder to encode FLAC data to the client via
  91103. * callbacks, and two for encoding directly to a file.
  91104. *
  91105. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91106. * You must also supply a write callback which will be called anytime
  91107. * there is raw encoded data to write. If the client can seek the output
  91108. * it is best to also supply seek and tell callbacks, as this allows the
  91109. * encoder to go back after encoding is finished to write back
  91110. * information that was collected while encoding, like seek point offsets,
  91111. * frame sizes, etc.
  91112. *
  91113. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91114. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91115. * filename or open \c FILE*; the encoder will handle all the callbacks
  91116. * internally. You may also supply a progress callback for periodic
  91117. * notification of the encoding progress.
  91118. *
  91119. * There are three similarly-named init functions for encoding to Ogg
  91120. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91121. * library has been built with Ogg support.
  91122. *
  91123. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91124. * call the write callback several times, once with the \c fLaC signature,
  91125. * and once for each encoded metadata block. Note that for Ogg FLAC
  91126. * encoding you will usually get at least twice the number of callbacks than
  91127. * with native FLAC, one for the Ogg page header and one for the page body.
  91128. *
  91129. * After initializing the instance, the client may feed audio data to the
  91130. * encoder in one of two ways:
  91131. *
  91132. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91133. * will pass an array of pointers to buffers, one for each channel, to
  91134. * the encoder, each of the same length. The samples need not be
  91135. * block-aligned, but each channel should have the same number of samples.
  91136. * - Channel interleaved, through
  91137. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91138. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91139. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91140. * Again, the samples need not be block-aligned but they must be
  91141. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91142. * the last value channelN_sampleM.
  91143. *
  91144. * Note that for either process call, each sample in the buffers should be a
  91145. * signed integer, right-justified to the resolution set by
  91146. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91147. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91148. *
  91149. * When the client is finished encoding data, it calls
  91150. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91151. * data still in its input pipe, and call the metadata callback with the
  91152. * final encoding statistics. Then the instance may be deleted with
  91153. * FLAC__stream_encoder_delete() or initialized again to encode another
  91154. * stream.
  91155. *
  91156. * For programs that write their own metadata, but that do not know the
  91157. * actual metadata until after encoding, it is advantageous to instruct
  91158. * the encoder to write a PADDING block of the correct size, so that
  91159. * instead of rewriting the whole stream after encoding, the program can
  91160. * just overwrite the PADDING block. If only the maximum size of the
  91161. * metadata is known, the program can write a slightly larger padding
  91162. * block, then split it after encoding.
  91163. *
  91164. * Make sure you understand how lengths are calculated. All FLAC metadata
  91165. * blocks have a 4 byte header which contains the type and length. This
  91166. * length does not include the 4 bytes of the header. See the format page
  91167. * for the specification of metadata blocks and their lengths.
  91168. *
  91169. * \note
  91170. * If you are writing the FLAC data to a file via callbacks, make sure it
  91171. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91172. * after the first encoding pass, the encoder will try to seek back to the
  91173. * beginning of the stream, to the STREAMINFO block, to write some data
  91174. * there. (If using FLAC__stream_encoder_init*_file() or
  91175. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91176. *
  91177. * \note
  91178. * The "set" functions may only be called when the encoder is in the
  91179. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91180. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91181. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91182. * return \c true, otherwise \c false.
  91183. *
  91184. * \note
  91185. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91186. * defaults.
  91187. *
  91188. * \{
  91189. */
  91190. /** State values for a FLAC__StreamEncoder.
  91191. *
  91192. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91193. *
  91194. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91195. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91196. * must be deleted with FLAC__stream_encoder_delete().
  91197. */
  91198. typedef enum {
  91199. FLAC__STREAM_ENCODER_OK = 0,
  91200. /**< The encoder is in the normal OK state and samples can be processed. */
  91201. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91202. /**< The encoder is in the uninitialized state; one of the
  91203. * FLAC__stream_encoder_init_*() functions must be called before samples
  91204. * can be processed.
  91205. */
  91206. FLAC__STREAM_ENCODER_OGG_ERROR,
  91207. /**< An error occurred in the underlying Ogg layer. */
  91208. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91209. /**< An error occurred in the underlying verify stream decoder;
  91210. * check FLAC__stream_encoder_get_verify_decoder_state().
  91211. */
  91212. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91213. /**< The verify decoder detected a mismatch between the original
  91214. * audio signal and the decoded audio signal.
  91215. */
  91216. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91217. /**< One of the callbacks returned a fatal error. */
  91218. FLAC__STREAM_ENCODER_IO_ERROR,
  91219. /**< An I/O error occurred while opening/reading/writing a file.
  91220. * Check \c errno.
  91221. */
  91222. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91223. /**< An error occurred while writing the stream; usually, the
  91224. * write_callback returned an error.
  91225. */
  91226. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91227. /**< Memory allocation failed. */
  91228. } FLAC__StreamEncoderState;
  91229. /** Maps a FLAC__StreamEncoderState to a C string.
  91230. *
  91231. * Using a FLAC__StreamEncoderState as the index to this array
  91232. * will give the string equivalent. The contents should not be modified.
  91233. */
  91234. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91235. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91236. */
  91237. typedef enum {
  91238. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91239. /**< Initialization was successful. */
  91240. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91241. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91242. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91243. /**< The library was not compiled with support for the given container
  91244. * format.
  91245. */
  91246. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91247. /**< A required callback was not supplied. */
  91248. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91249. /**< The encoder has an invalid setting for number of channels. */
  91250. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91251. /**< The encoder has an invalid setting for bits-per-sample.
  91252. * FLAC supports 4-32 bps but the reference encoder currently supports
  91253. * only up to 24 bps.
  91254. */
  91255. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91256. /**< The encoder has an invalid setting for the input sample rate. */
  91257. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91258. /**< The encoder has an invalid setting for the block size. */
  91259. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91260. /**< The encoder has an invalid setting for the maximum LPC order. */
  91261. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91262. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91263. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91264. /**< The specified block size is less than the maximum LPC order. */
  91265. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91266. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91267. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91268. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91269. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91270. * - One of the metadata blocks contains an undefined type
  91271. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91272. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91273. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91274. */
  91275. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91276. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91277. * already initialized, usually because
  91278. * FLAC__stream_encoder_finish() was not called.
  91279. */
  91280. } FLAC__StreamEncoderInitStatus;
  91281. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91282. *
  91283. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91284. * will give the string equivalent. The contents should not be modified.
  91285. */
  91286. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91287. /** Return values for the FLAC__StreamEncoder read callback.
  91288. */
  91289. typedef enum {
  91290. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91291. /**< The read was OK and decoding can continue. */
  91292. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91293. /**< The read was attempted at the end of the stream. */
  91294. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91295. /**< An unrecoverable error occurred. */
  91296. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91297. /**< Client does not support reading back from the output. */
  91298. } FLAC__StreamEncoderReadStatus;
  91299. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91300. *
  91301. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91302. * will give the string equivalent. The contents should not be modified.
  91303. */
  91304. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91305. /** Return values for the FLAC__StreamEncoder write callback.
  91306. */
  91307. typedef enum {
  91308. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91309. /**< The write was OK and encoding can continue. */
  91310. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91311. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91312. } FLAC__StreamEncoderWriteStatus;
  91313. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91314. *
  91315. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91316. * will give the string equivalent. The contents should not be modified.
  91317. */
  91318. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91319. /** Return values for the FLAC__StreamEncoder seek callback.
  91320. */
  91321. typedef enum {
  91322. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91323. /**< The seek was OK and encoding can continue. */
  91324. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91325. /**< An unrecoverable error occurred. */
  91326. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91327. /**< Client does not support seeking. */
  91328. } FLAC__StreamEncoderSeekStatus;
  91329. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91330. *
  91331. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91332. * will give the string equivalent. The contents should not be modified.
  91333. */
  91334. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91335. /** Return values for the FLAC__StreamEncoder tell callback.
  91336. */
  91337. typedef enum {
  91338. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91339. /**< The tell was OK and encoding can continue. */
  91340. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91341. /**< An unrecoverable error occurred. */
  91342. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91343. /**< Client does not support seeking. */
  91344. } FLAC__StreamEncoderTellStatus;
  91345. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91346. *
  91347. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91348. * will give the string equivalent. The contents should not be modified.
  91349. */
  91350. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91351. /***********************************************************************
  91352. *
  91353. * class FLAC__StreamEncoder
  91354. *
  91355. ***********************************************************************/
  91356. struct FLAC__StreamEncoderProtected;
  91357. struct FLAC__StreamEncoderPrivate;
  91358. /** The opaque structure definition for the stream encoder type.
  91359. * See the \link flac_stream_encoder stream encoder module \endlink
  91360. * for a detailed description.
  91361. */
  91362. typedef struct {
  91363. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91364. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91365. } FLAC__StreamEncoder;
  91366. /** Signature for the read callback.
  91367. *
  91368. * A function pointer matching this signature must be passed to
  91369. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91370. * The supplied function will be called when the encoder needs to read back
  91371. * encoded data. This happens during the metadata callback, when the encoder
  91372. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91373. * while encoding. The address of the buffer to be filled is supplied, along
  91374. * with the number of bytes the buffer can hold. The callback may choose to
  91375. * supply less data and modify the byte count but must be careful not to
  91376. * overflow the buffer. The callback then returns a status code chosen from
  91377. * FLAC__StreamEncoderReadStatus.
  91378. *
  91379. * Here is an example of a read callback for stdio streams:
  91380. * \code
  91381. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91382. * {
  91383. * FILE *file = ((MyClientData*)client_data)->file;
  91384. * if(*bytes > 0) {
  91385. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91386. * if(ferror(file))
  91387. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91388. * else if(*bytes == 0)
  91389. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91390. * else
  91391. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91392. * }
  91393. * else
  91394. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91395. * }
  91396. * \endcode
  91397. *
  91398. * \note In general, FLAC__StreamEncoder functions which change the
  91399. * state should not be called on the \a encoder while in the callback.
  91400. *
  91401. * \param encoder The encoder instance calling the callback.
  91402. * \param buffer A pointer to a location for the callee to store
  91403. * data to be encoded.
  91404. * \param bytes A pointer to the size of the buffer. On entry
  91405. * to the callback, it contains the maximum number
  91406. * of bytes that may be stored in \a buffer. The
  91407. * callee must set it to the actual number of bytes
  91408. * stored (0 in case of error or end-of-stream) before
  91409. * returning.
  91410. * \param client_data The callee's client data set through
  91411. * FLAC__stream_encoder_set_client_data().
  91412. * \retval FLAC__StreamEncoderReadStatus
  91413. * The callee's return status.
  91414. */
  91415. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91416. /** Signature for the write callback.
  91417. *
  91418. * A function pointer matching this signature must be passed to
  91419. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91420. * by the encoder anytime there is raw encoded data ready to write. It may
  91421. * include metadata mixed with encoded audio frames and the data is not
  91422. * guaranteed to be aligned on frame or metadata block boundaries.
  91423. *
  91424. * The only duty of the callback is to write out the \a bytes worth of data
  91425. * in \a buffer to the current position in the output stream. The arguments
  91426. * \a samples and \a current_frame are purely informational. If \a samples
  91427. * is greater than \c 0, then \a current_frame will hold the current frame
  91428. * number that is being written; otherwise it indicates that the write
  91429. * callback is being called to write metadata.
  91430. *
  91431. * \note
  91432. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91433. * write callback will be called twice when writing each audio
  91434. * frame; once for the page header, and once for the page body.
  91435. * When writing the page header, the \a samples argument to the
  91436. * write callback will be \c 0.
  91437. *
  91438. * \note In general, FLAC__StreamEncoder functions which change the
  91439. * state should not be called on the \a encoder while in the callback.
  91440. *
  91441. * \param encoder The encoder instance calling the callback.
  91442. * \param buffer An array of encoded data of length \a bytes.
  91443. * \param bytes The byte length of \a buffer.
  91444. * \param samples The number of samples encoded by \a buffer.
  91445. * \c 0 has a special meaning; see above.
  91446. * \param current_frame The number of the current frame being encoded.
  91447. * \param client_data The callee's client data set through
  91448. * FLAC__stream_encoder_init_*().
  91449. * \retval FLAC__StreamEncoderWriteStatus
  91450. * The callee's return status.
  91451. */
  91452. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91453. /** Signature for the seek callback.
  91454. *
  91455. * A function pointer matching this signature may be passed to
  91456. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91457. * when the encoder needs to seek the output stream. The encoder will pass
  91458. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91459. *
  91460. * Here is an example of a seek callback for stdio streams:
  91461. * \code
  91462. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91463. * {
  91464. * FILE *file = ((MyClientData*)client_data)->file;
  91465. * if(file == stdin)
  91466. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91467. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91468. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91469. * else
  91470. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91471. * }
  91472. * \endcode
  91473. *
  91474. * \note In general, FLAC__StreamEncoder functions which change the
  91475. * state should not be called on the \a encoder while in the callback.
  91476. *
  91477. * \param encoder The encoder instance calling the callback.
  91478. * \param absolute_byte_offset The offset from the beginning of the stream
  91479. * to seek to.
  91480. * \param client_data The callee's client data set through
  91481. * FLAC__stream_encoder_init_*().
  91482. * \retval FLAC__StreamEncoderSeekStatus
  91483. * The callee's return status.
  91484. */
  91485. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91486. /** Signature for the tell callback.
  91487. *
  91488. * A function pointer matching this signature may be passed to
  91489. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91490. * when the encoder needs to know the current position of the output stream.
  91491. *
  91492. * \warning
  91493. * The callback must return the true current byte offset of the output to
  91494. * which the encoder is writing. If you are buffering the output, make
  91495. * sure and take this into account. If you are writing directly to a
  91496. * FILE* from your write callback, ftell() is sufficient. If you are
  91497. * writing directly to a file descriptor from your write callback, you
  91498. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91499. * these points to rewrite metadata after encoding.
  91500. *
  91501. * Here is an example of a tell callback for stdio streams:
  91502. * \code
  91503. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91504. * {
  91505. * FILE *file = ((MyClientData*)client_data)->file;
  91506. * off_t pos;
  91507. * if(file == stdin)
  91508. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91509. * else if((pos = ftello(file)) < 0)
  91510. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91511. * else {
  91512. * *absolute_byte_offset = (FLAC__uint64)pos;
  91513. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91514. * }
  91515. * }
  91516. * \endcode
  91517. *
  91518. * \note In general, FLAC__StreamEncoder functions which change the
  91519. * state should not be called on the \a encoder while in the callback.
  91520. *
  91521. * \param encoder The encoder instance calling the callback.
  91522. * \param absolute_byte_offset The address at which to store the current
  91523. * position of the output.
  91524. * \param client_data The callee's client data set through
  91525. * FLAC__stream_encoder_init_*().
  91526. * \retval FLAC__StreamEncoderTellStatus
  91527. * The callee's return status.
  91528. */
  91529. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91530. /** Signature for the metadata callback.
  91531. *
  91532. * A function pointer matching this signature may be passed to
  91533. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91534. * once at the end of encoding with the populated STREAMINFO structure. This
  91535. * is so the client can seek back to the beginning of the file and write the
  91536. * STREAMINFO block with the correct statistics after encoding (like
  91537. * minimum/maximum frame size and total samples).
  91538. *
  91539. * \note In general, FLAC__StreamEncoder functions which change the
  91540. * state should not be called on the \a encoder while in the callback.
  91541. *
  91542. * \param encoder The encoder instance calling the callback.
  91543. * \param metadata The final populated STREAMINFO block.
  91544. * \param client_data The callee's client data set through
  91545. * FLAC__stream_encoder_init_*().
  91546. */
  91547. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91548. /** Signature for the progress callback.
  91549. *
  91550. * A function pointer matching this signature may be passed to
  91551. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91552. * The supplied function will be called when the encoder has finished
  91553. * writing a frame. The \c total_frames_estimate argument to the
  91554. * callback will be based on the value from
  91555. * FLAC__stream_encoder_set_total_samples_estimate().
  91556. *
  91557. * \note In general, FLAC__StreamEncoder functions which change the
  91558. * state should not be called on the \a encoder while in the callback.
  91559. *
  91560. * \param encoder The encoder instance calling the callback.
  91561. * \param bytes_written Bytes written so far.
  91562. * \param samples_written Samples written so far.
  91563. * \param frames_written Frames written so far.
  91564. * \param total_frames_estimate The estimate of the total number of
  91565. * frames to be written.
  91566. * \param client_data The callee's client data set through
  91567. * FLAC__stream_encoder_init_*().
  91568. */
  91569. 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);
  91570. /***********************************************************************
  91571. *
  91572. * Class constructor/destructor
  91573. *
  91574. ***********************************************************************/
  91575. /** Create a new stream encoder instance. The instance is created with
  91576. * default settings; see the individual FLAC__stream_encoder_set_*()
  91577. * functions for each setting's default.
  91578. *
  91579. * \retval FLAC__StreamEncoder*
  91580. * \c NULL if there was an error allocating memory, else the new instance.
  91581. */
  91582. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91583. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91584. *
  91585. * \param encoder A pointer to an existing encoder.
  91586. * \assert
  91587. * \code encoder != NULL \endcode
  91588. */
  91589. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91590. /***********************************************************************
  91591. *
  91592. * Public class method prototypes
  91593. *
  91594. ***********************************************************************/
  91595. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91596. *
  91597. * \note
  91598. * This does not need to be set for native FLAC encoding.
  91599. *
  91600. * \note
  91601. * It is recommended to set a serial number explicitly as the default of '0'
  91602. * may collide with other streams.
  91603. *
  91604. * \default \c 0
  91605. * \param encoder An encoder instance to set.
  91606. * \param serial_number See above.
  91607. * \assert
  91608. * \code encoder != NULL \endcode
  91609. * \retval FLAC__bool
  91610. * \c false if the encoder is already initialized, else \c true.
  91611. */
  91612. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91613. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91614. * encoded output by feeding it through an internal decoder and comparing
  91615. * the original signal against the decoded signal. If a mismatch occurs,
  91616. * the process call will return \c false. Note that this will slow the
  91617. * encoding process by the extra time required for decoding and comparison.
  91618. *
  91619. * \default \c false
  91620. * \param encoder An encoder instance to set.
  91621. * \param value Flag value (see above).
  91622. * \assert
  91623. * \code encoder != NULL \endcode
  91624. * \retval FLAC__bool
  91625. * \c false if the encoder is already initialized, else \c true.
  91626. */
  91627. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91628. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91629. * the encoder will comply with the Subset and will check the
  91630. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91631. * comply. If \c false, the settings may take advantage of the full
  91632. * range that the format allows.
  91633. *
  91634. * Make sure you know what it entails before setting this to \c false.
  91635. *
  91636. * \default \c true
  91637. * \param encoder An encoder instance to set.
  91638. * \param value Flag value (see above).
  91639. * \assert
  91640. * \code encoder != NULL \endcode
  91641. * \retval FLAC__bool
  91642. * \c false if the encoder is already initialized, else \c true.
  91643. */
  91644. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91645. /** Set the number of channels to be encoded.
  91646. *
  91647. * \default \c 2
  91648. * \param encoder An encoder instance to set.
  91649. * \param value See above.
  91650. * \assert
  91651. * \code encoder != NULL \endcode
  91652. * \retval FLAC__bool
  91653. * \c false if the encoder is already initialized, else \c true.
  91654. */
  91655. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91656. /** Set the sample resolution of the input to be encoded.
  91657. *
  91658. * \warning
  91659. * Do not feed the encoder data that is wider than the value you
  91660. * set here or you will generate an invalid stream.
  91661. *
  91662. * \default \c 16
  91663. * \param encoder An encoder instance to set.
  91664. * \param value See above.
  91665. * \assert
  91666. * \code encoder != NULL \endcode
  91667. * \retval FLAC__bool
  91668. * \c false if the encoder is already initialized, else \c true.
  91669. */
  91670. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91671. /** Set the sample rate (in Hz) of the input to be encoded.
  91672. *
  91673. * \default \c 44100
  91674. * \param encoder An encoder instance to set.
  91675. * \param value See above.
  91676. * \assert
  91677. * \code encoder != NULL \endcode
  91678. * \retval FLAC__bool
  91679. * \c false if the encoder is already initialized, else \c true.
  91680. */
  91681. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91682. /** Set the compression level
  91683. *
  91684. * The compression level is roughly proportional to the amount of effort
  91685. * the encoder expends to compress the file. A higher level usually
  91686. * means more computation but higher compression. The default level is
  91687. * suitable for most applications.
  91688. *
  91689. * Currently the levels range from \c 0 (fastest, least compression) to
  91690. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91691. * treated as \c 8.
  91692. *
  91693. * This function automatically calls the following other \c _set_
  91694. * functions with appropriate values, so the client does not need to
  91695. * unless it specifically wants to override them:
  91696. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91697. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91698. * - FLAC__stream_encoder_set_apodization()
  91699. * - FLAC__stream_encoder_set_max_lpc_order()
  91700. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91701. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91702. * - FLAC__stream_encoder_set_do_escape_coding()
  91703. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91704. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91705. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91706. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91707. *
  91708. * The actual values set for each level are:
  91709. * <table>
  91710. * <tr>
  91711. * <td><b>level</b><td>
  91712. * <td>do mid-side stereo<td>
  91713. * <td>loose mid-side stereo<td>
  91714. * <td>apodization<td>
  91715. * <td>max lpc order<td>
  91716. * <td>qlp coeff precision<td>
  91717. * <td>qlp coeff prec search<td>
  91718. * <td>escape coding<td>
  91719. * <td>exhaustive model search<td>
  91720. * <td>min residual partition order<td>
  91721. * <td>max residual partition order<td>
  91722. * <td>rice parameter search dist<td>
  91723. * </tr>
  91724. * <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>
  91725. * <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>
  91726. * <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>
  91727. * <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>
  91728. * <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>
  91729. * <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>
  91730. * <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>
  91731. * <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>
  91732. * <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>
  91733. * </table>
  91734. *
  91735. * \default \c 5
  91736. * \param encoder An encoder instance to set.
  91737. * \param value See above.
  91738. * \assert
  91739. * \code encoder != NULL \endcode
  91740. * \retval FLAC__bool
  91741. * \c false if the encoder is already initialized, else \c true.
  91742. */
  91743. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91744. /** Set the blocksize to use while encoding.
  91745. *
  91746. * The number of samples to use per frame. Use \c 0 to let the encoder
  91747. * estimate a blocksize; this is usually best.
  91748. *
  91749. * \default \c 0
  91750. * \param encoder An encoder instance to set.
  91751. * \param value See above.
  91752. * \assert
  91753. * \code encoder != NULL \endcode
  91754. * \retval FLAC__bool
  91755. * \c false if the encoder is already initialized, else \c true.
  91756. */
  91757. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91758. /** Set to \c true to enable mid-side encoding on stereo input. The
  91759. * number of channels must be 2 for this to have any effect. Set to
  91760. * \c false to use only independent channel coding.
  91761. *
  91762. * \default \c false
  91763. * \param encoder An encoder instance to set.
  91764. * \param value Flag value (see above).
  91765. * \assert
  91766. * \code encoder != NULL \endcode
  91767. * \retval FLAC__bool
  91768. * \c false if the encoder is already initialized, else \c true.
  91769. */
  91770. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91771. /** Set to \c true to enable adaptive switching between mid-side and
  91772. * left-right encoding on stereo input. Set to \c false to use
  91773. * exhaustive searching. Setting this to \c true requires
  91774. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91775. * \c true in order to have any effect.
  91776. *
  91777. * \default \c false
  91778. * \param encoder An encoder instance to set.
  91779. * \param value Flag value (see above).
  91780. * \assert
  91781. * \code encoder != NULL \endcode
  91782. * \retval FLAC__bool
  91783. * \c false if the encoder is already initialized, else \c true.
  91784. */
  91785. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91786. /** Sets the apodization function(s) the encoder will use when windowing
  91787. * audio data for LPC analysis.
  91788. *
  91789. * The \a specification is a plain ASCII string which specifies exactly
  91790. * which functions to use. There may be more than one (up to 32),
  91791. * separated by \c ';' characters. Some functions take one or more
  91792. * comma-separated arguments in parentheses.
  91793. *
  91794. * The available functions are \c bartlett, \c bartlett_hann,
  91795. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91796. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91797. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91798. *
  91799. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91800. * (0<STDDEV<=0.5).
  91801. *
  91802. * For \c tukey(P), P specifies the fraction of the window that is
  91803. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91804. * corresponds to \c hann.
  91805. *
  91806. * Example specifications are \c "blackman" or
  91807. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91808. *
  91809. * Any function that is specified erroneously is silently dropped. Up
  91810. * to 32 functions are kept, the rest are dropped. If the specification
  91811. * is empty the encoder defaults to \c "tukey(0.5)".
  91812. *
  91813. * When more than one function is specified, then for every subframe the
  91814. * encoder will try each of them separately and choose the window that
  91815. * results in the smallest compressed subframe.
  91816. *
  91817. * Note that each function specified causes the encoder to occupy a
  91818. * floating point array in which to store the window.
  91819. *
  91820. * \default \c "tukey(0.5)"
  91821. * \param encoder An encoder instance to set.
  91822. * \param specification See above.
  91823. * \assert
  91824. * \code encoder != NULL \endcode
  91825. * \code specification != NULL \endcode
  91826. * \retval FLAC__bool
  91827. * \c false if the encoder is already initialized, else \c true.
  91828. */
  91829. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91830. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91831. *
  91832. * \default \c 0
  91833. * \param encoder An encoder instance to set.
  91834. * \param value See above.
  91835. * \assert
  91836. * \code encoder != NULL \endcode
  91837. * \retval FLAC__bool
  91838. * \c false if the encoder is already initialized, else \c true.
  91839. */
  91840. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91841. /** Set the precision, in bits, of the quantized linear predictor
  91842. * coefficients, or \c 0 to let the encoder select it based on the
  91843. * blocksize.
  91844. *
  91845. * \note
  91846. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91847. * be less than 32.
  91848. *
  91849. * \default \c 0
  91850. * \param encoder An encoder instance to set.
  91851. * \param value See above.
  91852. * \assert
  91853. * \code encoder != NULL \endcode
  91854. * \retval FLAC__bool
  91855. * \c false if the encoder is already initialized, else \c true.
  91856. */
  91857. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91858. /** Set to \c false to use only the specified quantized linear predictor
  91859. * coefficient precision, or \c true to search neighboring precision
  91860. * values and use the best one.
  91861. *
  91862. * \default \c false
  91863. * \param encoder An encoder instance to set.
  91864. * \param value See above.
  91865. * \assert
  91866. * \code encoder != NULL \endcode
  91867. * \retval FLAC__bool
  91868. * \c false if the encoder is already initialized, else \c true.
  91869. */
  91870. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91871. /** Deprecated. Setting this value has no effect.
  91872. *
  91873. * \default \c false
  91874. * \param encoder An encoder instance to set.
  91875. * \param value See above.
  91876. * \assert
  91877. * \code encoder != NULL \endcode
  91878. * \retval FLAC__bool
  91879. * \c false if the encoder is already initialized, else \c true.
  91880. */
  91881. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91882. /** Set to \c false to let the encoder estimate the best model order
  91883. * based on the residual signal energy, or \c true to force the
  91884. * encoder to evaluate all order models and select the best.
  91885. *
  91886. * \default \c false
  91887. * \param encoder An encoder instance to set.
  91888. * \param value See above.
  91889. * \assert
  91890. * \code encoder != NULL \endcode
  91891. * \retval FLAC__bool
  91892. * \c false if the encoder is already initialized, else \c true.
  91893. */
  91894. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91895. /** Set the minimum partition order to search when coding the residual.
  91896. * This is used in tandem with
  91897. * FLAC__stream_encoder_set_max_residual_partition_order().
  91898. *
  91899. * The partition order determines the context size in the residual.
  91900. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91901. *
  91902. * Set both min and max values to \c 0 to force a single context,
  91903. * whose Rice parameter is based on the residual signal variance.
  91904. * Otherwise, set a min and max order, and the encoder will search
  91905. * all orders, using the mean of each context for its Rice parameter,
  91906. * and use the best.
  91907. *
  91908. * \default \c 0
  91909. * \param encoder An encoder instance to set.
  91910. * \param value See above.
  91911. * \assert
  91912. * \code encoder != NULL \endcode
  91913. * \retval FLAC__bool
  91914. * \c false if the encoder is already initialized, else \c true.
  91915. */
  91916. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91917. /** Set the maximum partition order to search when coding the residual.
  91918. * This is used in tandem with
  91919. * FLAC__stream_encoder_set_min_residual_partition_order().
  91920. *
  91921. * The partition order determines the context size in the residual.
  91922. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91923. *
  91924. * Set both min and max values to \c 0 to force a single context,
  91925. * whose Rice parameter is based on the residual signal variance.
  91926. * Otherwise, set a min and max order, and the encoder will search
  91927. * all orders, using the mean of each context for its Rice parameter,
  91928. * and use the best.
  91929. *
  91930. * \default \c 0
  91931. * \param encoder An encoder instance to set.
  91932. * \param value See above.
  91933. * \assert
  91934. * \code encoder != NULL \endcode
  91935. * \retval FLAC__bool
  91936. * \c false if the encoder is already initialized, else \c true.
  91937. */
  91938. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91939. /** Deprecated. Setting this value has no effect.
  91940. *
  91941. * \default \c 0
  91942. * \param encoder An encoder instance to set.
  91943. * \param value See above.
  91944. * \assert
  91945. * \code encoder != NULL \endcode
  91946. * \retval FLAC__bool
  91947. * \c false if the encoder is already initialized, else \c true.
  91948. */
  91949. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91950. /** Set an estimate of the total samples that will be encoded.
  91951. * This is merely an estimate and may be set to \c 0 if unknown.
  91952. * This value will be written to the STREAMINFO block before encoding,
  91953. * and can remove the need for the caller to rewrite the value later
  91954. * if the value is known before encoding.
  91955. *
  91956. * \default \c 0
  91957. * \param encoder An encoder instance to set.
  91958. * \param value See above.
  91959. * \assert
  91960. * \code encoder != NULL \endcode
  91961. * \retval FLAC__bool
  91962. * \c false if the encoder is already initialized, else \c true.
  91963. */
  91964. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91965. /** Set the metadata blocks to be emitted to the stream before encoding.
  91966. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91967. * array of pointers to metadata blocks. The array is non-const since
  91968. * the encoder may need to change the \a is_last flag inside them, and
  91969. * in some cases update seek point offsets. Otherwise, the encoder will
  91970. * not modify or free the blocks. It is up to the caller to free the
  91971. * metadata blocks after encoding finishes.
  91972. *
  91973. * \note
  91974. * The encoder stores only copies of the pointers in the \a metadata array;
  91975. * the metadata blocks themselves must survive at least until after
  91976. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91977. *
  91978. * \note
  91979. * The STREAMINFO block is always written and no STREAMINFO block may
  91980. * occur in the supplied array.
  91981. *
  91982. * \note
  91983. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91984. * in the \a metadata array, but the client has specified that it does not
  91985. * support seeking, then the SEEKTABLE will be written verbatim. However
  91986. * by itself this is not very useful as the client will not know the stream
  91987. * offsets for the seekpoints ahead of time. In order to get a proper
  91988. * seektable the client must support seeking. See next note.
  91989. *
  91990. * \note
  91991. * SEEKTABLE blocks are handled specially. Since you will not know
  91992. * the values for the seek point stream offsets, you should pass in
  91993. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91994. * required sample numbers (or placeholder points), with \c 0 for the
  91995. * \a frame_samples and \a stream_offset fields for each point. If the
  91996. * client has specified that it supports seeking by providing a seek
  91997. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91998. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91999. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  92000. * then while it is encoding the encoder will fill the stream offsets in
  92001. * for you and when encoding is finished, it will seek back and write the
  92002. * real values into the SEEKTABLE block in the stream. There are helper
  92003. * routines for manipulating seektable template blocks; see metadata.h:
  92004. * FLAC__metadata_object_seektable_template_*(). If the client does
  92005. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  92006. * will slow down or remove the ability to seek in the FLAC stream.
  92007. *
  92008. * \note
  92009. * The encoder instance \b will modify the first \c SEEKTABLE block
  92010. * as it transforms the template to a valid seektable while encoding,
  92011. * but it is still up to the caller to free all metadata blocks after
  92012. * encoding.
  92013. *
  92014. * \note
  92015. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  92016. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  92017. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  92018. * will simply write it's own into the stream. If no VORBIS_COMMENT
  92019. * block is present in the \a metadata array, libFLAC will write an
  92020. * empty one, containing only the vendor string.
  92021. *
  92022. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  92023. * the second metadata block of the stream. The encoder already supplies
  92024. * the STREAMINFO block automatically. If \a metadata does not contain a
  92025. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92026. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92027. * first, the init function will reorder \a metadata by moving the
  92028. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92029. * blocks will remain as they were.
  92030. *
  92031. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92032. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92033. * return \c false.
  92034. *
  92035. * \default \c NULL, 0
  92036. * \param encoder An encoder instance to set.
  92037. * \param metadata See above.
  92038. * \param num_blocks See above.
  92039. * \assert
  92040. * \code encoder != NULL \endcode
  92041. * \retval FLAC__bool
  92042. * \c false if the encoder is already initialized, else \c true.
  92043. * \c false if the encoder is already initialized, or if
  92044. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92045. */
  92046. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92047. /** Get the current encoder state.
  92048. *
  92049. * \param encoder An encoder instance to query.
  92050. * \assert
  92051. * \code encoder != NULL \endcode
  92052. * \retval FLAC__StreamEncoderState
  92053. * The current encoder state.
  92054. */
  92055. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92056. /** Get the state of the verify stream decoder.
  92057. * Useful when the stream encoder state is
  92058. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92059. *
  92060. * \param encoder An encoder instance to query.
  92061. * \assert
  92062. * \code encoder != NULL \endcode
  92063. * \retval FLAC__StreamDecoderState
  92064. * The verify stream decoder state.
  92065. */
  92066. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92067. /** Get the current encoder state as a C string.
  92068. * This version automatically resolves
  92069. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92070. * verify decoder's state.
  92071. *
  92072. * \param encoder A encoder instance to query.
  92073. * \assert
  92074. * \code encoder != NULL \endcode
  92075. * \retval const char *
  92076. * The encoder state as a C string. Do not modify the contents.
  92077. */
  92078. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92079. /** Get relevant values about the nature of a verify decoder error.
  92080. * Useful when the stream encoder state is
  92081. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92082. * be addresses in which the stats will be returned, or NULL if value
  92083. * is not desired.
  92084. *
  92085. * \param encoder An encoder instance to query.
  92086. * \param absolute_sample The absolute sample number of the mismatch.
  92087. * \param frame_number The number of the frame in which the mismatch occurred.
  92088. * \param channel The channel in which the mismatch occurred.
  92089. * \param sample The number of the sample (relative to the frame) in
  92090. * which the mismatch occurred.
  92091. * \param expected The expected value for the sample in question.
  92092. * \param got The actual value returned by the decoder.
  92093. * \assert
  92094. * \code encoder != NULL \endcode
  92095. */
  92096. 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);
  92097. /** Get the "verify" flag.
  92098. *
  92099. * \param encoder An encoder instance to query.
  92100. * \assert
  92101. * \code encoder != NULL \endcode
  92102. * \retval FLAC__bool
  92103. * See FLAC__stream_encoder_set_verify().
  92104. */
  92105. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92106. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92107. *
  92108. * \param encoder An encoder instance to query.
  92109. * \assert
  92110. * \code encoder != NULL \endcode
  92111. * \retval FLAC__bool
  92112. * See FLAC__stream_encoder_set_streamable_subset().
  92113. */
  92114. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92115. /** Get the number of input channels being processed.
  92116. *
  92117. * \param encoder An encoder instance to query.
  92118. * \assert
  92119. * \code encoder != NULL \endcode
  92120. * \retval unsigned
  92121. * See FLAC__stream_encoder_set_channels().
  92122. */
  92123. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92124. /** Get the input sample resolution setting.
  92125. *
  92126. * \param encoder An encoder instance to query.
  92127. * \assert
  92128. * \code encoder != NULL \endcode
  92129. * \retval unsigned
  92130. * See FLAC__stream_encoder_set_bits_per_sample().
  92131. */
  92132. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92133. /** Get the input sample rate setting.
  92134. *
  92135. * \param encoder An encoder instance to query.
  92136. * \assert
  92137. * \code encoder != NULL \endcode
  92138. * \retval unsigned
  92139. * See FLAC__stream_encoder_set_sample_rate().
  92140. */
  92141. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92142. /** Get the blocksize setting.
  92143. *
  92144. * \param encoder An encoder instance to query.
  92145. * \assert
  92146. * \code encoder != NULL \endcode
  92147. * \retval unsigned
  92148. * See FLAC__stream_encoder_set_blocksize().
  92149. */
  92150. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92151. /** Get the "mid/side stereo coding" flag.
  92152. *
  92153. * \param encoder An encoder instance to query.
  92154. * \assert
  92155. * \code encoder != NULL \endcode
  92156. * \retval FLAC__bool
  92157. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92158. */
  92159. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92160. /** Get the "adaptive mid/side switching" flag.
  92161. *
  92162. * \param encoder An encoder instance to query.
  92163. * \assert
  92164. * \code encoder != NULL \endcode
  92165. * \retval FLAC__bool
  92166. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92167. */
  92168. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92169. /** Get the maximum LPC order setting.
  92170. *
  92171. * \param encoder An encoder instance to query.
  92172. * \assert
  92173. * \code encoder != NULL \endcode
  92174. * \retval unsigned
  92175. * See FLAC__stream_encoder_set_max_lpc_order().
  92176. */
  92177. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92178. /** Get the quantized linear predictor coefficient precision setting.
  92179. *
  92180. * \param encoder An encoder instance to query.
  92181. * \assert
  92182. * \code encoder != NULL \endcode
  92183. * \retval unsigned
  92184. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92185. */
  92186. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92187. /** Get the qlp coefficient precision search flag.
  92188. *
  92189. * \param encoder An encoder instance to query.
  92190. * \assert
  92191. * \code encoder != NULL \endcode
  92192. * \retval FLAC__bool
  92193. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92194. */
  92195. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92196. /** Get the "escape coding" flag.
  92197. *
  92198. * \param encoder An encoder instance to query.
  92199. * \assert
  92200. * \code encoder != NULL \endcode
  92201. * \retval FLAC__bool
  92202. * See FLAC__stream_encoder_set_do_escape_coding().
  92203. */
  92204. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92205. /** Get the exhaustive model search flag.
  92206. *
  92207. * \param encoder An encoder instance to query.
  92208. * \assert
  92209. * \code encoder != NULL \endcode
  92210. * \retval FLAC__bool
  92211. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92212. */
  92213. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92214. /** Get the minimum residual partition order setting.
  92215. *
  92216. * \param encoder An encoder instance to query.
  92217. * \assert
  92218. * \code encoder != NULL \endcode
  92219. * \retval unsigned
  92220. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92221. */
  92222. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92223. /** Get maximum residual partition order setting.
  92224. *
  92225. * \param encoder An encoder instance to query.
  92226. * \assert
  92227. * \code encoder != NULL \endcode
  92228. * \retval unsigned
  92229. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92230. */
  92231. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92232. /** Get the Rice parameter search distance setting.
  92233. *
  92234. * \param encoder An encoder instance to query.
  92235. * \assert
  92236. * \code encoder != NULL \endcode
  92237. * \retval unsigned
  92238. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92239. */
  92240. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92241. /** Get the previously set estimate of the total samples to be encoded.
  92242. * The encoder merely mimics back the value given to
  92243. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92244. * other way of knowing how many samples the client will encode.
  92245. *
  92246. * \param encoder An encoder instance to set.
  92247. * \assert
  92248. * \code encoder != NULL \endcode
  92249. * \retval FLAC__uint64
  92250. * See FLAC__stream_encoder_get_total_samples_estimate().
  92251. */
  92252. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92253. /** Initialize the encoder instance to encode native FLAC streams.
  92254. *
  92255. * This flavor of initialization sets up the encoder to encode to a
  92256. * native FLAC stream. I/O is performed via callbacks to the client.
  92257. * For encoding to a plain file via filename or open \c FILE*,
  92258. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92259. * provide a simpler interface.
  92260. *
  92261. * This function should be called after FLAC__stream_encoder_new() and
  92262. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92263. * or FLAC__stream_encoder_process_interleaved().
  92264. * initialization succeeded.
  92265. *
  92266. * The call to FLAC__stream_encoder_init_stream() currently will also
  92267. * immediately call the write callback several times, once with the \c fLaC
  92268. * signature, and once for each encoded metadata block.
  92269. *
  92270. * \param encoder An uninitialized encoder instance.
  92271. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92272. * pointer must not be \c NULL.
  92273. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92274. * pointer may be \c NULL if seeking is not
  92275. * supported. The encoder uses seeking to go back
  92276. * and write some some stream statistics to the
  92277. * STREAMINFO block; this is recommended but not
  92278. * necessary to create a valid FLAC stream. If
  92279. * \a seek_callback is not \c NULL then a
  92280. * \a tell_callback must also be supplied.
  92281. * Alternatively, a dummy seek callback that just
  92282. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92283. * may also be supplied, all though this is slightly
  92284. * less efficient for the encoder.
  92285. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92286. * pointer may be \c NULL if seeking is not
  92287. * supported. If \a seek_callback is \c NULL then
  92288. * this argument will be ignored. If
  92289. * \a seek_callback is not \c NULL then a
  92290. * \a tell_callback must also be supplied.
  92291. * Alternatively, a dummy tell callback that just
  92292. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92293. * may also be supplied, all though this is slightly
  92294. * less efficient for the encoder.
  92295. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92296. * pointer may be \c NULL if the callback is not
  92297. * desired. If the client provides a seek callback,
  92298. * this function is not necessary as the encoder
  92299. * will automatically seek back and update the
  92300. * STREAMINFO block. It may also be \c NULL if the
  92301. * client does not support seeking, since it will
  92302. * have no way of going back to update the
  92303. * STREAMINFO. However the client can still supply
  92304. * a callback if it would like to know the details
  92305. * from the STREAMINFO.
  92306. * \param client_data This value will be supplied to callbacks in their
  92307. * \a client_data argument.
  92308. * \assert
  92309. * \code encoder != NULL \endcode
  92310. * \retval FLAC__StreamEncoderInitStatus
  92311. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92312. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92313. */
  92314. 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);
  92315. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92316. *
  92317. * This flavor of initialization sets up the encoder to encode to a FLAC
  92318. * stream in an Ogg container. I/O is performed via callbacks to the
  92319. * client. For encoding to a plain file via filename or open \c FILE*,
  92320. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92321. * provide a simpler interface.
  92322. *
  92323. * This function should be called after FLAC__stream_encoder_new() and
  92324. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92325. * or FLAC__stream_encoder_process_interleaved().
  92326. * initialization succeeded.
  92327. *
  92328. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92329. * immediately call the write callback several times to write the metadata
  92330. * packets.
  92331. *
  92332. * \param encoder An uninitialized encoder instance.
  92333. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92334. * pointer must not be \c NULL if \a seek_callback
  92335. * is non-NULL since they are both needed to be
  92336. * able to write data back to the Ogg FLAC stream
  92337. * in the post-encode phase.
  92338. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92339. * pointer must not be \c NULL.
  92340. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92341. * pointer may be \c NULL if seeking is not
  92342. * supported. The encoder uses seeking to go back
  92343. * and write some some stream statistics to the
  92344. * STREAMINFO block; this is recommended but not
  92345. * necessary to create a valid FLAC stream. If
  92346. * \a seek_callback is not \c NULL then a
  92347. * \a tell_callback must also be supplied.
  92348. * Alternatively, a dummy seek callback that just
  92349. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92350. * may also be supplied, all though this is slightly
  92351. * less efficient for the encoder.
  92352. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92353. * pointer may be \c NULL if seeking is not
  92354. * supported. If \a seek_callback is \c NULL then
  92355. * this argument will be ignored. If
  92356. * \a seek_callback is not \c NULL then a
  92357. * \a tell_callback must also be supplied.
  92358. * Alternatively, a dummy tell callback that just
  92359. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92360. * may also be supplied, all though this is slightly
  92361. * less efficient for the encoder.
  92362. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92363. * pointer may be \c NULL if the callback is not
  92364. * desired. If the client provides a seek callback,
  92365. * this function is not necessary as the encoder
  92366. * will automatically seek back and update the
  92367. * STREAMINFO block. It may also be \c NULL if the
  92368. * client does not support seeking, since it will
  92369. * have no way of going back to update the
  92370. * STREAMINFO. However the client can still supply
  92371. * a callback if it would like to know the details
  92372. * from the STREAMINFO.
  92373. * \param client_data This value will be supplied to callbacks in their
  92374. * \a client_data argument.
  92375. * \assert
  92376. * \code encoder != NULL \endcode
  92377. * \retval FLAC__StreamEncoderInitStatus
  92378. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92379. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92380. */
  92381. 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);
  92382. /** Initialize the encoder instance to encode native FLAC files.
  92383. *
  92384. * This flavor of initialization sets up the encoder to encode to a
  92385. * plain native FLAC file. For non-stdio streams, you must use
  92386. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92387. *
  92388. * This function should be called after FLAC__stream_encoder_new() and
  92389. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92390. * or FLAC__stream_encoder_process_interleaved().
  92391. * initialization succeeded.
  92392. *
  92393. * \param encoder An uninitialized encoder instance.
  92394. * \param file An open file. The file should have been opened
  92395. * with mode \c "w+b" and rewound. The file
  92396. * becomes owned by the encoder and should not be
  92397. * manipulated by the client while encoding.
  92398. * Unless \a file is \c stdout, it will be closed
  92399. * when FLAC__stream_encoder_finish() is called.
  92400. * Note however that a proper SEEKTABLE cannot be
  92401. * created when encoding to \c stdout since it is
  92402. * not seekable.
  92403. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92404. * pointer may be \c NULL if the callback is not
  92405. * desired.
  92406. * \param client_data This value will be supplied to callbacks in their
  92407. * \a client_data argument.
  92408. * \assert
  92409. * \code encoder != NULL \endcode
  92410. * \code file != NULL \endcode
  92411. * \retval FLAC__StreamEncoderInitStatus
  92412. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92413. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92414. */
  92415. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92416. /** Initialize the encoder instance to encode Ogg FLAC files.
  92417. *
  92418. * This flavor of initialization sets up the encoder to encode to a
  92419. * plain Ogg FLAC file. For non-stdio streams, you must use
  92420. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92421. *
  92422. * This function should be called after FLAC__stream_encoder_new() and
  92423. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92424. * or FLAC__stream_encoder_process_interleaved().
  92425. * initialization succeeded.
  92426. *
  92427. * \param encoder An uninitialized encoder instance.
  92428. * \param file An open file. The file should have been opened
  92429. * with mode \c "w+b" and rewound. The file
  92430. * becomes owned by the encoder and should not be
  92431. * manipulated by the client while encoding.
  92432. * Unless \a file is \c stdout, it will be closed
  92433. * when FLAC__stream_encoder_finish() is called.
  92434. * Note however that a proper SEEKTABLE cannot be
  92435. * created when encoding to \c stdout since it is
  92436. * not seekable.
  92437. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92438. * pointer may be \c NULL if the callback is not
  92439. * desired.
  92440. * \param client_data This value will be supplied to callbacks in their
  92441. * \a client_data argument.
  92442. * \assert
  92443. * \code encoder != NULL \endcode
  92444. * \code file != NULL \endcode
  92445. * \retval FLAC__StreamEncoderInitStatus
  92446. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92447. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92448. */
  92449. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92450. /** Initialize the encoder instance to encode native FLAC files.
  92451. *
  92452. * This flavor of initialization sets up the encoder to encode to a plain
  92453. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92454. * with Unicode filenames on Windows), you must use
  92455. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92456. * and provide callbacks for the I/O.
  92457. *
  92458. * This function should be called after FLAC__stream_encoder_new() and
  92459. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92460. * or FLAC__stream_encoder_process_interleaved().
  92461. * initialization succeeded.
  92462. *
  92463. * \param encoder An uninitialized encoder instance.
  92464. * \param filename The name of the file to encode to. The file will
  92465. * be opened with fopen(). Use \c NULL to encode to
  92466. * \c stdout. Note however that a proper SEEKTABLE
  92467. * cannot be created when encoding to \c stdout since
  92468. * it is not seekable.
  92469. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92470. * pointer may be \c NULL if the callback is not
  92471. * desired.
  92472. * \param client_data This value will be supplied to callbacks in their
  92473. * \a client_data argument.
  92474. * \assert
  92475. * \code encoder != NULL \endcode
  92476. * \retval FLAC__StreamEncoderInitStatus
  92477. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92478. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92479. */
  92480. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92481. /** Initialize the encoder instance to encode Ogg FLAC files.
  92482. *
  92483. * This flavor of initialization sets up the encoder to encode to a plain
  92484. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92485. * with Unicode filenames on Windows), you must use
  92486. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92487. * and provide callbacks for the I/O.
  92488. *
  92489. * This function should be called after FLAC__stream_encoder_new() and
  92490. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92491. * or FLAC__stream_encoder_process_interleaved().
  92492. * initialization succeeded.
  92493. *
  92494. * \param encoder An uninitialized encoder instance.
  92495. * \param filename The name of the file to encode to. The file will
  92496. * be opened with fopen(). Use \c NULL to encode to
  92497. * \c stdout. Note however that a proper SEEKTABLE
  92498. * cannot be created when encoding to \c stdout since
  92499. * it is not seekable.
  92500. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92501. * pointer may be \c NULL if the callback is not
  92502. * desired.
  92503. * \param client_data This value will be supplied to callbacks in their
  92504. * \a client_data argument.
  92505. * \assert
  92506. * \code encoder != NULL \endcode
  92507. * \retval FLAC__StreamEncoderInitStatus
  92508. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92509. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92510. */
  92511. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92512. /** Finish the encoding process.
  92513. * Flushes the encoding buffer, releases resources, resets the encoder
  92514. * settings to their defaults, and returns the encoder state to
  92515. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92516. * one or more write callbacks before returning, and will generate
  92517. * a metadata callback.
  92518. *
  92519. * Note that in the course of processing the last frame, errors can
  92520. * occur, so the caller should be sure to check the return value to
  92521. * ensure the file was encoded properly.
  92522. *
  92523. * In the event of a prematurely-terminated encode, it is not strictly
  92524. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92525. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92526. * with a FLAC__stream_encoder_finish().
  92527. *
  92528. * \param encoder An uninitialized encoder instance.
  92529. * \assert
  92530. * \code encoder != NULL \endcode
  92531. * \retval FLAC__bool
  92532. * \c false if an error occurred processing the last frame; or if verify
  92533. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92534. * verify mismatch; else \c true. If \c false, caller should check the
  92535. * state with FLAC__stream_encoder_get_state() for more information
  92536. * about the error.
  92537. */
  92538. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92539. /** Submit data for encoding.
  92540. * This version allows you to supply the input data via an array of
  92541. * pointers, each pointer pointing to an array of \a samples samples
  92542. * representing one channel. The samples need not be block-aligned,
  92543. * but each channel should have the same number of samples. Each sample
  92544. * should be a signed integer, right-justified to the resolution set by
  92545. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92546. * resolution is 16 bits per sample, the samples should all be in the
  92547. * range [-32768,32767].
  92548. *
  92549. * For applications where channel order is important, channels must
  92550. * follow the order as described in the
  92551. * <A HREF="../format.html#frame_header">frame header</A>.
  92552. *
  92553. * \param encoder An initialized encoder instance in the OK state.
  92554. * \param buffer An array of pointers to each channel's signal.
  92555. * \param samples The number of samples in one channel.
  92556. * \assert
  92557. * \code encoder != NULL \endcode
  92558. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92559. * \retval FLAC__bool
  92560. * \c true if successful, else \c false; in this case, check the
  92561. * encoder state with FLAC__stream_encoder_get_state() to see what
  92562. * went wrong.
  92563. */
  92564. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92565. /** Submit data for encoding.
  92566. * This version allows you to supply the input data where the channels
  92567. * are interleaved into a single array (i.e. channel0_sample0,
  92568. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92569. * The samples need not be block-aligned but they must be
  92570. * sample-aligned, i.e. the first value should be channel0_sample0
  92571. * and the last value channelN_sampleM. Each sample should be a signed
  92572. * integer, right-justified to the resolution set by
  92573. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92574. * resolution is 16 bits per sample, the samples should all be in the
  92575. * range [-32768,32767].
  92576. *
  92577. * For applications where channel order is important, channels must
  92578. * follow the order as described in the
  92579. * <A HREF="../format.html#frame_header">frame header</A>.
  92580. *
  92581. * \param encoder An initialized encoder instance in the OK state.
  92582. * \param buffer An array of channel-interleaved data (see above).
  92583. * \param samples The number of samples in one channel, the same as for
  92584. * FLAC__stream_encoder_process(). For example, if
  92585. * encoding two channels, \c 1000 \a samples corresponds
  92586. * to a \a buffer of 2000 values.
  92587. * \assert
  92588. * \code encoder != NULL \endcode
  92589. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92590. * \retval FLAC__bool
  92591. * \c true if successful, else \c false; in this case, check the
  92592. * encoder state with FLAC__stream_encoder_get_state() to see what
  92593. * went wrong.
  92594. */
  92595. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92596. /* \} */
  92597. #ifdef __cplusplus
  92598. }
  92599. #endif
  92600. #endif
  92601. /*** End of inlined file: stream_encoder.h ***/
  92602. #ifdef _MSC_VER
  92603. /* OPT: an MSVC built-in would be better */
  92604. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92605. {
  92606. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92607. return (x>>16) | (x<<16);
  92608. }
  92609. #endif
  92610. #if defined(_MSC_VER) && defined(_X86_)
  92611. /* OPT: an MSVC built-in would be better */
  92612. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92613. {
  92614. __asm {
  92615. mov edx, start
  92616. mov ecx, len
  92617. test ecx, ecx
  92618. loop1:
  92619. jz done1
  92620. mov eax, [edx]
  92621. bswap eax
  92622. mov [edx], eax
  92623. add edx, 4
  92624. dec ecx
  92625. jmp short loop1
  92626. done1:
  92627. }
  92628. }
  92629. #endif
  92630. /** \mainpage
  92631. *
  92632. * \section intro Introduction
  92633. *
  92634. * This is the documentation for the FLAC C and C++ APIs. It is
  92635. * highly interconnected; this introduction should give you a top
  92636. * level idea of the structure and how to find the information you
  92637. * need. As a prerequisite you should have at least a basic
  92638. * knowledge of the FLAC format, documented
  92639. * <A HREF="../format.html">here</A>.
  92640. *
  92641. * \section c_api FLAC C API
  92642. *
  92643. * The FLAC C API is the interface to libFLAC, a set of structures
  92644. * describing the components of FLAC streams, and functions for
  92645. * encoding and decoding streams, as well as manipulating FLAC
  92646. * metadata in files. The public include files will be installed
  92647. * in your include area (for example /usr/include/FLAC/...).
  92648. *
  92649. * By writing a little code and linking against libFLAC, it is
  92650. * relatively easy to add FLAC support to another program. The
  92651. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92652. * Complete source code of libFLAC as well as the command-line
  92653. * encoder and plugins is available and is a useful source of
  92654. * examples.
  92655. *
  92656. * Aside from encoders and decoders, libFLAC provides a powerful
  92657. * metadata interface for manipulating metadata in FLAC files. It
  92658. * allows the user to add, delete, and modify FLAC metadata blocks
  92659. * and it can automatically take advantage of PADDING blocks to avoid
  92660. * rewriting the entire FLAC file when changing the size of the
  92661. * metadata.
  92662. *
  92663. * libFLAC usually only requires the standard C library and C math
  92664. * library. In particular, threading is not used so there is no
  92665. * dependency on a thread library. However, libFLAC does not use
  92666. * global variables and should be thread-safe.
  92667. *
  92668. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92669. * However the metadata editing interfaces currently have limited
  92670. * read-only support for Ogg FLAC files.
  92671. *
  92672. * \section cpp_api FLAC C++ API
  92673. *
  92674. * The FLAC C++ API is a set of classes that encapsulate the
  92675. * structures and functions in libFLAC. They provide slightly more
  92676. * functionality with respect to metadata but are otherwise
  92677. * equivalent. For the most part, they share the same usage as
  92678. * their counterparts in libFLAC, and the FLAC C API documentation
  92679. * can be used as a supplement. The public include files
  92680. * for the C++ API will be installed in your include area (for
  92681. * example /usr/include/FLAC++/...).
  92682. *
  92683. * libFLAC++ is also licensed under
  92684. * <A HREF="../license.html">Xiph's BSD license</A>.
  92685. *
  92686. * \section getting_started Getting Started
  92687. *
  92688. * A good starting point for learning the API is to browse through
  92689. * the <A HREF="modules.html">modules</A>. Modules are logical
  92690. * groupings of related functions or classes, which correspond roughly
  92691. * to header files or sections of header files. Each module includes a
  92692. * detailed description of the general usage of its functions or
  92693. * classes.
  92694. *
  92695. * From there you can go on to look at the documentation of
  92696. * individual functions. You can see different views of the individual
  92697. * functions through the links in top bar across this page.
  92698. *
  92699. * If you prefer a more hands-on approach, you can jump right to some
  92700. * <A HREF="../documentation_example_code.html">example code</A>.
  92701. *
  92702. * \section porting_guide Porting Guide
  92703. *
  92704. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92705. * has been introduced which gives detailed instructions on how to
  92706. * port your code to newer versions of FLAC.
  92707. *
  92708. * \section embedded_developers Embedded Developers
  92709. *
  92710. * libFLAC has grown larger over time as more functionality has been
  92711. * included, but much of it may be unnecessary for a particular embedded
  92712. * implementation. Unused parts may be pruned by some simple editing of
  92713. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92714. * metadata interface are all independent from each other.
  92715. *
  92716. * It is easiest to just describe the dependencies:
  92717. *
  92718. * - All modules depend on the \link flac_format Format \endlink module.
  92719. * - The decoders and encoders depend on the bitbuffer.
  92720. * - The decoder is independent of the encoder. The encoder uses the
  92721. * decoder because of the verify feature, but this can be removed if
  92722. * not needed.
  92723. * - Parts of the metadata interface require the stream decoder (but not
  92724. * the encoder).
  92725. * - Ogg support is selectable through the compile time macro
  92726. * \c FLAC__HAS_OGG.
  92727. *
  92728. * For example, if your application only requires the stream decoder, no
  92729. * encoder, and no metadata interface, you can remove the stream encoder
  92730. * and the metadata interface, which will greatly reduce the size of the
  92731. * library.
  92732. *
  92733. * Also, there are several places in the libFLAC code with comments marked
  92734. * with "OPT:" where a #define can be changed to enable code that might be
  92735. * faster on a specific platform. Experimenting with these can yield faster
  92736. * binaries.
  92737. */
  92738. /** \defgroup porting Porting Guide for New Versions
  92739. *
  92740. * This module describes differences in the library interfaces from
  92741. * version to version. It assists in the porting of code that uses
  92742. * the libraries to newer versions of FLAC.
  92743. *
  92744. * One simple facility for making porting easier that has been added
  92745. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92746. * library's includes (e.g. \c include/FLAC/export.h). The
  92747. * \c #defines mirror the libraries'
  92748. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92749. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92750. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92751. * These can be used to support multiple versions of an API during the
  92752. * transition phase, e.g.
  92753. *
  92754. * \code
  92755. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92756. * legacy code
  92757. * #else
  92758. * new code
  92759. * #endif
  92760. * \endcode
  92761. *
  92762. * The the source will work for multiple versions and the legacy code can
  92763. * easily be removed when the transition is complete.
  92764. *
  92765. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92766. * include/FLAC/export.h), which can be used to determine whether or not
  92767. * the library has been compiled with support for Ogg FLAC. This is
  92768. * simpler than trying to call an Ogg init function and catching the
  92769. * error.
  92770. */
  92771. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92772. * \ingroup porting
  92773. *
  92774. * \brief
  92775. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92776. *
  92777. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92778. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92779. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92780. * decoding layers and three encoding layers have been merged into a
  92781. * single stream decoder and stream encoder. That is, the functionality
  92782. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92783. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92784. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92785. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92786. * is there is now a single API that can be used to encode or decode
  92787. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92788. * on both seekable and non-seekable streams.
  92789. *
  92790. * Instead of creating an encoder or decoder of a certain layer, now the
  92791. * client will always create a FLAC__StreamEncoder or
  92792. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92793. * initialization function. For example, for the decoder,
  92794. * FLAC__stream_decoder_init() has been replaced by
  92795. * FLAC__stream_decoder_init_stream(). This init function takes
  92796. * callbacks for the I/O, and the seeking callbacks are optional. This
  92797. * allows the client to use the same object for seekable and
  92798. * non-seekable streams. For decoding a FLAC file directly, the client
  92799. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92800. * and fewer callbacks; most of the other callbacks are supplied
  92801. * internally. For situations where fopen()ing by filename is not
  92802. * possible (e.g. Unicode filenames on Windows) the client can instead
  92803. * open the file itself and supply the FILE* to
  92804. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92805. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92806. * Since the callbacks and client data are now passed to the init
  92807. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92808. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92809. * rest of the calls to the decoder are the same as before.
  92810. *
  92811. * There are counterpart init functions for Ogg FLAC, e.g.
  92812. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92813. * and callbacks are the same as for native FLAC.
  92814. *
  92815. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92816. * been set up like so:
  92817. *
  92818. * \code
  92819. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92820. * if(decoder == NULL) do_something;
  92821. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92822. * [... other settings ...]
  92823. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92824. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92825. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92826. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92827. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92828. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92829. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92830. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92831. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92832. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92833. * \endcode
  92834. *
  92835. * In FLAC 1.1.3 it is like this:
  92836. *
  92837. * \code
  92838. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92839. * if(decoder == NULL) do_something;
  92840. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92841. * [... other settings ...]
  92842. * if(FLAC__stream_decoder_init_stream(
  92843. * decoder,
  92844. * my_read_callback,
  92845. * my_seek_callback, // or NULL
  92846. * my_tell_callback, // or NULL
  92847. * my_length_callback, // or NULL
  92848. * my_eof_callback, // or NULL
  92849. * my_write_callback,
  92850. * my_metadata_callback, // or NULL
  92851. * my_error_callback,
  92852. * my_client_data
  92853. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92854. * \endcode
  92855. *
  92856. * or you could do;
  92857. *
  92858. * \code
  92859. * [...]
  92860. * FILE *file = fopen("somefile.flac","rb");
  92861. * if(file == NULL) do_somthing;
  92862. * if(FLAC__stream_decoder_init_FILE(
  92863. * decoder,
  92864. * file,
  92865. * my_write_callback,
  92866. * my_metadata_callback, // or NULL
  92867. * my_error_callback,
  92868. * my_client_data
  92869. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92870. * \endcode
  92871. *
  92872. * or just:
  92873. *
  92874. * \code
  92875. * [...]
  92876. * if(FLAC__stream_decoder_init_file(
  92877. * decoder,
  92878. * "somefile.flac",
  92879. * my_write_callback,
  92880. * my_metadata_callback, // or NULL
  92881. * my_error_callback,
  92882. * my_client_data
  92883. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92884. * \endcode
  92885. *
  92886. * Another small change to the decoder is in how it handles unparseable
  92887. * streams. Before, when the decoder found an unparseable stream
  92888. * (reserved for when the decoder encounters a stream from a future
  92889. * encoder that it can't parse), it changed the state to
  92890. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92891. * drops sync and calls the error callback with a new error code
  92892. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92893. * more robust. If your error callback does not discriminate on the the
  92894. * error state, your code does not need to be changed.
  92895. *
  92896. * The encoder now has a new setting:
  92897. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92898. * method used to window the data before LPC analysis. You only need to
  92899. * add a call to this function if the default is not suitable. There
  92900. * are also two new convenience functions that may be useful:
  92901. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92902. * FLAC__metadata_get_cuesheet().
  92903. *
  92904. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92905. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92906. * is now \c size_t instead of \c unsigned.
  92907. */
  92908. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92909. * \ingroup porting
  92910. *
  92911. * \brief
  92912. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92913. *
  92914. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92915. * There was a slight change in the implementation of
  92916. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92917. * of the \a metadata array of pointers so the client no longer needs
  92918. * to maintain it after the call. The objects themselves that are
  92919. * pointed to by the array are still not copied though and must be
  92920. * maintained until the call to FLAC__stream_encoder_finish().
  92921. */
  92922. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92923. * \ingroup porting
  92924. *
  92925. * \brief
  92926. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92927. *
  92928. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92929. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92930. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92931. *
  92932. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92933. * has changed to reflect the conversion of one of the reserved bits
  92934. * into active use. It used to be \c 2 and now is \c 1. However the
  92935. * FLAC frame header length has not changed, so to skip the proper
  92936. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92937. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92938. */
  92939. /** \defgroup flac FLAC C API
  92940. *
  92941. * The FLAC C API is the interface to libFLAC, a set of structures
  92942. * describing the components of FLAC streams, and functions for
  92943. * encoding and decoding streams, as well as manipulating FLAC
  92944. * metadata in files.
  92945. *
  92946. * You should start with the format components as all other modules
  92947. * are dependent on it.
  92948. */
  92949. #endif
  92950. /*** End of inlined file: all.h ***/
  92951. /*** Start of inlined file: bitmath.c ***/
  92952. /*** Start of inlined file: juce_FlacHeader.h ***/
  92953. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92954. // tasks..
  92955. #define VERSION "1.2.1"
  92956. #define FLAC__NO_DLL 1
  92957. #if JUCE_MSVC
  92958. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92959. #endif
  92960. #if JUCE_MAC
  92961. #define FLAC__SYS_DARWIN 1
  92962. #endif
  92963. /*** End of inlined file: juce_FlacHeader.h ***/
  92964. #if JUCE_USE_FLAC
  92965. #if HAVE_CONFIG_H
  92966. # include <config.h>
  92967. #endif
  92968. /*** Start of inlined file: bitmath.h ***/
  92969. #ifndef FLAC__PRIVATE__BITMATH_H
  92970. #define FLAC__PRIVATE__BITMATH_H
  92971. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92972. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92973. unsigned FLAC__bitmath_silog2(int v);
  92974. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92975. #endif
  92976. /*** End of inlined file: bitmath.h ***/
  92977. /* An example of what FLAC__bitmath_ilog2() computes:
  92978. *
  92979. * ilog2( 0) = assertion failure
  92980. * ilog2( 1) = 0
  92981. * ilog2( 2) = 1
  92982. * ilog2( 3) = 1
  92983. * ilog2( 4) = 2
  92984. * ilog2( 5) = 2
  92985. * ilog2( 6) = 2
  92986. * ilog2( 7) = 2
  92987. * ilog2( 8) = 3
  92988. * ilog2( 9) = 3
  92989. * ilog2(10) = 3
  92990. * ilog2(11) = 3
  92991. * ilog2(12) = 3
  92992. * ilog2(13) = 3
  92993. * ilog2(14) = 3
  92994. * ilog2(15) = 3
  92995. * ilog2(16) = 4
  92996. * ilog2(17) = 4
  92997. * ilog2(18) = 4
  92998. */
  92999. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  93000. {
  93001. unsigned l = 0;
  93002. FLAC__ASSERT(v > 0);
  93003. while(v >>= 1)
  93004. l++;
  93005. return l;
  93006. }
  93007. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  93008. {
  93009. unsigned l = 0;
  93010. FLAC__ASSERT(v > 0);
  93011. while(v >>= 1)
  93012. l++;
  93013. return l;
  93014. }
  93015. /* An example of what FLAC__bitmath_silog2() computes:
  93016. *
  93017. * silog2(-10) = 5
  93018. * silog2(- 9) = 5
  93019. * silog2(- 8) = 4
  93020. * silog2(- 7) = 4
  93021. * silog2(- 6) = 4
  93022. * silog2(- 5) = 4
  93023. * silog2(- 4) = 3
  93024. * silog2(- 3) = 3
  93025. * silog2(- 2) = 2
  93026. * silog2(- 1) = 2
  93027. * silog2( 0) = 0
  93028. * silog2( 1) = 2
  93029. * silog2( 2) = 3
  93030. * silog2( 3) = 3
  93031. * silog2( 4) = 4
  93032. * silog2( 5) = 4
  93033. * silog2( 6) = 4
  93034. * silog2( 7) = 4
  93035. * silog2( 8) = 5
  93036. * silog2( 9) = 5
  93037. * silog2( 10) = 5
  93038. */
  93039. unsigned FLAC__bitmath_silog2(int v)
  93040. {
  93041. while(1) {
  93042. if(v == 0) {
  93043. return 0;
  93044. }
  93045. else if(v > 0) {
  93046. unsigned l = 0;
  93047. while(v) {
  93048. l++;
  93049. v >>= 1;
  93050. }
  93051. return l+1;
  93052. }
  93053. else if(v == -1) {
  93054. return 2;
  93055. }
  93056. else {
  93057. v++;
  93058. v = -v;
  93059. }
  93060. }
  93061. }
  93062. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93063. {
  93064. while(1) {
  93065. if(v == 0) {
  93066. return 0;
  93067. }
  93068. else if(v > 0) {
  93069. unsigned l = 0;
  93070. while(v) {
  93071. l++;
  93072. v >>= 1;
  93073. }
  93074. return l+1;
  93075. }
  93076. else if(v == -1) {
  93077. return 2;
  93078. }
  93079. else {
  93080. v++;
  93081. v = -v;
  93082. }
  93083. }
  93084. }
  93085. #endif
  93086. /*** End of inlined file: bitmath.c ***/
  93087. /*** Start of inlined file: bitreader.c ***/
  93088. /*** Start of inlined file: juce_FlacHeader.h ***/
  93089. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93090. // tasks..
  93091. #define VERSION "1.2.1"
  93092. #define FLAC__NO_DLL 1
  93093. #if JUCE_MSVC
  93094. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93095. #endif
  93096. #if JUCE_MAC
  93097. #define FLAC__SYS_DARWIN 1
  93098. #endif
  93099. /*** End of inlined file: juce_FlacHeader.h ***/
  93100. #if JUCE_USE_FLAC
  93101. #if HAVE_CONFIG_H
  93102. # include <config.h>
  93103. #endif
  93104. #include <stdlib.h> /* for malloc() */
  93105. #include <string.h> /* for memcpy(), memset() */
  93106. #ifdef _MSC_VER
  93107. #include <winsock.h> /* for ntohl() */
  93108. #elif defined FLAC__SYS_DARWIN
  93109. #include <machine/endian.h> /* for ntohl() */
  93110. #elif defined __MINGW32__
  93111. #include <winsock.h> /* for ntohl() */
  93112. #else
  93113. #include <netinet/in.h> /* for ntohl() */
  93114. #endif
  93115. /*** Start of inlined file: bitreader.h ***/
  93116. #ifndef FLAC__PRIVATE__BITREADER_H
  93117. #define FLAC__PRIVATE__BITREADER_H
  93118. #include <stdio.h> /* for FILE */
  93119. /*** Start of inlined file: cpu.h ***/
  93120. #ifndef FLAC__PRIVATE__CPU_H
  93121. #define FLAC__PRIVATE__CPU_H
  93122. #ifdef HAVE_CONFIG_H
  93123. #include <config.h>
  93124. #endif
  93125. typedef enum {
  93126. FLAC__CPUINFO_TYPE_IA32,
  93127. FLAC__CPUINFO_TYPE_PPC,
  93128. FLAC__CPUINFO_TYPE_UNKNOWN
  93129. } FLAC__CPUInfo_Type;
  93130. typedef struct {
  93131. FLAC__bool cpuid;
  93132. FLAC__bool bswap;
  93133. FLAC__bool cmov;
  93134. FLAC__bool mmx;
  93135. FLAC__bool fxsr;
  93136. FLAC__bool sse;
  93137. FLAC__bool sse2;
  93138. FLAC__bool sse3;
  93139. FLAC__bool ssse3;
  93140. FLAC__bool _3dnow;
  93141. FLAC__bool ext3dnow;
  93142. FLAC__bool extmmx;
  93143. } FLAC__CPUInfo_IA32;
  93144. typedef struct {
  93145. FLAC__bool altivec;
  93146. FLAC__bool ppc64;
  93147. } FLAC__CPUInfo_PPC;
  93148. typedef struct {
  93149. FLAC__bool use_asm;
  93150. FLAC__CPUInfo_Type type;
  93151. union {
  93152. FLAC__CPUInfo_IA32 ia32;
  93153. FLAC__CPUInfo_PPC ppc;
  93154. } data;
  93155. } FLAC__CPUInfo;
  93156. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93157. #ifndef FLAC__NO_ASM
  93158. #ifdef FLAC__CPU_IA32
  93159. #ifdef FLAC__HAS_NASM
  93160. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93161. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93162. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93163. #endif
  93164. #endif
  93165. #endif
  93166. #endif
  93167. /*** End of inlined file: cpu.h ***/
  93168. /*
  93169. * opaque structure definition
  93170. */
  93171. struct FLAC__BitReader;
  93172. typedef struct FLAC__BitReader FLAC__BitReader;
  93173. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93174. /*
  93175. * construction, deletion, initialization, etc functions
  93176. */
  93177. FLAC__BitReader *FLAC__bitreader_new(void);
  93178. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93179. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93180. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93181. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93182. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93183. /*
  93184. * CRC functions
  93185. */
  93186. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93187. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93188. /*
  93189. * info functions
  93190. */
  93191. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93192. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93193. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93194. /*
  93195. * read functions
  93196. */
  93197. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93198. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93199. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93200. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93201. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93202. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93203. 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! */
  93204. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93205. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93206. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93207. #ifndef FLAC__NO_ASM
  93208. # ifdef FLAC__CPU_IA32
  93209. # ifdef FLAC__HAS_NASM
  93210. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93211. # endif
  93212. # endif
  93213. #endif
  93214. #if 0 /* UNUSED */
  93215. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93216. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93217. #endif
  93218. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93219. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93220. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93221. #endif
  93222. /*** End of inlined file: bitreader.h ***/
  93223. /*** Start of inlined file: crc.h ***/
  93224. #ifndef FLAC__PRIVATE__CRC_H
  93225. #define FLAC__PRIVATE__CRC_H
  93226. /* 8 bit CRC generator, MSB shifted first
  93227. ** polynomial = x^8 + x^2 + x^1 + x^0
  93228. ** init = 0
  93229. */
  93230. extern FLAC__byte const FLAC__crc8_table[256];
  93231. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93232. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93233. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93234. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93235. /* 16 bit CRC generator, MSB shifted first
  93236. ** polynomial = x^16 + x^15 + x^2 + x^0
  93237. ** init = 0
  93238. */
  93239. extern unsigned FLAC__crc16_table[256];
  93240. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93241. /* this alternate may be faster on some systems/compilers */
  93242. #if 0
  93243. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93244. #endif
  93245. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93246. #endif
  93247. /*** End of inlined file: crc.h ***/
  93248. /* Things should be fastest when this matches the machine word size */
  93249. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93250. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93251. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93252. typedef FLAC__uint32 brword;
  93253. #define FLAC__BYTES_PER_WORD 4
  93254. #define FLAC__BITS_PER_WORD 32
  93255. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93256. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93257. #if WORDS_BIGENDIAN
  93258. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93259. #else
  93260. #if defined (_MSC_VER) && defined (_X86_)
  93261. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93262. #else
  93263. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93264. #endif
  93265. #endif
  93266. /* counts the # of zero MSBs in a word */
  93267. #define COUNT_ZERO_MSBS(word) ( \
  93268. (word) <= 0xffff ? \
  93269. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93270. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93271. )
  93272. /* this alternate might be slightly faster on some systems/compilers: */
  93273. #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])) )
  93274. /*
  93275. * This should be at least twice as large as the largest number of words
  93276. * required to represent any 'number' (in any encoding) you are going to
  93277. * read. With FLAC this is on the order of maybe a few hundred bits.
  93278. * If the buffer is smaller than that, the decoder won't be able to read
  93279. * in a whole number that is in a variable length encoding (e.g. Rice).
  93280. * But to be practical it should be at least 1K bytes.
  93281. *
  93282. * Increase this number to decrease the number of read callbacks, at the
  93283. * expense of using more memory. Or decrease for the reverse effect,
  93284. * keeping in mind the limit from the first paragraph. The optimal size
  93285. * also depends on the CPU cache size and other factors; some twiddling
  93286. * may be necessary to squeeze out the best performance.
  93287. */
  93288. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93289. static const unsigned char byte_to_unary_table[] = {
  93290. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93291. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93292. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93293. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93294. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93295. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93296. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93297. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93306. };
  93307. #ifdef min
  93308. #undef min
  93309. #endif
  93310. #define min(x,y) ((x)<(y)?(x):(y))
  93311. #ifdef max
  93312. #undef max
  93313. #endif
  93314. #define max(x,y) ((x)>(y)?(x):(y))
  93315. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93316. #ifdef _MSC_VER
  93317. #define FLAC__U64L(x) x
  93318. #else
  93319. #define FLAC__U64L(x) x##LLU
  93320. #endif
  93321. #ifndef FLaC__INLINE
  93322. #define FLaC__INLINE
  93323. #endif
  93324. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93325. struct FLAC__BitReader {
  93326. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93327. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93328. brword *buffer;
  93329. unsigned capacity; /* in words */
  93330. unsigned words; /* # of completed words in buffer */
  93331. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93332. unsigned consumed_words; /* #words ... */
  93333. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93334. unsigned read_crc16; /* the running frame CRC */
  93335. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93336. FLAC__BitReaderReadCallback read_callback;
  93337. void *client_data;
  93338. FLAC__CPUInfo cpu_info;
  93339. };
  93340. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93341. {
  93342. register unsigned crc = br->read_crc16;
  93343. #if FLAC__BYTES_PER_WORD == 4
  93344. switch(br->crc16_align) {
  93345. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93346. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93347. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93348. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93349. }
  93350. #elif FLAC__BYTES_PER_WORD == 8
  93351. switch(br->crc16_align) {
  93352. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93353. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93354. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93355. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93356. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93357. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93358. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93359. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93360. }
  93361. #else
  93362. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93363. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93364. br->read_crc16 = crc;
  93365. #endif
  93366. br->crc16_align = 0;
  93367. }
  93368. /* would be static except it needs to be called by asm routines */
  93369. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93370. {
  93371. unsigned start, end;
  93372. size_t bytes;
  93373. FLAC__byte *target;
  93374. /* first shift the unconsumed buffer data toward the front as much as possible */
  93375. if(br->consumed_words > 0) {
  93376. start = br->consumed_words;
  93377. end = br->words + (br->bytes? 1:0);
  93378. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93379. br->words -= start;
  93380. br->consumed_words = 0;
  93381. }
  93382. /*
  93383. * set the target for reading, taking into account word alignment and endianness
  93384. */
  93385. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93386. if(bytes == 0)
  93387. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93388. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93389. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93390. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93391. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93392. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93393. * ^^-------target, bytes=3
  93394. * on LE machines, have to byteswap the odd tail word so nothing is
  93395. * overwritten:
  93396. */
  93397. #if WORDS_BIGENDIAN
  93398. #else
  93399. if(br->bytes)
  93400. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93401. #endif
  93402. /* now it looks like:
  93403. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93404. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93405. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93406. * ^^-------target, bytes=3
  93407. */
  93408. /* read in the data; note that the callback may return a smaller number of bytes */
  93409. if(!br->read_callback(target, &bytes, br->client_data))
  93410. return false;
  93411. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93412. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93413. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93414. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93415. * now have to byteswap on LE machines:
  93416. */
  93417. #if WORDS_BIGENDIAN
  93418. #else
  93419. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93420. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93421. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93422. start = br->words;
  93423. local_swap32_block_(br->buffer + start, end - start);
  93424. }
  93425. else
  93426. # endif
  93427. for(start = br->words; start < end; start++)
  93428. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93429. #endif
  93430. /* now it looks like:
  93431. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93432. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93433. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93434. * finally we'll update the reader values:
  93435. */
  93436. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93437. br->words = end / FLAC__BYTES_PER_WORD;
  93438. br->bytes = end % FLAC__BYTES_PER_WORD;
  93439. return true;
  93440. }
  93441. /***********************************************************************
  93442. *
  93443. * Class constructor/destructor
  93444. *
  93445. ***********************************************************************/
  93446. FLAC__BitReader *FLAC__bitreader_new(void)
  93447. {
  93448. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93449. /* calloc() implies:
  93450. memset(br, 0, sizeof(FLAC__BitReader));
  93451. br->buffer = 0;
  93452. br->capacity = 0;
  93453. br->words = br->bytes = 0;
  93454. br->consumed_words = br->consumed_bits = 0;
  93455. br->read_callback = 0;
  93456. br->client_data = 0;
  93457. */
  93458. return br;
  93459. }
  93460. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93461. {
  93462. FLAC__ASSERT(0 != br);
  93463. FLAC__bitreader_free(br);
  93464. free(br);
  93465. }
  93466. /***********************************************************************
  93467. *
  93468. * Public class methods
  93469. *
  93470. ***********************************************************************/
  93471. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93472. {
  93473. FLAC__ASSERT(0 != br);
  93474. br->words = br->bytes = 0;
  93475. br->consumed_words = br->consumed_bits = 0;
  93476. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93477. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93478. if(br->buffer == 0)
  93479. return false;
  93480. br->read_callback = rcb;
  93481. br->client_data = cd;
  93482. br->cpu_info = cpu;
  93483. return true;
  93484. }
  93485. void FLAC__bitreader_free(FLAC__BitReader *br)
  93486. {
  93487. FLAC__ASSERT(0 != br);
  93488. if(0 != br->buffer)
  93489. free(br->buffer);
  93490. br->buffer = 0;
  93491. br->capacity = 0;
  93492. br->words = br->bytes = 0;
  93493. br->consumed_words = br->consumed_bits = 0;
  93494. br->read_callback = 0;
  93495. br->client_data = 0;
  93496. }
  93497. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93498. {
  93499. br->words = br->bytes = 0;
  93500. br->consumed_words = br->consumed_bits = 0;
  93501. return true;
  93502. }
  93503. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93504. {
  93505. unsigned i, j;
  93506. if(br == 0) {
  93507. fprintf(out, "bitreader is NULL\n");
  93508. }
  93509. else {
  93510. 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);
  93511. for(i = 0; i < br->words; i++) {
  93512. fprintf(out, "%08X: ", i);
  93513. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93514. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93515. fprintf(out, ".");
  93516. else
  93517. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93518. fprintf(out, "\n");
  93519. }
  93520. if(br->bytes > 0) {
  93521. fprintf(out, "%08X: ", i);
  93522. for(j = 0; j < br->bytes*8; j++)
  93523. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93524. fprintf(out, ".");
  93525. else
  93526. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93527. fprintf(out, "\n");
  93528. }
  93529. }
  93530. }
  93531. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93532. {
  93533. FLAC__ASSERT(0 != br);
  93534. FLAC__ASSERT(0 != br->buffer);
  93535. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93536. br->read_crc16 = (unsigned)seed;
  93537. br->crc16_align = br->consumed_bits;
  93538. }
  93539. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93540. {
  93541. FLAC__ASSERT(0 != br);
  93542. FLAC__ASSERT(0 != br->buffer);
  93543. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93544. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93545. /* CRC any tail bytes in a partially-consumed word */
  93546. if(br->consumed_bits) {
  93547. const brword tail = br->buffer[br->consumed_words];
  93548. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93549. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93550. }
  93551. return br->read_crc16;
  93552. }
  93553. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93554. {
  93555. return ((br->consumed_bits & 7) == 0);
  93556. }
  93557. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93558. {
  93559. return 8 - (br->consumed_bits & 7);
  93560. }
  93561. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93562. {
  93563. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93564. }
  93565. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93566. {
  93567. FLAC__ASSERT(0 != br);
  93568. FLAC__ASSERT(0 != br->buffer);
  93569. FLAC__ASSERT(bits <= 32);
  93570. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93571. FLAC__ASSERT(br->consumed_words <= br->words);
  93572. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93573. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93574. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93575. *val = 0;
  93576. return true;
  93577. }
  93578. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93579. if(!bitreader_read_from_client_(br))
  93580. return false;
  93581. }
  93582. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93583. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93584. if(br->consumed_bits) {
  93585. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93586. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93587. const brword word = br->buffer[br->consumed_words];
  93588. if(bits < n) {
  93589. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93590. br->consumed_bits += bits;
  93591. return true;
  93592. }
  93593. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93594. bits -= n;
  93595. crc16_update_word_(br, word);
  93596. br->consumed_words++;
  93597. br->consumed_bits = 0;
  93598. 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 */
  93599. *val <<= bits;
  93600. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93601. br->consumed_bits = bits;
  93602. }
  93603. return true;
  93604. }
  93605. else {
  93606. const brword word = br->buffer[br->consumed_words];
  93607. if(bits < FLAC__BITS_PER_WORD) {
  93608. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93609. br->consumed_bits = bits;
  93610. return true;
  93611. }
  93612. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93613. *val = word;
  93614. crc16_update_word_(br, word);
  93615. br->consumed_words++;
  93616. return true;
  93617. }
  93618. }
  93619. else {
  93620. /* in this case we're starting our read at a partial tail word;
  93621. * the reader has guaranteed that we have at least 'bits' bits
  93622. * available to read, which makes this case simpler.
  93623. */
  93624. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93625. if(br->consumed_bits) {
  93626. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93627. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93628. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93629. br->consumed_bits += bits;
  93630. return true;
  93631. }
  93632. else {
  93633. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93634. br->consumed_bits += bits;
  93635. return true;
  93636. }
  93637. }
  93638. }
  93639. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93640. {
  93641. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93642. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93643. return false;
  93644. /* sign-extend: */
  93645. *val <<= (32-bits);
  93646. *val >>= (32-bits);
  93647. return true;
  93648. }
  93649. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93650. {
  93651. FLAC__uint32 hi, lo;
  93652. if(bits > 32) {
  93653. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93654. return false;
  93655. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93656. return false;
  93657. *val = hi;
  93658. *val <<= 32;
  93659. *val |= lo;
  93660. }
  93661. else {
  93662. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93663. return false;
  93664. *val = lo;
  93665. }
  93666. return true;
  93667. }
  93668. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93669. {
  93670. FLAC__uint32 x8, x32 = 0;
  93671. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93672. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93673. return false;
  93674. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93675. return false;
  93676. x32 |= (x8 << 8);
  93677. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93678. return false;
  93679. x32 |= (x8 << 16);
  93680. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93681. return false;
  93682. x32 |= (x8 << 24);
  93683. *val = x32;
  93684. return true;
  93685. }
  93686. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93687. {
  93688. /*
  93689. * OPT: a faster implementation is possible but probably not that useful
  93690. * since this is only called a couple of times in the metadata readers.
  93691. */
  93692. FLAC__ASSERT(0 != br);
  93693. FLAC__ASSERT(0 != br->buffer);
  93694. if(bits > 0) {
  93695. const unsigned n = br->consumed_bits & 7;
  93696. unsigned m;
  93697. FLAC__uint32 x;
  93698. if(n != 0) {
  93699. m = min(8-n, bits);
  93700. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93701. return false;
  93702. bits -= m;
  93703. }
  93704. m = bits / 8;
  93705. if(m > 0) {
  93706. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93707. return false;
  93708. bits %= 8;
  93709. }
  93710. if(bits > 0) {
  93711. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93712. return false;
  93713. }
  93714. }
  93715. return true;
  93716. }
  93717. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93718. {
  93719. FLAC__uint32 x;
  93720. FLAC__ASSERT(0 != br);
  93721. FLAC__ASSERT(0 != br->buffer);
  93722. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93723. /* step 1: skip over partial head word to get word aligned */
  93724. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93725. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93726. return false;
  93727. nvals--;
  93728. }
  93729. if(0 == nvals)
  93730. return true;
  93731. /* step 2: skip whole words in chunks */
  93732. while(nvals >= FLAC__BYTES_PER_WORD) {
  93733. if(br->consumed_words < br->words) {
  93734. br->consumed_words++;
  93735. nvals -= FLAC__BYTES_PER_WORD;
  93736. }
  93737. else if(!bitreader_read_from_client_(br))
  93738. return false;
  93739. }
  93740. /* step 3: skip any remainder from partial tail bytes */
  93741. while(nvals) {
  93742. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93743. return false;
  93744. nvals--;
  93745. }
  93746. return true;
  93747. }
  93748. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93749. {
  93750. FLAC__uint32 x;
  93751. FLAC__ASSERT(0 != br);
  93752. FLAC__ASSERT(0 != br->buffer);
  93753. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93754. /* step 1: read from partial head word to get word aligned */
  93755. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93756. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93757. return false;
  93758. *val++ = (FLAC__byte)x;
  93759. nvals--;
  93760. }
  93761. if(0 == nvals)
  93762. return true;
  93763. /* step 2: read whole words in chunks */
  93764. while(nvals >= FLAC__BYTES_PER_WORD) {
  93765. if(br->consumed_words < br->words) {
  93766. const brword word = br->buffer[br->consumed_words++];
  93767. #if FLAC__BYTES_PER_WORD == 4
  93768. val[0] = (FLAC__byte)(word >> 24);
  93769. val[1] = (FLAC__byte)(word >> 16);
  93770. val[2] = (FLAC__byte)(word >> 8);
  93771. val[3] = (FLAC__byte)word;
  93772. #elif FLAC__BYTES_PER_WORD == 8
  93773. val[0] = (FLAC__byte)(word >> 56);
  93774. val[1] = (FLAC__byte)(word >> 48);
  93775. val[2] = (FLAC__byte)(word >> 40);
  93776. val[3] = (FLAC__byte)(word >> 32);
  93777. val[4] = (FLAC__byte)(word >> 24);
  93778. val[5] = (FLAC__byte)(word >> 16);
  93779. val[6] = (FLAC__byte)(word >> 8);
  93780. val[7] = (FLAC__byte)word;
  93781. #else
  93782. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93783. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93784. #endif
  93785. val += FLAC__BYTES_PER_WORD;
  93786. nvals -= FLAC__BYTES_PER_WORD;
  93787. }
  93788. else if(!bitreader_read_from_client_(br))
  93789. return false;
  93790. }
  93791. /* step 3: read any remainder from partial tail bytes */
  93792. while(nvals) {
  93793. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93794. return false;
  93795. *val++ = (FLAC__byte)x;
  93796. nvals--;
  93797. }
  93798. return true;
  93799. }
  93800. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93801. #if 0 /* slow but readable version */
  93802. {
  93803. unsigned bit;
  93804. FLAC__ASSERT(0 != br);
  93805. FLAC__ASSERT(0 != br->buffer);
  93806. *val = 0;
  93807. while(1) {
  93808. if(!FLAC__bitreader_read_bit(br, &bit))
  93809. return false;
  93810. if(bit)
  93811. break;
  93812. else
  93813. *val++;
  93814. }
  93815. return true;
  93816. }
  93817. #else
  93818. {
  93819. unsigned i;
  93820. FLAC__ASSERT(0 != br);
  93821. FLAC__ASSERT(0 != br->buffer);
  93822. *val = 0;
  93823. while(1) {
  93824. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93825. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93826. if(b) {
  93827. i = COUNT_ZERO_MSBS(b);
  93828. *val += i;
  93829. i++;
  93830. br->consumed_bits += i;
  93831. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93832. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93833. br->consumed_words++;
  93834. br->consumed_bits = 0;
  93835. }
  93836. return true;
  93837. }
  93838. else {
  93839. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93840. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93841. br->consumed_words++;
  93842. br->consumed_bits = 0;
  93843. /* didn't find stop bit yet, have to keep going... */
  93844. }
  93845. }
  93846. /* at this point we've eaten up all the whole words; have to try
  93847. * reading through any tail bytes before calling the read callback.
  93848. * this is a repeat of the above logic adjusted for the fact we
  93849. * don't have a whole word. note though if the client is feeding
  93850. * us data a byte at a time (unlikely), br->consumed_bits may not
  93851. * be zero.
  93852. */
  93853. if(br->bytes) {
  93854. const unsigned end = br->bytes * 8;
  93855. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93856. if(b) {
  93857. i = COUNT_ZERO_MSBS(b);
  93858. *val += i;
  93859. i++;
  93860. br->consumed_bits += i;
  93861. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93862. return true;
  93863. }
  93864. else {
  93865. *val += end - br->consumed_bits;
  93866. br->consumed_bits += end;
  93867. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93868. /* didn't find stop bit yet, have to keep going... */
  93869. }
  93870. }
  93871. if(!bitreader_read_from_client_(br))
  93872. return false;
  93873. }
  93874. }
  93875. #endif
  93876. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93877. {
  93878. FLAC__uint32 lsbs = 0, msbs = 0;
  93879. unsigned uval;
  93880. FLAC__ASSERT(0 != br);
  93881. FLAC__ASSERT(0 != br->buffer);
  93882. FLAC__ASSERT(parameter <= 31);
  93883. /* read the unary MSBs and end bit */
  93884. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93885. return false;
  93886. /* read the binary LSBs */
  93887. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93888. return false;
  93889. /* compose the value */
  93890. uval = (msbs << parameter) | lsbs;
  93891. if(uval & 1)
  93892. *val = -((int)(uval >> 1)) - 1;
  93893. else
  93894. *val = (int)(uval >> 1);
  93895. return true;
  93896. }
  93897. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93898. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93899. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93900. /* OPT: possibly faster version for use with MSVC */
  93901. #ifdef _MSC_VER
  93902. {
  93903. unsigned i;
  93904. unsigned uval = 0;
  93905. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93906. /* try and get br->consumed_words and br->consumed_bits into register;
  93907. * must remember to flush them back to *br before calling other
  93908. * bitwriter functions that use them, and before returning */
  93909. register unsigned cwords;
  93910. register unsigned cbits;
  93911. FLAC__ASSERT(0 != br);
  93912. FLAC__ASSERT(0 != br->buffer);
  93913. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93914. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93915. FLAC__ASSERT(parameter < 32);
  93916. /* 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 */
  93917. if(nvals == 0)
  93918. return true;
  93919. cbits = br->consumed_bits;
  93920. cwords = br->consumed_words;
  93921. while(1) {
  93922. /* read unary part */
  93923. while(1) {
  93924. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93925. brword b = br->buffer[cwords] << cbits;
  93926. if(b) {
  93927. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93928. __asm {
  93929. bsr eax, b
  93930. not eax
  93931. and eax, 31
  93932. mov i, eax
  93933. }
  93934. #else
  93935. i = COUNT_ZERO_MSBS(b);
  93936. #endif
  93937. uval += i;
  93938. bits = parameter;
  93939. i++;
  93940. cbits += i;
  93941. if(cbits == FLAC__BITS_PER_WORD) {
  93942. crc16_update_word_(br, br->buffer[cwords]);
  93943. cwords++;
  93944. cbits = 0;
  93945. }
  93946. goto break1;
  93947. }
  93948. else {
  93949. uval += FLAC__BITS_PER_WORD - cbits;
  93950. crc16_update_word_(br, br->buffer[cwords]);
  93951. cwords++;
  93952. cbits = 0;
  93953. /* didn't find stop bit yet, have to keep going... */
  93954. }
  93955. }
  93956. /* at this point we've eaten up all the whole words; have to try
  93957. * reading through any tail bytes before calling the read callback.
  93958. * this is a repeat of the above logic adjusted for the fact we
  93959. * don't have a whole word. note though if the client is feeding
  93960. * us data a byte at a time (unlikely), br->consumed_bits may not
  93961. * be zero.
  93962. */
  93963. if(br->bytes) {
  93964. const unsigned end = br->bytes * 8;
  93965. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93966. if(b) {
  93967. i = COUNT_ZERO_MSBS(b);
  93968. uval += i;
  93969. bits = parameter;
  93970. i++;
  93971. cbits += i;
  93972. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93973. goto break1;
  93974. }
  93975. else {
  93976. uval += end - cbits;
  93977. cbits += end;
  93978. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93979. /* didn't find stop bit yet, have to keep going... */
  93980. }
  93981. }
  93982. /* flush registers and read; bitreader_read_from_client_() does
  93983. * not touch br->consumed_bits at all but we still need to set
  93984. * it in case it fails and we have to return false.
  93985. */
  93986. br->consumed_bits = cbits;
  93987. br->consumed_words = cwords;
  93988. if(!bitreader_read_from_client_(br))
  93989. return false;
  93990. cwords = br->consumed_words;
  93991. }
  93992. break1:
  93993. /* read binary part */
  93994. FLAC__ASSERT(cwords <= br->words);
  93995. if(bits) {
  93996. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93997. /* flush registers and read; bitreader_read_from_client_() does
  93998. * not touch br->consumed_bits at all but we still need to set
  93999. * it in case it fails and we have to return false.
  94000. */
  94001. br->consumed_bits = cbits;
  94002. br->consumed_words = cwords;
  94003. if(!bitreader_read_from_client_(br))
  94004. return false;
  94005. cwords = br->consumed_words;
  94006. }
  94007. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94008. if(cbits) {
  94009. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94010. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94011. const brword word = br->buffer[cwords];
  94012. if(bits < n) {
  94013. uval <<= bits;
  94014. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  94015. cbits += bits;
  94016. goto break2;
  94017. }
  94018. uval <<= n;
  94019. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94020. bits -= n;
  94021. crc16_update_word_(br, word);
  94022. cwords++;
  94023. cbits = 0;
  94024. 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 */
  94025. uval <<= bits;
  94026. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94027. cbits = bits;
  94028. }
  94029. goto break2;
  94030. }
  94031. else {
  94032. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94033. uval <<= bits;
  94034. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94035. cbits = bits;
  94036. goto break2;
  94037. }
  94038. }
  94039. else {
  94040. /* in this case we're starting our read at a partial tail word;
  94041. * the reader has guaranteed that we have at least 'bits' bits
  94042. * available to read, which makes this case simpler.
  94043. */
  94044. uval <<= bits;
  94045. if(cbits) {
  94046. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94047. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94048. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94049. cbits += bits;
  94050. goto break2;
  94051. }
  94052. else {
  94053. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94054. cbits += bits;
  94055. goto break2;
  94056. }
  94057. }
  94058. }
  94059. break2:
  94060. /* compose the value */
  94061. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94062. /* are we done? */
  94063. --nvals;
  94064. if(nvals == 0) {
  94065. br->consumed_bits = cbits;
  94066. br->consumed_words = cwords;
  94067. return true;
  94068. }
  94069. uval = 0;
  94070. ++vals;
  94071. }
  94072. }
  94073. #else
  94074. {
  94075. unsigned i;
  94076. unsigned uval = 0;
  94077. /* try and get br->consumed_words and br->consumed_bits into register;
  94078. * must remember to flush them back to *br before calling other
  94079. * bitwriter functions that use them, and before returning */
  94080. register unsigned cwords;
  94081. register unsigned cbits;
  94082. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94083. FLAC__ASSERT(0 != br);
  94084. FLAC__ASSERT(0 != br->buffer);
  94085. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94086. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94087. FLAC__ASSERT(parameter < 32);
  94088. /* 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 */
  94089. if(nvals == 0)
  94090. return true;
  94091. cbits = br->consumed_bits;
  94092. cwords = br->consumed_words;
  94093. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94094. while(1) {
  94095. /* read unary part */
  94096. while(1) {
  94097. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94098. brword b = br->buffer[cwords] << cbits;
  94099. if(b) {
  94100. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94101. asm volatile (
  94102. "bsrl %1, %0;"
  94103. "notl %0;"
  94104. "andl $31, %0;"
  94105. : "=r"(i)
  94106. : "r"(b)
  94107. );
  94108. #else
  94109. i = COUNT_ZERO_MSBS(b);
  94110. #endif
  94111. uval += i;
  94112. cbits += i;
  94113. cbits++; /* skip over stop bit */
  94114. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94115. crc16_update_word_(br, br->buffer[cwords]);
  94116. cwords++;
  94117. cbits = 0;
  94118. }
  94119. goto break1;
  94120. }
  94121. else {
  94122. uval += FLAC__BITS_PER_WORD - cbits;
  94123. crc16_update_word_(br, br->buffer[cwords]);
  94124. cwords++;
  94125. cbits = 0;
  94126. /* didn't find stop bit yet, have to keep going... */
  94127. }
  94128. }
  94129. /* at this point we've eaten up all the whole words; have to try
  94130. * reading through any tail bytes before calling the read callback.
  94131. * this is a repeat of the above logic adjusted for the fact we
  94132. * don't have a whole word. note though if the client is feeding
  94133. * us data a byte at a time (unlikely), br->consumed_bits may not
  94134. * be zero.
  94135. */
  94136. if(br->bytes) {
  94137. const unsigned end = br->bytes * 8;
  94138. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94139. if(b) {
  94140. i = COUNT_ZERO_MSBS(b);
  94141. uval += i;
  94142. cbits += i;
  94143. cbits++; /* skip over stop bit */
  94144. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94145. goto break1;
  94146. }
  94147. else {
  94148. uval += end - cbits;
  94149. cbits += end;
  94150. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94151. /* didn't find stop bit yet, have to keep going... */
  94152. }
  94153. }
  94154. /* flush registers and read; bitreader_read_from_client_() does
  94155. * not touch br->consumed_bits at all but we still need to set
  94156. * it in case it fails and we have to return false.
  94157. */
  94158. br->consumed_bits = cbits;
  94159. br->consumed_words = cwords;
  94160. if(!bitreader_read_from_client_(br))
  94161. return false;
  94162. cwords = br->consumed_words;
  94163. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94164. /* + uval to offset our count by the # of unary bits already
  94165. * consumed before the read, because we will add these back
  94166. * in all at once at break1
  94167. */
  94168. }
  94169. break1:
  94170. ucbits -= uval;
  94171. ucbits--; /* account for stop bit */
  94172. /* read binary part */
  94173. FLAC__ASSERT(cwords <= br->words);
  94174. if(parameter) {
  94175. while(ucbits < parameter) {
  94176. /* flush registers and read; bitreader_read_from_client_() does
  94177. * not touch br->consumed_bits at all but we still need to set
  94178. * it in case it fails and we have to return false.
  94179. */
  94180. br->consumed_bits = cbits;
  94181. br->consumed_words = cwords;
  94182. if(!bitreader_read_from_client_(br))
  94183. return false;
  94184. cwords = br->consumed_words;
  94185. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94186. }
  94187. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94188. if(cbits) {
  94189. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94190. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94191. const brword word = br->buffer[cwords];
  94192. if(parameter < n) {
  94193. uval <<= parameter;
  94194. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94195. cbits += parameter;
  94196. }
  94197. else {
  94198. uval <<= n;
  94199. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94200. crc16_update_word_(br, word);
  94201. cwords++;
  94202. cbits = parameter - n;
  94203. 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 */
  94204. uval <<= cbits;
  94205. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94206. }
  94207. }
  94208. }
  94209. else {
  94210. cbits = parameter;
  94211. uval <<= parameter;
  94212. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94213. }
  94214. }
  94215. else {
  94216. /* in this case we're starting our read at a partial tail word;
  94217. * the reader has guaranteed that we have at least 'parameter'
  94218. * bits available to read, which makes this case simpler.
  94219. */
  94220. uval <<= parameter;
  94221. if(cbits) {
  94222. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94223. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94224. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94225. cbits += parameter;
  94226. }
  94227. else {
  94228. cbits = parameter;
  94229. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94230. }
  94231. }
  94232. }
  94233. ucbits -= parameter;
  94234. /* compose the value */
  94235. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94236. /* are we done? */
  94237. --nvals;
  94238. if(nvals == 0) {
  94239. br->consumed_bits = cbits;
  94240. br->consumed_words = cwords;
  94241. return true;
  94242. }
  94243. uval = 0;
  94244. ++vals;
  94245. }
  94246. }
  94247. #endif
  94248. #if 0 /* UNUSED */
  94249. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94250. {
  94251. FLAC__uint32 lsbs = 0, msbs = 0;
  94252. unsigned bit, uval, k;
  94253. FLAC__ASSERT(0 != br);
  94254. FLAC__ASSERT(0 != br->buffer);
  94255. k = FLAC__bitmath_ilog2(parameter);
  94256. /* read the unary MSBs and end bit */
  94257. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94258. return false;
  94259. /* read the binary LSBs */
  94260. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94261. return false;
  94262. if(parameter == 1u<<k) {
  94263. /* compose the value */
  94264. uval = (msbs << k) | lsbs;
  94265. }
  94266. else {
  94267. unsigned d = (1 << (k+1)) - parameter;
  94268. if(lsbs >= d) {
  94269. if(!FLAC__bitreader_read_bit(br, &bit))
  94270. return false;
  94271. lsbs <<= 1;
  94272. lsbs |= bit;
  94273. lsbs -= d;
  94274. }
  94275. /* compose the value */
  94276. uval = msbs * parameter + lsbs;
  94277. }
  94278. /* unfold unsigned to signed */
  94279. if(uval & 1)
  94280. *val = -((int)(uval >> 1)) - 1;
  94281. else
  94282. *val = (int)(uval >> 1);
  94283. return true;
  94284. }
  94285. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94286. {
  94287. FLAC__uint32 lsbs, msbs = 0;
  94288. unsigned bit, k;
  94289. FLAC__ASSERT(0 != br);
  94290. FLAC__ASSERT(0 != br->buffer);
  94291. k = FLAC__bitmath_ilog2(parameter);
  94292. /* read the unary MSBs and end bit */
  94293. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94294. return false;
  94295. /* read the binary LSBs */
  94296. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94297. return false;
  94298. if(parameter == 1u<<k) {
  94299. /* compose the value */
  94300. *val = (msbs << k) | lsbs;
  94301. }
  94302. else {
  94303. unsigned d = (1 << (k+1)) - parameter;
  94304. if(lsbs >= d) {
  94305. if(!FLAC__bitreader_read_bit(br, &bit))
  94306. return false;
  94307. lsbs <<= 1;
  94308. lsbs |= bit;
  94309. lsbs -= d;
  94310. }
  94311. /* compose the value */
  94312. *val = msbs * parameter + lsbs;
  94313. }
  94314. return true;
  94315. }
  94316. #endif /* UNUSED */
  94317. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94318. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94319. {
  94320. FLAC__uint32 v = 0;
  94321. FLAC__uint32 x;
  94322. unsigned i;
  94323. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94324. return false;
  94325. if(raw)
  94326. raw[(*rawlen)++] = (FLAC__byte)x;
  94327. if(!(x & 0x80)) { /* 0xxxxxxx */
  94328. v = x;
  94329. i = 0;
  94330. }
  94331. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94332. v = x & 0x1F;
  94333. i = 1;
  94334. }
  94335. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94336. v = x & 0x0F;
  94337. i = 2;
  94338. }
  94339. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94340. v = x & 0x07;
  94341. i = 3;
  94342. }
  94343. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94344. v = x & 0x03;
  94345. i = 4;
  94346. }
  94347. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94348. v = x & 0x01;
  94349. i = 5;
  94350. }
  94351. else {
  94352. *val = 0xffffffff;
  94353. return true;
  94354. }
  94355. for( ; i; i--) {
  94356. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94357. return false;
  94358. if(raw)
  94359. raw[(*rawlen)++] = (FLAC__byte)x;
  94360. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94361. *val = 0xffffffff;
  94362. return true;
  94363. }
  94364. v <<= 6;
  94365. v |= (x & 0x3F);
  94366. }
  94367. *val = v;
  94368. return true;
  94369. }
  94370. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94371. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94372. {
  94373. FLAC__uint64 v = 0;
  94374. FLAC__uint32 x;
  94375. unsigned i;
  94376. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94377. return false;
  94378. if(raw)
  94379. raw[(*rawlen)++] = (FLAC__byte)x;
  94380. if(!(x & 0x80)) { /* 0xxxxxxx */
  94381. v = x;
  94382. i = 0;
  94383. }
  94384. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94385. v = x & 0x1F;
  94386. i = 1;
  94387. }
  94388. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94389. v = x & 0x0F;
  94390. i = 2;
  94391. }
  94392. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94393. v = x & 0x07;
  94394. i = 3;
  94395. }
  94396. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94397. v = x & 0x03;
  94398. i = 4;
  94399. }
  94400. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94401. v = x & 0x01;
  94402. i = 5;
  94403. }
  94404. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94405. v = 0;
  94406. i = 6;
  94407. }
  94408. else {
  94409. *val = FLAC__U64L(0xffffffffffffffff);
  94410. return true;
  94411. }
  94412. for( ; i; i--) {
  94413. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94414. return false;
  94415. if(raw)
  94416. raw[(*rawlen)++] = (FLAC__byte)x;
  94417. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94418. *val = FLAC__U64L(0xffffffffffffffff);
  94419. return true;
  94420. }
  94421. v <<= 6;
  94422. v |= (x & 0x3F);
  94423. }
  94424. *val = v;
  94425. return true;
  94426. }
  94427. #endif
  94428. /*** End of inlined file: bitreader.c ***/
  94429. /*** Start of inlined file: bitwriter.c ***/
  94430. /*** Start of inlined file: juce_FlacHeader.h ***/
  94431. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94432. // tasks..
  94433. #define VERSION "1.2.1"
  94434. #define FLAC__NO_DLL 1
  94435. #if JUCE_MSVC
  94436. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94437. #endif
  94438. #if JUCE_MAC
  94439. #define FLAC__SYS_DARWIN 1
  94440. #endif
  94441. /*** End of inlined file: juce_FlacHeader.h ***/
  94442. #if JUCE_USE_FLAC
  94443. #if HAVE_CONFIG_H
  94444. # include <config.h>
  94445. #endif
  94446. #include <stdlib.h> /* for malloc() */
  94447. #include <string.h> /* for memcpy(), memset() */
  94448. #ifdef _MSC_VER
  94449. #include <winsock.h> /* for ntohl() */
  94450. #elif defined FLAC__SYS_DARWIN
  94451. #include <machine/endian.h> /* for ntohl() */
  94452. #elif defined __MINGW32__
  94453. #include <winsock.h> /* for ntohl() */
  94454. #else
  94455. #include <netinet/in.h> /* for ntohl() */
  94456. #endif
  94457. #if 0 /* UNUSED */
  94458. #endif
  94459. /*** Start of inlined file: bitwriter.h ***/
  94460. #ifndef FLAC__PRIVATE__BITWRITER_H
  94461. #define FLAC__PRIVATE__BITWRITER_H
  94462. #include <stdio.h> /* for FILE */
  94463. /*
  94464. * opaque structure definition
  94465. */
  94466. struct FLAC__BitWriter;
  94467. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94468. /*
  94469. * construction, deletion, initialization, etc functions
  94470. */
  94471. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94472. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94473. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94474. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94475. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94476. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94477. /*
  94478. * CRC functions
  94479. *
  94480. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94481. */
  94482. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94483. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94484. /*
  94485. * info functions
  94486. */
  94487. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94488. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94489. /*
  94490. * direct buffer access
  94491. *
  94492. * there may be no calls on the bitwriter between get and release.
  94493. * the bitwriter continues to own the returned buffer.
  94494. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94495. */
  94496. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94497. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94498. /*
  94499. * write functions
  94500. */
  94501. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94502. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94503. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94504. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94505. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94506. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94507. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94508. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94509. #if 0 /* UNUSED */
  94510. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94511. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94512. #endif
  94513. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94514. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94515. #if 0 /* UNUSED */
  94516. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94517. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94518. #endif
  94519. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94520. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94521. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94522. #endif
  94523. /*** End of inlined file: bitwriter.h ***/
  94524. /*** Start of inlined file: alloc.h ***/
  94525. #ifndef FLAC__SHARE__ALLOC_H
  94526. #define FLAC__SHARE__ALLOC_H
  94527. #if HAVE_CONFIG_H
  94528. # include <config.h>
  94529. #endif
  94530. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94531. * before #including this file, otherwise SIZE_MAX might not be defined
  94532. */
  94533. #include <limits.h> /* for SIZE_MAX */
  94534. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94535. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94536. #endif
  94537. #include <stdlib.h> /* for size_t, malloc(), etc */
  94538. #ifndef SIZE_MAX
  94539. # ifndef SIZE_T_MAX
  94540. # ifdef _MSC_VER
  94541. # define SIZE_T_MAX UINT_MAX
  94542. # else
  94543. # error
  94544. # endif
  94545. # endif
  94546. # define SIZE_MAX SIZE_T_MAX
  94547. #endif
  94548. #ifndef FLaC__INLINE
  94549. #define FLaC__INLINE
  94550. #endif
  94551. /* avoid malloc()ing 0 bytes, see:
  94552. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94553. */
  94554. static FLaC__INLINE void *safe_malloc_(size_t size)
  94555. {
  94556. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94557. if(!size)
  94558. size++;
  94559. return malloc(size);
  94560. }
  94561. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94562. {
  94563. if(!nmemb || !size)
  94564. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94565. return calloc(nmemb, size);
  94566. }
  94567. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94568. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94569. {
  94570. size2 += size1;
  94571. if(size2 < size1)
  94572. return 0;
  94573. return safe_malloc_(size2);
  94574. }
  94575. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94576. {
  94577. size2 += size1;
  94578. if(size2 < size1)
  94579. return 0;
  94580. size3 += size2;
  94581. if(size3 < size2)
  94582. return 0;
  94583. return safe_malloc_(size3);
  94584. }
  94585. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94586. {
  94587. size2 += size1;
  94588. if(size2 < size1)
  94589. return 0;
  94590. size3 += size2;
  94591. if(size3 < size2)
  94592. return 0;
  94593. size4 += size3;
  94594. if(size4 < size3)
  94595. return 0;
  94596. return safe_malloc_(size4);
  94597. }
  94598. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94599. #if 0
  94600. needs support for cases where sizeof(size_t) != 4
  94601. {
  94602. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94603. if(sizeof(size_t) == 4) {
  94604. if ((double)size1 * (double)size2 < 4294967296.0)
  94605. return malloc(size1*size2);
  94606. }
  94607. return 0;
  94608. }
  94609. #else
  94610. /* better? */
  94611. {
  94612. if(!size1 || !size2)
  94613. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94614. if(size1 > SIZE_MAX / size2)
  94615. return 0;
  94616. return malloc(size1*size2);
  94617. }
  94618. #endif
  94619. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94620. {
  94621. if(!size1 || !size2 || !size3)
  94622. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94623. if(size1 > SIZE_MAX / size2)
  94624. return 0;
  94625. size1 *= size2;
  94626. if(size1 > SIZE_MAX / size3)
  94627. return 0;
  94628. return malloc(size1*size3);
  94629. }
  94630. /* size1*size2 + size3 */
  94631. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94632. {
  94633. if(!size1 || !size2)
  94634. return safe_malloc_(size3);
  94635. if(size1 > SIZE_MAX / size2)
  94636. return 0;
  94637. return safe_malloc_add_2op_(size1*size2, size3);
  94638. }
  94639. /* size1 * (size2 + size3) */
  94640. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94641. {
  94642. if(!size1 || (!size2 && !size3))
  94643. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94644. size2 += size3;
  94645. if(size2 < size3)
  94646. return 0;
  94647. return safe_malloc_mul_2op_(size1, size2);
  94648. }
  94649. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94650. {
  94651. size2 += size1;
  94652. if(size2 < size1)
  94653. return 0;
  94654. return realloc(ptr, size2);
  94655. }
  94656. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94657. {
  94658. size2 += size1;
  94659. if(size2 < size1)
  94660. return 0;
  94661. size3 += size2;
  94662. if(size3 < size2)
  94663. return 0;
  94664. return realloc(ptr, size3);
  94665. }
  94666. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94667. {
  94668. size2 += size1;
  94669. if(size2 < size1)
  94670. return 0;
  94671. size3 += size2;
  94672. if(size3 < size2)
  94673. return 0;
  94674. size4 += size3;
  94675. if(size4 < size3)
  94676. return 0;
  94677. return realloc(ptr, size4);
  94678. }
  94679. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94680. {
  94681. if(!size1 || !size2)
  94682. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94683. if(size1 > SIZE_MAX / size2)
  94684. return 0;
  94685. return realloc(ptr, size1*size2);
  94686. }
  94687. /* size1 * (size2 + size3) */
  94688. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94689. {
  94690. if(!size1 || (!size2 && !size3))
  94691. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94692. size2 += size3;
  94693. if(size2 < size3)
  94694. return 0;
  94695. return safe_realloc_mul_2op_(ptr, size1, size2);
  94696. }
  94697. #endif
  94698. /*** End of inlined file: alloc.h ***/
  94699. /* Things should be fastest when this matches the machine word size */
  94700. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94701. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94702. typedef FLAC__uint32 bwword;
  94703. #define FLAC__BYTES_PER_WORD 4
  94704. #define FLAC__BITS_PER_WORD 32
  94705. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94706. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94707. #if WORDS_BIGENDIAN
  94708. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94709. #else
  94710. #ifdef _MSC_VER
  94711. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94712. #else
  94713. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94714. #endif
  94715. #endif
  94716. /*
  94717. * The default capacity here doesn't matter too much. The buffer always grows
  94718. * to hold whatever is written to it. Usually the encoder will stop adding at
  94719. * a frame or metadata block, then write that out and clear the buffer for the
  94720. * next one.
  94721. */
  94722. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94723. /* When growing, increment 4K at a time */
  94724. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94725. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94726. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94727. #ifdef min
  94728. #undef min
  94729. #endif
  94730. #define min(x,y) ((x)<(y)?(x):(y))
  94731. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94732. #ifdef _MSC_VER
  94733. #define FLAC__U64L(x) x
  94734. #else
  94735. #define FLAC__U64L(x) x##LLU
  94736. #endif
  94737. #ifndef FLaC__INLINE
  94738. #define FLaC__INLINE
  94739. #endif
  94740. struct FLAC__BitWriter {
  94741. bwword *buffer;
  94742. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94743. unsigned capacity; /* capacity of buffer in words */
  94744. unsigned words; /* # of complete words in buffer */
  94745. unsigned bits; /* # of used bits in accum */
  94746. };
  94747. /* * WATCHOUT: The current implementation only grows the buffer. */
  94748. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94749. {
  94750. unsigned new_capacity;
  94751. bwword *new_buffer;
  94752. FLAC__ASSERT(0 != bw);
  94753. FLAC__ASSERT(0 != bw->buffer);
  94754. /* calculate total words needed to store 'bits_to_add' additional bits */
  94755. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94756. /* it's possible (due to pessimism in the growth estimation that
  94757. * leads to this call) that we don't actually need to grow
  94758. */
  94759. if(bw->capacity >= new_capacity)
  94760. return true;
  94761. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94762. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94763. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94764. /* make sure we got everything right */
  94765. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94766. FLAC__ASSERT(new_capacity > bw->capacity);
  94767. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94768. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94769. if(new_buffer == 0)
  94770. return false;
  94771. bw->buffer = new_buffer;
  94772. bw->capacity = new_capacity;
  94773. return true;
  94774. }
  94775. /***********************************************************************
  94776. *
  94777. * Class constructor/destructor
  94778. *
  94779. ***********************************************************************/
  94780. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94781. {
  94782. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94783. /* note that calloc() sets all members to 0 for us */
  94784. return bw;
  94785. }
  94786. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94787. {
  94788. FLAC__ASSERT(0 != bw);
  94789. FLAC__bitwriter_free(bw);
  94790. free(bw);
  94791. }
  94792. /***********************************************************************
  94793. *
  94794. * Public class methods
  94795. *
  94796. ***********************************************************************/
  94797. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94798. {
  94799. FLAC__ASSERT(0 != bw);
  94800. bw->words = bw->bits = 0;
  94801. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94802. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94803. if(bw->buffer == 0)
  94804. return false;
  94805. return true;
  94806. }
  94807. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94808. {
  94809. FLAC__ASSERT(0 != bw);
  94810. if(0 != bw->buffer)
  94811. free(bw->buffer);
  94812. bw->buffer = 0;
  94813. bw->capacity = 0;
  94814. bw->words = bw->bits = 0;
  94815. }
  94816. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94817. {
  94818. bw->words = bw->bits = 0;
  94819. }
  94820. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94821. {
  94822. unsigned i, j;
  94823. if(bw == 0) {
  94824. fprintf(out, "bitwriter is NULL\n");
  94825. }
  94826. else {
  94827. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94828. for(i = 0; i < bw->words; i++) {
  94829. fprintf(out, "%08X: ", i);
  94830. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94831. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94832. fprintf(out, "\n");
  94833. }
  94834. if(bw->bits > 0) {
  94835. fprintf(out, "%08X: ", i);
  94836. for(j = 0; j < bw->bits; j++)
  94837. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94838. fprintf(out, "\n");
  94839. }
  94840. }
  94841. }
  94842. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94843. {
  94844. const FLAC__byte *buffer;
  94845. size_t bytes;
  94846. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94847. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94848. return false;
  94849. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94850. FLAC__bitwriter_release_buffer(bw);
  94851. return true;
  94852. }
  94853. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94854. {
  94855. const FLAC__byte *buffer;
  94856. size_t bytes;
  94857. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94858. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94859. return false;
  94860. *crc = FLAC__crc8(buffer, bytes);
  94861. FLAC__bitwriter_release_buffer(bw);
  94862. return true;
  94863. }
  94864. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94865. {
  94866. return ((bw->bits & 7) == 0);
  94867. }
  94868. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94869. {
  94870. return FLAC__TOTAL_BITS(bw);
  94871. }
  94872. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94873. {
  94874. FLAC__ASSERT((bw->bits & 7) == 0);
  94875. /* double protection */
  94876. if(bw->bits & 7)
  94877. return false;
  94878. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94879. if(bw->bits) {
  94880. FLAC__ASSERT(bw->words <= bw->capacity);
  94881. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94882. return false;
  94883. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94884. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94885. }
  94886. /* now we can just return what we have */
  94887. *buffer = (FLAC__byte*)bw->buffer;
  94888. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94889. return true;
  94890. }
  94891. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94892. {
  94893. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94894. * get-mode' flag could be added everywhere and then cleared here
  94895. */
  94896. (void)bw;
  94897. }
  94898. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94899. {
  94900. unsigned n;
  94901. FLAC__ASSERT(0 != bw);
  94902. FLAC__ASSERT(0 != bw->buffer);
  94903. if(bits == 0)
  94904. return true;
  94905. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94906. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94907. return false;
  94908. /* first part gets to word alignment */
  94909. if(bw->bits) {
  94910. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94911. bw->accum <<= n;
  94912. bits -= n;
  94913. bw->bits += n;
  94914. if(bw->bits == FLAC__BITS_PER_WORD) {
  94915. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94916. bw->bits = 0;
  94917. }
  94918. else
  94919. return true;
  94920. }
  94921. /* do whole words */
  94922. while(bits >= FLAC__BITS_PER_WORD) {
  94923. bw->buffer[bw->words++] = 0;
  94924. bits -= FLAC__BITS_PER_WORD;
  94925. }
  94926. /* do any leftovers */
  94927. if(bits > 0) {
  94928. bw->accum = 0;
  94929. bw->bits = bits;
  94930. }
  94931. return true;
  94932. }
  94933. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94934. {
  94935. register unsigned left;
  94936. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94937. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94938. FLAC__ASSERT(0 != bw);
  94939. FLAC__ASSERT(0 != bw->buffer);
  94940. FLAC__ASSERT(bits <= 32);
  94941. if(bits == 0)
  94942. return true;
  94943. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94944. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94945. return false;
  94946. left = FLAC__BITS_PER_WORD - bw->bits;
  94947. if(bits < left) {
  94948. bw->accum <<= bits;
  94949. bw->accum |= val;
  94950. bw->bits += bits;
  94951. }
  94952. 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 */
  94953. bw->accum <<= left;
  94954. bw->accum |= val >> (bw->bits = bits - left);
  94955. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94956. bw->accum = val;
  94957. }
  94958. else {
  94959. bw->accum = val;
  94960. bw->bits = 0;
  94961. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94962. }
  94963. return true;
  94964. }
  94965. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94966. {
  94967. /* zero-out unused bits */
  94968. if(bits < 32)
  94969. val &= (~(0xffffffff << bits));
  94970. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94971. }
  94972. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94973. {
  94974. /* this could be a little faster but it's not used for much */
  94975. if(bits > 32) {
  94976. return
  94977. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94978. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94979. }
  94980. else
  94981. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94982. }
  94983. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94984. {
  94985. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94986. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94987. return false;
  94988. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94989. return false;
  94990. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94991. return false;
  94992. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94993. return false;
  94994. return true;
  94995. }
  94996. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94997. {
  94998. unsigned i;
  94999. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  95000. for(i = 0; i < nvals; i++) {
  95001. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  95002. return false;
  95003. }
  95004. return true;
  95005. }
  95006. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  95007. {
  95008. if(val < 32)
  95009. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  95010. else
  95011. return
  95012. FLAC__bitwriter_write_zeroes(bw, val) &&
  95013. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  95014. }
  95015. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  95016. {
  95017. FLAC__uint32 uval;
  95018. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  95019. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95020. uval = (val<<1) ^ (val>>31);
  95021. return 1 + parameter + (uval >> parameter);
  95022. }
  95023. #if 0 /* UNUSED */
  95024. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95025. {
  95026. unsigned bits, msbs, uval;
  95027. unsigned k;
  95028. FLAC__ASSERT(parameter > 0);
  95029. /* fold signed to unsigned */
  95030. if(val < 0)
  95031. uval = (unsigned)(((-(++val)) << 1) + 1);
  95032. else
  95033. uval = (unsigned)(val << 1);
  95034. k = FLAC__bitmath_ilog2(parameter);
  95035. if(parameter == 1u<<k) {
  95036. FLAC__ASSERT(k <= 30);
  95037. msbs = uval >> k;
  95038. bits = 1 + k + msbs;
  95039. }
  95040. else {
  95041. unsigned q, r, d;
  95042. d = (1 << (k+1)) - parameter;
  95043. q = uval / parameter;
  95044. r = uval - (q * parameter);
  95045. bits = 1 + q + k;
  95046. if(r >= d)
  95047. bits++;
  95048. }
  95049. return bits;
  95050. }
  95051. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95052. {
  95053. unsigned bits, msbs;
  95054. unsigned k;
  95055. FLAC__ASSERT(parameter > 0);
  95056. k = FLAC__bitmath_ilog2(parameter);
  95057. if(parameter == 1u<<k) {
  95058. FLAC__ASSERT(k <= 30);
  95059. msbs = uval >> k;
  95060. bits = 1 + k + msbs;
  95061. }
  95062. else {
  95063. unsigned q, r, d;
  95064. d = (1 << (k+1)) - parameter;
  95065. q = uval / parameter;
  95066. r = uval - (q * parameter);
  95067. bits = 1 + q + k;
  95068. if(r >= d)
  95069. bits++;
  95070. }
  95071. return bits;
  95072. }
  95073. #endif /* UNUSED */
  95074. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95075. {
  95076. unsigned total_bits, interesting_bits, msbs;
  95077. FLAC__uint32 uval, pattern;
  95078. FLAC__ASSERT(0 != bw);
  95079. FLAC__ASSERT(0 != bw->buffer);
  95080. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95081. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95082. uval = (val<<1) ^ (val>>31);
  95083. msbs = uval >> parameter;
  95084. interesting_bits = 1 + parameter;
  95085. total_bits = interesting_bits + msbs;
  95086. pattern = 1 << parameter; /* the unary end bit */
  95087. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95088. if(total_bits <= 32)
  95089. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95090. else
  95091. return
  95092. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95093. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95094. }
  95095. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95096. {
  95097. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95098. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95099. FLAC__uint32 uval;
  95100. unsigned left;
  95101. const unsigned lsbits = 1 + parameter;
  95102. unsigned msbits;
  95103. FLAC__ASSERT(0 != bw);
  95104. FLAC__ASSERT(0 != bw->buffer);
  95105. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95106. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95107. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95108. while(nvals) {
  95109. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95110. uval = (*vals<<1) ^ (*vals>>31);
  95111. msbits = uval >> parameter;
  95112. #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) */
  95113. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95114. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95115. bw->bits = bw->bits + msbits + lsbits;
  95116. uval |= mask1; /* set stop bit */
  95117. uval &= mask2; /* mask off unused top bits */
  95118. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95119. bw->accum <<= msbits;
  95120. bw->accum <<= lsbits;
  95121. bw->accum |= uval;
  95122. if(bw->bits == FLAC__BITS_PER_WORD) {
  95123. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95124. bw->bits = 0;
  95125. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95126. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95127. FLAC__ASSERT(bw->capacity == bw->words);
  95128. return false;
  95129. }
  95130. }
  95131. }
  95132. else {
  95133. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95134. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95135. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95136. bw->bits = bw->bits + msbits + lsbits;
  95137. uval |= mask1; /* set stop bit */
  95138. uval &= mask2; /* mask off unused top bits */
  95139. bw->accum <<= msbits + lsbits;
  95140. bw->accum |= uval;
  95141. }
  95142. else {
  95143. #endif
  95144. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95145. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95146. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95147. return false;
  95148. if(msbits) {
  95149. /* first part gets to word alignment */
  95150. if(bw->bits) {
  95151. left = FLAC__BITS_PER_WORD - bw->bits;
  95152. if(msbits < left) {
  95153. bw->accum <<= msbits;
  95154. bw->bits += msbits;
  95155. goto break1;
  95156. }
  95157. else {
  95158. bw->accum <<= left;
  95159. msbits -= left;
  95160. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95161. bw->bits = 0;
  95162. }
  95163. }
  95164. /* do whole words */
  95165. while(msbits >= FLAC__BITS_PER_WORD) {
  95166. bw->buffer[bw->words++] = 0;
  95167. msbits -= FLAC__BITS_PER_WORD;
  95168. }
  95169. /* do any leftovers */
  95170. if(msbits > 0) {
  95171. bw->accum = 0;
  95172. bw->bits = msbits;
  95173. }
  95174. }
  95175. break1:
  95176. uval |= mask1; /* set stop bit */
  95177. uval &= mask2; /* mask off unused top bits */
  95178. left = FLAC__BITS_PER_WORD - bw->bits;
  95179. if(lsbits < left) {
  95180. bw->accum <<= lsbits;
  95181. bw->accum |= uval;
  95182. bw->bits += lsbits;
  95183. }
  95184. else {
  95185. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95186. * be > lsbits (because of previous assertions) so it would have
  95187. * triggered the (lsbits<left) case above.
  95188. */
  95189. FLAC__ASSERT(bw->bits);
  95190. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95191. bw->accum <<= left;
  95192. bw->accum |= uval >> (bw->bits = lsbits - left);
  95193. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95194. bw->accum = uval;
  95195. }
  95196. #if 1
  95197. }
  95198. #endif
  95199. vals++;
  95200. nvals--;
  95201. }
  95202. return true;
  95203. }
  95204. #if 0 /* UNUSED */
  95205. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95206. {
  95207. unsigned total_bits, msbs, uval;
  95208. unsigned k;
  95209. FLAC__ASSERT(0 != bw);
  95210. FLAC__ASSERT(0 != bw->buffer);
  95211. FLAC__ASSERT(parameter > 0);
  95212. /* fold signed to unsigned */
  95213. if(val < 0)
  95214. uval = (unsigned)(((-(++val)) << 1) + 1);
  95215. else
  95216. uval = (unsigned)(val << 1);
  95217. k = FLAC__bitmath_ilog2(parameter);
  95218. if(parameter == 1u<<k) {
  95219. unsigned pattern;
  95220. FLAC__ASSERT(k <= 30);
  95221. msbs = uval >> k;
  95222. total_bits = 1 + k + msbs;
  95223. pattern = 1 << k; /* the unary end bit */
  95224. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95225. if(total_bits <= 32) {
  95226. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95227. return false;
  95228. }
  95229. else {
  95230. /* write the unary MSBs */
  95231. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95232. return false;
  95233. /* write the unary end bit and binary LSBs */
  95234. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95235. return false;
  95236. }
  95237. }
  95238. else {
  95239. unsigned q, r, d;
  95240. d = (1 << (k+1)) - parameter;
  95241. q = uval / parameter;
  95242. r = uval - (q * parameter);
  95243. /* write the unary MSBs */
  95244. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95245. return false;
  95246. /* write the unary end bit */
  95247. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95248. return false;
  95249. /* write the binary LSBs */
  95250. if(r >= d) {
  95251. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95252. return false;
  95253. }
  95254. else {
  95255. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95256. return false;
  95257. }
  95258. }
  95259. return true;
  95260. }
  95261. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95262. {
  95263. unsigned total_bits, msbs;
  95264. unsigned k;
  95265. FLAC__ASSERT(0 != bw);
  95266. FLAC__ASSERT(0 != bw->buffer);
  95267. FLAC__ASSERT(parameter > 0);
  95268. k = FLAC__bitmath_ilog2(parameter);
  95269. if(parameter == 1u<<k) {
  95270. unsigned pattern;
  95271. FLAC__ASSERT(k <= 30);
  95272. msbs = uval >> k;
  95273. total_bits = 1 + k + msbs;
  95274. pattern = 1 << k; /* the unary end bit */
  95275. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95276. if(total_bits <= 32) {
  95277. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95278. return false;
  95279. }
  95280. else {
  95281. /* write the unary MSBs */
  95282. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95283. return false;
  95284. /* write the unary end bit and binary LSBs */
  95285. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95286. return false;
  95287. }
  95288. }
  95289. else {
  95290. unsigned q, r, d;
  95291. d = (1 << (k+1)) - parameter;
  95292. q = uval / parameter;
  95293. r = uval - (q * parameter);
  95294. /* write the unary MSBs */
  95295. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95296. return false;
  95297. /* write the unary end bit */
  95298. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95299. return false;
  95300. /* write the binary LSBs */
  95301. if(r >= d) {
  95302. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95303. return false;
  95304. }
  95305. else {
  95306. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95307. return false;
  95308. }
  95309. }
  95310. return true;
  95311. }
  95312. #endif /* UNUSED */
  95313. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95314. {
  95315. FLAC__bool ok = 1;
  95316. FLAC__ASSERT(0 != bw);
  95317. FLAC__ASSERT(0 != bw->buffer);
  95318. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95319. if(val < 0x80) {
  95320. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95321. }
  95322. else if(val < 0x800) {
  95323. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95324. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95325. }
  95326. else if(val < 0x10000) {
  95327. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95328. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95329. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95330. }
  95331. else if(val < 0x200000) {
  95332. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95333. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95334. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95335. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95336. }
  95337. else if(val < 0x4000000) {
  95338. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95339. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95340. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95341. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95342. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95343. }
  95344. else {
  95345. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95346. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95347. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95348. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95349. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95351. }
  95352. return ok;
  95353. }
  95354. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95355. {
  95356. FLAC__bool ok = 1;
  95357. FLAC__ASSERT(0 != bw);
  95358. FLAC__ASSERT(0 != bw->buffer);
  95359. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95360. if(val < 0x80) {
  95361. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95362. }
  95363. else if(val < 0x800) {
  95364. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95365. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95366. }
  95367. else if(val < 0x10000) {
  95368. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95369. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95370. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95371. }
  95372. else if(val < 0x200000) {
  95373. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95374. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95375. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95376. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95377. }
  95378. else if(val < 0x4000000) {
  95379. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95380. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95381. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95382. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95383. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95384. }
  95385. else if(val < 0x80000000) {
  95386. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95387. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95388. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95389. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95390. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95391. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95392. }
  95393. else {
  95394. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95395. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95396. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95397. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95398. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95399. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95400. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95401. }
  95402. return ok;
  95403. }
  95404. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95405. {
  95406. /* 0-pad to byte boundary */
  95407. if(bw->bits & 7u)
  95408. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95409. else
  95410. return true;
  95411. }
  95412. #endif
  95413. /*** End of inlined file: bitwriter.c ***/
  95414. /*** Start of inlined file: cpu.c ***/
  95415. /*** Start of inlined file: juce_FlacHeader.h ***/
  95416. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95417. // tasks..
  95418. #define VERSION "1.2.1"
  95419. #define FLAC__NO_DLL 1
  95420. #if JUCE_MSVC
  95421. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95422. #endif
  95423. #if JUCE_MAC
  95424. #define FLAC__SYS_DARWIN 1
  95425. #endif
  95426. /*** End of inlined file: juce_FlacHeader.h ***/
  95427. #if JUCE_USE_FLAC
  95428. #if HAVE_CONFIG_H
  95429. # include <config.h>
  95430. #endif
  95431. #include <stdlib.h>
  95432. #include <stdio.h>
  95433. #if defined FLAC__CPU_IA32
  95434. # include <signal.h>
  95435. #elif defined FLAC__CPU_PPC
  95436. # if !defined FLAC__NO_ASM
  95437. # if defined FLAC__SYS_DARWIN
  95438. # include <sys/sysctl.h>
  95439. # include <mach/mach.h>
  95440. # include <mach/mach_host.h>
  95441. # include <mach/host_info.h>
  95442. # include <mach/machine.h>
  95443. # ifndef CPU_SUBTYPE_POWERPC_970
  95444. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95445. # endif
  95446. # else /* FLAC__SYS_DARWIN */
  95447. # include <signal.h>
  95448. # include <setjmp.h>
  95449. static sigjmp_buf jmpbuf;
  95450. static volatile sig_atomic_t canjump = 0;
  95451. static void sigill_handler (int sig)
  95452. {
  95453. if (!canjump) {
  95454. signal (sig, SIG_DFL);
  95455. raise (sig);
  95456. }
  95457. canjump = 0;
  95458. siglongjmp (jmpbuf, 1);
  95459. }
  95460. # endif /* FLAC__SYS_DARWIN */
  95461. # endif /* FLAC__NO_ASM */
  95462. #endif /* FLAC__CPU_PPC */
  95463. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95464. #include <sys/param.h>
  95465. #include <sys/sysctl.h>
  95466. #include <machine/cpu.h>
  95467. #endif
  95468. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95469. #include <sys/types.h>
  95470. #include <sys/sysctl.h>
  95471. #endif
  95472. #if defined(__APPLE__)
  95473. /* how to get sysctlbyname()? */
  95474. #endif
  95475. /* these are flags in EDX of CPUID AX=00000001 */
  95476. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95477. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95478. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95479. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95480. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95481. /* these are flags in ECX of CPUID AX=00000001 */
  95482. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95483. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95484. /* these are flags in EDX of CPUID AX=80000001 */
  95485. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95486. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95487. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95488. /*
  95489. * Extra stuff needed for detection of OS support for SSE on IA-32
  95490. */
  95491. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95492. # if defined(__linux__)
  95493. /*
  95494. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95495. * modify the return address to jump over the offending SSE instruction
  95496. * and also the operation following it that indicates the instruction
  95497. * executed successfully. In this way we use no global variables and
  95498. * stay thread-safe.
  95499. *
  95500. * 3 + 3 + 6:
  95501. * 3 bytes for "xorps xmm0,xmm0"
  95502. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95503. * 6 bytes extra in case our estimate is wrong
  95504. * 12 bytes puts us in the NOP "landing zone"
  95505. */
  95506. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95507. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95508. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95509. {
  95510. (void)signal;
  95511. sc.eip += 3 + 3 + 6;
  95512. }
  95513. # else
  95514. # include <sys/ucontext.h>
  95515. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95516. {
  95517. (void)signal, (void)si;
  95518. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95519. }
  95520. # endif
  95521. # elif defined(_MSC_VER)
  95522. # include <windows.h>
  95523. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95524. # ifdef USE_TRY_CATCH_FLAVOR
  95525. # else
  95526. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95527. {
  95528. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95529. ep->ContextRecord->Eip += 3 + 3 + 6;
  95530. return EXCEPTION_CONTINUE_EXECUTION;
  95531. }
  95532. return EXCEPTION_CONTINUE_SEARCH;
  95533. }
  95534. # endif
  95535. # endif
  95536. #endif
  95537. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95538. {
  95539. /*
  95540. * IA32-specific
  95541. */
  95542. #ifdef FLAC__CPU_IA32
  95543. info->type = FLAC__CPUINFO_TYPE_IA32;
  95544. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95545. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95546. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95547. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95548. info->data.ia32.cmov = false;
  95549. info->data.ia32.mmx = false;
  95550. info->data.ia32.fxsr = false;
  95551. info->data.ia32.sse = false;
  95552. info->data.ia32.sse2 = false;
  95553. info->data.ia32.sse3 = false;
  95554. info->data.ia32.ssse3 = false;
  95555. info->data.ia32._3dnow = false;
  95556. info->data.ia32.ext3dnow = false;
  95557. info->data.ia32.extmmx = false;
  95558. if(info->data.ia32.cpuid) {
  95559. /* http://www.sandpile.org/ia32/cpuid.htm */
  95560. FLAC__uint32 flags_edx, flags_ecx;
  95561. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95562. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95563. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95564. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95565. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95566. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95567. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95568. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95569. #ifdef FLAC__USE_3DNOW
  95570. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95571. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95572. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95573. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95574. #else
  95575. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95576. #endif
  95577. #ifdef DEBUG
  95578. fprintf(stderr, "CPU info (IA-32):\n");
  95579. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95580. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95581. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95582. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95583. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95584. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95585. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95586. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95587. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95588. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95589. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95590. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95591. #endif
  95592. /*
  95593. * now have to check for OS support of SSE/SSE2
  95594. */
  95595. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95596. #if defined FLAC__NO_SSE_OS
  95597. /* assume user knows better than us; turn it off */
  95598. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95599. #elif defined FLAC__SSE_OS
  95600. /* assume user knows better than us; leave as detected above */
  95601. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95602. int sse = 0;
  95603. size_t len;
  95604. /* at least one of these must work: */
  95605. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95606. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95607. if(!sse)
  95608. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95609. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95610. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95611. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95612. size_t len = sizeof(val);
  95613. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95614. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95615. else { /* double-check SSE2 */
  95616. mib[1] = CPU_SSE2;
  95617. len = sizeof(val);
  95618. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95619. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95620. }
  95621. # else
  95622. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95623. # endif
  95624. #elif defined(__linux__)
  95625. int sse = 0;
  95626. struct sigaction sigill_save;
  95627. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95628. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95629. #else
  95630. struct sigaction sigill_sse;
  95631. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95632. __sigemptyset(&sigill_sse.sa_mask);
  95633. 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 */
  95634. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95635. #endif
  95636. {
  95637. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95638. /* see sigill_handler_sse_os() for an explanation of the following: */
  95639. asm volatile (
  95640. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95641. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95642. "incl %0\n\t" /* SIGILL handler will jump over this */
  95643. /* landing zone */
  95644. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95645. "nop\n\t"
  95646. "nop\n\t"
  95647. "nop\n\t"
  95648. "nop\n\t"
  95649. "nop\n\t"
  95650. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95651. "nop\n\t"
  95652. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95653. : "=r"(sse)
  95654. : "r"(sse)
  95655. );
  95656. sigaction(SIGILL, &sigill_save, NULL);
  95657. }
  95658. if(!sse)
  95659. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95660. #elif defined(_MSC_VER)
  95661. # ifdef USE_TRY_CATCH_FLAVOR
  95662. _try {
  95663. __asm {
  95664. # if _MSC_VER <= 1200
  95665. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95666. _emit 0x0F
  95667. _emit 0x57
  95668. _emit 0xC0
  95669. # else
  95670. xorps xmm0,xmm0
  95671. # endif
  95672. }
  95673. }
  95674. _except(EXCEPTION_EXECUTE_HANDLER) {
  95675. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95676. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95677. }
  95678. # else
  95679. int sse = 0;
  95680. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95681. /* see GCC version above for explanation */
  95682. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95683. /* http://www.codeproject.com/cpp/gccasm.asp */
  95684. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95685. __asm {
  95686. # if _MSC_VER <= 1200
  95687. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95688. _emit 0x0F
  95689. _emit 0x57
  95690. _emit 0xC0
  95691. # else
  95692. xorps xmm0,xmm0
  95693. # endif
  95694. inc sse
  95695. nop
  95696. nop
  95697. nop
  95698. nop
  95699. nop
  95700. nop
  95701. nop
  95702. nop
  95703. nop
  95704. }
  95705. SetUnhandledExceptionFilter(save);
  95706. if(!sse)
  95707. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95708. # endif
  95709. #else
  95710. /* no way to test, disable to be safe */
  95711. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95712. #endif
  95713. #ifdef DEBUG
  95714. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95715. #endif
  95716. }
  95717. }
  95718. #else
  95719. info->use_asm = false;
  95720. #endif
  95721. /*
  95722. * PPC-specific
  95723. */
  95724. #elif defined FLAC__CPU_PPC
  95725. info->type = FLAC__CPUINFO_TYPE_PPC;
  95726. # if !defined FLAC__NO_ASM
  95727. info->use_asm = true;
  95728. # ifdef FLAC__USE_ALTIVEC
  95729. # if defined FLAC__SYS_DARWIN
  95730. {
  95731. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95732. size_t len = sizeof(val);
  95733. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95734. }
  95735. {
  95736. host_basic_info_data_t hostInfo;
  95737. mach_msg_type_number_t infoCount;
  95738. infoCount = HOST_BASIC_INFO_COUNT;
  95739. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95740. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95741. }
  95742. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95743. {
  95744. /* no Darwin, do it the brute-force way */
  95745. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95746. info->data.ppc.altivec = 0;
  95747. info->data.ppc.ppc64 = 0;
  95748. signal (SIGILL, sigill_handler);
  95749. canjump = 0;
  95750. if (!sigsetjmp (jmpbuf, 1)) {
  95751. canjump = 1;
  95752. asm volatile (
  95753. "mtspr 256, %0\n\t"
  95754. "vand %%v0, %%v0, %%v0"
  95755. :
  95756. : "r" (-1)
  95757. );
  95758. info->data.ppc.altivec = 1;
  95759. }
  95760. canjump = 0;
  95761. if (!sigsetjmp (jmpbuf, 1)) {
  95762. int x = 0;
  95763. canjump = 1;
  95764. /* PPC64 hardware implements the cntlzd instruction */
  95765. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95766. info->data.ppc.ppc64 = 1;
  95767. }
  95768. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95769. }
  95770. # endif
  95771. # else /* !FLAC__USE_ALTIVEC */
  95772. info->data.ppc.altivec = 0;
  95773. info->data.ppc.ppc64 = 0;
  95774. # endif
  95775. # else
  95776. info->use_asm = false;
  95777. # endif
  95778. /*
  95779. * unknown CPI
  95780. */
  95781. #else
  95782. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95783. info->use_asm = false;
  95784. #endif
  95785. }
  95786. #endif
  95787. /*** End of inlined file: cpu.c ***/
  95788. /*** Start of inlined file: crc.c ***/
  95789. /*** Start of inlined file: juce_FlacHeader.h ***/
  95790. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95791. // tasks..
  95792. #define VERSION "1.2.1"
  95793. #define FLAC__NO_DLL 1
  95794. #if JUCE_MSVC
  95795. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95796. #endif
  95797. #if JUCE_MAC
  95798. #define FLAC__SYS_DARWIN 1
  95799. #endif
  95800. /*** End of inlined file: juce_FlacHeader.h ***/
  95801. #if JUCE_USE_FLAC
  95802. #if HAVE_CONFIG_H
  95803. # include <config.h>
  95804. #endif
  95805. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95806. FLAC__byte const FLAC__crc8_table[256] = {
  95807. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95808. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95809. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95810. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95811. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95812. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95813. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95814. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95815. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95816. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95817. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95818. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95819. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95820. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95821. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95822. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95823. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95824. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95825. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95826. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95827. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95828. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95829. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95830. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95831. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95832. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95833. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95834. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95835. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95836. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95837. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95838. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95839. };
  95840. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95841. unsigned FLAC__crc16_table[256] = {
  95842. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95843. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95844. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95845. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95846. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95847. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95848. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95849. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95850. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95851. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95852. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95853. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95854. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95855. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95856. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95857. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95858. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95859. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95860. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95861. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95862. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95863. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95864. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95865. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95866. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95867. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95868. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95869. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95870. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95871. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95872. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95873. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95874. };
  95875. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95876. {
  95877. *crc = FLAC__crc8_table[*crc ^ data];
  95878. }
  95879. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95880. {
  95881. while(len--)
  95882. *crc = FLAC__crc8_table[*crc ^ *data++];
  95883. }
  95884. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95885. {
  95886. FLAC__uint8 crc = 0;
  95887. while(len--)
  95888. crc = FLAC__crc8_table[crc ^ *data++];
  95889. return crc;
  95890. }
  95891. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95892. {
  95893. unsigned crc = 0;
  95894. while(len--)
  95895. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95896. return crc;
  95897. }
  95898. #endif
  95899. /*** End of inlined file: crc.c ***/
  95900. /*** Start of inlined file: fixed.c ***/
  95901. /*** Start of inlined file: juce_FlacHeader.h ***/
  95902. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95903. // tasks..
  95904. #define VERSION "1.2.1"
  95905. #define FLAC__NO_DLL 1
  95906. #if JUCE_MSVC
  95907. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95908. #endif
  95909. #if JUCE_MAC
  95910. #define FLAC__SYS_DARWIN 1
  95911. #endif
  95912. /*** End of inlined file: juce_FlacHeader.h ***/
  95913. #if JUCE_USE_FLAC
  95914. #if HAVE_CONFIG_H
  95915. # include <config.h>
  95916. #endif
  95917. #include <math.h>
  95918. #include <string.h>
  95919. /*** Start of inlined file: fixed.h ***/
  95920. #ifndef FLAC__PRIVATE__FIXED_H
  95921. #define FLAC__PRIVATE__FIXED_H
  95922. #ifdef HAVE_CONFIG_H
  95923. #include <config.h>
  95924. #endif
  95925. /*** Start of inlined file: float.h ***/
  95926. #ifndef FLAC__PRIVATE__FLOAT_H
  95927. #define FLAC__PRIVATE__FLOAT_H
  95928. #ifdef HAVE_CONFIG_H
  95929. #include <config.h>
  95930. #endif
  95931. /*
  95932. * These typedefs make it easier to ensure that integer versions of
  95933. * the library really only contain integer operations. All the code
  95934. * in libFLAC should use FLAC__float and FLAC__double in place of
  95935. * float and double, and be protected by checks of the macro
  95936. * FLAC__INTEGER_ONLY_LIBRARY.
  95937. *
  95938. * FLAC__real is the basic floating point type used in LPC analysis.
  95939. */
  95940. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95941. typedef double FLAC__double;
  95942. typedef float FLAC__float;
  95943. /*
  95944. * WATCHOUT: changing FLAC__real will change the signatures of many
  95945. * functions that have assembly language equivalents and break them.
  95946. */
  95947. typedef float FLAC__real;
  95948. #else
  95949. /*
  95950. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95951. * for the integer part and lower 16 bits for the fractional part.
  95952. */
  95953. typedef FLAC__int32 FLAC__fixedpoint;
  95954. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95955. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95956. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95957. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95958. extern const FLAC__fixedpoint FLAC__FP_E;
  95959. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95960. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95961. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95962. /*
  95963. * FLAC__fixedpoint_log2()
  95964. * --------------------------------------------------------------------
  95965. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95966. * algorithm by Knuth for x >= 1.0
  95967. *
  95968. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95969. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95970. *
  95971. * 'precision' roughly limits the number of iterations that are done;
  95972. * use (unsigned)(-1) for maximum precision.
  95973. *
  95974. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95975. * function will punt and return 0.
  95976. *
  95977. * The return value will also have 'fracbits' fractional bits.
  95978. */
  95979. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95980. #endif
  95981. #endif
  95982. /*** End of inlined file: float.h ***/
  95983. /*** Start of inlined file: format.h ***/
  95984. #ifndef FLAC__PRIVATE__FORMAT_H
  95985. #define FLAC__PRIVATE__FORMAT_H
  95986. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95987. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95988. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95989. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95990. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95991. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95992. #endif
  95993. /*** End of inlined file: format.h ***/
  95994. /*
  95995. * FLAC__fixed_compute_best_predictor()
  95996. * --------------------------------------------------------------------
  95997. * Compute the best fixed predictor and the expected bits-per-sample
  95998. * of the residual signal for each order. The _wide() version uses
  95999. * 64-bit integers which is statistically necessary when bits-per-
  96000. * sample + log2(blocksize) > 30
  96001. *
  96002. * IN data[0,data_len-1]
  96003. * IN data_len
  96004. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  96005. */
  96006. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96007. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96008. # ifndef FLAC__NO_ASM
  96009. # ifdef FLAC__CPU_IA32
  96010. # ifdef FLAC__HAS_NASM
  96011. 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]);
  96012. # endif
  96013. # endif
  96014. # endif
  96015. 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]);
  96016. #else
  96017. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96018. 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]);
  96019. #endif
  96020. /*
  96021. * FLAC__fixed_compute_residual()
  96022. * --------------------------------------------------------------------
  96023. * Compute the residual signal obtained from sutracting the predicted
  96024. * signal from the original.
  96025. *
  96026. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96027. * IN data_len length of original signal
  96028. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96029. * OUT residual[0,data_len-1] residual signal
  96030. */
  96031. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96032. /*
  96033. * FLAC__fixed_restore_signal()
  96034. * --------------------------------------------------------------------
  96035. * Restore the original signal by summing the residual and the
  96036. * predictor.
  96037. *
  96038. * IN residual[0,data_len-1] residual signal
  96039. * IN data_len length of original signal
  96040. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96041. * *** IMPORTANT: the caller must pass in the historical samples:
  96042. * IN data[-order,-1] previously-reconstructed historical samples
  96043. * OUT data[0,data_len-1] original signal
  96044. */
  96045. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96046. #endif
  96047. /*** End of inlined file: fixed.h ***/
  96048. #ifndef M_LN2
  96049. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96050. #define M_LN2 0.69314718055994530942
  96051. #endif
  96052. #ifdef min
  96053. #undef min
  96054. #endif
  96055. #define min(x,y) ((x) < (y)? (x) : (y))
  96056. #ifdef local_abs
  96057. #undef local_abs
  96058. #endif
  96059. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96060. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96061. /* rbps stands for residual bits per sample
  96062. *
  96063. * (ln(2) * err)
  96064. * rbps = log (-----------)
  96065. * 2 ( n )
  96066. */
  96067. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96068. {
  96069. FLAC__uint32 rbps;
  96070. unsigned bits; /* the number of bits required to represent a number */
  96071. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96072. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96073. FLAC__ASSERT(err > 0);
  96074. FLAC__ASSERT(n > 0);
  96075. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96076. if(err <= n)
  96077. return 0;
  96078. /*
  96079. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96080. * These allow us later to know we won't lose too much precision in the
  96081. * fixed-point division (err<<fracbits)/n.
  96082. */
  96083. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96084. err <<= fracbits;
  96085. err /= n;
  96086. /* err now holds err/n with fracbits fractional bits */
  96087. /*
  96088. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96089. * our purposes.
  96090. */
  96091. FLAC__ASSERT(err > 0);
  96092. bits = FLAC__bitmath_ilog2(err)+1;
  96093. if(bits > 16) {
  96094. err >>= (bits-16);
  96095. fracbits -= (bits-16);
  96096. }
  96097. rbps = (FLAC__uint32)err;
  96098. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96099. rbps *= FLAC__FP_LN2;
  96100. fracbits += 16;
  96101. FLAC__ASSERT(fracbits >= 0);
  96102. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96103. {
  96104. const int f = fracbits & 3;
  96105. if(f) {
  96106. rbps >>= f;
  96107. fracbits -= f;
  96108. }
  96109. }
  96110. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96111. if(rbps == 0)
  96112. return 0;
  96113. /*
  96114. * The return value must have 16 fractional bits. Since the whole part
  96115. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96116. * must be >= -3, these assertion allows us to be able to shift rbps
  96117. * left if necessary to get 16 fracbits without losing any bits of the
  96118. * whole part of rbps.
  96119. *
  96120. * There is a slight chance due to accumulated error that the whole part
  96121. * will require 6 bits, so we use 6 in the assertion. Really though as
  96122. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96123. */
  96124. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96125. FLAC__ASSERT(fracbits >= -3);
  96126. /* now shift the decimal point into place */
  96127. if(fracbits < 16)
  96128. return rbps << (16-fracbits);
  96129. else if(fracbits > 16)
  96130. return rbps >> (fracbits-16);
  96131. else
  96132. return rbps;
  96133. }
  96134. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96135. {
  96136. FLAC__uint32 rbps;
  96137. unsigned bits; /* the number of bits required to represent a number */
  96138. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96139. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96140. FLAC__ASSERT(err > 0);
  96141. FLAC__ASSERT(n > 0);
  96142. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96143. if(err <= n)
  96144. return 0;
  96145. /*
  96146. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96147. * These allow us later to know we won't lose too much precision in the
  96148. * fixed-point division (err<<fracbits)/n.
  96149. */
  96150. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96151. err <<= fracbits;
  96152. err /= n;
  96153. /* err now holds err/n with fracbits fractional bits */
  96154. /*
  96155. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96156. * our purposes.
  96157. */
  96158. FLAC__ASSERT(err > 0);
  96159. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96160. if(bits > 16) {
  96161. err >>= (bits-16);
  96162. fracbits -= (bits-16);
  96163. }
  96164. rbps = (FLAC__uint32)err;
  96165. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96166. rbps *= FLAC__FP_LN2;
  96167. fracbits += 16;
  96168. FLAC__ASSERT(fracbits >= 0);
  96169. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96170. {
  96171. const int f = fracbits & 3;
  96172. if(f) {
  96173. rbps >>= f;
  96174. fracbits -= f;
  96175. }
  96176. }
  96177. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96178. if(rbps == 0)
  96179. return 0;
  96180. /*
  96181. * The return value must have 16 fractional bits. Since the whole part
  96182. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96183. * must be >= -3, these assertion allows us to be able to shift rbps
  96184. * left if necessary to get 16 fracbits without losing any bits of the
  96185. * whole part of rbps.
  96186. *
  96187. * There is a slight chance due to accumulated error that the whole part
  96188. * will require 6 bits, so we use 6 in the assertion. Really though as
  96189. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96190. */
  96191. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96192. FLAC__ASSERT(fracbits >= -3);
  96193. /* now shift the decimal point into place */
  96194. if(fracbits < 16)
  96195. return rbps << (16-fracbits);
  96196. else if(fracbits > 16)
  96197. return rbps >> (fracbits-16);
  96198. else
  96199. return rbps;
  96200. }
  96201. #endif
  96202. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96203. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96204. #else
  96205. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96206. #endif
  96207. {
  96208. FLAC__int32 last_error_0 = data[-1];
  96209. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96210. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96211. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96212. FLAC__int32 error, save;
  96213. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96214. unsigned i, order;
  96215. for(i = 0; i < data_len; i++) {
  96216. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96217. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96218. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96219. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96220. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96221. }
  96222. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96223. order = 0;
  96224. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96225. order = 1;
  96226. else if(total_error_2 < min(total_error_3, total_error_4))
  96227. order = 2;
  96228. else if(total_error_3 < total_error_4)
  96229. order = 3;
  96230. else
  96231. order = 4;
  96232. /* Estimate the expected number of bits per residual signal sample. */
  96233. /* 'total_error*' is linearly related to the variance of the residual */
  96234. /* signal, so we use it directly to compute E(|x|) */
  96235. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96236. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96237. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96238. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96239. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96240. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96241. 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);
  96242. 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);
  96243. 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);
  96244. 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);
  96245. 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);
  96246. #else
  96247. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96248. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96249. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96250. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96251. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96252. #endif
  96253. return order;
  96254. }
  96255. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96256. 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])
  96257. #else
  96258. 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])
  96259. #endif
  96260. {
  96261. FLAC__int32 last_error_0 = data[-1];
  96262. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96263. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96264. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96265. FLAC__int32 error, save;
  96266. /* total_error_* are 64-bits to avoid overflow when encoding
  96267. * erratic signals when the bits-per-sample and blocksize are
  96268. * large.
  96269. */
  96270. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96271. unsigned i, order;
  96272. for(i = 0; i < data_len; i++) {
  96273. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96274. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96275. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96276. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96277. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96278. }
  96279. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96280. order = 0;
  96281. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96282. order = 1;
  96283. else if(total_error_2 < min(total_error_3, total_error_4))
  96284. order = 2;
  96285. else if(total_error_3 < total_error_4)
  96286. order = 3;
  96287. else
  96288. order = 4;
  96289. /* Estimate the expected number of bits per residual signal sample. */
  96290. /* 'total_error*' is linearly related to the variance of the residual */
  96291. /* signal, so we use it directly to compute E(|x|) */
  96292. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96293. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96294. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96295. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96296. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96297. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96298. #if defined _MSC_VER || defined __MINGW32__
  96299. /* with MSVC you have to spoon feed it the casting */
  96300. 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);
  96301. 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);
  96302. 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);
  96303. 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);
  96304. 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);
  96305. #else
  96306. 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);
  96307. 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);
  96308. 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);
  96309. 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);
  96310. 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);
  96311. #endif
  96312. #else
  96313. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96314. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96315. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96316. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96317. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96318. #endif
  96319. return order;
  96320. }
  96321. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96322. {
  96323. const int idata_len = (int)data_len;
  96324. int i;
  96325. switch(order) {
  96326. case 0:
  96327. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96328. memcpy(residual, data, sizeof(residual[0])*data_len);
  96329. break;
  96330. case 1:
  96331. for(i = 0; i < idata_len; i++)
  96332. residual[i] = data[i] - data[i-1];
  96333. break;
  96334. case 2:
  96335. for(i = 0; i < idata_len; i++)
  96336. #if 1 /* OPT: may be faster with some compilers on some systems */
  96337. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96338. #else
  96339. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96340. #endif
  96341. break;
  96342. case 3:
  96343. for(i = 0; i < idata_len; i++)
  96344. #if 1 /* OPT: may be faster with some compilers on some systems */
  96345. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96346. #else
  96347. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96348. #endif
  96349. break;
  96350. case 4:
  96351. for(i = 0; i < idata_len; i++)
  96352. #if 1 /* OPT: may be faster with some compilers on some systems */
  96353. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96354. #else
  96355. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96356. #endif
  96357. break;
  96358. default:
  96359. FLAC__ASSERT(0);
  96360. }
  96361. }
  96362. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96363. {
  96364. int i, idata_len = (int)data_len;
  96365. switch(order) {
  96366. case 0:
  96367. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96368. memcpy(data, residual, sizeof(residual[0])*data_len);
  96369. break;
  96370. case 1:
  96371. for(i = 0; i < idata_len; i++)
  96372. data[i] = residual[i] + data[i-1];
  96373. break;
  96374. case 2:
  96375. for(i = 0; i < idata_len; i++)
  96376. #if 1 /* OPT: may be faster with some compilers on some systems */
  96377. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96378. #else
  96379. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96380. #endif
  96381. break;
  96382. case 3:
  96383. for(i = 0; i < idata_len; i++)
  96384. #if 1 /* OPT: may be faster with some compilers on some systems */
  96385. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96386. #else
  96387. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96388. #endif
  96389. break;
  96390. case 4:
  96391. for(i = 0; i < idata_len; i++)
  96392. #if 1 /* OPT: may be faster with some compilers on some systems */
  96393. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96394. #else
  96395. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96396. #endif
  96397. break;
  96398. default:
  96399. FLAC__ASSERT(0);
  96400. }
  96401. }
  96402. #endif
  96403. /*** End of inlined file: fixed.c ***/
  96404. /*** Start of inlined file: float.c ***/
  96405. /*** Start of inlined file: juce_FlacHeader.h ***/
  96406. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96407. // tasks..
  96408. #define VERSION "1.2.1"
  96409. #define FLAC__NO_DLL 1
  96410. #if JUCE_MSVC
  96411. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96412. #endif
  96413. #if JUCE_MAC
  96414. #define FLAC__SYS_DARWIN 1
  96415. #endif
  96416. /*** End of inlined file: juce_FlacHeader.h ***/
  96417. #if JUCE_USE_FLAC
  96418. #if HAVE_CONFIG_H
  96419. # include <config.h>
  96420. #endif
  96421. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96422. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96423. #ifdef _MSC_VER
  96424. #define FLAC__U64L(x) x
  96425. #else
  96426. #define FLAC__U64L(x) x##LLU
  96427. #endif
  96428. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96429. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96430. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96431. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96432. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96433. /* Lookup tables for Knuth's logarithm algorithm */
  96434. #define LOG2_LOOKUP_PRECISION 16
  96435. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96436. {
  96437. /*
  96438. * 0 fraction bits
  96439. */
  96440. /* undefined */ 0x00000000,
  96441. /* lg(2/1) = */ 0x00000001,
  96442. /* lg(4/3) = */ 0x00000000,
  96443. /* lg(8/7) = */ 0x00000000,
  96444. /* lg(16/15) = */ 0x00000000,
  96445. /* lg(32/31) = */ 0x00000000,
  96446. /* lg(64/63) = */ 0x00000000,
  96447. /* lg(128/127) = */ 0x00000000,
  96448. /* lg(256/255) = */ 0x00000000,
  96449. /* lg(512/511) = */ 0x00000000,
  96450. /* lg(1024/1023) = */ 0x00000000,
  96451. /* lg(2048/2047) = */ 0x00000000,
  96452. /* lg(4096/4095) = */ 0x00000000,
  96453. /* lg(8192/8191) = */ 0x00000000,
  96454. /* lg(16384/16383) = */ 0x00000000,
  96455. /* lg(32768/32767) = */ 0x00000000
  96456. },
  96457. {
  96458. /*
  96459. * 4 fraction bits
  96460. */
  96461. /* undefined */ 0x00000000,
  96462. /* lg(2/1) = */ 0x00000010,
  96463. /* lg(4/3) = */ 0x00000007,
  96464. /* lg(8/7) = */ 0x00000003,
  96465. /* lg(16/15) = */ 0x00000001,
  96466. /* lg(32/31) = */ 0x00000001,
  96467. /* lg(64/63) = */ 0x00000000,
  96468. /* lg(128/127) = */ 0x00000000,
  96469. /* lg(256/255) = */ 0x00000000,
  96470. /* lg(512/511) = */ 0x00000000,
  96471. /* lg(1024/1023) = */ 0x00000000,
  96472. /* lg(2048/2047) = */ 0x00000000,
  96473. /* lg(4096/4095) = */ 0x00000000,
  96474. /* lg(8192/8191) = */ 0x00000000,
  96475. /* lg(16384/16383) = */ 0x00000000,
  96476. /* lg(32768/32767) = */ 0x00000000
  96477. },
  96478. {
  96479. /*
  96480. * 8 fraction bits
  96481. */
  96482. /* undefined */ 0x00000000,
  96483. /* lg(2/1) = */ 0x00000100,
  96484. /* lg(4/3) = */ 0x0000006a,
  96485. /* lg(8/7) = */ 0x00000031,
  96486. /* lg(16/15) = */ 0x00000018,
  96487. /* lg(32/31) = */ 0x0000000c,
  96488. /* lg(64/63) = */ 0x00000006,
  96489. /* lg(128/127) = */ 0x00000003,
  96490. /* lg(256/255) = */ 0x00000001,
  96491. /* lg(512/511) = */ 0x00000001,
  96492. /* lg(1024/1023) = */ 0x00000000,
  96493. /* lg(2048/2047) = */ 0x00000000,
  96494. /* lg(4096/4095) = */ 0x00000000,
  96495. /* lg(8192/8191) = */ 0x00000000,
  96496. /* lg(16384/16383) = */ 0x00000000,
  96497. /* lg(32768/32767) = */ 0x00000000
  96498. },
  96499. {
  96500. /*
  96501. * 12 fraction bits
  96502. */
  96503. /* undefined */ 0x00000000,
  96504. /* lg(2/1) = */ 0x00001000,
  96505. /* lg(4/3) = */ 0x000006a4,
  96506. /* lg(8/7) = */ 0x00000315,
  96507. /* lg(16/15) = */ 0x0000017d,
  96508. /* lg(32/31) = */ 0x000000bc,
  96509. /* lg(64/63) = */ 0x0000005d,
  96510. /* lg(128/127) = */ 0x0000002e,
  96511. /* lg(256/255) = */ 0x00000017,
  96512. /* lg(512/511) = */ 0x0000000c,
  96513. /* lg(1024/1023) = */ 0x00000006,
  96514. /* lg(2048/2047) = */ 0x00000003,
  96515. /* lg(4096/4095) = */ 0x00000001,
  96516. /* lg(8192/8191) = */ 0x00000001,
  96517. /* lg(16384/16383) = */ 0x00000000,
  96518. /* lg(32768/32767) = */ 0x00000000
  96519. },
  96520. {
  96521. /*
  96522. * 16 fraction bits
  96523. */
  96524. /* undefined */ 0x00000000,
  96525. /* lg(2/1) = */ 0x00010000,
  96526. /* lg(4/3) = */ 0x00006a40,
  96527. /* lg(8/7) = */ 0x00003151,
  96528. /* lg(16/15) = */ 0x000017d6,
  96529. /* lg(32/31) = */ 0x00000bba,
  96530. /* lg(64/63) = */ 0x000005d1,
  96531. /* lg(128/127) = */ 0x000002e6,
  96532. /* lg(256/255) = */ 0x00000172,
  96533. /* lg(512/511) = */ 0x000000b9,
  96534. /* lg(1024/1023) = */ 0x0000005c,
  96535. /* lg(2048/2047) = */ 0x0000002e,
  96536. /* lg(4096/4095) = */ 0x00000017,
  96537. /* lg(8192/8191) = */ 0x0000000c,
  96538. /* lg(16384/16383) = */ 0x00000006,
  96539. /* lg(32768/32767) = */ 0x00000003
  96540. },
  96541. {
  96542. /*
  96543. * 20 fraction bits
  96544. */
  96545. /* undefined */ 0x00000000,
  96546. /* lg(2/1) = */ 0x00100000,
  96547. /* lg(4/3) = */ 0x0006a3fe,
  96548. /* lg(8/7) = */ 0x00031513,
  96549. /* lg(16/15) = */ 0x00017d60,
  96550. /* lg(32/31) = */ 0x0000bb9d,
  96551. /* lg(64/63) = */ 0x00005d10,
  96552. /* lg(128/127) = */ 0x00002e59,
  96553. /* lg(256/255) = */ 0x00001721,
  96554. /* lg(512/511) = */ 0x00000b8e,
  96555. /* lg(1024/1023) = */ 0x000005c6,
  96556. /* lg(2048/2047) = */ 0x000002e3,
  96557. /* lg(4096/4095) = */ 0x00000171,
  96558. /* lg(8192/8191) = */ 0x000000b9,
  96559. /* lg(16384/16383) = */ 0x0000005c,
  96560. /* lg(32768/32767) = */ 0x0000002e
  96561. },
  96562. {
  96563. /*
  96564. * 24 fraction bits
  96565. */
  96566. /* undefined */ 0x00000000,
  96567. /* lg(2/1) = */ 0x01000000,
  96568. /* lg(4/3) = */ 0x006a3fe6,
  96569. /* lg(8/7) = */ 0x00315130,
  96570. /* lg(16/15) = */ 0x0017d605,
  96571. /* lg(32/31) = */ 0x000bb9ca,
  96572. /* lg(64/63) = */ 0x0005d0fc,
  96573. /* lg(128/127) = */ 0x0002e58f,
  96574. /* lg(256/255) = */ 0x0001720e,
  96575. /* lg(512/511) = */ 0x0000b8d8,
  96576. /* lg(1024/1023) = */ 0x00005c61,
  96577. /* lg(2048/2047) = */ 0x00002e2d,
  96578. /* lg(4096/4095) = */ 0x00001716,
  96579. /* lg(8192/8191) = */ 0x00000b8b,
  96580. /* lg(16384/16383) = */ 0x000005c5,
  96581. /* lg(32768/32767) = */ 0x000002e3
  96582. },
  96583. {
  96584. /*
  96585. * 28 fraction bits
  96586. */
  96587. /* undefined */ 0x00000000,
  96588. /* lg(2/1) = */ 0x10000000,
  96589. /* lg(4/3) = */ 0x06a3fe5c,
  96590. /* lg(8/7) = */ 0x03151301,
  96591. /* lg(16/15) = */ 0x017d6049,
  96592. /* lg(32/31) = */ 0x00bb9ca6,
  96593. /* lg(64/63) = */ 0x005d0fba,
  96594. /* lg(128/127) = */ 0x002e58f7,
  96595. /* lg(256/255) = */ 0x001720da,
  96596. /* lg(512/511) = */ 0x000b8d87,
  96597. /* lg(1024/1023) = */ 0x0005c60b,
  96598. /* lg(2048/2047) = */ 0x0002e2d7,
  96599. /* lg(4096/4095) = */ 0x00017160,
  96600. /* lg(8192/8191) = */ 0x0000b8ad,
  96601. /* lg(16384/16383) = */ 0x00005c56,
  96602. /* lg(32768/32767) = */ 0x00002e2b
  96603. }
  96604. };
  96605. #if 0
  96606. static const FLAC__uint64 log2_lookup_wide[] = {
  96607. {
  96608. /*
  96609. * 32 fraction bits
  96610. */
  96611. /* undefined */ 0x00000000,
  96612. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96613. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96614. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96615. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96616. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96617. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96618. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96619. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96620. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96621. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96622. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96623. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96624. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96625. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96626. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96627. },
  96628. {
  96629. /*
  96630. * 48 fraction bits
  96631. */
  96632. /* undefined */ 0x00000000,
  96633. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96634. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96635. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96636. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96637. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96638. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96639. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96640. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96641. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96642. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96643. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96644. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96645. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96646. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96647. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96648. }
  96649. };
  96650. #endif
  96651. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96652. {
  96653. const FLAC__uint32 ONE = (1u << fracbits);
  96654. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96655. FLAC__ASSERT(fracbits < 32);
  96656. FLAC__ASSERT((fracbits & 0x3) == 0);
  96657. if(x < ONE)
  96658. return 0;
  96659. if(precision > LOG2_LOOKUP_PRECISION)
  96660. precision = LOG2_LOOKUP_PRECISION;
  96661. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96662. {
  96663. FLAC__uint32 y = 0;
  96664. FLAC__uint32 z = x >> 1, k = 1;
  96665. while (x > ONE && k < precision) {
  96666. if (x - z >= ONE) {
  96667. x -= z;
  96668. z = x >> k;
  96669. y += table[k];
  96670. }
  96671. else {
  96672. z >>= 1;
  96673. k++;
  96674. }
  96675. }
  96676. return y;
  96677. }
  96678. }
  96679. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96680. #endif
  96681. /*** End of inlined file: float.c ***/
  96682. /*** Start of inlined file: format.c ***/
  96683. /*** Start of inlined file: juce_FlacHeader.h ***/
  96684. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96685. // tasks..
  96686. #define VERSION "1.2.1"
  96687. #define FLAC__NO_DLL 1
  96688. #if JUCE_MSVC
  96689. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96690. #endif
  96691. #if JUCE_MAC
  96692. #define FLAC__SYS_DARWIN 1
  96693. #endif
  96694. /*** End of inlined file: juce_FlacHeader.h ***/
  96695. #if JUCE_USE_FLAC
  96696. #if HAVE_CONFIG_H
  96697. # include <config.h>
  96698. #endif
  96699. #include <stdio.h>
  96700. #include <stdlib.h> /* for qsort() */
  96701. #include <string.h> /* for memset() */
  96702. #ifndef FLaC__INLINE
  96703. #define FLaC__INLINE
  96704. #endif
  96705. #ifdef min
  96706. #undef min
  96707. #endif
  96708. #define min(a,b) ((a)<(b)?(a):(b))
  96709. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96710. #ifdef _MSC_VER
  96711. #define FLAC__U64L(x) x
  96712. #else
  96713. #define FLAC__U64L(x) x##LLU
  96714. #endif
  96715. /* VERSION should come from configure */
  96716. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96717. ;
  96718. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96719. /* yet one more hack because of MSVC6: */
  96720. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96721. #else
  96722. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96723. #endif
  96724. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96725. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96726. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96727. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96728. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96729. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96730. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96731. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96732. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96733. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96734. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96735. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96736. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96737. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96738. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96739. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96740. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96741. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96742. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96743. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96744. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96745. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96746. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96747. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96748. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96749. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96750. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96751. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96752. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96753. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96754. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96755. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96756. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96757. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96758. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96759. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96760. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96761. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96762. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96763. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96764. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96765. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96766. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96767. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96768. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96769. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96770. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96771. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96772. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96773. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96774. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96775. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96776. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96777. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96778. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96779. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96780. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96781. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96782. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96783. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96784. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96785. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96786. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96787. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96788. "PARTITIONED_RICE",
  96789. "PARTITIONED_RICE2"
  96790. };
  96791. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96792. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96793. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96794. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96795. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96796. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96797. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96798. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96799. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96800. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96801. "CONSTANT",
  96802. "VERBATIM",
  96803. "FIXED",
  96804. "LPC"
  96805. };
  96806. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96807. "INDEPENDENT",
  96808. "LEFT_SIDE",
  96809. "RIGHT_SIDE",
  96810. "MID_SIDE"
  96811. };
  96812. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96813. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96814. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96815. };
  96816. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96817. "STREAMINFO",
  96818. "PADDING",
  96819. "APPLICATION",
  96820. "SEEKTABLE",
  96821. "VORBIS_COMMENT",
  96822. "CUESHEET",
  96823. "PICTURE"
  96824. };
  96825. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96826. "Other",
  96827. "32x32 pixels 'file icon' (PNG only)",
  96828. "Other file icon",
  96829. "Cover (front)",
  96830. "Cover (back)",
  96831. "Leaflet page",
  96832. "Media (e.g. label side of CD)",
  96833. "Lead artist/lead performer/soloist",
  96834. "Artist/performer",
  96835. "Conductor",
  96836. "Band/Orchestra",
  96837. "Composer",
  96838. "Lyricist/text writer",
  96839. "Recording Location",
  96840. "During recording",
  96841. "During performance",
  96842. "Movie/video screen capture",
  96843. "A bright coloured fish",
  96844. "Illustration",
  96845. "Band/artist logotype",
  96846. "Publisher/Studio logotype"
  96847. };
  96848. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96849. {
  96850. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96851. return false;
  96852. }
  96853. else
  96854. return true;
  96855. }
  96856. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96857. {
  96858. if(
  96859. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96860. (
  96861. sample_rate >= (1u << 16) &&
  96862. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96863. )
  96864. ) {
  96865. return false;
  96866. }
  96867. else
  96868. return true;
  96869. }
  96870. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96871. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96872. {
  96873. unsigned i;
  96874. FLAC__uint64 prev_sample_number = 0;
  96875. FLAC__bool got_prev = false;
  96876. FLAC__ASSERT(0 != seek_table);
  96877. for(i = 0; i < seek_table->num_points; i++) {
  96878. if(got_prev) {
  96879. if(
  96880. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96881. seek_table->points[i].sample_number <= prev_sample_number
  96882. )
  96883. return false;
  96884. }
  96885. prev_sample_number = seek_table->points[i].sample_number;
  96886. got_prev = true;
  96887. }
  96888. return true;
  96889. }
  96890. /* used as the sort predicate for qsort() */
  96891. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96892. {
  96893. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96894. if(l->sample_number == r->sample_number)
  96895. return 0;
  96896. else if(l->sample_number < r->sample_number)
  96897. return -1;
  96898. else
  96899. return 1;
  96900. }
  96901. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96902. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96903. {
  96904. unsigned i, j;
  96905. FLAC__bool first;
  96906. FLAC__ASSERT(0 != seek_table);
  96907. /* sort the seekpoints */
  96908. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96909. /* uniquify the seekpoints */
  96910. first = true;
  96911. for(i = j = 0; i < seek_table->num_points; i++) {
  96912. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96913. if(!first) {
  96914. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96915. continue;
  96916. }
  96917. }
  96918. first = false;
  96919. seek_table->points[j++] = seek_table->points[i];
  96920. }
  96921. for(i = j; i < seek_table->num_points; i++) {
  96922. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96923. seek_table->points[i].stream_offset = 0;
  96924. seek_table->points[i].frame_samples = 0;
  96925. }
  96926. return j;
  96927. }
  96928. /*
  96929. * also disallows non-shortest-form encodings, c.f.
  96930. * http://www.unicode.org/versions/corrigendum1.html
  96931. * and a more clear explanation at the end of this section:
  96932. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96933. */
  96934. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96935. {
  96936. FLAC__ASSERT(0 != utf8);
  96937. if ((utf8[0] & 0x80) == 0) {
  96938. return 1;
  96939. }
  96940. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96941. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96942. return 0;
  96943. return 2;
  96944. }
  96945. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96946. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96947. return 0;
  96948. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96949. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96950. return 0;
  96951. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96952. return 0;
  96953. return 3;
  96954. }
  96955. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96956. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96957. return 0;
  96958. return 4;
  96959. }
  96960. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96961. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96962. return 0;
  96963. return 5;
  96964. }
  96965. 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) {
  96966. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96967. return 0;
  96968. return 6;
  96969. }
  96970. else {
  96971. return 0;
  96972. }
  96973. }
  96974. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96975. {
  96976. char c;
  96977. for(c = *name; c; c = *(++name))
  96978. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96979. return false;
  96980. return true;
  96981. }
  96982. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96983. {
  96984. if(length == (unsigned)(-1)) {
  96985. while(*value) {
  96986. unsigned n = utf8len_(value);
  96987. if(n == 0)
  96988. return false;
  96989. value += n;
  96990. }
  96991. }
  96992. else {
  96993. const FLAC__byte *end = value + length;
  96994. while(value < end) {
  96995. unsigned n = utf8len_(value);
  96996. if(n == 0)
  96997. return false;
  96998. value += n;
  96999. }
  97000. if(value != end)
  97001. return false;
  97002. }
  97003. return true;
  97004. }
  97005. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  97006. {
  97007. const FLAC__byte *s, *end;
  97008. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  97009. if(*s < 0x20 || *s > 0x7D)
  97010. return false;
  97011. }
  97012. if(s == end)
  97013. return false;
  97014. s++; /* skip '=' */
  97015. while(s < end) {
  97016. unsigned n = utf8len_(s);
  97017. if(n == 0)
  97018. return false;
  97019. s += n;
  97020. }
  97021. if(s != end)
  97022. return false;
  97023. return true;
  97024. }
  97025. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97026. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97027. {
  97028. unsigned i, j;
  97029. if(check_cd_da_subset) {
  97030. if(cue_sheet->lead_in < 2 * 44100) {
  97031. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97032. return false;
  97033. }
  97034. if(cue_sheet->lead_in % 588 != 0) {
  97035. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97036. return false;
  97037. }
  97038. }
  97039. if(cue_sheet->num_tracks == 0) {
  97040. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97041. return false;
  97042. }
  97043. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97044. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97045. return false;
  97046. }
  97047. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97048. if(cue_sheet->tracks[i].number == 0) {
  97049. if(violation) *violation = "cue sheet may not have a track number 0";
  97050. return false;
  97051. }
  97052. if(check_cd_da_subset) {
  97053. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97054. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97055. return false;
  97056. }
  97057. }
  97058. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97059. if(violation) {
  97060. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97061. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97062. else
  97063. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97064. }
  97065. return false;
  97066. }
  97067. if(i < cue_sheet->num_tracks - 1) {
  97068. if(cue_sheet->tracks[i].num_indices == 0) {
  97069. if(violation) *violation = "cue sheet track must have at least one index point";
  97070. return false;
  97071. }
  97072. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97073. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97074. return false;
  97075. }
  97076. }
  97077. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97078. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97079. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97080. return false;
  97081. }
  97082. if(j > 0) {
  97083. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97084. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97085. return false;
  97086. }
  97087. }
  97088. }
  97089. }
  97090. return true;
  97091. }
  97092. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97093. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97094. {
  97095. char *p;
  97096. FLAC__byte *b;
  97097. for(p = picture->mime_type; *p; p++) {
  97098. if(*p < 0x20 || *p > 0x7e) {
  97099. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97100. return false;
  97101. }
  97102. }
  97103. for(b = picture->description; *b; ) {
  97104. unsigned n = utf8len_(b);
  97105. if(n == 0) {
  97106. if(violation) *violation = "description string must be valid UTF-8";
  97107. return false;
  97108. }
  97109. b += n;
  97110. }
  97111. return true;
  97112. }
  97113. /*
  97114. * These routines are private to libFLAC
  97115. */
  97116. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97117. {
  97118. return
  97119. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97120. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97121. blocksize,
  97122. predictor_order
  97123. );
  97124. }
  97125. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97126. {
  97127. unsigned max_rice_partition_order = 0;
  97128. while(!(blocksize & 1)) {
  97129. max_rice_partition_order++;
  97130. blocksize >>= 1;
  97131. }
  97132. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97133. }
  97134. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97135. {
  97136. unsigned max_rice_partition_order = limit;
  97137. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97138. max_rice_partition_order--;
  97139. FLAC__ASSERT(
  97140. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97141. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97142. );
  97143. return max_rice_partition_order;
  97144. }
  97145. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97146. {
  97147. FLAC__ASSERT(0 != object);
  97148. object->parameters = 0;
  97149. object->raw_bits = 0;
  97150. object->capacity_by_order = 0;
  97151. }
  97152. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97153. {
  97154. FLAC__ASSERT(0 != object);
  97155. if(0 != object->parameters)
  97156. free(object->parameters);
  97157. if(0 != object->raw_bits)
  97158. free(object->raw_bits);
  97159. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97160. }
  97161. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97162. {
  97163. FLAC__ASSERT(0 != object);
  97164. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97165. if(object->capacity_by_order < max_partition_order) {
  97166. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97167. return false;
  97168. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97169. return false;
  97170. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97171. object->capacity_by_order = max_partition_order;
  97172. }
  97173. return true;
  97174. }
  97175. #endif
  97176. /*** End of inlined file: format.c ***/
  97177. /*** Start of inlined file: lpc_flac.c ***/
  97178. /*** Start of inlined file: juce_FlacHeader.h ***/
  97179. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97180. // tasks..
  97181. #define VERSION "1.2.1"
  97182. #define FLAC__NO_DLL 1
  97183. #if JUCE_MSVC
  97184. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97185. #endif
  97186. #if JUCE_MAC
  97187. #define FLAC__SYS_DARWIN 1
  97188. #endif
  97189. /*** End of inlined file: juce_FlacHeader.h ***/
  97190. #if JUCE_USE_FLAC
  97191. #if HAVE_CONFIG_H
  97192. # include <config.h>
  97193. #endif
  97194. #include <math.h>
  97195. /*** Start of inlined file: lpc.h ***/
  97196. #ifndef FLAC__PRIVATE__LPC_H
  97197. #define FLAC__PRIVATE__LPC_H
  97198. #ifdef HAVE_CONFIG_H
  97199. #include <config.h>
  97200. #endif
  97201. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97202. /*
  97203. * FLAC__lpc_window_data()
  97204. * --------------------------------------------------------------------
  97205. * Applies the given window to the data.
  97206. * OPT: asm implementation
  97207. *
  97208. * IN in[0,data_len-1]
  97209. * IN window[0,data_len-1]
  97210. * OUT out[0,lag-1]
  97211. * IN data_len
  97212. */
  97213. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97214. /*
  97215. * FLAC__lpc_compute_autocorrelation()
  97216. * --------------------------------------------------------------------
  97217. * Compute the autocorrelation for lags between 0 and lag-1.
  97218. * Assumes data[] outside of [0,data_len-1] == 0.
  97219. * Asserts that lag > 0.
  97220. *
  97221. * IN data[0,data_len-1]
  97222. * IN data_len
  97223. * IN 0 < lag <= data_len
  97224. * OUT autoc[0,lag-1]
  97225. */
  97226. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97227. #ifndef FLAC__NO_ASM
  97228. # ifdef FLAC__CPU_IA32
  97229. # ifdef FLAC__HAS_NASM
  97230. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97231. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97232. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97233. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97234. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97235. # endif
  97236. # endif
  97237. #endif
  97238. /*
  97239. * FLAC__lpc_compute_lp_coefficients()
  97240. * --------------------------------------------------------------------
  97241. * Computes LP coefficients for orders 1..max_order.
  97242. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97243. * and there is no point in calculating a predictor.
  97244. *
  97245. * IN autoc[0,max_order] autocorrelation values
  97246. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97247. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97248. * *** IMPORTANT:
  97249. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97250. * OUT error[0,max_order-1] error for each order (more
  97251. * specifically, the variance of
  97252. * the error signal times # of
  97253. * samples in the signal)
  97254. *
  97255. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97256. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97257. * in lp_coeff[7][0,7], etc.
  97258. */
  97259. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97260. /*
  97261. * FLAC__lpc_quantize_coefficients()
  97262. * --------------------------------------------------------------------
  97263. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97264. * must be less than 32 (sizeof(FLAC__int32)*8).
  97265. *
  97266. * IN lp_coeff[0,order-1] LP coefficients
  97267. * IN order LP order
  97268. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97269. * desired precision (in bits, including sign
  97270. * bit) of largest coefficient
  97271. * OUT qlp_coeff[0,order-1] quantized coefficients
  97272. * OUT shift # of bits to shift right to get approximated
  97273. * LP coefficients. NOTE: could be negative.
  97274. * RETURN 0 => quantization OK
  97275. * 1 => coefficients require too much shifting for *shift to
  97276. * fit in the LPC subframe header. 'shift' is unset.
  97277. * 2 => coefficients are all zero, which is bad. 'shift' is
  97278. * unset.
  97279. */
  97280. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97281. /*
  97282. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97283. * --------------------------------------------------------------------
  97284. * Compute the residual signal obtained from sutracting the predicted
  97285. * signal from the original.
  97286. *
  97287. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97288. * IN data_len length of original signal
  97289. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97290. * IN order > 0 LP order
  97291. * IN lp_quantization quantization of LP coefficients in bits
  97292. * OUT residual[0,data_len-1] residual signal
  97293. */
  97294. 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[]);
  97295. 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[]);
  97296. #ifndef FLAC__NO_ASM
  97297. # ifdef FLAC__CPU_IA32
  97298. # ifdef FLAC__HAS_NASM
  97299. 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[]);
  97300. 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[]);
  97301. # endif
  97302. # endif
  97303. #endif
  97304. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97305. /*
  97306. * FLAC__lpc_restore_signal()
  97307. * --------------------------------------------------------------------
  97308. * Restore the original signal by summing the residual and the
  97309. * predictor.
  97310. *
  97311. * IN residual[0,data_len-1] residual signal
  97312. * IN data_len length of original signal
  97313. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97314. * IN order > 0 LP order
  97315. * IN lp_quantization quantization of LP coefficients in bits
  97316. * *** IMPORTANT: the caller must pass in the historical samples:
  97317. * IN data[-order,-1] previously-reconstructed historical samples
  97318. * OUT data[0,data_len-1] original signal
  97319. */
  97320. 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[]);
  97321. 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[]);
  97322. #ifndef FLAC__NO_ASM
  97323. # ifdef FLAC__CPU_IA32
  97324. # ifdef FLAC__HAS_NASM
  97325. 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[]);
  97326. 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[]);
  97327. # endif /* FLAC__HAS_NASM */
  97328. # elif defined FLAC__CPU_PPC
  97329. 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[]);
  97330. 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[]);
  97331. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97332. #endif /* FLAC__NO_ASM */
  97333. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97334. /*
  97335. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97336. * --------------------------------------------------------------------
  97337. * Compute the expected number of bits per residual signal sample
  97338. * based on the LP error (which is related to the residual variance).
  97339. *
  97340. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97341. * IN total_samples > 0 # of samples in residual signal
  97342. * RETURN expected bits per sample
  97343. */
  97344. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97345. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97346. /*
  97347. * FLAC__lpc_compute_best_order()
  97348. * --------------------------------------------------------------------
  97349. * Compute the best order from the array of signal errors returned
  97350. * during coefficient computation.
  97351. *
  97352. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97353. * IN max_order > 0 max LP order
  97354. * IN total_samples > 0 # of samples in residual signal
  97355. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97356. * (includes warmup sample size and quantized LP coefficient)
  97357. * RETURN [1,max_order] best order
  97358. */
  97359. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97360. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97361. #endif
  97362. /*** End of inlined file: lpc.h ***/
  97363. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97364. #include <stdio.h>
  97365. #endif
  97366. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97367. #ifndef M_LN2
  97368. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97369. #define M_LN2 0.69314718055994530942
  97370. #endif
  97371. /* OPT: #undef'ing this may improve the speed on some architectures */
  97372. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97373. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97374. {
  97375. unsigned i;
  97376. for(i = 0; i < data_len; i++)
  97377. out[i] = in[i] * window[i];
  97378. }
  97379. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97380. {
  97381. /* a readable, but slower, version */
  97382. #if 0
  97383. FLAC__real d;
  97384. unsigned i;
  97385. FLAC__ASSERT(lag > 0);
  97386. FLAC__ASSERT(lag <= data_len);
  97387. /*
  97388. * Technically we should subtract the mean first like so:
  97389. * for(i = 0; i < data_len; i++)
  97390. * data[i] -= mean;
  97391. * but it appears not to make enough of a difference to matter, and
  97392. * most signals are already closely centered around zero
  97393. */
  97394. while(lag--) {
  97395. for(i = lag, d = 0.0; i < data_len; i++)
  97396. d += data[i] * data[i - lag];
  97397. autoc[lag] = d;
  97398. }
  97399. #endif
  97400. /*
  97401. * this version tends to run faster because of better data locality
  97402. * ('data_len' is usually much larger than 'lag')
  97403. */
  97404. FLAC__real d;
  97405. unsigned sample, coeff;
  97406. const unsigned limit = data_len - lag;
  97407. FLAC__ASSERT(lag > 0);
  97408. FLAC__ASSERT(lag <= data_len);
  97409. for(coeff = 0; coeff < lag; coeff++)
  97410. autoc[coeff] = 0.0;
  97411. for(sample = 0; sample <= limit; sample++) {
  97412. d = data[sample];
  97413. for(coeff = 0; coeff < lag; coeff++)
  97414. autoc[coeff] += d * data[sample+coeff];
  97415. }
  97416. for(; sample < data_len; sample++) {
  97417. d = data[sample];
  97418. for(coeff = 0; coeff < data_len - sample; coeff++)
  97419. autoc[coeff] += d * data[sample+coeff];
  97420. }
  97421. }
  97422. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97423. {
  97424. unsigned i, j;
  97425. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97426. FLAC__ASSERT(0 != max_order);
  97427. FLAC__ASSERT(0 < *max_order);
  97428. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97429. FLAC__ASSERT(autoc[0] != 0.0);
  97430. err = autoc[0];
  97431. for(i = 0; i < *max_order; i++) {
  97432. /* Sum up this iteration's reflection coefficient. */
  97433. r = -autoc[i+1];
  97434. for(j = 0; j < i; j++)
  97435. r -= lpc[j] * autoc[i-j];
  97436. ref[i] = (r/=err);
  97437. /* Update LPC coefficients and total error. */
  97438. lpc[i]=r;
  97439. for(j = 0; j < (i>>1); j++) {
  97440. FLAC__double tmp = lpc[j];
  97441. lpc[j] += r * lpc[i-1-j];
  97442. lpc[i-1-j] += r * tmp;
  97443. }
  97444. if(i & 1)
  97445. lpc[j] += lpc[j] * r;
  97446. err *= (1.0 - r * r);
  97447. /* save this order */
  97448. for(j = 0; j <= i; j++)
  97449. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97450. error[i] = err;
  97451. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97452. if(err == 0.0) {
  97453. *max_order = i+1;
  97454. return;
  97455. }
  97456. }
  97457. }
  97458. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97459. {
  97460. unsigned i;
  97461. FLAC__double cmax;
  97462. FLAC__int32 qmax, qmin;
  97463. FLAC__ASSERT(precision > 0);
  97464. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97465. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97466. precision--;
  97467. qmax = 1 << precision;
  97468. qmin = -qmax;
  97469. qmax--;
  97470. /* calc cmax = max( |lp_coeff[i]| ) */
  97471. cmax = 0.0;
  97472. for(i = 0; i < order; i++) {
  97473. const FLAC__double d = fabs(lp_coeff[i]);
  97474. if(d > cmax)
  97475. cmax = d;
  97476. }
  97477. if(cmax <= 0.0) {
  97478. /* => coefficients are all 0, which means our constant-detect didn't work */
  97479. return 2;
  97480. }
  97481. else {
  97482. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97483. const int min_shiftlimit = -max_shiftlimit - 1;
  97484. int log2cmax;
  97485. (void)frexp(cmax, &log2cmax);
  97486. log2cmax--;
  97487. *shift = (int)precision - log2cmax - 1;
  97488. if(*shift > max_shiftlimit)
  97489. *shift = max_shiftlimit;
  97490. else if(*shift < min_shiftlimit)
  97491. return 1;
  97492. }
  97493. if(*shift >= 0) {
  97494. FLAC__double error = 0.0;
  97495. FLAC__int32 q;
  97496. for(i = 0; i < order; i++) {
  97497. error += lp_coeff[i] * (1 << *shift);
  97498. #if 1 /* unfortunately lround() is C99 */
  97499. if(error >= 0.0)
  97500. q = (FLAC__int32)(error + 0.5);
  97501. else
  97502. q = (FLAC__int32)(error - 0.5);
  97503. #else
  97504. q = lround(error);
  97505. #endif
  97506. #ifdef FLAC__OVERFLOW_DETECT
  97507. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97508. 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]);
  97509. else if(q < qmin)
  97510. 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]);
  97511. #endif
  97512. if(q > qmax)
  97513. q = qmax;
  97514. else if(q < qmin)
  97515. q = qmin;
  97516. error -= q;
  97517. qlp_coeff[i] = q;
  97518. }
  97519. }
  97520. /* negative shift is very rare but due to design flaw, negative shift is
  97521. * a NOP in the decoder, so it must be handled specially by scaling down
  97522. * coeffs
  97523. */
  97524. else {
  97525. const int nshift = -(*shift);
  97526. FLAC__double error = 0.0;
  97527. FLAC__int32 q;
  97528. #ifdef DEBUG
  97529. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97530. #endif
  97531. for(i = 0; i < order; i++) {
  97532. error += lp_coeff[i] / (1 << nshift);
  97533. #if 1 /* unfortunately lround() is C99 */
  97534. if(error >= 0.0)
  97535. q = (FLAC__int32)(error + 0.5);
  97536. else
  97537. q = (FLAC__int32)(error - 0.5);
  97538. #else
  97539. q = lround(error);
  97540. #endif
  97541. #ifdef FLAC__OVERFLOW_DETECT
  97542. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97543. 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]);
  97544. else if(q < qmin)
  97545. 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]);
  97546. #endif
  97547. if(q > qmax)
  97548. q = qmax;
  97549. else if(q < qmin)
  97550. q = qmin;
  97551. error -= q;
  97552. qlp_coeff[i] = q;
  97553. }
  97554. *shift = 0;
  97555. }
  97556. return 0;
  97557. }
  97558. 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[])
  97559. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97560. {
  97561. FLAC__int64 sumo;
  97562. unsigned i, j;
  97563. FLAC__int32 sum;
  97564. const FLAC__int32 *history;
  97565. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97566. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97567. for(i=0;i<order;i++)
  97568. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97569. fprintf(stderr,"\n");
  97570. #endif
  97571. FLAC__ASSERT(order > 0);
  97572. for(i = 0; i < data_len; i++) {
  97573. sumo = 0;
  97574. sum = 0;
  97575. history = data;
  97576. for(j = 0; j < order; j++) {
  97577. sum += qlp_coeff[j] * (*(--history));
  97578. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97579. #if defined _MSC_VER
  97580. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97581. 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);
  97582. #else
  97583. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97584. 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);
  97585. #endif
  97586. }
  97587. *(residual++) = *(data++) - (sum >> lp_quantization);
  97588. }
  97589. /* Here's a slower but clearer version:
  97590. for(i = 0; i < data_len; i++) {
  97591. sum = 0;
  97592. for(j = 0; j < order; j++)
  97593. sum += qlp_coeff[j] * data[i-j-1];
  97594. residual[i] = data[i] - (sum >> lp_quantization);
  97595. }
  97596. */
  97597. }
  97598. #else /* fully unrolled version for normal use */
  97599. {
  97600. int i;
  97601. FLAC__int32 sum;
  97602. FLAC__ASSERT(order > 0);
  97603. FLAC__ASSERT(order <= 32);
  97604. /*
  97605. * We do unique versions up to 12th order since that's the subset limit.
  97606. * Also they are roughly ordered to match frequency of occurrence to
  97607. * minimize branching.
  97608. */
  97609. if(order <= 12) {
  97610. if(order > 8) {
  97611. if(order > 10) {
  97612. if(order == 12) {
  97613. for(i = 0; i < (int)data_len; i++) {
  97614. sum = 0;
  97615. sum += qlp_coeff[11] * data[i-12];
  97616. sum += qlp_coeff[10] * data[i-11];
  97617. sum += qlp_coeff[9] * data[i-10];
  97618. sum += qlp_coeff[8] * data[i-9];
  97619. sum += qlp_coeff[7] * data[i-8];
  97620. sum += qlp_coeff[6] * data[i-7];
  97621. sum += qlp_coeff[5] * data[i-6];
  97622. sum += qlp_coeff[4] * data[i-5];
  97623. sum += qlp_coeff[3] * data[i-4];
  97624. sum += qlp_coeff[2] * data[i-3];
  97625. sum += qlp_coeff[1] * data[i-2];
  97626. sum += qlp_coeff[0] * data[i-1];
  97627. residual[i] = data[i] - (sum >> lp_quantization);
  97628. }
  97629. }
  97630. else { /* order == 11 */
  97631. for(i = 0; i < (int)data_len; i++) {
  97632. sum = 0;
  97633. sum += qlp_coeff[10] * data[i-11];
  97634. sum += qlp_coeff[9] * data[i-10];
  97635. sum += qlp_coeff[8] * data[i-9];
  97636. sum += qlp_coeff[7] * data[i-8];
  97637. sum += qlp_coeff[6] * data[i-7];
  97638. sum += qlp_coeff[5] * data[i-6];
  97639. sum += qlp_coeff[4] * data[i-5];
  97640. sum += qlp_coeff[3] * data[i-4];
  97641. sum += qlp_coeff[2] * data[i-3];
  97642. sum += qlp_coeff[1] * data[i-2];
  97643. sum += qlp_coeff[0] * data[i-1];
  97644. residual[i] = data[i] - (sum >> lp_quantization);
  97645. }
  97646. }
  97647. }
  97648. else {
  97649. if(order == 10) {
  97650. for(i = 0; i < (int)data_len; i++) {
  97651. sum = 0;
  97652. sum += qlp_coeff[9] * data[i-10];
  97653. sum += qlp_coeff[8] * data[i-9];
  97654. sum += qlp_coeff[7] * data[i-8];
  97655. sum += qlp_coeff[6] * data[i-7];
  97656. sum += qlp_coeff[5] * data[i-6];
  97657. sum += qlp_coeff[4] * data[i-5];
  97658. sum += qlp_coeff[3] * data[i-4];
  97659. sum += qlp_coeff[2] * data[i-3];
  97660. sum += qlp_coeff[1] * data[i-2];
  97661. sum += qlp_coeff[0] * data[i-1];
  97662. residual[i] = data[i] - (sum >> lp_quantization);
  97663. }
  97664. }
  97665. else { /* order == 9 */
  97666. for(i = 0; i < (int)data_len; i++) {
  97667. sum = 0;
  97668. sum += qlp_coeff[8] * data[i-9];
  97669. sum += qlp_coeff[7] * data[i-8];
  97670. sum += qlp_coeff[6] * data[i-7];
  97671. sum += qlp_coeff[5] * data[i-6];
  97672. sum += qlp_coeff[4] * data[i-5];
  97673. sum += qlp_coeff[3] * data[i-4];
  97674. sum += qlp_coeff[2] * data[i-3];
  97675. sum += qlp_coeff[1] * data[i-2];
  97676. sum += qlp_coeff[0] * data[i-1];
  97677. residual[i] = data[i] - (sum >> lp_quantization);
  97678. }
  97679. }
  97680. }
  97681. }
  97682. else if(order > 4) {
  97683. if(order > 6) {
  97684. if(order == 8) {
  97685. for(i = 0; i < (int)data_len; i++) {
  97686. sum = 0;
  97687. sum += qlp_coeff[7] * data[i-8];
  97688. sum += qlp_coeff[6] * data[i-7];
  97689. sum += qlp_coeff[5] * data[i-6];
  97690. sum += qlp_coeff[4] * data[i-5];
  97691. sum += qlp_coeff[3] * data[i-4];
  97692. sum += qlp_coeff[2] * data[i-3];
  97693. sum += qlp_coeff[1] * data[i-2];
  97694. sum += qlp_coeff[0] * data[i-1];
  97695. residual[i] = data[i] - (sum >> lp_quantization);
  97696. }
  97697. }
  97698. else { /* order == 7 */
  97699. for(i = 0; i < (int)data_len; i++) {
  97700. sum = 0;
  97701. sum += qlp_coeff[6] * data[i-7];
  97702. sum += qlp_coeff[5] * data[i-6];
  97703. sum += qlp_coeff[4] * data[i-5];
  97704. sum += qlp_coeff[3] * data[i-4];
  97705. sum += qlp_coeff[2] * data[i-3];
  97706. sum += qlp_coeff[1] * data[i-2];
  97707. sum += qlp_coeff[0] * data[i-1];
  97708. residual[i] = data[i] - (sum >> lp_quantization);
  97709. }
  97710. }
  97711. }
  97712. else {
  97713. if(order == 6) {
  97714. for(i = 0; i < (int)data_len; i++) {
  97715. sum = 0;
  97716. sum += qlp_coeff[5] * data[i-6];
  97717. sum += qlp_coeff[4] * data[i-5];
  97718. sum += qlp_coeff[3] * data[i-4];
  97719. sum += qlp_coeff[2] * data[i-3];
  97720. sum += qlp_coeff[1] * data[i-2];
  97721. sum += qlp_coeff[0] * data[i-1];
  97722. residual[i] = data[i] - (sum >> lp_quantization);
  97723. }
  97724. }
  97725. else { /* order == 5 */
  97726. for(i = 0; i < (int)data_len; i++) {
  97727. sum = 0;
  97728. sum += qlp_coeff[4] * data[i-5];
  97729. sum += qlp_coeff[3] * data[i-4];
  97730. sum += qlp_coeff[2] * data[i-3];
  97731. sum += qlp_coeff[1] * data[i-2];
  97732. sum += qlp_coeff[0] * data[i-1];
  97733. residual[i] = data[i] - (sum >> lp_quantization);
  97734. }
  97735. }
  97736. }
  97737. }
  97738. else {
  97739. if(order > 2) {
  97740. if(order == 4) {
  97741. for(i = 0; i < (int)data_len; i++) {
  97742. sum = 0;
  97743. sum += qlp_coeff[3] * data[i-4];
  97744. sum += qlp_coeff[2] * data[i-3];
  97745. sum += qlp_coeff[1] * data[i-2];
  97746. sum += qlp_coeff[0] * data[i-1];
  97747. residual[i] = data[i] - (sum >> lp_quantization);
  97748. }
  97749. }
  97750. else { /* order == 3 */
  97751. for(i = 0; i < (int)data_len; i++) {
  97752. sum = 0;
  97753. sum += qlp_coeff[2] * data[i-3];
  97754. sum += qlp_coeff[1] * data[i-2];
  97755. sum += qlp_coeff[0] * data[i-1];
  97756. residual[i] = data[i] - (sum >> lp_quantization);
  97757. }
  97758. }
  97759. }
  97760. else {
  97761. if(order == 2) {
  97762. for(i = 0; i < (int)data_len; i++) {
  97763. sum = 0;
  97764. sum += qlp_coeff[1] * data[i-2];
  97765. sum += qlp_coeff[0] * data[i-1];
  97766. residual[i] = data[i] - (sum >> lp_quantization);
  97767. }
  97768. }
  97769. else { /* order == 1 */
  97770. for(i = 0; i < (int)data_len; i++)
  97771. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97772. }
  97773. }
  97774. }
  97775. }
  97776. else { /* order > 12 */
  97777. for(i = 0; i < (int)data_len; i++) {
  97778. sum = 0;
  97779. switch(order) {
  97780. case 32: sum += qlp_coeff[31] * data[i-32];
  97781. case 31: sum += qlp_coeff[30] * data[i-31];
  97782. case 30: sum += qlp_coeff[29] * data[i-30];
  97783. case 29: sum += qlp_coeff[28] * data[i-29];
  97784. case 28: sum += qlp_coeff[27] * data[i-28];
  97785. case 27: sum += qlp_coeff[26] * data[i-27];
  97786. case 26: sum += qlp_coeff[25] * data[i-26];
  97787. case 25: sum += qlp_coeff[24] * data[i-25];
  97788. case 24: sum += qlp_coeff[23] * data[i-24];
  97789. case 23: sum += qlp_coeff[22] * data[i-23];
  97790. case 22: sum += qlp_coeff[21] * data[i-22];
  97791. case 21: sum += qlp_coeff[20] * data[i-21];
  97792. case 20: sum += qlp_coeff[19] * data[i-20];
  97793. case 19: sum += qlp_coeff[18] * data[i-19];
  97794. case 18: sum += qlp_coeff[17] * data[i-18];
  97795. case 17: sum += qlp_coeff[16] * data[i-17];
  97796. case 16: sum += qlp_coeff[15] * data[i-16];
  97797. case 15: sum += qlp_coeff[14] * data[i-15];
  97798. case 14: sum += qlp_coeff[13] * data[i-14];
  97799. case 13: sum += qlp_coeff[12] * data[i-13];
  97800. sum += qlp_coeff[11] * data[i-12];
  97801. sum += qlp_coeff[10] * data[i-11];
  97802. sum += qlp_coeff[ 9] * data[i-10];
  97803. sum += qlp_coeff[ 8] * data[i- 9];
  97804. sum += qlp_coeff[ 7] * data[i- 8];
  97805. sum += qlp_coeff[ 6] * data[i- 7];
  97806. sum += qlp_coeff[ 5] * data[i- 6];
  97807. sum += qlp_coeff[ 4] * data[i- 5];
  97808. sum += qlp_coeff[ 3] * data[i- 4];
  97809. sum += qlp_coeff[ 2] * data[i- 3];
  97810. sum += qlp_coeff[ 1] * data[i- 2];
  97811. sum += qlp_coeff[ 0] * data[i- 1];
  97812. }
  97813. residual[i] = data[i] - (sum >> lp_quantization);
  97814. }
  97815. }
  97816. }
  97817. #endif
  97818. 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[])
  97819. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97820. {
  97821. unsigned i, j;
  97822. FLAC__int64 sum;
  97823. const FLAC__int32 *history;
  97824. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97825. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97826. for(i=0;i<order;i++)
  97827. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97828. fprintf(stderr,"\n");
  97829. #endif
  97830. FLAC__ASSERT(order > 0);
  97831. for(i = 0; i < data_len; i++) {
  97832. sum = 0;
  97833. history = data;
  97834. for(j = 0; j < order; j++)
  97835. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97836. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97837. #if defined _MSC_VER
  97838. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97839. #else
  97840. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97841. #endif
  97842. break;
  97843. }
  97844. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97845. #if defined _MSC_VER
  97846. 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));
  97847. #else
  97848. 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)));
  97849. #endif
  97850. break;
  97851. }
  97852. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97853. }
  97854. }
  97855. #else /* fully unrolled version for normal use */
  97856. {
  97857. int i;
  97858. FLAC__int64 sum;
  97859. FLAC__ASSERT(order > 0);
  97860. FLAC__ASSERT(order <= 32);
  97861. /*
  97862. * We do unique versions up to 12th order since that's the subset limit.
  97863. * Also they are roughly ordered to match frequency of occurrence to
  97864. * minimize branching.
  97865. */
  97866. if(order <= 12) {
  97867. if(order > 8) {
  97868. if(order > 10) {
  97869. if(order == 12) {
  97870. for(i = 0; i < (int)data_len; i++) {
  97871. sum = 0;
  97872. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97873. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97874. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97875. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97876. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97877. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97878. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97879. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97880. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97881. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97882. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97883. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97884. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97885. }
  97886. }
  97887. else { /* order == 11 */
  97888. for(i = 0; i < (int)data_len; i++) {
  97889. sum = 0;
  97890. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97891. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97892. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97893. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97894. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97895. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97896. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97897. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97898. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97899. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97900. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97901. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97902. }
  97903. }
  97904. }
  97905. else {
  97906. if(order == 10) {
  97907. for(i = 0; i < (int)data_len; i++) {
  97908. sum = 0;
  97909. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97910. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97911. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97912. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97913. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97914. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97915. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97916. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97917. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97918. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97919. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97920. }
  97921. }
  97922. else { /* order == 9 */
  97923. for(i = 0; i < (int)data_len; i++) {
  97924. sum = 0;
  97925. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97926. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97927. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97928. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97929. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97930. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97931. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97932. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97933. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97934. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97935. }
  97936. }
  97937. }
  97938. }
  97939. else if(order > 4) {
  97940. if(order > 6) {
  97941. if(order == 8) {
  97942. for(i = 0; i < (int)data_len; i++) {
  97943. sum = 0;
  97944. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97945. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97946. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97947. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97948. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97949. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97950. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97951. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97952. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97953. }
  97954. }
  97955. else { /* order == 7 */
  97956. for(i = 0; i < (int)data_len; i++) {
  97957. sum = 0;
  97958. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97959. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97960. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97961. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97962. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97963. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97964. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97965. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97966. }
  97967. }
  97968. }
  97969. else {
  97970. if(order == 6) {
  97971. for(i = 0; i < (int)data_len; i++) {
  97972. sum = 0;
  97973. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97974. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97975. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97976. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97977. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97978. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97979. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97980. }
  97981. }
  97982. else { /* order == 5 */
  97983. for(i = 0; i < (int)data_len; i++) {
  97984. sum = 0;
  97985. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97986. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97987. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97988. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97989. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97990. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97991. }
  97992. }
  97993. }
  97994. }
  97995. else {
  97996. if(order > 2) {
  97997. if(order == 4) {
  97998. for(i = 0; i < (int)data_len; i++) {
  97999. sum = 0;
  98000. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98001. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98002. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98003. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98004. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98005. }
  98006. }
  98007. else { /* order == 3 */
  98008. for(i = 0; i < (int)data_len; i++) {
  98009. sum = 0;
  98010. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98011. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98012. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98013. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98014. }
  98015. }
  98016. }
  98017. else {
  98018. if(order == 2) {
  98019. for(i = 0; i < (int)data_len; i++) {
  98020. sum = 0;
  98021. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98022. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98023. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98024. }
  98025. }
  98026. else { /* order == 1 */
  98027. for(i = 0; i < (int)data_len; i++)
  98028. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98029. }
  98030. }
  98031. }
  98032. }
  98033. else { /* order > 12 */
  98034. for(i = 0; i < (int)data_len; i++) {
  98035. sum = 0;
  98036. switch(order) {
  98037. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98038. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98039. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98040. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98041. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98042. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98043. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98044. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98045. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98046. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98047. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98048. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98049. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98050. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98051. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98052. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98053. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98054. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98055. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98056. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98057. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98058. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98059. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98060. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98061. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98062. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98063. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98064. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98065. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98066. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98067. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98068. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98069. }
  98070. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98071. }
  98072. }
  98073. }
  98074. #endif
  98075. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98076. 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[])
  98077. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98078. {
  98079. FLAC__int64 sumo;
  98080. unsigned i, j;
  98081. FLAC__int32 sum;
  98082. const FLAC__int32 *r = residual, *history;
  98083. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98084. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98085. for(i=0;i<order;i++)
  98086. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98087. fprintf(stderr,"\n");
  98088. #endif
  98089. FLAC__ASSERT(order > 0);
  98090. for(i = 0; i < data_len; i++) {
  98091. sumo = 0;
  98092. sum = 0;
  98093. history = data;
  98094. for(j = 0; j < order; j++) {
  98095. sum += qlp_coeff[j] * (*(--history));
  98096. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98097. #if defined _MSC_VER
  98098. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98099. 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);
  98100. #else
  98101. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98102. 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);
  98103. #endif
  98104. }
  98105. *(data++) = *(r++) + (sum >> lp_quantization);
  98106. }
  98107. /* Here's a slower but clearer version:
  98108. for(i = 0; i < data_len; i++) {
  98109. sum = 0;
  98110. for(j = 0; j < order; j++)
  98111. sum += qlp_coeff[j] * data[i-j-1];
  98112. data[i] = residual[i] + (sum >> lp_quantization);
  98113. }
  98114. */
  98115. }
  98116. #else /* fully unrolled version for normal use */
  98117. {
  98118. int i;
  98119. FLAC__int32 sum;
  98120. FLAC__ASSERT(order > 0);
  98121. FLAC__ASSERT(order <= 32);
  98122. /*
  98123. * We do unique versions up to 12th order since that's the subset limit.
  98124. * Also they are roughly ordered to match frequency of occurrence to
  98125. * minimize branching.
  98126. */
  98127. if(order <= 12) {
  98128. if(order > 8) {
  98129. if(order > 10) {
  98130. if(order == 12) {
  98131. for(i = 0; i < (int)data_len; i++) {
  98132. sum = 0;
  98133. sum += qlp_coeff[11] * data[i-12];
  98134. sum += qlp_coeff[10] * data[i-11];
  98135. sum += qlp_coeff[9] * data[i-10];
  98136. sum += qlp_coeff[8] * data[i-9];
  98137. sum += qlp_coeff[7] * data[i-8];
  98138. sum += qlp_coeff[6] * data[i-7];
  98139. sum += qlp_coeff[5] * data[i-6];
  98140. sum += qlp_coeff[4] * data[i-5];
  98141. sum += qlp_coeff[3] * data[i-4];
  98142. sum += qlp_coeff[2] * data[i-3];
  98143. sum += qlp_coeff[1] * data[i-2];
  98144. sum += qlp_coeff[0] * data[i-1];
  98145. data[i] = residual[i] + (sum >> lp_quantization);
  98146. }
  98147. }
  98148. else { /* order == 11 */
  98149. for(i = 0; i < (int)data_len; i++) {
  98150. sum = 0;
  98151. sum += qlp_coeff[10] * data[i-11];
  98152. sum += qlp_coeff[9] * data[i-10];
  98153. sum += qlp_coeff[8] * data[i-9];
  98154. sum += qlp_coeff[7] * data[i-8];
  98155. sum += qlp_coeff[6] * data[i-7];
  98156. sum += qlp_coeff[5] * data[i-6];
  98157. sum += qlp_coeff[4] * data[i-5];
  98158. sum += qlp_coeff[3] * data[i-4];
  98159. sum += qlp_coeff[2] * data[i-3];
  98160. sum += qlp_coeff[1] * data[i-2];
  98161. sum += qlp_coeff[0] * data[i-1];
  98162. data[i] = residual[i] + (sum >> lp_quantization);
  98163. }
  98164. }
  98165. }
  98166. else {
  98167. if(order == 10) {
  98168. for(i = 0; i < (int)data_len; i++) {
  98169. sum = 0;
  98170. sum += qlp_coeff[9] * data[i-10];
  98171. sum += qlp_coeff[8] * data[i-9];
  98172. sum += qlp_coeff[7] * data[i-8];
  98173. sum += qlp_coeff[6] * data[i-7];
  98174. sum += qlp_coeff[5] * data[i-6];
  98175. sum += qlp_coeff[4] * data[i-5];
  98176. sum += qlp_coeff[3] * data[i-4];
  98177. sum += qlp_coeff[2] * data[i-3];
  98178. sum += qlp_coeff[1] * data[i-2];
  98179. sum += qlp_coeff[0] * data[i-1];
  98180. data[i] = residual[i] + (sum >> lp_quantization);
  98181. }
  98182. }
  98183. else { /* order == 9 */
  98184. for(i = 0; i < (int)data_len; i++) {
  98185. sum = 0;
  98186. sum += qlp_coeff[8] * data[i-9];
  98187. sum += qlp_coeff[7] * data[i-8];
  98188. sum += qlp_coeff[6] * data[i-7];
  98189. sum += qlp_coeff[5] * data[i-6];
  98190. sum += qlp_coeff[4] * data[i-5];
  98191. sum += qlp_coeff[3] * data[i-4];
  98192. sum += qlp_coeff[2] * data[i-3];
  98193. sum += qlp_coeff[1] * data[i-2];
  98194. sum += qlp_coeff[0] * data[i-1];
  98195. data[i] = residual[i] + (sum >> lp_quantization);
  98196. }
  98197. }
  98198. }
  98199. }
  98200. else if(order > 4) {
  98201. if(order > 6) {
  98202. if(order == 8) {
  98203. for(i = 0; i < (int)data_len; i++) {
  98204. sum = 0;
  98205. sum += qlp_coeff[7] * data[i-8];
  98206. sum += qlp_coeff[6] * data[i-7];
  98207. sum += qlp_coeff[5] * data[i-6];
  98208. sum += qlp_coeff[4] * data[i-5];
  98209. sum += qlp_coeff[3] * data[i-4];
  98210. sum += qlp_coeff[2] * data[i-3];
  98211. sum += qlp_coeff[1] * data[i-2];
  98212. sum += qlp_coeff[0] * data[i-1];
  98213. data[i] = residual[i] + (sum >> lp_quantization);
  98214. }
  98215. }
  98216. else { /* order == 7 */
  98217. for(i = 0; i < (int)data_len; i++) {
  98218. sum = 0;
  98219. sum += qlp_coeff[6] * data[i-7];
  98220. sum += qlp_coeff[5] * data[i-6];
  98221. sum += qlp_coeff[4] * data[i-5];
  98222. sum += qlp_coeff[3] * data[i-4];
  98223. sum += qlp_coeff[2] * data[i-3];
  98224. sum += qlp_coeff[1] * data[i-2];
  98225. sum += qlp_coeff[0] * data[i-1];
  98226. data[i] = residual[i] + (sum >> lp_quantization);
  98227. }
  98228. }
  98229. }
  98230. else {
  98231. if(order == 6) {
  98232. for(i = 0; i < (int)data_len; i++) {
  98233. sum = 0;
  98234. sum += qlp_coeff[5] * data[i-6];
  98235. sum += qlp_coeff[4] * data[i-5];
  98236. sum += qlp_coeff[3] * data[i-4];
  98237. sum += qlp_coeff[2] * data[i-3];
  98238. sum += qlp_coeff[1] * data[i-2];
  98239. sum += qlp_coeff[0] * data[i-1];
  98240. data[i] = residual[i] + (sum >> lp_quantization);
  98241. }
  98242. }
  98243. else { /* order == 5 */
  98244. for(i = 0; i < (int)data_len; i++) {
  98245. sum = 0;
  98246. sum += qlp_coeff[4] * data[i-5];
  98247. sum += qlp_coeff[3] * data[i-4];
  98248. sum += qlp_coeff[2] * data[i-3];
  98249. sum += qlp_coeff[1] * data[i-2];
  98250. sum += qlp_coeff[0] * data[i-1];
  98251. data[i] = residual[i] + (sum >> lp_quantization);
  98252. }
  98253. }
  98254. }
  98255. }
  98256. else {
  98257. if(order > 2) {
  98258. if(order == 4) {
  98259. for(i = 0; i < (int)data_len; i++) {
  98260. sum = 0;
  98261. sum += qlp_coeff[3] * data[i-4];
  98262. sum += qlp_coeff[2] * data[i-3];
  98263. sum += qlp_coeff[1] * data[i-2];
  98264. sum += qlp_coeff[0] * data[i-1];
  98265. data[i] = residual[i] + (sum >> lp_quantization);
  98266. }
  98267. }
  98268. else { /* order == 3 */
  98269. for(i = 0; i < (int)data_len; i++) {
  98270. sum = 0;
  98271. sum += qlp_coeff[2] * data[i-3];
  98272. sum += qlp_coeff[1] * data[i-2];
  98273. sum += qlp_coeff[0] * data[i-1];
  98274. data[i] = residual[i] + (sum >> lp_quantization);
  98275. }
  98276. }
  98277. }
  98278. else {
  98279. if(order == 2) {
  98280. for(i = 0; i < (int)data_len; i++) {
  98281. sum = 0;
  98282. sum += qlp_coeff[1] * data[i-2];
  98283. sum += qlp_coeff[0] * data[i-1];
  98284. data[i] = residual[i] + (sum >> lp_quantization);
  98285. }
  98286. }
  98287. else { /* order == 1 */
  98288. for(i = 0; i < (int)data_len; i++)
  98289. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98290. }
  98291. }
  98292. }
  98293. }
  98294. else { /* order > 12 */
  98295. for(i = 0; i < (int)data_len; i++) {
  98296. sum = 0;
  98297. switch(order) {
  98298. case 32: sum += qlp_coeff[31] * data[i-32];
  98299. case 31: sum += qlp_coeff[30] * data[i-31];
  98300. case 30: sum += qlp_coeff[29] * data[i-30];
  98301. case 29: sum += qlp_coeff[28] * data[i-29];
  98302. case 28: sum += qlp_coeff[27] * data[i-28];
  98303. case 27: sum += qlp_coeff[26] * data[i-27];
  98304. case 26: sum += qlp_coeff[25] * data[i-26];
  98305. case 25: sum += qlp_coeff[24] * data[i-25];
  98306. case 24: sum += qlp_coeff[23] * data[i-24];
  98307. case 23: sum += qlp_coeff[22] * data[i-23];
  98308. case 22: sum += qlp_coeff[21] * data[i-22];
  98309. case 21: sum += qlp_coeff[20] * data[i-21];
  98310. case 20: sum += qlp_coeff[19] * data[i-20];
  98311. case 19: sum += qlp_coeff[18] * data[i-19];
  98312. case 18: sum += qlp_coeff[17] * data[i-18];
  98313. case 17: sum += qlp_coeff[16] * data[i-17];
  98314. case 16: sum += qlp_coeff[15] * data[i-16];
  98315. case 15: sum += qlp_coeff[14] * data[i-15];
  98316. case 14: sum += qlp_coeff[13] * data[i-14];
  98317. case 13: sum += qlp_coeff[12] * data[i-13];
  98318. sum += qlp_coeff[11] * data[i-12];
  98319. sum += qlp_coeff[10] * data[i-11];
  98320. sum += qlp_coeff[ 9] * data[i-10];
  98321. sum += qlp_coeff[ 8] * data[i- 9];
  98322. sum += qlp_coeff[ 7] * data[i- 8];
  98323. sum += qlp_coeff[ 6] * data[i- 7];
  98324. sum += qlp_coeff[ 5] * data[i- 6];
  98325. sum += qlp_coeff[ 4] * data[i- 5];
  98326. sum += qlp_coeff[ 3] * data[i- 4];
  98327. sum += qlp_coeff[ 2] * data[i- 3];
  98328. sum += qlp_coeff[ 1] * data[i- 2];
  98329. sum += qlp_coeff[ 0] * data[i- 1];
  98330. }
  98331. data[i] = residual[i] + (sum >> lp_quantization);
  98332. }
  98333. }
  98334. }
  98335. #endif
  98336. 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[])
  98337. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98338. {
  98339. unsigned i, j;
  98340. FLAC__int64 sum;
  98341. const FLAC__int32 *r = residual, *history;
  98342. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98343. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98344. for(i=0;i<order;i++)
  98345. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98346. fprintf(stderr,"\n");
  98347. #endif
  98348. FLAC__ASSERT(order > 0);
  98349. for(i = 0; i < data_len; i++) {
  98350. sum = 0;
  98351. history = data;
  98352. for(j = 0; j < order; j++)
  98353. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98354. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98355. #ifdef _MSC_VER
  98356. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98357. #else
  98358. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98359. #endif
  98360. break;
  98361. }
  98362. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98363. #ifdef _MSC_VER
  98364. 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));
  98365. #else
  98366. 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)));
  98367. #endif
  98368. break;
  98369. }
  98370. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98371. }
  98372. }
  98373. #else /* fully unrolled version for normal use */
  98374. {
  98375. int i;
  98376. FLAC__int64 sum;
  98377. FLAC__ASSERT(order > 0);
  98378. FLAC__ASSERT(order <= 32);
  98379. /*
  98380. * We do unique versions up to 12th order since that's the subset limit.
  98381. * Also they are roughly ordered to match frequency of occurrence to
  98382. * minimize branching.
  98383. */
  98384. if(order <= 12) {
  98385. if(order > 8) {
  98386. if(order > 10) {
  98387. if(order == 12) {
  98388. for(i = 0; i < (int)data_len; i++) {
  98389. sum = 0;
  98390. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98391. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98392. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98393. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98394. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98395. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98396. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98397. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98398. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98399. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98400. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98401. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98402. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98403. }
  98404. }
  98405. else { /* order == 11 */
  98406. for(i = 0; i < (int)data_len; i++) {
  98407. sum = 0;
  98408. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98409. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98410. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98411. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98412. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98413. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98414. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98415. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98416. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98417. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98418. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98419. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98420. }
  98421. }
  98422. }
  98423. else {
  98424. if(order == 10) {
  98425. for(i = 0; i < (int)data_len; i++) {
  98426. sum = 0;
  98427. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98428. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98429. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98430. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98431. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98432. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98433. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98434. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98435. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98436. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98437. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98438. }
  98439. }
  98440. else { /* order == 9 */
  98441. for(i = 0; i < (int)data_len; i++) {
  98442. sum = 0;
  98443. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98444. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98445. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98446. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98447. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98448. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98449. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98450. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98451. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98452. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98453. }
  98454. }
  98455. }
  98456. }
  98457. else if(order > 4) {
  98458. if(order > 6) {
  98459. if(order == 8) {
  98460. for(i = 0; i < (int)data_len; i++) {
  98461. sum = 0;
  98462. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98463. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98464. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98465. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98466. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98467. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98468. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98469. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98470. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98471. }
  98472. }
  98473. else { /* order == 7 */
  98474. for(i = 0; i < (int)data_len; i++) {
  98475. sum = 0;
  98476. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98477. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98478. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98479. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98480. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98481. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98482. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98483. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98484. }
  98485. }
  98486. }
  98487. else {
  98488. if(order == 6) {
  98489. for(i = 0; i < (int)data_len; i++) {
  98490. sum = 0;
  98491. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98492. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98493. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98494. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98495. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98496. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98497. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98498. }
  98499. }
  98500. else { /* order == 5 */
  98501. for(i = 0; i < (int)data_len; i++) {
  98502. sum = 0;
  98503. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98504. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98505. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98506. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98507. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98508. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98509. }
  98510. }
  98511. }
  98512. }
  98513. else {
  98514. if(order > 2) {
  98515. if(order == 4) {
  98516. for(i = 0; i < (int)data_len; i++) {
  98517. sum = 0;
  98518. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98519. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98520. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98521. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98522. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98523. }
  98524. }
  98525. else { /* order == 3 */
  98526. for(i = 0; i < (int)data_len; i++) {
  98527. sum = 0;
  98528. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98529. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98530. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98531. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98532. }
  98533. }
  98534. }
  98535. else {
  98536. if(order == 2) {
  98537. for(i = 0; i < (int)data_len; i++) {
  98538. sum = 0;
  98539. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98540. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98541. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98542. }
  98543. }
  98544. else { /* order == 1 */
  98545. for(i = 0; i < (int)data_len; i++)
  98546. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98547. }
  98548. }
  98549. }
  98550. }
  98551. else { /* order > 12 */
  98552. for(i = 0; i < (int)data_len; i++) {
  98553. sum = 0;
  98554. switch(order) {
  98555. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98556. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98557. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98558. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98559. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98560. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98561. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98562. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98563. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98564. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98565. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98566. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98567. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98568. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98569. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98570. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98571. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98572. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98573. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98574. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98575. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98576. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98577. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98578. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98579. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98580. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98581. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98582. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98583. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98584. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98585. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98586. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98587. }
  98588. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98589. }
  98590. }
  98591. }
  98592. #endif
  98593. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98594. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98595. {
  98596. FLAC__double error_scale;
  98597. FLAC__ASSERT(total_samples > 0);
  98598. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98599. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98600. }
  98601. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98602. {
  98603. if(lpc_error > 0.0) {
  98604. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98605. if(bps >= 0.0)
  98606. return bps;
  98607. else
  98608. return 0.0;
  98609. }
  98610. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98611. return 1e32;
  98612. }
  98613. else {
  98614. return 0.0;
  98615. }
  98616. }
  98617. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98618. {
  98619. 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 */
  98620. FLAC__double bits, best_bits, error_scale;
  98621. FLAC__ASSERT(max_order > 0);
  98622. FLAC__ASSERT(total_samples > 0);
  98623. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98624. best_index = 0;
  98625. best_bits = (unsigned)(-1);
  98626. for(index = 0, order = 1; index < max_order; index++, order++) {
  98627. 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);
  98628. if(bits < best_bits) {
  98629. best_index = index;
  98630. best_bits = bits;
  98631. }
  98632. }
  98633. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98634. }
  98635. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98636. #endif
  98637. /*** End of inlined file: lpc_flac.c ***/
  98638. /*** Start of inlined file: md5.c ***/
  98639. /*** Start of inlined file: juce_FlacHeader.h ***/
  98640. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98641. // tasks..
  98642. #define VERSION "1.2.1"
  98643. #define FLAC__NO_DLL 1
  98644. #if JUCE_MSVC
  98645. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98646. #endif
  98647. #if JUCE_MAC
  98648. #define FLAC__SYS_DARWIN 1
  98649. #endif
  98650. /*** End of inlined file: juce_FlacHeader.h ***/
  98651. #if JUCE_USE_FLAC
  98652. #if HAVE_CONFIG_H
  98653. # include <config.h>
  98654. #endif
  98655. #include <stdlib.h> /* for malloc() */
  98656. #include <string.h> /* for memcpy() */
  98657. /*** Start of inlined file: md5.h ***/
  98658. #ifndef FLAC__PRIVATE__MD5_H
  98659. #define FLAC__PRIVATE__MD5_H
  98660. /*
  98661. * This is the header file for the MD5 message-digest algorithm.
  98662. * The algorithm is due to Ron Rivest. This code was
  98663. * written by Colin Plumb in 1993, no copyright is claimed.
  98664. * This code is in the public domain; do with it what you wish.
  98665. *
  98666. * Equivalent code is available from RSA Data Security, Inc.
  98667. * This code has been tested against that, and is equivalent,
  98668. * except that you don't need to include two pages of legalese
  98669. * with every copy.
  98670. *
  98671. * To compute the message digest of a chunk of bytes, declare an
  98672. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98673. * needed on buffers full of bytes, and then call MD5Final, which
  98674. * will fill a supplied 16-byte array with the digest.
  98675. *
  98676. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98677. * header definitions; now uses stuff from dpkg's config.h
  98678. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98679. * Still in the public domain.
  98680. *
  98681. * Josh Coalson: made some changes to integrate with libFLAC.
  98682. * Still in the public domain, with no warranty.
  98683. */
  98684. typedef struct {
  98685. FLAC__uint32 in[16];
  98686. FLAC__uint32 buf[4];
  98687. FLAC__uint32 bytes[2];
  98688. FLAC__byte *internal_buf;
  98689. size_t capacity;
  98690. } FLAC__MD5Context;
  98691. void FLAC__MD5Init(FLAC__MD5Context *context);
  98692. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98693. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98694. #endif
  98695. /*** End of inlined file: md5.h ***/
  98696. #ifndef FLaC__INLINE
  98697. #define FLaC__INLINE
  98698. #endif
  98699. /*
  98700. * This code implements the MD5 message-digest algorithm.
  98701. * The algorithm is due to Ron Rivest. This code was
  98702. * written by Colin Plumb in 1993, no copyright is claimed.
  98703. * This code is in the public domain; do with it what you wish.
  98704. *
  98705. * Equivalent code is available from RSA Data Security, Inc.
  98706. * This code has been tested against that, and is equivalent,
  98707. * except that you don't need to include two pages of legalese
  98708. * with every copy.
  98709. *
  98710. * To compute the message digest of a chunk of bytes, declare an
  98711. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98712. * needed on buffers full of bytes, and then call MD5Final, which
  98713. * will fill a supplied 16-byte array with the digest.
  98714. *
  98715. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98716. * definitions; now uses stuff from dpkg's config.h.
  98717. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98718. * Still in the public domain.
  98719. *
  98720. * Josh Coalson: made some changes to integrate with libFLAC.
  98721. * Still in the public domain.
  98722. */
  98723. /* The four core functions - F1 is optimized somewhat */
  98724. /* #define F1(x, y, z) (x & y | ~x & z) */
  98725. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98726. #define F2(x, y, z) F1(z, x, y)
  98727. #define F3(x, y, z) (x ^ y ^ z)
  98728. #define F4(x, y, z) (y ^ (x | ~z))
  98729. /* This is the central step in the MD5 algorithm. */
  98730. #define MD5STEP(f,w,x,y,z,in,s) \
  98731. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98732. /*
  98733. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98734. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98735. * the data and converts bytes into longwords for this routine.
  98736. */
  98737. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98738. {
  98739. register FLAC__uint32 a, b, c, d;
  98740. a = buf[0];
  98741. b = buf[1];
  98742. c = buf[2];
  98743. d = buf[3];
  98744. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98745. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98746. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98747. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98748. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98749. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98750. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98751. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98752. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98753. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98754. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98755. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98756. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98757. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98758. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98759. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98760. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98761. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98762. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98763. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98764. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98765. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98766. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98767. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98768. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98769. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98770. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98771. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98772. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98773. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98774. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98775. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98776. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98777. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98778. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98779. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98780. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98781. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98782. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98783. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98784. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98785. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98786. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98787. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98788. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98789. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98790. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98791. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98792. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98793. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98794. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98795. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98796. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98797. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98798. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98799. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98800. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98801. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98802. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98803. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98804. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98805. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98806. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98807. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98808. buf[0] += a;
  98809. buf[1] += b;
  98810. buf[2] += c;
  98811. buf[3] += d;
  98812. }
  98813. #if WORDS_BIGENDIAN
  98814. //@@@@@@ OPT: use bswap/intrinsics
  98815. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98816. {
  98817. register FLAC__uint32 x;
  98818. do {
  98819. x = *buf;
  98820. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98821. *buf++ = (x >> 16) | (x << 16);
  98822. } while (--words);
  98823. }
  98824. static void byteSwapX16(FLAC__uint32 *buf)
  98825. {
  98826. register FLAC__uint32 x;
  98827. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98828. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98829. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98830. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98831. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98832. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98833. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98834. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98835. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98836. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98837. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98838. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98839. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98840. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98841. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98842. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98843. }
  98844. #else
  98845. #define byteSwap(buf, words)
  98846. #define byteSwapX16(buf)
  98847. #endif
  98848. /*
  98849. * Update context to reflect the concatenation of another buffer full
  98850. * of bytes.
  98851. */
  98852. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98853. {
  98854. FLAC__uint32 t;
  98855. /* Update byte count */
  98856. t = ctx->bytes[0];
  98857. if ((ctx->bytes[0] = t + len) < t)
  98858. ctx->bytes[1]++; /* Carry from low to high */
  98859. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98860. if (t > len) {
  98861. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98862. return;
  98863. }
  98864. /* First chunk is an odd size */
  98865. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98866. byteSwapX16(ctx->in);
  98867. FLAC__MD5Transform(ctx->buf, ctx->in);
  98868. buf += t;
  98869. len -= t;
  98870. /* Process data in 64-byte chunks */
  98871. while (len >= 64) {
  98872. memcpy(ctx->in, buf, 64);
  98873. byteSwapX16(ctx->in);
  98874. FLAC__MD5Transform(ctx->buf, ctx->in);
  98875. buf += 64;
  98876. len -= 64;
  98877. }
  98878. /* Handle any remaining bytes of data. */
  98879. memcpy(ctx->in, buf, len);
  98880. }
  98881. /*
  98882. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98883. * initialization constants.
  98884. */
  98885. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98886. {
  98887. ctx->buf[0] = 0x67452301;
  98888. ctx->buf[1] = 0xefcdab89;
  98889. ctx->buf[2] = 0x98badcfe;
  98890. ctx->buf[3] = 0x10325476;
  98891. ctx->bytes[0] = 0;
  98892. ctx->bytes[1] = 0;
  98893. ctx->internal_buf = 0;
  98894. ctx->capacity = 0;
  98895. }
  98896. /*
  98897. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98898. * 1 0* (64-bit count of bits processed, MSB-first)
  98899. */
  98900. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98901. {
  98902. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98903. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98904. /* Set the first char of padding to 0x80. There is always room. */
  98905. *p++ = 0x80;
  98906. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98907. count = 56 - 1 - count;
  98908. if (count < 0) { /* Padding forces an extra block */
  98909. memset(p, 0, count + 8);
  98910. byteSwapX16(ctx->in);
  98911. FLAC__MD5Transform(ctx->buf, ctx->in);
  98912. p = (FLAC__byte *)ctx->in;
  98913. count = 56;
  98914. }
  98915. memset(p, 0, count);
  98916. byteSwap(ctx->in, 14);
  98917. /* Append length in bits and transform */
  98918. ctx->in[14] = ctx->bytes[0] << 3;
  98919. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98920. FLAC__MD5Transform(ctx->buf, ctx->in);
  98921. byteSwap(ctx->buf, 4);
  98922. memcpy(digest, ctx->buf, 16);
  98923. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98924. if(0 != ctx->internal_buf) {
  98925. free(ctx->internal_buf);
  98926. ctx->internal_buf = 0;
  98927. ctx->capacity = 0;
  98928. }
  98929. }
  98930. /*
  98931. * Convert the incoming audio signal to a byte stream
  98932. */
  98933. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98934. {
  98935. unsigned channel, sample;
  98936. register FLAC__int32 a_word;
  98937. register FLAC__byte *buf_ = buf;
  98938. #if WORDS_BIGENDIAN
  98939. #else
  98940. if(channels == 2 && bytes_per_sample == 2) {
  98941. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98942. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98943. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98944. *buf1_ = (FLAC__int16)signal[1][sample];
  98945. }
  98946. else if(channels == 1 && bytes_per_sample == 2) {
  98947. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98948. for(sample = 0; sample < samples; sample++)
  98949. *buf1_++ = (FLAC__int16)signal[0][sample];
  98950. }
  98951. else
  98952. #endif
  98953. if(bytes_per_sample == 2) {
  98954. if(channels == 2) {
  98955. for(sample = 0; sample < samples; sample++) {
  98956. a_word = signal[0][sample];
  98957. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98958. *buf_++ = (FLAC__byte)a_word;
  98959. a_word = signal[1][sample];
  98960. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98961. *buf_++ = (FLAC__byte)a_word;
  98962. }
  98963. }
  98964. else if(channels == 1) {
  98965. for(sample = 0; sample < samples; sample++) {
  98966. a_word = signal[0][sample];
  98967. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98968. *buf_++ = (FLAC__byte)a_word;
  98969. }
  98970. }
  98971. else {
  98972. for(sample = 0; sample < samples; sample++) {
  98973. for(channel = 0; channel < channels; channel++) {
  98974. a_word = signal[channel][sample];
  98975. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98976. *buf_++ = (FLAC__byte)a_word;
  98977. }
  98978. }
  98979. }
  98980. }
  98981. else if(bytes_per_sample == 3) {
  98982. if(channels == 2) {
  98983. for(sample = 0; sample < samples; sample++) {
  98984. a_word = signal[0][sample];
  98985. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98986. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98987. *buf_++ = (FLAC__byte)a_word;
  98988. a_word = signal[1][sample];
  98989. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98990. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98991. *buf_++ = (FLAC__byte)a_word;
  98992. }
  98993. }
  98994. else if(channels == 1) {
  98995. for(sample = 0; sample < samples; sample++) {
  98996. a_word = signal[0][sample];
  98997. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98998. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98999. *buf_++ = (FLAC__byte)a_word;
  99000. }
  99001. }
  99002. else {
  99003. for(sample = 0; sample < samples; sample++) {
  99004. for(channel = 0; channel < channels; channel++) {
  99005. a_word = signal[channel][sample];
  99006. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99007. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99008. *buf_++ = (FLAC__byte)a_word;
  99009. }
  99010. }
  99011. }
  99012. }
  99013. else if(bytes_per_sample == 1) {
  99014. if(channels == 2) {
  99015. for(sample = 0; sample < samples; sample++) {
  99016. a_word = signal[0][sample];
  99017. *buf_++ = (FLAC__byte)a_word;
  99018. a_word = signal[1][sample];
  99019. *buf_++ = (FLAC__byte)a_word;
  99020. }
  99021. }
  99022. else if(channels == 1) {
  99023. for(sample = 0; sample < samples; sample++) {
  99024. a_word = signal[0][sample];
  99025. *buf_++ = (FLAC__byte)a_word;
  99026. }
  99027. }
  99028. else {
  99029. for(sample = 0; sample < samples; sample++) {
  99030. for(channel = 0; channel < channels; channel++) {
  99031. a_word = signal[channel][sample];
  99032. *buf_++ = (FLAC__byte)a_word;
  99033. }
  99034. }
  99035. }
  99036. }
  99037. else { /* bytes_per_sample == 4, maybe optimize more later */
  99038. for(sample = 0; sample < samples; sample++) {
  99039. for(channel = 0; channel < channels; channel++) {
  99040. a_word = signal[channel][sample];
  99041. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99042. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99043. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99044. *buf_++ = (FLAC__byte)a_word;
  99045. }
  99046. }
  99047. }
  99048. }
  99049. /*
  99050. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99051. */
  99052. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99053. {
  99054. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99055. /* overflow check */
  99056. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99057. return false;
  99058. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99059. return false;
  99060. if(ctx->capacity < bytes_needed) {
  99061. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99062. if(0 == tmp) {
  99063. free(ctx->internal_buf);
  99064. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99065. return false;
  99066. }
  99067. ctx->internal_buf = tmp;
  99068. ctx->capacity = bytes_needed;
  99069. }
  99070. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99071. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99072. return true;
  99073. }
  99074. #endif
  99075. /*** End of inlined file: md5.c ***/
  99076. /*** Start of inlined file: memory.c ***/
  99077. /*** Start of inlined file: juce_FlacHeader.h ***/
  99078. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99079. // tasks..
  99080. #define VERSION "1.2.1"
  99081. #define FLAC__NO_DLL 1
  99082. #if JUCE_MSVC
  99083. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99084. #endif
  99085. #if JUCE_MAC
  99086. #define FLAC__SYS_DARWIN 1
  99087. #endif
  99088. /*** End of inlined file: juce_FlacHeader.h ***/
  99089. #if JUCE_USE_FLAC
  99090. #if HAVE_CONFIG_H
  99091. # include <config.h>
  99092. #endif
  99093. /*** Start of inlined file: memory.h ***/
  99094. #ifndef FLAC__PRIVATE__MEMORY_H
  99095. #define FLAC__PRIVATE__MEMORY_H
  99096. #ifdef HAVE_CONFIG_H
  99097. #include <config.h>
  99098. #endif
  99099. #include <stdlib.h> /* for size_t */
  99100. /* Returns the unaligned address returned by malloc.
  99101. * Use free() on this address to deallocate.
  99102. */
  99103. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99104. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99105. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99106. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99107. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99108. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99109. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99110. #endif
  99111. #endif
  99112. /*** End of inlined file: memory.h ***/
  99113. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99114. {
  99115. void *x;
  99116. FLAC__ASSERT(0 != aligned_address);
  99117. #ifdef FLAC__ALIGN_MALLOC_DATA
  99118. /* align on 32-byte (256-bit) boundary */
  99119. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99120. #ifdef SIZEOF_VOIDP
  99121. #if SIZEOF_VOIDP == 4
  99122. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99123. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99124. #elif SIZEOF_VOIDP == 8
  99125. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99126. #else
  99127. # error Unsupported sizeof(void*)
  99128. #endif
  99129. #else
  99130. /* there's got to be a better way to do this right for all archs */
  99131. if(sizeof(void*) == sizeof(unsigned))
  99132. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99133. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99134. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99135. else
  99136. return 0;
  99137. #endif
  99138. #else
  99139. x = safe_malloc_(bytes);
  99140. *aligned_address = x;
  99141. #endif
  99142. return x;
  99143. }
  99144. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99145. {
  99146. FLAC__int32 *pu; /* unaligned pointer */
  99147. union { /* union needed to comply with C99 pointer aliasing rules */
  99148. FLAC__int32 *pa; /* aligned pointer */
  99149. void *pv; /* aligned pointer alias */
  99150. } u;
  99151. FLAC__ASSERT(elements > 0);
  99152. FLAC__ASSERT(0 != unaligned_pointer);
  99153. FLAC__ASSERT(0 != aligned_pointer);
  99154. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99155. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99156. if(0 == pu) {
  99157. return false;
  99158. }
  99159. else {
  99160. if(*unaligned_pointer != 0)
  99161. free(*unaligned_pointer);
  99162. *unaligned_pointer = pu;
  99163. *aligned_pointer = u.pa;
  99164. return true;
  99165. }
  99166. }
  99167. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99168. {
  99169. FLAC__uint32 *pu; /* unaligned pointer */
  99170. union { /* union needed to comply with C99 pointer aliasing rules */
  99171. FLAC__uint32 *pa; /* aligned pointer */
  99172. void *pv; /* aligned pointer alias */
  99173. } u;
  99174. FLAC__ASSERT(elements > 0);
  99175. FLAC__ASSERT(0 != unaligned_pointer);
  99176. FLAC__ASSERT(0 != aligned_pointer);
  99177. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99178. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99179. if(0 == pu) {
  99180. return false;
  99181. }
  99182. else {
  99183. if(*unaligned_pointer != 0)
  99184. free(*unaligned_pointer);
  99185. *unaligned_pointer = pu;
  99186. *aligned_pointer = u.pa;
  99187. return true;
  99188. }
  99189. }
  99190. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99191. {
  99192. FLAC__uint64 *pu; /* unaligned pointer */
  99193. union { /* union needed to comply with C99 pointer aliasing rules */
  99194. FLAC__uint64 *pa; /* aligned pointer */
  99195. void *pv; /* aligned pointer alias */
  99196. } u;
  99197. FLAC__ASSERT(elements > 0);
  99198. FLAC__ASSERT(0 != unaligned_pointer);
  99199. FLAC__ASSERT(0 != aligned_pointer);
  99200. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99201. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99202. if(0 == pu) {
  99203. return false;
  99204. }
  99205. else {
  99206. if(*unaligned_pointer != 0)
  99207. free(*unaligned_pointer);
  99208. *unaligned_pointer = pu;
  99209. *aligned_pointer = u.pa;
  99210. return true;
  99211. }
  99212. }
  99213. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99214. {
  99215. unsigned *pu; /* unaligned pointer */
  99216. union { /* union needed to comply with C99 pointer aliasing rules */
  99217. unsigned *pa; /* aligned pointer */
  99218. void *pv; /* aligned pointer alias */
  99219. } u;
  99220. FLAC__ASSERT(elements > 0);
  99221. FLAC__ASSERT(0 != unaligned_pointer);
  99222. FLAC__ASSERT(0 != aligned_pointer);
  99223. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99224. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99225. if(0 == pu) {
  99226. return false;
  99227. }
  99228. else {
  99229. if(*unaligned_pointer != 0)
  99230. free(*unaligned_pointer);
  99231. *unaligned_pointer = pu;
  99232. *aligned_pointer = u.pa;
  99233. return true;
  99234. }
  99235. }
  99236. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99237. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99238. {
  99239. FLAC__real *pu; /* unaligned pointer */
  99240. union { /* union needed to comply with C99 pointer aliasing rules */
  99241. FLAC__real *pa; /* aligned pointer */
  99242. void *pv; /* aligned pointer alias */
  99243. } u;
  99244. FLAC__ASSERT(elements > 0);
  99245. FLAC__ASSERT(0 != unaligned_pointer);
  99246. FLAC__ASSERT(0 != aligned_pointer);
  99247. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99248. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99249. if(0 == pu) {
  99250. return false;
  99251. }
  99252. else {
  99253. if(*unaligned_pointer != 0)
  99254. free(*unaligned_pointer);
  99255. *unaligned_pointer = pu;
  99256. *aligned_pointer = u.pa;
  99257. return true;
  99258. }
  99259. }
  99260. #endif
  99261. #endif
  99262. /*** End of inlined file: memory.c ***/
  99263. /*** Start of inlined file: stream_decoder.c ***/
  99264. /*** Start of inlined file: juce_FlacHeader.h ***/
  99265. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99266. // tasks..
  99267. #define VERSION "1.2.1"
  99268. #define FLAC__NO_DLL 1
  99269. #if JUCE_MSVC
  99270. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99271. #endif
  99272. #if JUCE_MAC
  99273. #define FLAC__SYS_DARWIN 1
  99274. #endif
  99275. /*** End of inlined file: juce_FlacHeader.h ***/
  99276. #if JUCE_USE_FLAC
  99277. #if HAVE_CONFIG_H
  99278. # include <config.h>
  99279. #endif
  99280. #if defined _MSC_VER || defined __MINGW32__
  99281. #include <io.h> /* for _setmode() */
  99282. #include <fcntl.h> /* for _O_BINARY */
  99283. #endif
  99284. #if defined __CYGWIN__ || defined __EMX__
  99285. #include <io.h> /* for setmode(), O_BINARY */
  99286. #include <fcntl.h> /* for _O_BINARY */
  99287. #endif
  99288. #include <stdio.h>
  99289. #include <stdlib.h> /* for malloc() */
  99290. #include <string.h> /* for memset/memcpy() */
  99291. #include <sys/stat.h> /* for stat() */
  99292. #include <sys/types.h> /* for off_t */
  99293. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99294. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99295. #define fseeko fseek
  99296. #define ftello ftell
  99297. #endif
  99298. #endif
  99299. /*** Start of inlined file: stream_decoder.h ***/
  99300. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99301. #define FLAC__PROTECTED__STREAM_DECODER_H
  99302. #if FLAC__HAS_OGG
  99303. #include "include/private/ogg_decoder_aspect.h"
  99304. #endif
  99305. typedef struct FLAC__StreamDecoderProtected {
  99306. FLAC__StreamDecoderState state;
  99307. unsigned channels;
  99308. FLAC__ChannelAssignment channel_assignment;
  99309. unsigned bits_per_sample;
  99310. unsigned sample_rate; /* in Hz */
  99311. unsigned blocksize; /* in samples (per channel) */
  99312. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99313. #if FLAC__HAS_OGG
  99314. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99315. #endif
  99316. } FLAC__StreamDecoderProtected;
  99317. /*
  99318. * return the number of input bytes consumed
  99319. */
  99320. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99321. #endif
  99322. /*** End of inlined file: stream_decoder.h ***/
  99323. #ifdef max
  99324. #undef max
  99325. #endif
  99326. #define max(a,b) ((a)>(b)?(a):(b))
  99327. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99328. #ifdef _MSC_VER
  99329. #define FLAC__U64L(x) x
  99330. #else
  99331. #define FLAC__U64L(x) x##LLU
  99332. #endif
  99333. /* technically this should be in an "export.c" but this is convenient enough */
  99334. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99335. #if FLAC__HAS_OGG
  99336. 1
  99337. #else
  99338. 0
  99339. #endif
  99340. ;
  99341. /***********************************************************************
  99342. *
  99343. * Private static data
  99344. *
  99345. ***********************************************************************/
  99346. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99347. /***********************************************************************
  99348. *
  99349. * Private class method prototypes
  99350. *
  99351. ***********************************************************************/
  99352. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99353. static FILE *get_binary_stdin_(void);
  99354. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99355. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99356. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99357. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99358. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99359. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99360. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99361. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99362. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99363. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99364. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99365. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99366. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99367. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99368. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99369. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99370. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99371. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99372. 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);
  99373. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99374. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99375. #if FLAC__HAS_OGG
  99376. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99377. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99378. #endif
  99379. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99380. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99381. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99382. #if FLAC__HAS_OGG
  99383. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99384. #endif
  99385. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99386. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99387. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99388. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99389. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99390. /***********************************************************************
  99391. *
  99392. * Private class data
  99393. *
  99394. ***********************************************************************/
  99395. typedef struct FLAC__StreamDecoderPrivate {
  99396. #if FLAC__HAS_OGG
  99397. FLAC__bool is_ogg;
  99398. #endif
  99399. FLAC__StreamDecoderReadCallback read_callback;
  99400. FLAC__StreamDecoderSeekCallback seek_callback;
  99401. FLAC__StreamDecoderTellCallback tell_callback;
  99402. FLAC__StreamDecoderLengthCallback length_callback;
  99403. FLAC__StreamDecoderEofCallback eof_callback;
  99404. FLAC__StreamDecoderWriteCallback write_callback;
  99405. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99406. FLAC__StreamDecoderErrorCallback error_callback;
  99407. /* generic 32-bit datapath: */
  99408. 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[]);
  99409. /* generic 64-bit datapath: */
  99410. 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[]);
  99411. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99412. 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[]);
  99413. /* 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: */
  99414. 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[]);
  99415. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99416. void *client_data;
  99417. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99418. FLAC__BitReader *input;
  99419. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99420. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99421. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99422. unsigned output_capacity, output_channels;
  99423. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99424. FLAC__uint64 samples_decoded;
  99425. FLAC__bool has_stream_info, has_seek_table;
  99426. FLAC__StreamMetadata stream_info;
  99427. FLAC__StreamMetadata seek_table;
  99428. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99429. FLAC__byte *metadata_filter_ids;
  99430. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99431. FLAC__Frame frame;
  99432. FLAC__bool cached; /* true if there is a byte in lookahead */
  99433. FLAC__CPUInfo cpuinfo;
  99434. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99435. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99436. /* unaligned (original) pointers to allocated data */
  99437. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99438. 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 */
  99439. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99440. FLAC__bool is_seeking;
  99441. FLAC__MD5Context md5context;
  99442. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99443. /* (the rest of these are only used for seeking) */
  99444. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99445. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99446. FLAC__uint64 target_sample;
  99447. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99448. #if FLAC__HAS_OGG
  99449. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99450. #endif
  99451. } FLAC__StreamDecoderPrivate;
  99452. /***********************************************************************
  99453. *
  99454. * Public static class data
  99455. *
  99456. ***********************************************************************/
  99457. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99458. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99459. "FLAC__STREAM_DECODER_READ_METADATA",
  99460. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99461. "FLAC__STREAM_DECODER_READ_FRAME",
  99462. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99463. "FLAC__STREAM_DECODER_OGG_ERROR",
  99464. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99465. "FLAC__STREAM_DECODER_ABORTED",
  99466. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99467. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99468. };
  99469. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99470. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99471. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99472. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99473. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99474. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99475. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99476. };
  99477. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99478. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99479. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99480. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99481. };
  99482. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99483. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99484. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99485. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99486. };
  99487. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99488. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99489. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99490. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99491. };
  99492. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99493. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99494. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99495. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99496. };
  99497. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99498. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99499. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99500. };
  99501. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99502. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99503. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99504. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99505. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99506. };
  99507. /***********************************************************************
  99508. *
  99509. * Class constructor/destructor
  99510. *
  99511. ***********************************************************************/
  99512. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99513. {
  99514. FLAC__StreamDecoder *decoder;
  99515. unsigned i;
  99516. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99517. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99518. if(decoder == 0) {
  99519. return 0;
  99520. }
  99521. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99522. if(decoder->protected_ == 0) {
  99523. free(decoder);
  99524. return 0;
  99525. }
  99526. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99527. if(decoder->private_ == 0) {
  99528. free(decoder->protected_);
  99529. free(decoder);
  99530. return 0;
  99531. }
  99532. decoder->private_->input = FLAC__bitreader_new();
  99533. if(decoder->private_->input == 0) {
  99534. free(decoder->private_);
  99535. free(decoder->protected_);
  99536. free(decoder);
  99537. return 0;
  99538. }
  99539. decoder->private_->metadata_filter_ids_capacity = 16;
  99540. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99541. FLAC__bitreader_delete(decoder->private_->input);
  99542. free(decoder->private_);
  99543. free(decoder->protected_);
  99544. free(decoder);
  99545. return 0;
  99546. }
  99547. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99548. decoder->private_->output[i] = 0;
  99549. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99550. }
  99551. decoder->private_->output_capacity = 0;
  99552. decoder->private_->output_channels = 0;
  99553. decoder->private_->has_seek_table = false;
  99554. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99555. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99556. decoder->private_->file = 0;
  99557. set_defaults_dec(decoder);
  99558. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99559. return decoder;
  99560. }
  99561. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99562. {
  99563. unsigned i;
  99564. FLAC__ASSERT(0 != decoder);
  99565. FLAC__ASSERT(0 != decoder->protected_);
  99566. FLAC__ASSERT(0 != decoder->private_);
  99567. FLAC__ASSERT(0 != decoder->private_->input);
  99568. (void)FLAC__stream_decoder_finish(decoder);
  99569. if(0 != decoder->private_->metadata_filter_ids)
  99570. free(decoder->private_->metadata_filter_ids);
  99571. FLAC__bitreader_delete(decoder->private_->input);
  99572. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99573. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99574. free(decoder->private_);
  99575. free(decoder->protected_);
  99576. free(decoder);
  99577. }
  99578. /***********************************************************************
  99579. *
  99580. * Public class methods
  99581. *
  99582. ***********************************************************************/
  99583. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99584. FLAC__StreamDecoder *decoder,
  99585. FLAC__StreamDecoderReadCallback read_callback,
  99586. FLAC__StreamDecoderSeekCallback seek_callback,
  99587. FLAC__StreamDecoderTellCallback tell_callback,
  99588. FLAC__StreamDecoderLengthCallback length_callback,
  99589. FLAC__StreamDecoderEofCallback eof_callback,
  99590. FLAC__StreamDecoderWriteCallback write_callback,
  99591. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99592. FLAC__StreamDecoderErrorCallback error_callback,
  99593. void *client_data,
  99594. FLAC__bool is_ogg
  99595. )
  99596. {
  99597. FLAC__ASSERT(0 != decoder);
  99598. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99599. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99600. #if !FLAC__HAS_OGG
  99601. if(is_ogg)
  99602. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99603. #endif
  99604. if(
  99605. 0 == read_callback ||
  99606. 0 == write_callback ||
  99607. 0 == error_callback ||
  99608. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99609. )
  99610. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99611. #if FLAC__HAS_OGG
  99612. decoder->private_->is_ogg = is_ogg;
  99613. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99614. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99615. #endif
  99616. /*
  99617. * get the CPU info and set the function pointers
  99618. */
  99619. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99620. /* first default to the non-asm routines */
  99621. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99622. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99623. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99624. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99625. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99626. /* now override with asm where appropriate */
  99627. #ifndef FLAC__NO_ASM
  99628. if(decoder->private_->cpuinfo.use_asm) {
  99629. #ifdef FLAC__CPU_IA32
  99630. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99631. #ifdef FLAC__HAS_NASM
  99632. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99633. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99634. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99635. #endif
  99636. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99637. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99638. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99639. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99640. }
  99641. else {
  99642. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99643. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99644. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99645. }
  99646. #endif
  99647. #elif defined FLAC__CPU_PPC
  99648. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99649. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99650. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99651. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99652. }
  99653. #endif
  99654. }
  99655. #endif
  99656. /* from here on, errors are fatal */
  99657. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99658. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99659. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99660. }
  99661. decoder->private_->read_callback = read_callback;
  99662. decoder->private_->seek_callback = seek_callback;
  99663. decoder->private_->tell_callback = tell_callback;
  99664. decoder->private_->length_callback = length_callback;
  99665. decoder->private_->eof_callback = eof_callback;
  99666. decoder->private_->write_callback = write_callback;
  99667. decoder->private_->metadata_callback = metadata_callback;
  99668. decoder->private_->error_callback = error_callback;
  99669. decoder->private_->client_data = client_data;
  99670. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99671. decoder->private_->samples_decoded = 0;
  99672. decoder->private_->has_stream_info = false;
  99673. decoder->private_->cached = false;
  99674. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99675. decoder->private_->is_seeking = false;
  99676. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99677. if(!FLAC__stream_decoder_reset(decoder)) {
  99678. /* above call sets the state for us */
  99679. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99680. }
  99681. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99682. }
  99683. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99684. FLAC__StreamDecoder *decoder,
  99685. FLAC__StreamDecoderReadCallback read_callback,
  99686. FLAC__StreamDecoderSeekCallback seek_callback,
  99687. FLAC__StreamDecoderTellCallback tell_callback,
  99688. FLAC__StreamDecoderLengthCallback length_callback,
  99689. FLAC__StreamDecoderEofCallback eof_callback,
  99690. FLAC__StreamDecoderWriteCallback write_callback,
  99691. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99692. FLAC__StreamDecoderErrorCallback error_callback,
  99693. void *client_data
  99694. )
  99695. {
  99696. return init_stream_internal_dec(
  99697. decoder,
  99698. read_callback,
  99699. seek_callback,
  99700. tell_callback,
  99701. length_callback,
  99702. eof_callback,
  99703. write_callback,
  99704. metadata_callback,
  99705. error_callback,
  99706. client_data,
  99707. /*is_ogg=*/false
  99708. );
  99709. }
  99710. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99711. FLAC__StreamDecoder *decoder,
  99712. FLAC__StreamDecoderReadCallback read_callback,
  99713. FLAC__StreamDecoderSeekCallback seek_callback,
  99714. FLAC__StreamDecoderTellCallback tell_callback,
  99715. FLAC__StreamDecoderLengthCallback length_callback,
  99716. FLAC__StreamDecoderEofCallback eof_callback,
  99717. FLAC__StreamDecoderWriteCallback write_callback,
  99718. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99719. FLAC__StreamDecoderErrorCallback error_callback,
  99720. void *client_data
  99721. )
  99722. {
  99723. return init_stream_internal_dec(
  99724. decoder,
  99725. read_callback,
  99726. seek_callback,
  99727. tell_callback,
  99728. length_callback,
  99729. eof_callback,
  99730. write_callback,
  99731. metadata_callback,
  99732. error_callback,
  99733. client_data,
  99734. /*is_ogg=*/true
  99735. );
  99736. }
  99737. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99738. FLAC__StreamDecoder *decoder,
  99739. FILE *file,
  99740. FLAC__StreamDecoderWriteCallback write_callback,
  99741. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99742. FLAC__StreamDecoderErrorCallback error_callback,
  99743. void *client_data,
  99744. FLAC__bool is_ogg
  99745. )
  99746. {
  99747. FLAC__ASSERT(0 != decoder);
  99748. FLAC__ASSERT(0 != file);
  99749. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99750. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99751. if(0 == write_callback || 0 == error_callback)
  99752. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99753. /*
  99754. * To make sure that our file does not go unclosed after an error, we
  99755. * must assign the FILE pointer before any further error can occur in
  99756. * this routine.
  99757. */
  99758. if(file == stdin)
  99759. file = get_binary_stdin_(); /* just to be safe */
  99760. decoder->private_->file = file;
  99761. return init_stream_internal_dec(
  99762. decoder,
  99763. file_read_callback_dec,
  99764. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99765. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99766. decoder->private_->file == stdin? 0: file_length_callback_,
  99767. file_eof_callback_,
  99768. write_callback,
  99769. metadata_callback,
  99770. error_callback,
  99771. client_data,
  99772. is_ogg
  99773. );
  99774. }
  99775. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99776. FLAC__StreamDecoder *decoder,
  99777. FILE *file,
  99778. FLAC__StreamDecoderWriteCallback write_callback,
  99779. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99780. FLAC__StreamDecoderErrorCallback error_callback,
  99781. void *client_data
  99782. )
  99783. {
  99784. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99785. }
  99786. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99787. FLAC__StreamDecoder *decoder,
  99788. FILE *file,
  99789. FLAC__StreamDecoderWriteCallback write_callback,
  99790. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99791. FLAC__StreamDecoderErrorCallback error_callback,
  99792. void *client_data
  99793. )
  99794. {
  99795. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99796. }
  99797. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99798. FLAC__StreamDecoder *decoder,
  99799. const char *filename,
  99800. FLAC__StreamDecoderWriteCallback write_callback,
  99801. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99802. FLAC__StreamDecoderErrorCallback error_callback,
  99803. void *client_data,
  99804. FLAC__bool is_ogg
  99805. )
  99806. {
  99807. FILE *file;
  99808. FLAC__ASSERT(0 != decoder);
  99809. /*
  99810. * To make sure that our file does not go unclosed after an error, we
  99811. * have to do the same entrance checks here that are later performed
  99812. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99813. */
  99814. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99815. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99816. if(0 == write_callback || 0 == error_callback)
  99817. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99818. file = filename? fopen(filename, "rb") : stdin;
  99819. if(0 == file)
  99820. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99821. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99822. }
  99823. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99824. FLAC__StreamDecoder *decoder,
  99825. const char *filename,
  99826. FLAC__StreamDecoderWriteCallback write_callback,
  99827. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99828. FLAC__StreamDecoderErrorCallback error_callback,
  99829. void *client_data
  99830. )
  99831. {
  99832. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99833. }
  99834. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99835. FLAC__StreamDecoder *decoder,
  99836. const char *filename,
  99837. FLAC__StreamDecoderWriteCallback write_callback,
  99838. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99839. FLAC__StreamDecoderErrorCallback error_callback,
  99840. void *client_data
  99841. )
  99842. {
  99843. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99844. }
  99845. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99846. {
  99847. FLAC__bool md5_failed = false;
  99848. unsigned i;
  99849. FLAC__ASSERT(0 != decoder);
  99850. FLAC__ASSERT(0 != decoder->private_);
  99851. FLAC__ASSERT(0 != decoder->protected_);
  99852. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99853. return true;
  99854. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99855. * always call FLAC__MD5Final()
  99856. */
  99857. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99858. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99859. free(decoder->private_->seek_table.data.seek_table.points);
  99860. decoder->private_->seek_table.data.seek_table.points = 0;
  99861. decoder->private_->has_seek_table = false;
  99862. }
  99863. FLAC__bitreader_free(decoder->private_->input);
  99864. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99865. /* WATCHOUT:
  99866. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99867. * output arrays have a buffer of up to 3 zeroes in front
  99868. * (at negative indices) for alignment purposes; we use 4
  99869. * to keep the data well-aligned.
  99870. */
  99871. if(0 != decoder->private_->output[i]) {
  99872. free(decoder->private_->output[i]-4);
  99873. decoder->private_->output[i] = 0;
  99874. }
  99875. if(0 != decoder->private_->residual_unaligned[i]) {
  99876. free(decoder->private_->residual_unaligned[i]);
  99877. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99878. }
  99879. }
  99880. decoder->private_->output_capacity = 0;
  99881. decoder->private_->output_channels = 0;
  99882. #if FLAC__HAS_OGG
  99883. if(decoder->private_->is_ogg)
  99884. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99885. #endif
  99886. if(0 != decoder->private_->file) {
  99887. if(decoder->private_->file != stdin)
  99888. fclose(decoder->private_->file);
  99889. decoder->private_->file = 0;
  99890. }
  99891. if(decoder->private_->do_md5_checking) {
  99892. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99893. md5_failed = true;
  99894. }
  99895. decoder->private_->is_seeking = false;
  99896. set_defaults_dec(decoder);
  99897. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99898. return !md5_failed;
  99899. }
  99900. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99901. {
  99902. FLAC__ASSERT(0 != decoder);
  99903. FLAC__ASSERT(0 != decoder->private_);
  99904. FLAC__ASSERT(0 != decoder->protected_);
  99905. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99906. return false;
  99907. #if FLAC__HAS_OGG
  99908. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99909. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99910. return true;
  99911. #else
  99912. (void)value;
  99913. return false;
  99914. #endif
  99915. }
  99916. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99917. {
  99918. FLAC__ASSERT(0 != decoder);
  99919. FLAC__ASSERT(0 != decoder->protected_);
  99920. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99921. return false;
  99922. decoder->protected_->md5_checking = value;
  99923. return true;
  99924. }
  99925. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99926. {
  99927. FLAC__ASSERT(0 != decoder);
  99928. FLAC__ASSERT(0 != decoder->private_);
  99929. FLAC__ASSERT(0 != decoder->protected_);
  99930. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99931. /* double protection */
  99932. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99933. return false;
  99934. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99935. return false;
  99936. decoder->private_->metadata_filter[type] = true;
  99937. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99938. decoder->private_->metadata_filter_ids_count = 0;
  99939. return true;
  99940. }
  99941. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99942. {
  99943. FLAC__ASSERT(0 != decoder);
  99944. FLAC__ASSERT(0 != decoder->private_);
  99945. FLAC__ASSERT(0 != decoder->protected_);
  99946. FLAC__ASSERT(0 != id);
  99947. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99948. return false;
  99949. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99950. return true;
  99951. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99952. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99953. 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))) {
  99954. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99955. return false;
  99956. }
  99957. decoder->private_->metadata_filter_ids_capacity *= 2;
  99958. }
  99959. 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));
  99960. decoder->private_->metadata_filter_ids_count++;
  99961. return true;
  99962. }
  99963. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99964. {
  99965. unsigned i;
  99966. FLAC__ASSERT(0 != decoder);
  99967. FLAC__ASSERT(0 != decoder->private_);
  99968. FLAC__ASSERT(0 != decoder->protected_);
  99969. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99970. return false;
  99971. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99972. decoder->private_->metadata_filter[i] = true;
  99973. decoder->private_->metadata_filter_ids_count = 0;
  99974. return true;
  99975. }
  99976. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99977. {
  99978. FLAC__ASSERT(0 != decoder);
  99979. FLAC__ASSERT(0 != decoder->private_);
  99980. FLAC__ASSERT(0 != decoder->protected_);
  99981. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99982. /* double protection */
  99983. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99984. return false;
  99985. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99986. return false;
  99987. decoder->private_->metadata_filter[type] = false;
  99988. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99989. decoder->private_->metadata_filter_ids_count = 0;
  99990. return true;
  99991. }
  99992. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99993. {
  99994. FLAC__ASSERT(0 != decoder);
  99995. FLAC__ASSERT(0 != decoder->private_);
  99996. FLAC__ASSERT(0 != decoder->protected_);
  99997. FLAC__ASSERT(0 != id);
  99998. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99999. return false;
  100000. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  100001. return true;
  100002. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  100003. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  100004. 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))) {
  100005. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100006. return false;
  100007. }
  100008. decoder->private_->metadata_filter_ids_capacity *= 2;
  100009. }
  100010. 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));
  100011. decoder->private_->metadata_filter_ids_count++;
  100012. return true;
  100013. }
  100014. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  100015. {
  100016. FLAC__ASSERT(0 != decoder);
  100017. FLAC__ASSERT(0 != decoder->private_);
  100018. FLAC__ASSERT(0 != decoder->protected_);
  100019. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100020. return false;
  100021. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100022. decoder->private_->metadata_filter_ids_count = 0;
  100023. return true;
  100024. }
  100025. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100026. {
  100027. FLAC__ASSERT(0 != decoder);
  100028. FLAC__ASSERT(0 != decoder->protected_);
  100029. return decoder->protected_->state;
  100030. }
  100031. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100032. {
  100033. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100034. }
  100035. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100036. {
  100037. FLAC__ASSERT(0 != decoder);
  100038. FLAC__ASSERT(0 != decoder->protected_);
  100039. return decoder->protected_->md5_checking;
  100040. }
  100041. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100042. {
  100043. FLAC__ASSERT(0 != decoder);
  100044. FLAC__ASSERT(0 != decoder->protected_);
  100045. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100046. }
  100047. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100048. {
  100049. FLAC__ASSERT(0 != decoder);
  100050. FLAC__ASSERT(0 != decoder->protected_);
  100051. return decoder->protected_->channels;
  100052. }
  100053. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100054. {
  100055. FLAC__ASSERT(0 != decoder);
  100056. FLAC__ASSERT(0 != decoder->protected_);
  100057. return decoder->protected_->channel_assignment;
  100058. }
  100059. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100060. {
  100061. FLAC__ASSERT(0 != decoder);
  100062. FLAC__ASSERT(0 != decoder->protected_);
  100063. return decoder->protected_->bits_per_sample;
  100064. }
  100065. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100066. {
  100067. FLAC__ASSERT(0 != decoder);
  100068. FLAC__ASSERT(0 != decoder->protected_);
  100069. return decoder->protected_->sample_rate;
  100070. }
  100071. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100072. {
  100073. FLAC__ASSERT(0 != decoder);
  100074. FLAC__ASSERT(0 != decoder->protected_);
  100075. return decoder->protected_->blocksize;
  100076. }
  100077. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100078. {
  100079. FLAC__ASSERT(0 != decoder);
  100080. FLAC__ASSERT(0 != decoder->private_);
  100081. FLAC__ASSERT(0 != position);
  100082. #if FLAC__HAS_OGG
  100083. if(decoder->private_->is_ogg)
  100084. return false;
  100085. #endif
  100086. if(0 == decoder->private_->tell_callback)
  100087. return false;
  100088. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100089. return false;
  100090. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100091. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100092. return false;
  100093. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100094. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100095. return true;
  100096. }
  100097. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100098. {
  100099. FLAC__ASSERT(0 != decoder);
  100100. FLAC__ASSERT(0 != decoder->private_);
  100101. FLAC__ASSERT(0 != decoder->protected_);
  100102. decoder->private_->samples_decoded = 0;
  100103. decoder->private_->do_md5_checking = false;
  100104. #if FLAC__HAS_OGG
  100105. if(decoder->private_->is_ogg)
  100106. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100107. #endif
  100108. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100109. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100110. return false;
  100111. }
  100112. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100113. return true;
  100114. }
  100115. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100116. {
  100117. FLAC__ASSERT(0 != decoder);
  100118. FLAC__ASSERT(0 != decoder->private_);
  100119. FLAC__ASSERT(0 != decoder->protected_);
  100120. if(!FLAC__stream_decoder_flush(decoder)) {
  100121. /* above call sets the state for us */
  100122. return false;
  100123. }
  100124. #if FLAC__HAS_OGG
  100125. /*@@@ could go in !internal_reset_hack block below */
  100126. if(decoder->private_->is_ogg)
  100127. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100128. #endif
  100129. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100130. * (internal_reset_hack) don't try to rewind since we are already at
  100131. * the beginning of the stream and don't want to fail if the input is
  100132. * not seekable.
  100133. */
  100134. if(!decoder->private_->internal_reset_hack) {
  100135. if(decoder->private_->file == stdin)
  100136. return false; /* can't rewind stdin, reset fails */
  100137. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100138. return false; /* seekable and seek fails, reset fails */
  100139. }
  100140. else
  100141. decoder->private_->internal_reset_hack = false;
  100142. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100143. decoder->private_->has_stream_info = false;
  100144. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100145. free(decoder->private_->seek_table.data.seek_table.points);
  100146. decoder->private_->seek_table.data.seek_table.points = 0;
  100147. decoder->private_->has_seek_table = false;
  100148. }
  100149. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100150. /*
  100151. * This goes in reset() and not flush() because according to the spec, a
  100152. * fixed-blocksize stream must stay that way through the whole stream.
  100153. */
  100154. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100155. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100156. * is because md5 checking may be turned on to start and then turned off if
  100157. * a seek occurs. So we init the context here and finalize it in
  100158. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100159. * properly.
  100160. */
  100161. FLAC__MD5Init(&decoder->private_->md5context);
  100162. decoder->private_->first_frame_offset = 0;
  100163. decoder->private_->unparseable_frame_count = 0;
  100164. return true;
  100165. }
  100166. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100167. {
  100168. FLAC__bool got_a_frame;
  100169. FLAC__ASSERT(0 != decoder);
  100170. FLAC__ASSERT(0 != decoder->protected_);
  100171. while(1) {
  100172. switch(decoder->protected_->state) {
  100173. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100174. if(!find_metadata_(decoder))
  100175. return false; /* above function sets the status for us */
  100176. break;
  100177. case FLAC__STREAM_DECODER_READ_METADATA:
  100178. if(!read_metadata_(decoder))
  100179. return false; /* above function sets the status for us */
  100180. else
  100181. return true;
  100182. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100183. if(!frame_sync_(decoder))
  100184. return true; /* above function sets the status for us */
  100185. break;
  100186. case FLAC__STREAM_DECODER_READ_FRAME:
  100187. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100188. return false; /* above function sets the status for us */
  100189. if(got_a_frame)
  100190. return true; /* above function sets the status for us */
  100191. break;
  100192. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100193. case FLAC__STREAM_DECODER_ABORTED:
  100194. return true;
  100195. default:
  100196. FLAC__ASSERT(0);
  100197. return false;
  100198. }
  100199. }
  100200. }
  100201. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100202. {
  100203. FLAC__ASSERT(0 != decoder);
  100204. FLAC__ASSERT(0 != decoder->protected_);
  100205. while(1) {
  100206. switch(decoder->protected_->state) {
  100207. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100208. if(!find_metadata_(decoder))
  100209. return false; /* above function sets the status for us */
  100210. break;
  100211. case FLAC__STREAM_DECODER_READ_METADATA:
  100212. if(!read_metadata_(decoder))
  100213. return false; /* above function sets the status for us */
  100214. break;
  100215. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100216. case FLAC__STREAM_DECODER_READ_FRAME:
  100217. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100218. case FLAC__STREAM_DECODER_ABORTED:
  100219. return true;
  100220. default:
  100221. FLAC__ASSERT(0);
  100222. return false;
  100223. }
  100224. }
  100225. }
  100226. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100227. {
  100228. FLAC__bool dummy;
  100229. FLAC__ASSERT(0 != decoder);
  100230. FLAC__ASSERT(0 != decoder->protected_);
  100231. while(1) {
  100232. switch(decoder->protected_->state) {
  100233. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100234. if(!find_metadata_(decoder))
  100235. return false; /* above function sets the status for us */
  100236. break;
  100237. case FLAC__STREAM_DECODER_READ_METADATA:
  100238. if(!read_metadata_(decoder))
  100239. return false; /* above function sets the status for us */
  100240. break;
  100241. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100242. if(!frame_sync_(decoder))
  100243. return true; /* above function sets the status for us */
  100244. break;
  100245. case FLAC__STREAM_DECODER_READ_FRAME:
  100246. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100247. return false; /* above function sets the status for us */
  100248. break;
  100249. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100250. case FLAC__STREAM_DECODER_ABORTED:
  100251. return true;
  100252. default:
  100253. FLAC__ASSERT(0);
  100254. return false;
  100255. }
  100256. }
  100257. }
  100258. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100259. {
  100260. FLAC__bool got_a_frame;
  100261. FLAC__ASSERT(0 != decoder);
  100262. FLAC__ASSERT(0 != decoder->protected_);
  100263. while(1) {
  100264. switch(decoder->protected_->state) {
  100265. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100266. case FLAC__STREAM_DECODER_READ_METADATA:
  100267. return false; /* above function sets the status for us */
  100268. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100269. if(!frame_sync_(decoder))
  100270. return true; /* above function sets the status for us */
  100271. break;
  100272. case FLAC__STREAM_DECODER_READ_FRAME:
  100273. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100274. return false; /* above function sets the status for us */
  100275. if(got_a_frame)
  100276. return true; /* above function sets the status for us */
  100277. break;
  100278. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100279. case FLAC__STREAM_DECODER_ABORTED:
  100280. return true;
  100281. default:
  100282. FLAC__ASSERT(0);
  100283. return false;
  100284. }
  100285. }
  100286. }
  100287. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100288. {
  100289. FLAC__uint64 length;
  100290. FLAC__ASSERT(0 != decoder);
  100291. if(
  100292. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100293. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100294. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100295. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100296. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100297. )
  100298. return false;
  100299. if(0 == decoder->private_->seek_callback)
  100300. return false;
  100301. FLAC__ASSERT(decoder->private_->seek_callback);
  100302. FLAC__ASSERT(decoder->private_->tell_callback);
  100303. FLAC__ASSERT(decoder->private_->length_callback);
  100304. FLAC__ASSERT(decoder->private_->eof_callback);
  100305. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100306. return false;
  100307. decoder->private_->is_seeking = true;
  100308. /* turn off md5 checking if a seek is attempted */
  100309. decoder->private_->do_md5_checking = false;
  100310. /* 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) */
  100311. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100312. decoder->private_->is_seeking = false;
  100313. return false;
  100314. }
  100315. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100316. if(
  100317. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100318. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100319. ) {
  100320. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100321. /* above call sets the state for us */
  100322. decoder->private_->is_seeking = false;
  100323. return false;
  100324. }
  100325. /* check this again in case we didn't know total_samples the first time */
  100326. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100327. decoder->private_->is_seeking = false;
  100328. return false;
  100329. }
  100330. }
  100331. {
  100332. const FLAC__bool ok =
  100333. #if FLAC__HAS_OGG
  100334. decoder->private_->is_ogg?
  100335. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100336. #endif
  100337. seek_to_absolute_sample_(decoder, length, sample)
  100338. ;
  100339. decoder->private_->is_seeking = false;
  100340. return ok;
  100341. }
  100342. }
  100343. /***********************************************************************
  100344. *
  100345. * Protected class methods
  100346. *
  100347. ***********************************************************************/
  100348. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100349. {
  100350. FLAC__ASSERT(0 != decoder);
  100351. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100352. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100353. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100354. }
  100355. /***********************************************************************
  100356. *
  100357. * Private class methods
  100358. *
  100359. ***********************************************************************/
  100360. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100361. {
  100362. #if FLAC__HAS_OGG
  100363. decoder->private_->is_ogg = false;
  100364. #endif
  100365. decoder->private_->read_callback = 0;
  100366. decoder->private_->seek_callback = 0;
  100367. decoder->private_->tell_callback = 0;
  100368. decoder->private_->length_callback = 0;
  100369. decoder->private_->eof_callback = 0;
  100370. decoder->private_->write_callback = 0;
  100371. decoder->private_->metadata_callback = 0;
  100372. decoder->private_->error_callback = 0;
  100373. decoder->private_->client_data = 0;
  100374. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100375. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100376. decoder->private_->metadata_filter_ids_count = 0;
  100377. decoder->protected_->md5_checking = false;
  100378. #if FLAC__HAS_OGG
  100379. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100380. #endif
  100381. }
  100382. /*
  100383. * This will forcibly set stdin to binary mode (for OSes that require it)
  100384. */
  100385. FILE *get_binary_stdin_(void)
  100386. {
  100387. /* if something breaks here it is probably due to the presence or
  100388. * absence of an underscore before the identifiers 'setmode',
  100389. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100390. */
  100391. #if defined _MSC_VER || defined __MINGW32__
  100392. _setmode(_fileno(stdin), _O_BINARY);
  100393. #elif defined __CYGWIN__
  100394. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100395. setmode(_fileno(stdin), _O_BINARY);
  100396. #elif defined __EMX__
  100397. setmode(fileno(stdin), O_BINARY);
  100398. #endif
  100399. return stdin;
  100400. }
  100401. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100402. {
  100403. unsigned i;
  100404. FLAC__int32 *tmp;
  100405. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100406. return true;
  100407. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100408. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100409. if(0 != decoder->private_->output[i]) {
  100410. free(decoder->private_->output[i]-4);
  100411. decoder->private_->output[i] = 0;
  100412. }
  100413. if(0 != decoder->private_->residual_unaligned[i]) {
  100414. free(decoder->private_->residual_unaligned[i]);
  100415. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100416. }
  100417. }
  100418. for(i = 0; i < channels; i++) {
  100419. /* WATCHOUT:
  100420. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100421. * output arrays have a buffer of up to 3 zeroes in front
  100422. * (at negative indices) for alignment purposes; we use 4
  100423. * to keep the data well-aligned.
  100424. */
  100425. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100426. if(tmp == 0) {
  100427. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100428. return false;
  100429. }
  100430. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100431. decoder->private_->output[i] = tmp + 4;
  100432. /* WATCHOUT:
  100433. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100434. */
  100435. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100436. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100437. return false;
  100438. }
  100439. }
  100440. decoder->private_->output_capacity = size;
  100441. decoder->private_->output_channels = channels;
  100442. return true;
  100443. }
  100444. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100445. {
  100446. size_t i;
  100447. FLAC__ASSERT(0 != decoder);
  100448. FLAC__ASSERT(0 != decoder->private_);
  100449. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100450. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100451. return true;
  100452. return false;
  100453. }
  100454. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100455. {
  100456. FLAC__uint32 x;
  100457. unsigned i, id_;
  100458. FLAC__bool first = true;
  100459. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100460. for(i = id_ = 0; i < 4; ) {
  100461. if(decoder->private_->cached) {
  100462. x = (FLAC__uint32)decoder->private_->lookahead;
  100463. decoder->private_->cached = false;
  100464. }
  100465. else {
  100466. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100467. return false; /* read_callback_ sets the state for us */
  100468. }
  100469. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100470. first = true;
  100471. i++;
  100472. id_ = 0;
  100473. continue;
  100474. }
  100475. if(x == ID3V2_TAG_[id_]) {
  100476. id_++;
  100477. i = 0;
  100478. if(id_ == 3) {
  100479. if(!skip_id3v2_tag_(decoder))
  100480. return false; /* skip_id3v2_tag_ sets the state for us */
  100481. }
  100482. continue;
  100483. }
  100484. id_ = 0;
  100485. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100486. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100487. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100488. return false; /* read_callback_ sets the state for us */
  100489. /* 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 */
  100490. /* else we have to check if the second byte is the end of a sync code */
  100491. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100492. decoder->private_->lookahead = (FLAC__byte)x;
  100493. decoder->private_->cached = true;
  100494. }
  100495. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100496. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100497. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100498. return true;
  100499. }
  100500. }
  100501. i = 0;
  100502. if(first) {
  100503. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100504. first = false;
  100505. }
  100506. }
  100507. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100508. return true;
  100509. }
  100510. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100511. {
  100512. FLAC__bool is_last;
  100513. FLAC__uint32 i, x, type, length;
  100514. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100515. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100516. return false; /* read_callback_ sets the state for us */
  100517. is_last = x? true : false;
  100518. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100519. return false; /* read_callback_ sets the state for us */
  100520. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100521. return false; /* read_callback_ sets the state for us */
  100522. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100523. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100524. return false;
  100525. decoder->private_->has_stream_info = true;
  100526. 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))
  100527. decoder->private_->do_md5_checking = false;
  100528. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100529. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100530. }
  100531. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100532. if(!read_metadata_seektable_(decoder, is_last, length))
  100533. return false;
  100534. decoder->private_->has_seek_table = true;
  100535. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100536. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100537. }
  100538. else {
  100539. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100540. unsigned real_length = length;
  100541. FLAC__StreamMetadata block;
  100542. block.is_last = is_last;
  100543. block.type = (FLAC__MetadataType)type;
  100544. block.length = length;
  100545. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100546. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100547. return false; /* read_callback_ sets the state for us */
  100548. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100549. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100550. return false;
  100551. }
  100552. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100553. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100554. skip_it = !skip_it;
  100555. }
  100556. if(skip_it) {
  100557. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100558. return false; /* read_callback_ sets the state for us */
  100559. }
  100560. else {
  100561. switch(type) {
  100562. case FLAC__METADATA_TYPE_PADDING:
  100563. /* skip the padding bytes */
  100564. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100565. return false; /* read_callback_ sets the state for us */
  100566. break;
  100567. case FLAC__METADATA_TYPE_APPLICATION:
  100568. /* remember, we read the ID already */
  100569. if(real_length > 0) {
  100570. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100571. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100572. return false;
  100573. }
  100574. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100575. return false; /* read_callback_ sets the state for us */
  100576. }
  100577. else
  100578. block.data.application.data = 0;
  100579. break;
  100580. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100581. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100582. return false;
  100583. break;
  100584. case FLAC__METADATA_TYPE_CUESHEET:
  100585. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100586. return false;
  100587. break;
  100588. case FLAC__METADATA_TYPE_PICTURE:
  100589. if(!read_metadata_picture_(decoder, &block.data.picture))
  100590. return false;
  100591. break;
  100592. case FLAC__METADATA_TYPE_STREAMINFO:
  100593. case FLAC__METADATA_TYPE_SEEKTABLE:
  100594. FLAC__ASSERT(0);
  100595. break;
  100596. default:
  100597. if(real_length > 0) {
  100598. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100599. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100600. return false;
  100601. }
  100602. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100603. return false; /* read_callback_ sets the state for us */
  100604. }
  100605. else
  100606. block.data.unknown.data = 0;
  100607. break;
  100608. }
  100609. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100610. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100611. /* now we have to free any malloc()ed data in the block */
  100612. switch(type) {
  100613. case FLAC__METADATA_TYPE_PADDING:
  100614. break;
  100615. case FLAC__METADATA_TYPE_APPLICATION:
  100616. if(0 != block.data.application.data)
  100617. free(block.data.application.data);
  100618. break;
  100619. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100620. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100621. free(block.data.vorbis_comment.vendor_string.entry);
  100622. if(block.data.vorbis_comment.num_comments > 0)
  100623. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100624. if(0 != block.data.vorbis_comment.comments[i].entry)
  100625. free(block.data.vorbis_comment.comments[i].entry);
  100626. if(0 != block.data.vorbis_comment.comments)
  100627. free(block.data.vorbis_comment.comments);
  100628. break;
  100629. case FLAC__METADATA_TYPE_CUESHEET:
  100630. if(block.data.cue_sheet.num_tracks > 0)
  100631. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100632. if(0 != block.data.cue_sheet.tracks[i].indices)
  100633. free(block.data.cue_sheet.tracks[i].indices);
  100634. if(0 != block.data.cue_sheet.tracks)
  100635. free(block.data.cue_sheet.tracks);
  100636. break;
  100637. case FLAC__METADATA_TYPE_PICTURE:
  100638. if(0 != block.data.picture.mime_type)
  100639. free(block.data.picture.mime_type);
  100640. if(0 != block.data.picture.description)
  100641. free(block.data.picture.description);
  100642. if(0 != block.data.picture.data)
  100643. free(block.data.picture.data);
  100644. break;
  100645. case FLAC__METADATA_TYPE_STREAMINFO:
  100646. case FLAC__METADATA_TYPE_SEEKTABLE:
  100647. FLAC__ASSERT(0);
  100648. default:
  100649. if(0 != block.data.unknown.data)
  100650. free(block.data.unknown.data);
  100651. break;
  100652. }
  100653. }
  100654. }
  100655. if(is_last) {
  100656. /* if this fails, it's OK, it's just a hint for the seek routine */
  100657. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100658. decoder->private_->first_frame_offset = 0;
  100659. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100660. }
  100661. return true;
  100662. }
  100663. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100664. {
  100665. FLAC__uint32 x;
  100666. unsigned bits, used_bits = 0;
  100667. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100668. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100669. decoder->private_->stream_info.is_last = is_last;
  100670. decoder->private_->stream_info.length = length;
  100671. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100672. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100673. return false; /* read_callback_ sets the state for us */
  100674. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100675. used_bits += bits;
  100676. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100677. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100678. return false; /* read_callback_ sets the state for us */
  100679. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100680. used_bits += bits;
  100681. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100682. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100683. return false; /* read_callback_ sets the state for us */
  100684. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100685. used_bits += bits;
  100686. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100687. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100688. return false; /* read_callback_ sets the state for us */
  100689. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100690. used_bits += bits;
  100691. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100692. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100693. return false; /* read_callback_ sets the state for us */
  100694. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100695. used_bits += bits;
  100696. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100697. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100698. return false; /* read_callback_ sets the state for us */
  100699. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100700. used_bits += bits;
  100701. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100702. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100703. return false; /* read_callback_ sets the state for us */
  100704. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100705. used_bits += bits;
  100706. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100707. 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))
  100708. return false; /* read_callback_ sets the state for us */
  100709. used_bits += bits;
  100710. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100711. return false; /* read_callback_ sets the state for us */
  100712. used_bits += 16*8;
  100713. /* skip the rest of the block */
  100714. FLAC__ASSERT(used_bits % 8 == 0);
  100715. length -= (used_bits / 8);
  100716. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100717. return false; /* read_callback_ sets the state for us */
  100718. return true;
  100719. }
  100720. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100721. {
  100722. FLAC__uint32 i, x;
  100723. FLAC__uint64 xx;
  100724. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100725. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100726. decoder->private_->seek_table.is_last = is_last;
  100727. decoder->private_->seek_table.length = length;
  100728. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100729. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100730. 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)))) {
  100731. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100732. return false;
  100733. }
  100734. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100735. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100736. return false; /* read_callback_ sets the state for us */
  100737. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100738. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100739. return false; /* read_callback_ sets the state for us */
  100740. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100741. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100742. return false; /* read_callback_ sets the state for us */
  100743. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100744. }
  100745. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100746. /* if there is a partial point left, skip over it */
  100747. if(length > 0) {
  100748. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100749. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100750. return false; /* read_callback_ sets the state for us */
  100751. }
  100752. return true;
  100753. }
  100754. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100755. {
  100756. FLAC__uint32 i;
  100757. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100758. /* read vendor string */
  100759. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100760. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100761. return false; /* read_callback_ sets the state for us */
  100762. if(obj->vendor_string.length > 0) {
  100763. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100764. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100765. return false;
  100766. }
  100767. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100768. return false; /* read_callback_ sets the state for us */
  100769. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100770. }
  100771. else
  100772. obj->vendor_string.entry = 0;
  100773. /* read num comments */
  100774. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100775. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100776. return false; /* read_callback_ sets the state for us */
  100777. /* read comments */
  100778. if(obj->num_comments > 0) {
  100779. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100780. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100781. return false;
  100782. }
  100783. for(i = 0; i < obj->num_comments; i++) {
  100784. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100785. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100786. return false; /* read_callback_ sets the state for us */
  100787. if(obj->comments[i].length > 0) {
  100788. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100789. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100790. return false;
  100791. }
  100792. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100793. return false; /* read_callback_ sets the state for us */
  100794. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100795. }
  100796. else
  100797. obj->comments[i].entry = 0;
  100798. }
  100799. }
  100800. else {
  100801. obj->comments = 0;
  100802. }
  100803. return true;
  100804. }
  100805. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100806. {
  100807. FLAC__uint32 i, j, x;
  100808. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100809. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100810. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100811. 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))
  100812. return false; /* read_callback_ sets the state for us */
  100813. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100814. return false; /* read_callback_ sets the state for us */
  100815. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100816. return false; /* read_callback_ sets the state for us */
  100817. obj->is_cd = x? true : false;
  100818. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100819. return false; /* read_callback_ sets the state for us */
  100820. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100821. return false; /* read_callback_ sets the state for us */
  100822. obj->num_tracks = x;
  100823. if(obj->num_tracks > 0) {
  100824. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100825. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100826. return false;
  100827. }
  100828. for(i = 0; i < obj->num_tracks; i++) {
  100829. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100830. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100831. return false; /* read_callback_ sets the state for us */
  100832. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100833. return false; /* read_callback_ sets the state for us */
  100834. track->number = (FLAC__byte)x;
  100835. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100836. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100837. return false; /* read_callback_ sets the state for us */
  100838. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100839. return false; /* read_callback_ sets the state for us */
  100840. track->type = x;
  100841. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100842. return false; /* read_callback_ sets the state for us */
  100843. track->pre_emphasis = x;
  100844. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100845. return false; /* read_callback_ sets the state for us */
  100846. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100847. return false; /* read_callback_ sets the state for us */
  100848. track->num_indices = (FLAC__byte)x;
  100849. if(track->num_indices > 0) {
  100850. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100851. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100852. return false;
  100853. }
  100854. for(j = 0; j < track->num_indices; j++) {
  100855. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100856. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100857. return false; /* read_callback_ sets the state for us */
  100858. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100859. return false; /* read_callback_ sets the state for us */
  100860. index->number = (FLAC__byte)x;
  100861. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100862. return false; /* read_callback_ sets the state for us */
  100863. }
  100864. }
  100865. }
  100866. }
  100867. return true;
  100868. }
  100869. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100870. {
  100871. FLAC__uint32 x;
  100872. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100873. /* read type */
  100874. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100875. return false; /* read_callback_ sets the state for us */
  100876. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100877. /* read MIME type */
  100878. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100879. return false; /* read_callback_ sets the state for us */
  100880. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100881. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100882. return false;
  100883. }
  100884. if(x > 0) {
  100885. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100886. return false; /* read_callback_ sets the state for us */
  100887. }
  100888. obj->mime_type[x] = '\0';
  100889. /* read description */
  100890. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100891. return false; /* read_callback_ sets the state for us */
  100892. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100893. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100894. return false;
  100895. }
  100896. if(x > 0) {
  100897. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100898. return false; /* read_callback_ sets the state for us */
  100899. }
  100900. obj->description[x] = '\0';
  100901. /* read width */
  100902. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100903. return false; /* read_callback_ sets the state for us */
  100904. /* read height */
  100905. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100906. return false; /* read_callback_ sets the state for us */
  100907. /* read depth */
  100908. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100909. return false; /* read_callback_ sets the state for us */
  100910. /* read colors */
  100911. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100912. return false; /* read_callback_ sets the state for us */
  100913. /* read data */
  100914. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100915. return false; /* read_callback_ sets the state for us */
  100916. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100917. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100918. return false;
  100919. }
  100920. if(obj->data_length > 0) {
  100921. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100922. return false; /* read_callback_ sets the state for us */
  100923. }
  100924. return true;
  100925. }
  100926. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100927. {
  100928. FLAC__uint32 x;
  100929. unsigned i, skip;
  100930. /* skip the version and flags bytes */
  100931. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100932. return false; /* read_callback_ sets the state for us */
  100933. /* get the size (in bytes) to skip */
  100934. skip = 0;
  100935. for(i = 0; i < 4; i++) {
  100936. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100937. return false; /* read_callback_ sets the state for us */
  100938. skip <<= 7;
  100939. skip |= (x & 0x7f);
  100940. }
  100941. /* skip the rest of the tag */
  100942. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100943. return false; /* read_callback_ sets the state for us */
  100944. return true;
  100945. }
  100946. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100947. {
  100948. FLAC__uint32 x;
  100949. FLAC__bool first = true;
  100950. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100951. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100952. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100953. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100954. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100955. return true;
  100956. }
  100957. }
  100958. /* make sure we're byte aligned */
  100959. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100960. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100961. return false; /* read_callback_ sets the state for us */
  100962. }
  100963. while(1) {
  100964. if(decoder->private_->cached) {
  100965. x = (FLAC__uint32)decoder->private_->lookahead;
  100966. decoder->private_->cached = false;
  100967. }
  100968. else {
  100969. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100970. return false; /* read_callback_ sets the state for us */
  100971. }
  100972. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100973. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100974. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100975. return false; /* read_callback_ sets the state for us */
  100976. /* 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 */
  100977. /* else we have to check if the second byte is the end of a sync code */
  100978. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100979. decoder->private_->lookahead = (FLAC__byte)x;
  100980. decoder->private_->cached = true;
  100981. }
  100982. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100983. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100984. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100985. return true;
  100986. }
  100987. }
  100988. if(first) {
  100989. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100990. first = false;
  100991. }
  100992. }
  100993. return true;
  100994. }
  100995. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100996. {
  100997. unsigned channel;
  100998. unsigned i;
  100999. FLAC__int32 mid, side;
  101000. unsigned frame_crc; /* the one we calculate from the input stream */
  101001. FLAC__uint32 x;
  101002. *got_a_frame = false;
  101003. /* init the CRC */
  101004. frame_crc = 0;
  101005. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  101006. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  101007. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  101008. if(!read_frame_header_(decoder))
  101009. return false;
  101010. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  101011. return true;
  101012. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  101013. return false;
  101014. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101015. /*
  101016. * first figure the correct bits-per-sample of the subframe
  101017. */
  101018. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  101019. switch(decoder->private_->frame.header.channel_assignment) {
  101020. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101021. /* no adjustment needed */
  101022. break;
  101023. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101024. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101025. if(channel == 1)
  101026. bps++;
  101027. break;
  101028. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101029. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101030. if(channel == 0)
  101031. bps++;
  101032. break;
  101033. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101034. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101035. if(channel == 1)
  101036. bps++;
  101037. break;
  101038. default:
  101039. FLAC__ASSERT(0);
  101040. }
  101041. /*
  101042. * now read it
  101043. */
  101044. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101045. return false;
  101046. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101047. return true;
  101048. }
  101049. if(!read_zero_padding_(decoder))
  101050. return false;
  101051. 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) */
  101052. return true;
  101053. /*
  101054. * Read the frame CRC-16 from the footer and check
  101055. */
  101056. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101057. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101058. return false; /* read_callback_ sets the state for us */
  101059. if(frame_crc == x) {
  101060. if(do_full_decode) {
  101061. /* Undo any special channel coding */
  101062. switch(decoder->private_->frame.header.channel_assignment) {
  101063. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101064. /* do nothing */
  101065. break;
  101066. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101067. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101068. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101069. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101070. break;
  101071. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101072. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101073. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101074. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101075. break;
  101076. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101077. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101078. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101079. #if 1
  101080. mid = decoder->private_->output[0][i];
  101081. side = decoder->private_->output[1][i];
  101082. mid <<= 1;
  101083. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101084. decoder->private_->output[0][i] = (mid + side) >> 1;
  101085. decoder->private_->output[1][i] = (mid - side) >> 1;
  101086. #else
  101087. /* OPT: without 'side' temp variable */
  101088. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101089. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101090. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101091. #endif
  101092. }
  101093. break;
  101094. default:
  101095. FLAC__ASSERT(0);
  101096. break;
  101097. }
  101098. }
  101099. }
  101100. else {
  101101. /* Bad frame, emit error and zero the output signal */
  101102. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101103. if(do_full_decode) {
  101104. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101105. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101106. }
  101107. }
  101108. }
  101109. *got_a_frame = true;
  101110. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101111. if(decoder->private_->next_fixed_block_size)
  101112. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101113. /* put the latest values into the public section of the decoder instance */
  101114. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101115. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101116. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101117. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101118. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101119. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101120. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101121. /* write it */
  101122. if(do_full_decode) {
  101123. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101124. return false;
  101125. }
  101126. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101127. return true;
  101128. }
  101129. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101130. {
  101131. FLAC__uint32 x;
  101132. FLAC__uint64 xx;
  101133. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101134. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101135. unsigned raw_header_len;
  101136. FLAC__bool is_unparseable = false;
  101137. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101138. /* init the raw header with the saved bits from synchronization */
  101139. raw_header[0] = decoder->private_->header_warmup[0];
  101140. raw_header[1] = decoder->private_->header_warmup[1];
  101141. raw_header_len = 2;
  101142. /* check to make sure that reserved bit is 0 */
  101143. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101144. is_unparseable = true;
  101145. /*
  101146. * Note that along the way as we read the header, we look for a sync
  101147. * code inside. If we find one it would indicate that our original
  101148. * sync was bad since there cannot be a sync code in a valid header.
  101149. *
  101150. * Three kinds of things can go wrong when reading the frame header:
  101151. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101152. * If we don't find a sync code, it can end up looking like we read
  101153. * a valid but unparseable header, until getting to the frame header
  101154. * CRC. Even then we could get a false positive on the CRC.
  101155. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101156. * future encoder).
  101157. * 3) We may be on a damaged frame which appears valid but unparseable.
  101158. *
  101159. * For all these reasons, we try and read a complete frame header as
  101160. * long as it seems valid, even if unparseable, up until the frame
  101161. * header CRC.
  101162. */
  101163. /*
  101164. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101165. */
  101166. for(i = 0; i < 2; i++) {
  101167. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101168. return false; /* read_callback_ sets the state for us */
  101169. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101170. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101171. decoder->private_->lookahead = (FLAC__byte)x;
  101172. decoder->private_->cached = true;
  101173. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101174. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101175. return true;
  101176. }
  101177. raw_header[raw_header_len++] = (FLAC__byte)x;
  101178. }
  101179. switch(x = raw_header[2] >> 4) {
  101180. case 0:
  101181. is_unparseable = true;
  101182. break;
  101183. case 1:
  101184. decoder->private_->frame.header.blocksize = 192;
  101185. break;
  101186. case 2:
  101187. case 3:
  101188. case 4:
  101189. case 5:
  101190. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101191. break;
  101192. case 6:
  101193. case 7:
  101194. blocksize_hint = x;
  101195. break;
  101196. case 8:
  101197. case 9:
  101198. case 10:
  101199. case 11:
  101200. case 12:
  101201. case 13:
  101202. case 14:
  101203. case 15:
  101204. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101205. break;
  101206. default:
  101207. FLAC__ASSERT(0);
  101208. break;
  101209. }
  101210. switch(x = raw_header[2] & 0x0f) {
  101211. case 0:
  101212. if(decoder->private_->has_stream_info)
  101213. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101214. else
  101215. is_unparseable = true;
  101216. break;
  101217. case 1:
  101218. decoder->private_->frame.header.sample_rate = 88200;
  101219. break;
  101220. case 2:
  101221. decoder->private_->frame.header.sample_rate = 176400;
  101222. break;
  101223. case 3:
  101224. decoder->private_->frame.header.sample_rate = 192000;
  101225. break;
  101226. case 4:
  101227. decoder->private_->frame.header.sample_rate = 8000;
  101228. break;
  101229. case 5:
  101230. decoder->private_->frame.header.sample_rate = 16000;
  101231. break;
  101232. case 6:
  101233. decoder->private_->frame.header.sample_rate = 22050;
  101234. break;
  101235. case 7:
  101236. decoder->private_->frame.header.sample_rate = 24000;
  101237. break;
  101238. case 8:
  101239. decoder->private_->frame.header.sample_rate = 32000;
  101240. break;
  101241. case 9:
  101242. decoder->private_->frame.header.sample_rate = 44100;
  101243. break;
  101244. case 10:
  101245. decoder->private_->frame.header.sample_rate = 48000;
  101246. break;
  101247. case 11:
  101248. decoder->private_->frame.header.sample_rate = 96000;
  101249. break;
  101250. case 12:
  101251. case 13:
  101252. case 14:
  101253. sample_rate_hint = x;
  101254. break;
  101255. case 15:
  101256. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101257. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101258. return true;
  101259. default:
  101260. FLAC__ASSERT(0);
  101261. }
  101262. x = (unsigned)(raw_header[3] >> 4);
  101263. if(x & 8) {
  101264. decoder->private_->frame.header.channels = 2;
  101265. switch(x & 7) {
  101266. case 0:
  101267. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101268. break;
  101269. case 1:
  101270. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101271. break;
  101272. case 2:
  101273. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101274. break;
  101275. default:
  101276. is_unparseable = true;
  101277. break;
  101278. }
  101279. }
  101280. else {
  101281. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101282. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101283. }
  101284. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101285. case 0:
  101286. if(decoder->private_->has_stream_info)
  101287. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101288. else
  101289. is_unparseable = true;
  101290. break;
  101291. case 1:
  101292. decoder->private_->frame.header.bits_per_sample = 8;
  101293. break;
  101294. case 2:
  101295. decoder->private_->frame.header.bits_per_sample = 12;
  101296. break;
  101297. case 4:
  101298. decoder->private_->frame.header.bits_per_sample = 16;
  101299. break;
  101300. case 5:
  101301. decoder->private_->frame.header.bits_per_sample = 20;
  101302. break;
  101303. case 6:
  101304. decoder->private_->frame.header.bits_per_sample = 24;
  101305. break;
  101306. case 3:
  101307. case 7:
  101308. is_unparseable = true;
  101309. break;
  101310. default:
  101311. FLAC__ASSERT(0);
  101312. break;
  101313. }
  101314. /* check to make sure that reserved bit is 0 */
  101315. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101316. is_unparseable = true;
  101317. /* read the frame's starting sample number (or frame number as the case may be) */
  101318. if(
  101319. raw_header[1] & 0x01 ||
  101320. /*@@@ 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 */
  101321. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101322. ) { /* variable blocksize */
  101323. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101324. return false; /* read_callback_ sets the state for us */
  101325. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101326. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101327. decoder->private_->cached = true;
  101328. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101329. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101330. return true;
  101331. }
  101332. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101333. decoder->private_->frame.header.number.sample_number = xx;
  101334. }
  101335. else { /* fixed blocksize */
  101336. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101337. return false; /* read_callback_ sets the state for us */
  101338. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101339. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101340. decoder->private_->cached = true;
  101341. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101342. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101343. return true;
  101344. }
  101345. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101346. decoder->private_->frame.header.number.frame_number = x;
  101347. }
  101348. if(blocksize_hint) {
  101349. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101350. return false; /* read_callback_ sets the state for us */
  101351. raw_header[raw_header_len++] = (FLAC__byte)x;
  101352. if(blocksize_hint == 7) {
  101353. FLAC__uint32 _x;
  101354. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101355. return false; /* read_callback_ sets the state for us */
  101356. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101357. x = (x << 8) | _x;
  101358. }
  101359. decoder->private_->frame.header.blocksize = x+1;
  101360. }
  101361. if(sample_rate_hint) {
  101362. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101363. return false; /* read_callback_ sets the state for us */
  101364. raw_header[raw_header_len++] = (FLAC__byte)x;
  101365. if(sample_rate_hint != 12) {
  101366. FLAC__uint32 _x;
  101367. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101368. return false; /* read_callback_ sets the state for us */
  101369. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101370. x = (x << 8) | _x;
  101371. }
  101372. if(sample_rate_hint == 12)
  101373. decoder->private_->frame.header.sample_rate = x*1000;
  101374. else if(sample_rate_hint == 13)
  101375. decoder->private_->frame.header.sample_rate = x;
  101376. else
  101377. decoder->private_->frame.header.sample_rate = x*10;
  101378. }
  101379. /* read the CRC-8 byte */
  101380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101381. return false; /* read_callback_ sets the state for us */
  101382. crc8 = (FLAC__byte)x;
  101383. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101384. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101385. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101386. return true;
  101387. }
  101388. /* calculate the sample number from the frame number if needed */
  101389. decoder->private_->next_fixed_block_size = 0;
  101390. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101391. x = decoder->private_->frame.header.number.frame_number;
  101392. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101393. if(decoder->private_->fixed_block_size)
  101394. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101395. else if(decoder->private_->has_stream_info) {
  101396. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101397. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101398. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101399. }
  101400. else
  101401. is_unparseable = true;
  101402. }
  101403. else if(x == 0) {
  101404. decoder->private_->frame.header.number.sample_number = 0;
  101405. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101406. }
  101407. else {
  101408. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101409. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101410. }
  101411. }
  101412. if(is_unparseable) {
  101413. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101414. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101415. return true;
  101416. }
  101417. return true;
  101418. }
  101419. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101420. {
  101421. FLAC__uint32 x;
  101422. FLAC__bool wasted_bits;
  101423. unsigned i;
  101424. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101425. return false; /* read_callback_ sets the state for us */
  101426. wasted_bits = (x & 1);
  101427. x &= 0xfe;
  101428. if(wasted_bits) {
  101429. unsigned u;
  101430. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101431. return false; /* read_callback_ sets the state for us */
  101432. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101433. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101434. }
  101435. else
  101436. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101437. /*
  101438. * Lots of magic numbers here
  101439. */
  101440. if(x & 0x80) {
  101441. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101442. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101443. return true;
  101444. }
  101445. else if(x == 0) {
  101446. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101447. return false;
  101448. }
  101449. else if(x == 2) {
  101450. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101451. return false;
  101452. }
  101453. else if(x < 16) {
  101454. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101455. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101456. return true;
  101457. }
  101458. else if(x <= 24) {
  101459. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101460. return false;
  101461. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101462. return true;
  101463. }
  101464. else if(x < 64) {
  101465. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101466. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101467. return true;
  101468. }
  101469. else {
  101470. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101471. return false;
  101472. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101473. return true;
  101474. }
  101475. if(wasted_bits && do_full_decode) {
  101476. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101477. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101478. decoder->private_->output[channel][i] <<= x;
  101479. }
  101480. return true;
  101481. }
  101482. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101483. {
  101484. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101485. FLAC__int32 x;
  101486. unsigned i;
  101487. FLAC__int32 *output = decoder->private_->output[channel];
  101488. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101489. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101490. return false; /* read_callback_ sets the state for us */
  101491. subframe->value = x;
  101492. /* decode the subframe */
  101493. if(do_full_decode) {
  101494. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101495. output[i] = x;
  101496. }
  101497. return true;
  101498. }
  101499. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101500. {
  101501. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101502. FLAC__int32 i32;
  101503. FLAC__uint32 u32;
  101504. unsigned u;
  101505. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101506. subframe->residual = decoder->private_->residual[channel];
  101507. subframe->order = order;
  101508. /* read warm-up samples */
  101509. for(u = 0; u < order; u++) {
  101510. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101511. return false; /* read_callback_ sets the state for us */
  101512. subframe->warmup[u] = i32;
  101513. }
  101514. /* read entropy coding method info */
  101515. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101516. return false; /* read_callback_ sets the state for us */
  101517. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101518. switch(subframe->entropy_coding_method.type) {
  101519. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101520. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101521. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101522. return false; /* read_callback_ sets the state for us */
  101523. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101524. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101525. break;
  101526. default:
  101527. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101528. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101529. return true;
  101530. }
  101531. /* read residual */
  101532. switch(subframe->entropy_coding_method.type) {
  101533. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101534. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101535. 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))
  101536. return false;
  101537. break;
  101538. default:
  101539. FLAC__ASSERT(0);
  101540. }
  101541. /* decode the subframe */
  101542. if(do_full_decode) {
  101543. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101544. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101545. }
  101546. return true;
  101547. }
  101548. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101549. {
  101550. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101551. FLAC__int32 i32;
  101552. FLAC__uint32 u32;
  101553. unsigned u;
  101554. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101555. subframe->residual = decoder->private_->residual[channel];
  101556. subframe->order = order;
  101557. /* read warm-up samples */
  101558. for(u = 0; u < order; u++) {
  101559. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101560. return false; /* read_callback_ sets the state for us */
  101561. subframe->warmup[u] = i32;
  101562. }
  101563. /* read qlp coeff precision */
  101564. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101565. return false; /* read_callback_ sets the state for us */
  101566. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101567. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101568. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101569. return true;
  101570. }
  101571. subframe->qlp_coeff_precision = u32+1;
  101572. /* read qlp shift */
  101573. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101574. return false; /* read_callback_ sets the state for us */
  101575. subframe->quantization_level = i32;
  101576. /* read quantized lp coefficiencts */
  101577. for(u = 0; u < order; u++) {
  101578. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101579. return false; /* read_callback_ sets the state for us */
  101580. subframe->qlp_coeff[u] = i32;
  101581. }
  101582. /* read entropy coding method info */
  101583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101584. return false; /* read_callback_ sets the state for us */
  101585. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101586. switch(subframe->entropy_coding_method.type) {
  101587. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101588. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101589. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101590. return false; /* read_callback_ sets the state for us */
  101591. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101592. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101593. break;
  101594. default:
  101595. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101596. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101597. return true;
  101598. }
  101599. /* read residual */
  101600. switch(subframe->entropy_coding_method.type) {
  101601. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101602. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101603. 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))
  101604. return false;
  101605. break;
  101606. default:
  101607. FLAC__ASSERT(0);
  101608. }
  101609. /* decode the subframe */
  101610. if(do_full_decode) {
  101611. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101612. /*@@@@@@ technically not pessimistic enough, should be more like
  101613. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101614. */
  101615. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101616. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101617. if(order <= 8)
  101618. 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);
  101619. else
  101620. 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);
  101621. }
  101622. else
  101623. 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);
  101624. else
  101625. 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);
  101626. }
  101627. return true;
  101628. }
  101629. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101630. {
  101631. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101632. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101633. unsigned i;
  101634. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101635. subframe->data = residual;
  101636. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101637. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101638. return false; /* read_callback_ sets the state for us */
  101639. residual[i] = x;
  101640. }
  101641. /* decode the subframe */
  101642. if(do_full_decode)
  101643. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101644. return true;
  101645. }
  101646. 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)
  101647. {
  101648. FLAC__uint32 rice_parameter;
  101649. int i;
  101650. unsigned partition, sample, u;
  101651. const unsigned partitions = 1u << partition_order;
  101652. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101653. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101654. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101655. /* sanity checks */
  101656. if(partition_order == 0) {
  101657. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101658. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101659. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101660. return true;
  101661. }
  101662. }
  101663. else {
  101664. if(partition_samples < predictor_order) {
  101665. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101666. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101667. return true;
  101668. }
  101669. }
  101670. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101671. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101672. return false;
  101673. }
  101674. sample = 0;
  101675. for(partition = 0; partition < partitions; partition++) {
  101676. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101677. return false; /* read_callback_ sets the state for us */
  101678. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101679. if(rice_parameter < pesc) {
  101680. partitioned_rice_contents->raw_bits[partition] = 0;
  101681. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101682. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101683. return false; /* read_callback_ sets the state for us */
  101684. sample += u;
  101685. }
  101686. else {
  101687. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101688. return false; /* read_callback_ sets the state for us */
  101689. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101690. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101691. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101692. return false; /* read_callback_ sets the state for us */
  101693. residual[sample] = i;
  101694. }
  101695. }
  101696. }
  101697. return true;
  101698. }
  101699. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101700. {
  101701. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101702. FLAC__uint32 zero = 0;
  101703. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101704. return false; /* read_callback_ sets the state for us */
  101705. if(zero != 0) {
  101706. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101707. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101708. }
  101709. }
  101710. return true;
  101711. }
  101712. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101713. {
  101714. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101715. if(
  101716. #if FLAC__HAS_OGG
  101717. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101718. !decoder->private_->is_ogg &&
  101719. #endif
  101720. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101721. ) {
  101722. *bytes = 0;
  101723. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101724. return false;
  101725. }
  101726. else if(*bytes > 0) {
  101727. /* While seeking, it is possible for our seek to land in the
  101728. * middle of audio data that looks exactly like a frame header
  101729. * from a future version of an encoder. When that happens, our
  101730. * error callback will get an
  101731. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101732. * unparseable_frame_count. But there is a remote possibility
  101733. * that it is properly synced at such a "future-codec frame",
  101734. * so to make sure, we wait to see many "unparseable" errors in
  101735. * a row before bailing out.
  101736. */
  101737. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101738. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101739. return false;
  101740. }
  101741. else {
  101742. const FLAC__StreamDecoderReadStatus status =
  101743. #if FLAC__HAS_OGG
  101744. decoder->private_->is_ogg?
  101745. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101746. #endif
  101747. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101748. ;
  101749. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101750. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101751. return false;
  101752. }
  101753. else if(*bytes == 0) {
  101754. if(
  101755. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101756. (
  101757. #if FLAC__HAS_OGG
  101758. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101759. !decoder->private_->is_ogg &&
  101760. #endif
  101761. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101762. )
  101763. ) {
  101764. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101765. return false;
  101766. }
  101767. else
  101768. return true;
  101769. }
  101770. else
  101771. return true;
  101772. }
  101773. }
  101774. else {
  101775. /* abort to avoid a deadlock */
  101776. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101777. return false;
  101778. }
  101779. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101780. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101781. * and at the same time hit the end of the stream (for example, seeking
  101782. * to a point that is after the beginning of the last Ogg page). There
  101783. * is no way to report an Ogg sync loss through the callbacks (see note
  101784. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101785. * So to keep the decoder from stopping at this point we gate the call
  101786. * to the eof_callback and let the Ogg decoder aspect set the
  101787. * end-of-stream state when it is needed.
  101788. */
  101789. }
  101790. #if FLAC__HAS_OGG
  101791. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101792. {
  101793. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101794. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101795. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101796. /* we don't really have a way to handle lost sync via read
  101797. * callback so we'll let it pass and let the underlying
  101798. * FLAC decoder catch the error
  101799. */
  101800. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101801. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101802. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101803. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101804. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101805. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101806. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101807. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101808. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101809. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101810. default:
  101811. FLAC__ASSERT(0);
  101812. /* double protection */
  101813. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101814. }
  101815. }
  101816. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101817. {
  101818. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101819. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101820. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101821. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101822. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101823. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101824. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101825. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101826. default:
  101827. /* double protection: */
  101828. FLAC__ASSERT(0);
  101829. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101830. }
  101831. }
  101832. #endif
  101833. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101834. {
  101835. if(decoder->private_->is_seeking) {
  101836. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101837. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101838. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101839. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101840. #if FLAC__HAS_OGG
  101841. decoder->private_->got_a_frame = true;
  101842. #endif
  101843. decoder->private_->last_frame = *frame; /* save the frame */
  101844. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101845. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101846. /* kick out of seek mode */
  101847. decoder->private_->is_seeking = false;
  101848. /* shift out the samples before target_sample */
  101849. if(delta > 0) {
  101850. unsigned channel;
  101851. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101852. for(channel = 0; channel < frame->header.channels; channel++)
  101853. newbuffer[channel] = buffer[channel] + delta;
  101854. decoder->private_->last_frame.header.blocksize -= delta;
  101855. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101856. /* write the relevant samples */
  101857. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101858. }
  101859. else {
  101860. /* write the relevant samples */
  101861. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101862. }
  101863. }
  101864. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101865. }
  101866. /*
  101867. * If we never got STREAMINFO, turn off MD5 checking to save
  101868. * cycles since we don't have a sum to compare to anyway
  101869. */
  101870. if(!decoder->private_->has_stream_info)
  101871. decoder->private_->do_md5_checking = false;
  101872. if(decoder->private_->do_md5_checking) {
  101873. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101874. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101875. }
  101876. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101877. }
  101878. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101879. {
  101880. if(!decoder->private_->is_seeking)
  101881. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101882. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101883. decoder->private_->unparseable_frame_count++;
  101884. }
  101885. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101886. {
  101887. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101888. FLAC__int64 pos = -1;
  101889. int i;
  101890. unsigned approx_bytes_per_frame;
  101891. FLAC__bool first_seek = true;
  101892. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101893. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101894. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101895. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101896. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101897. /* take these from the current frame in case they've changed mid-stream */
  101898. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101899. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101900. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101901. /* use values from stream info if we didn't decode a frame */
  101902. if(channels == 0)
  101903. channels = decoder->private_->stream_info.data.stream_info.channels;
  101904. if(bps == 0)
  101905. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101906. /* we are just guessing here */
  101907. if(max_framesize > 0)
  101908. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101909. /*
  101910. * Check if it's a known fixed-blocksize stream. Note that though
  101911. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101912. * never get a STREAMINFO block when decoding so the value of
  101913. * min_blocksize might be zero.
  101914. */
  101915. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101916. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101917. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101918. }
  101919. else
  101920. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101921. /*
  101922. * First, we set an upper and lower bound on where in the
  101923. * stream we will search. For now we assume the worst case
  101924. * scenario, which is our best guess at the beginning of
  101925. * the first frame and end of the stream.
  101926. */
  101927. lower_bound = first_frame_offset;
  101928. lower_bound_sample = 0;
  101929. upper_bound = stream_length;
  101930. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101931. /*
  101932. * Now we refine the bounds if we have a seektable with
  101933. * suitable points. Note that according to the spec they
  101934. * must be ordered by ascending sample number.
  101935. *
  101936. * Note: to protect against invalid seek tables we will ignore points
  101937. * that have frame_samples==0 or sample_number>=total_samples
  101938. */
  101939. if(seek_table) {
  101940. FLAC__uint64 new_lower_bound = lower_bound;
  101941. FLAC__uint64 new_upper_bound = upper_bound;
  101942. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101943. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101944. /* find the closest seek point <= target_sample, if it exists */
  101945. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101946. if(
  101947. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101948. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101949. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101950. seek_table->points[i].sample_number <= target_sample
  101951. )
  101952. break;
  101953. }
  101954. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101955. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101956. new_lower_bound_sample = seek_table->points[i].sample_number;
  101957. }
  101958. /* find the closest seek point > target_sample, if it exists */
  101959. for(i = 0; i < (int)seek_table->num_points; i++) {
  101960. if(
  101961. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101962. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101963. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101964. seek_table->points[i].sample_number > target_sample
  101965. )
  101966. break;
  101967. }
  101968. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101969. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101970. new_upper_bound_sample = seek_table->points[i].sample_number;
  101971. }
  101972. /* final protection against unsorted seek tables; keep original values if bogus */
  101973. if(new_upper_bound >= new_lower_bound) {
  101974. lower_bound = new_lower_bound;
  101975. upper_bound = new_upper_bound;
  101976. lower_bound_sample = new_lower_bound_sample;
  101977. upper_bound_sample = new_upper_bound_sample;
  101978. }
  101979. }
  101980. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101981. /* there are 2 insidious ways that the following equality occurs, which
  101982. * we need to fix:
  101983. * 1) total_samples is 0 (unknown) and target_sample is 0
  101984. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101985. * exactly equal to the last seek point in the seek table; this
  101986. * means there is no seek point above it, and upper_bound_samples
  101987. * remains equal to the estimate (of target_samples) we made above
  101988. * in either case it does not hurt to move upper_bound_sample up by 1
  101989. */
  101990. if(upper_bound_sample == lower_bound_sample)
  101991. upper_bound_sample++;
  101992. decoder->private_->target_sample = target_sample;
  101993. while(1) {
  101994. /* check if the bounds are still ok */
  101995. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101996. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101997. return false;
  101998. }
  101999. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102000. #if defined _MSC_VER || defined __MINGW32__
  102001. /* with VC++ you have to spoon feed it the casting */
  102002. 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;
  102003. #else
  102004. 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;
  102005. #endif
  102006. #else
  102007. /* a little less accurate: */
  102008. if(upper_bound - lower_bound < 0xffffffff)
  102009. 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;
  102010. else /* @@@ WATCHOUT, ~2TB limit */
  102011. 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;
  102012. #endif
  102013. if(pos >= (FLAC__int64)upper_bound)
  102014. pos = (FLAC__int64)upper_bound - 1;
  102015. if(pos < (FLAC__int64)lower_bound)
  102016. pos = (FLAC__int64)lower_bound;
  102017. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102018. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102019. return false;
  102020. }
  102021. if(!FLAC__stream_decoder_flush(decoder)) {
  102022. /* above call sets the state for us */
  102023. return false;
  102024. }
  102025. /* Now we need to get a frame. First we need to reset our
  102026. * unparseable_frame_count; if we get too many unparseable
  102027. * frames in a row, the read callback will return
  102028. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102029. * FLAC__stream_decoder_process_single() to return false.
  102030. */
  102031. decoder->private_->unparseable_frame_count = 0;
  102032. if(!FLAC__stream_decoder_process_single(decoder)) {
  102033. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102034. return false;
  102035. }
  102036. /* our write callback will change the state when it gets to the target frame */
  102037. /* 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 */
  102038. #if 0
  102039. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102040. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102041. break;
  102042. #endif
  102043. if(!decoder->private_->is_seeking)
  102044. break;
  102045. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102046. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102047. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102048. if (pos == (FLAC__int64)lower_bound) {
  102049. /* can't move back any more than the first frame, something is fatally wrong */
  102050. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102051. return false;
  102052. }
  102053. /* our last move backwards wasn't big enough, try again */
  102054. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102055. continue;
  102056. }
  102057. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102058. first_seek = false;
  102059. /* make sure we are not seeking in corrupted stream */
  102060. if (this_frame_sample < lower_bound_sample) {
  102061. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102062. return false;
  102063. }
  102064. /* we need to narrow the search */
  102065. if(target_sample < this_frame_sample) {
  102066. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102067. /*@@@@@@ what will decode position be if at end of stream? */
  102068. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102069. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102070. return false;
  102071. }
  102072. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102073. }
  102074. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102075. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102076. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102077. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102078. return false;
  102079. }
  102080. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102081. }
  102082. }
  102083. return true;
  102084. }
  102085. #if FLAC__HAS_OGG
  102086. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102087. {
  102088. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102089. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102090. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102091. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102092. FLAC__bool did_a_seek;
  102093. unsigned iteration = 0;
  102094. /* In the first iterations, we will calculate the target byte position
  102095. * by the distance from the target sample to left_sample and
  102096. * right_sample (let's call it "proportional search"). After that, we
  102097. * will switch to binary search.
  102098. */
  102099. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102100. /* We will switch to a linear search once our current sample is less
  102101. * than this number of samples ahead of the target sample
  102102. */
  102103. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102104. /* If the total number of samples is unknown, use a large value, and
  102105. * force binary search immediately.
  102106. */
  102107. if(right_sample == 0) {
  102108. right_sample = (FLAC__uint64)(-1);
  102109. BINARY_SEARCH_AFTER_ITERATION = 0;
  102110. }
  102111. decoder->private_->target_sample = target_sample;
  102112. for( ; ; iteration++) {
  102113. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102114. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102115. pos = (right_pos + left_pos) / 2;
  102116. }
  102117. else {
  102118. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102119. #if defined _MSC_VER || defined __MINGW32__
  102120. /* with MSVC you have to spoon feed it the casting */
  102121. 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));
  102122. #else
  102123. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102124. #endif
  102125. #else
  102126. /* a little less accurate: */
  102127. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102128. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102129. else /* @@@ WATCHOUT, ~2TB limit */
  102130. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102131. #endif
  102132. /* @@@ TODO: might want to limit pos to some distance
  102133. * before EOF, to make sure we land before the last frame,
  102134. * thereby getting a this_frame_sample and so having a better
  102135. * estimate.
  102136. */
  102137. }
  102138. /* physical seek */
  102139. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102140. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102141. return false;
  102142. }
  102143. if(!FLAC__stream_decoder_flush(decoder)) {
  102144. /* above call sets the state for us */
  102145. return false;
  102146. }
  102147. did_a_seek = true;
  102148. }
  102149. else
  102150. did_a_seek = false;
  102151. decoder->private_->got_a_frame = false;
  102152. if(!FLAC__stream_decoder_process_single(decoder)) {
  102153. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102154. return false;
  102155. }
  102156. if(!decoder->private_->got_a_frame) {
  102157. if(did_a_seek) {
  102158. /* this can happen if we seek to a point after the last frame; we drop
  102159. * to binary search right away in this case to avoid any wasted
  102160. * iterations of proportional search.
  102161. */
  102162. right_pos = pos;
  102163. BINARY_SEARCH_AFTER_ITERATION = 0;
  102164. }
  102165. else {
  102166. /* this can probably only happen if total_samples is unknown and the
  102167. * target_sample is past the end of the stream
  102168. */
  102169. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102170. return false;
  102171. }
  102172. }
  102173. /* our write callback will change the state when it gets to the target frame */
  102174. else if(!decoder->private_->is_seeking) {
  102175. break;
  102176. }
  102177. else {
  102178. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102179. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102180. if (did_a_seek) {
  102181. if (this_frame_sample <= target_sample) {
  102182. /* The 'equal' case should not happen, since
  102183. * FLAC__stream_decoder_process_single()
  102184. * should recognize that it has hit the
  102185. * target sample and we would exit through
  102186. * the 'break' above.
  102187. */
  102188. FLAC__ASSERT(this_frame_sample != target_sample);
  102189. left_sample = this_frame_sample;
  102190. /* sanity check to avoid infinite loop */
  102191. if (left_pos == pos) {
  102192. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102193. return false;
  102194. }
  102195. left_pos = pos;
  102196. }
  102197. else if(this_frame_sample > target_sample) {
  102198. right_sample = this_frame_sample;
  102199. /* sanity check to avoid infinite loop */
  102200. if (right_pos == pos) {
  102201. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102202. return false;
  102203. }
  102204. right_pos = pos;
  102205. }
  102206. }
  102207. }
  102208. }
  102209. return true;
  102210. }
  102211. #endif
  102212. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102213. {
  102214. (void)client_data;
  102215. if(*bytes > 0) {
  102216. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102217. if(ferror(decoder->private_->file))
  102218. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102219. else if(*bytes == 0)
  102220. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102221. else
  102222. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102223. }
  102224. else
  102225. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102226. }
  102227. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102228. {
  102229. (void)client_data;
  102230. if(decoder->private_->file == stdin)
  102231. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102232. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102233. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102234. else
  102235. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102236. }
  102237. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102238. {
  102239. off_t pos;
  102240. (void)client_data;
  102241. if(decoder->private_->file == stdin)
  102242. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102243. else if((pos = ftello(decoder->private_->file)) < 0)
  102244. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102245. else {
  102246. *absolute_byte_offset = (FLAC__uint64)pos;
  102247. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102248. }
  102249. }
  102250. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102251. {
  102252. struct stat filestats;
  102253. (void)client_data;
  102254. if(decoder->private_->file == stdin)
  102255. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102256. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102257. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102258. else {
  102259. *stream_length = (FLAC__uint64)filestats.st_size;
  102260. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102261. }
  102262. }
  102263. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102264. {
  102265. (void)client_data;
  102266. return feof(decoder->private_->file)? true : false;
  102267. }
  102268. #endif
  102269. /*** End of inlined file: stream_decoder.c ***/
  102270. /*** Start of inlined file: stream_encoder.c ***/
  102271. /*** Start of inlined file: juce_FlacHeader.h ***/
  102272. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102273. // tasks..
  102274. #define VERSION "1.2.1"
  102275. #define FLAC__NO_DLL 1
  102276. #if JUCE_MSVC
  102277. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102278. #endif
  102279. #if JUCE_MAC
  102280. #define FLAC__SYS_DARWIN 1
  102281. #endif
  102282. /*** End of inlined file: juce_FlacHeader.h ***/
  102283. #if JUCE_USE_FLAC
  102284. #if HAVE_CONFIG_H
  102285. # include <config.h>
  102286. #endif
  102287. #if defined _MSC_VER || defined __MINGW32__
  102288. #include <io.h> /* for _setmode() */
  102289. #include <fcntl.h> /* for _O_BINARY */
  102290. #endif
  102291. #if defined __CYGWIN__ || defined __EMX__
  102292. #include <io.h> /* for setmode(), O_BINARY */
  102293. #include <fcntl.h> /* for _O_BINARY */
  102294. #endif
  102295. #include <limits.h>
  102296. #include <stdio.h>
  102297. #include <stdlib.h> /* for malloc() */
  102298. #include <string.h> /* for memcpy() */
  102299. #include <sys/types.h> /* for off_t */
  102300. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102301. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102302. #define fseeko fseek
  102303. #define ftello ftell
  102304. #endif
  102305. #endif
  102306. /*** Start of inlined file: stream_encoder.h ***/
  102307. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102308. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102309. #if FLAC__HAS_OGG
  102310. #include "private/ogg_encoder_aspect.h"
  102311. #endif
  102312. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102313. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102314. typedef enum {
  102315. FLAC__APODIZATION_BARTLETT,
  102316. FLAC__APODIZATION_BARTLETT_HANN,
  102317. FLAC__APODIZATION_BLACKMAN,
  102318. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102319. FLAC__APODIZATION_CONNES,
  102320. FLAC__APODIZATION_FLATTOP,
  102321. FLAC__APODIZATION_GAUSS,
  102322. FLAC__APODIZATION_HAMMING,
  102323. FLAC__APODIZATION_HANN,
  102324. FLAC__APODIZATION_KAISER_BESSEL,
  102325. FLAC__APODIZATION_NUTTALL,
  102326. FLAC__APODIZATION_RECTANGLE,
  102327. FLAC__APODIZATION_TRIANGLE,
  102328. FLAC__APODIZATION_TUKEY,
  102329. FLAC__APODIZATION_WELCH
  102330. } FLAC__ApodizationFunction;
  102331. typedef struct {
  102332. FLAC__ApodizationFunction type;
  102333. union {
  102334. struct {
  102335. FLAC__real stddev;
  102336. } gauss;
  102337. struct {
  102338. FLAC__real p;
  102339. } tukey;
  102340. } parameters;
  102341. } FLAC__ApodizationSpecification;
  102342. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102343. typedef struct FLAC__StreamEncoderProtected {
  102344. FLAC__StreamEncoderState state;
  102345. FLAC__bool verify;
  102346. FLAC__bool streamable_subset;
  102347. FLAC__bool do_md5;
  102348. FLAC__bool do_mid_side_stereo;
  102349. FLAC__bool loose_mid_side_stereo;
  102350. unsigned channels;
  102351. unsigned bits_per_sample;
  102352. unsigned sample_rate;
  102353. unsigned blocksize;
  102354. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102355. unsigned num_apodizations;
  102356. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102357. #endif
  102358. unsigned max_lpc_order;
  102359. unsigned qlp_coeff_precision;
  102360. FLAC__bool do_qlp_coeff_prec_search;
  102361. FLAC__bool do_exhaustive_model_search;
  102362. FLAC__bool do_escape_coding;
  102363. unsigned min_residual_partition_order;
  102364. unsigned max_residual_partition_order;
  102365. unsigned rice_parameter_search_dist;
  102366. FLAC__uint64 total_samples_estimate;
  102367. FLAC__StreamMetadata **metadata;
  102368. unsigned num_metadata_blocks;
  102369. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102370. #if FLAC__HAS_OGG
  102371. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102372. #endif
  102373. } FLAC__StreamEncoderProtected;
  102374. #endif
  102375. /*** End of inlined file: stream_encoder.h ***/
  102376. #if FLAC__HAS_OGG
  102377. #include "include/private/ogg_helper.h"
  102378. #include "include/private/ogg_mapping.h"
  102379. #endif
  102380. /*** Start of inlined file: stream_encoder_framing.h ***/
  102381. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102382. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102383. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102384. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102385. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102386. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102387. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102388. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102389. #endif
  102390. /*** End of inlined file: stream_encoder_framing.h ***/
  102391. /*** Start of inlined file: window.h ***/
  102392. #ifndef FLAC__PRIVATE__WINDOW_H
  102393. #define FLAC__PRIVATE__WINDOW_H
  102394. #ifdef HAVE_CONFIG_H
  102395. #include <config.h>
  102396. #endif
  102397. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102398. /*
  102399. * FLAC__window_*()
  102400. * --------------------------------------------------------------------
  102401. * Calculates window coefficients according to different apodization
  102402. * functions.
  102403. *
  102404. * OUT window[0,L-1]
  102405. * IN L (number of points in window)
  102406. */
  102407. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102408. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102409. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102410. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102411. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102412. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102413. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102414. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102415. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102416. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102417. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102418. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102419. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102420. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102421. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102422. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102423. #endif
  102424. /*** End of inlined file: window.h ***/
  102425. #ifndef FLaC__INLINE
  102426. #define FLaC__INLINE
  102427. #endif
  102428. #ifdef min
  102429. #undef min
  102430. #endif
  102431. #define min(x,y) ((x)<(y)?(x):(y))
  102432. #ifdef max
  102433. #undef max
  102434. #endif
  102435. #define max(x,y) ((x)>(y)?(x):(y))
  102436. /* Exact Rice codeword length calculation is off by default. The simple
  102437. * (and fast) estimation (of how many bits a residual value will be
  102438. * encoded with) in this encoder is very good, almost always yielding
  102439. * compression within 0.1% of exact calculation.
  102440. */
  102441. #undef EXACT_RICE_BITS_CALCULATION
  102442. /* Rice parameter searching is off by default. The simple (and fast)
  102443. * parameter estimation in this encoder is very good, almost always
  102444. * yielding compression within 0.1% of the optimal parameters.
  102445. */
  102446. #undef ENABLE_RICE_PARAMETER_SEARCH
  102447. typedef struct {
  102448. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102449. unsigned size; /* of each data[] in samples */
  102450. unsigned tail;
  102451. } verify_input_fifo;
  102452. typedef struct {
  102453. const FLAC__byte *data;
  102454. unsigned capacity;
  102455. unsigned bytes;
  102456. } verify_output;
  102457. typedef enum {
  102458. ENCODER_IN_MAGIC = 0,
  102459. ENCODER_IN_METADATA = 1,
  102460. ENCODER_IN_AUDIO = 2
  102461. } EncoderStateHint;
  102462. static struct CompressionLevels {
  102463. FLAC__bool do_mid_side_stereo;
  102464. FLAC__bool loose_mid_side_stereo;
  102465. unsigned max_lpc_order;
  102466. unsigned qlp_coeff_precision;
  102467. FLAC__bool do_qlp_coeff_prec_search;
  102468. FLAC__bool do_escape_coding;
  102469. FLAC__bool do_exhaustive_model_search;
  102470. unsigned min_residual_partition_order;
  102471. unsigned max_residual_partition_order;
  102472. unsigned rice_parameter_search_dist;
  102473. } compression_levels_[] = {
  102474. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102475. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102476. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102477. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102478. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102479. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102480. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102481. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102482. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102483. };
  102484. /***********************************************************************
  102485. *
  102486. * Private class method prototypes
  102487. *
  102488. ***********************************************************************/
  102489. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102490. static void free_(FLAC__StreamEncoder *encoder);
  102491. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102492. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102493. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102494. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102495. #if FLAC__HAS_OGG
  102496. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102497. #endif
  102498. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102499. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102500. static FLAC__bool process_subframe_(
  102501. FLAC__StreamEncoder *encoder,
  102502. unsigned min_partition_order,
  102503. unsigned max_partition_order,
  102504. const FLAC__FrameHeader *frame_header,
  102505. unsigned subframe_bps,
  102506. const FLAC__int32 integer_signal[],
  102507. FLAC__Subframe *subframe[2],
  102508. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102509. FLAC__int32 *residual[2],
  102510. unsigned *best_subframe,
  102511. unsigned *best_bits
  102512. );
  102513. static FLAC__bool add_subframe_(
  102514. FLAC__StreamEncoder *encoder,
  102515. unsigned blocksize,
  102516. unsigned subframe_bps,
  102517. const FLAC__Subframe *subframe,
  102518. FLAC__BitWriter *frame
  102519. );
  102520. static unsigned evaluate_constant_subframe_(
  102521. FLAC__StreamEncoder *encoder,
  102522. const FLAC__int32 signal,
  102523. unsigned blocksize,
  102524. unsigned subframe_bps,
  102525. FLAC__Subframe *subframe
  102526. );
  102527. static unsigned evaluate_fixed_subframe_(
  102528. FLAC__StreamEncoder *encoder,
  102529. const FLAC__int32 signal[],
  102530. FLAC__int32 residual[],
  102531. FLAC__uint64 abs_residual_partition_sums[],
  102532. unsigned raw_bits_per_partition[],
  102533. unsigned blocksize,
  102534. unsigned subframe_bps,
  102535. unsigned order,
  102536. unsigned rice_parameter,
  102537. unsigned rice_parameter_limit,
  102538. unsigned min_partition_order,
  102539. unsigned max_partition_order,
  102540. FLAC__bool do_escape_coding,
  102541. unsigned rice_parameter_search_dist,
  102542. FLAC__Subframe *subframe,
  102543. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102544. );
  102545. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102546. static unsigned evaluate_lpc_subframe_(
  102547. FLAC__StreamEncoder *encoder,
  102548. const FLAC__int32 signal[],
  102549. FLAC__int32 residual[],
  102550. FLAC__uint64 abs_residual_partition_sums[],
  102551. unsigned raw_bits_per_partition[],
  102552. const FLAC__real lp_coeff[],
  102553. unsigned blocksize,
  102554. unsigned subframe_bps,
  102555. unsigned order,
  102556. unsigned qlp_coeff_precision,
  102557. unsigned rice_parameter,
  102558. unsigned rice_parameter_limit,
  102559. unsigned min_partition_order,
  102560. unsigned max_partition_order,
  102561. FLAC__bool do_escape_coding,
  102562. unsigned rice_parameter_search_dist,
  102563. FLAC__Subframe *subframe,
  102564. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102565. );
  102566. #endif
  102567. static unsigned evaluate_verbatim_subframe_(
  102568. FLAC__StreamEncoder *encoder,
  102569. const FLAC__int32 signal[],
  102570. unsigned blocksize,
  102571. unsigned subframe_bps,
  102572. FLAC__Subframe *subframe
  102573. );
  102574. static unsigned find_best_partition_order_(
  102575. struct FLAC__StreamEncoderPrivate *private_,
  102576. const FLAC__int32 residual[],
  102577. FLAC__uint64 abs_residual_partition_sums[],
  102578. unsigned raw_bits_per_partition[],
  102579. unsigned residual_samples,
  102580. unsigned predictor_order,
  102581. unsigned rice_parameter,
  102582. unsigned rice_parameter_limit,
  102583. unsigned min_partition_order,
  102584. unsigned max_partition_order,
  102585. unsigned bps,
  102586. FLAC__bool do_escape_coding,
  102587. unsigned rice_parameter_search_dist,
  102588. FLAC__EntropyCodingMethod *best_ecm
  102589. );
  102590. static void precompute_partition_info_sums_(
  102591. const FLAC__int32 residual[],
  102592. FLAC__uint64 abs_residual_partition_sums[],
  102593. unsigned residual_samples,
  102594. unsigned predictor_order,
  102595. unsigned min_partition_order,
  102596. unsigned max_partition_order,
  102597. unsigned bps
  102598. );
  102599. static void precompute_partition_info_escapes_(
  102600. const FLAC__int32 residual[],
  102601. unsigned raw_bits_per_partition[],
  102602. unsigned residual_samples,
  102603. unsigned predictor_order,
  102604. unsigned min_partition_order,
  102605. unsigned max_partition_order
  102606. );
  102607. static FLAC__bool set_partitioned_rice_(
  102608. #ifdef EXACT_RICE_BITS_CALCULATION
  102609. const FLAC__int32 residual[],
  102610. #endif
  102611. const FLAC__uint64 abs_residual_partition_sums[],
  102612. const unsigned raw_bits_per_partition[],
  102613. const unsigned residual_samples,
  102614. const unsigned predictor_order,
  102615. const unsigned suggested_rice_parameter,
  102616. const unsigned rice_parameter_limit,
  102617. const unsigned rice_parameter_search_dist,
  102618. const unsigned partition_order,
  102619. const FLAC__bool search_for_escapes,
  102620. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102621. unsigned *bits
  102622. );
  102623. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102624. /* verify-related routines: */
  102625. static void append_to_verify_fifo_(
  102626. verify_input_fifo *fifo,
  102627. const FLAC__int32 * const input[],
  102628. unsigned input_offset,
  102629. unsigned channels,
  102630. unsigned wide_samples
  102631. );
  102632. static void append_to_verify_fifo_interleaved_(
  102633. verify_input_fifo *fifo,
  102634. const FLAC__int32 input[],
  102635. unsigned input_offset,
  102636. unsigned channels,
  102637. unsigned wide_samples
  102638. );
  102639. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102640. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102641. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102642. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102643. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102644. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102645. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102646. 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);
  102647. static FILE *get_binary_stdout_(void);
  102648. /***********************************************************************
  102649. *
  102650. * Private class data
  102651. *
  102652. ***********************************************************************/
  102653. typedef struct FLAC__StreamEncoderPrivate {
  102654. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102655. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102656. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102657. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102658. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102659. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102660. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102661. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102662. #endif
  102663. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102664. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102665. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102666. FLAC__int32 *residual_workspace_mid_side[2][2];
  102667. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102668. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102669. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102670. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102671. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102672. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102673. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102674. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102675. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102676. unsigned best_subframe_mid_side[2];
  102677. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102678. unsigned best_subframe_bits_mid_side[2];
  102679. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102680. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102681. FLAC__BitWriter *frame; /* the current frame being worked on */
  102682. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102683. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102684. FLAC__ChannelAssignment last_channel_assignment;
  102685. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102686. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102687. unsigned current_sample_number;
  102688. unsigned current_frame_number;
  102689. FLAC__MD5Context md5context;
  102690. FLAC__CPUInfo cpuinfo;
  102691. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102692. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102693. #else
  102694. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102695. #endif
  102696. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102697. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102698. 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[]);
  102699. 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[]);
  102700. 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[]);
  102701. #endif
  102702. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102703. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102704. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102705. FLAC__bool disable_constant_subframes;
  102706. FLAC__bool disable_fixed_subframes;
  102707. FLAC__bool disable_verbatim_subframes;
  102708. #if FLAC__HAS_OGG
  102709. FLAC__bool is_ogg;
  102710. #endif
  102711. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102712. FLAC__StreamEncoderSeekCallback seek_callback;
  102713. FLAC__StreamEncoderTellCallback tell_callback;
  102714. FLAC__StreamEncoderWriteCallback write_callback;
  102715. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102716. FLAC__StreamEncoderProgressCallback progress_callback;
  102717. void *client_data;
  102718. unsigned first_seekpoint_to_check;
  102719. FILE *file; /* only used when encoding to a file */
  102720. FLAC__uint64 bytes_written;
  102721. FLAC__uint64 samples_written;
  102722. unsigned frames_written;
  102723. unsigned total_frames_estimate;
  102724. /* unaligned (original) pointers to allocated data */
  102725. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102726. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102727. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102728. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102729. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102730. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102731. FLAC__real *windowed_signal_unaligned;
  102732. #endif
  102733. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102734. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102735. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102736. unsigned *raw_bits_per_partition_unaligned;
  102737. /*
  102738. * These fields have been moved here from private function local
  102739. * declarations merely to save stack space during encoding.
  102740. */
  102741. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102742. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102743. #endif
  102744. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102745. /*
  102746. * The data for the verify section
  102747. */
  102748. struct {
  102749. FLAC__StreamDecoder *decoder;
  102750. EncoderStateHint state_hint;
  102751. FLAC__bool needs_magic_hack;
  102752. verify_input_fifo input_fifo;
  102753. verify_output output;
  102754. struct {
  102755. FLAC__uint64 absolute_sample;
  102756. unsigned frame_number;
  102757. unsigned channel;
  102758. unsigned sample;
  102759. FLAC__int32 expected;
  102760. FLAC__int32 got;
  102761. } error_stats;
  102762. } verify;
  102763. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102764. } FLAC__StreamEncoderPrivate;
  102765. /***********************************************************************
  102766. *
  102767. * Public static class data
  102768. *
  102769. ***********************************************************************/
  102770. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102771. "FLAC__STREAM_ENCODER_OK",
  102772. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102773. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102774. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102775. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102776. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102777. "FLAC__STREAM_ENCODER_IO_ERROR",
  102778. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102779. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102780. };
  102781. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102782. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102783. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102784. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102785. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102786. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102787. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102788. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102789. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102790. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102791. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102792. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102793. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102794. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102795. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102796. };
  102797. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102798. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102799. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102800. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102801. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102802. };
  102803. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102804. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102805. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102806. };
  102807. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102808. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102809. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102810. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102811. };
  102812. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102813. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102814. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102815. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102816. };
  102817. /* Number of samples that will be overread to watch for end of stream. By
  102818. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102819. * always try to read blocksize+1 samples before encoding a block, so that
  102820. * even if the stream has a total sample count that is an integral multiple
  102821. * of the blocksize, we will still notice when we are encoding the last
  102822. * block. This is needed, for example, to correctly set the end-of-stream
  102823. * marker in Ogg FLAC.
  102824. *
  102825. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102826. * not really any reason to change it.
  102827. */
  102828. static const unsigned OVERREAD_ = 1;
  102829. /***********************************************************************
  102830. *
  102831. * Class constructor/destructor
  102832. *
  102833. */
  102834. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102835. {
  102836. FLAC__StreamEncoder *encoder;
  102837. unsigned i;
  102838. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102839. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102840. if(encoder == 0) {
  102841. return 0;
  102842. }
  102843. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102844. if(encoder->protected_ == 0) {
  102845. free(encoder);
  102846. return 0;
  102847. }
  102848. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102849. if(encoder->private_ == 0) {
  102850. free(encoder->protected_);
  102851. free(encoder);
  102852. return 0;
  102853. }
  102854. encoder->private_->frame = FLAC__bitwriter_new();
  102855. if(encoder->private_->frame == 0) {
  102856. free(encoder->private_);
  102857. free(encoder->protected_);
  102858. free(encoder);
  102859. return 0;
  102860. }
  102861. encoder->private_->file = 0;
  102862. set_defaults_enc(encoder);
  102863. encoder->private_->is_being_deleted = false;
  102864. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102865. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102866. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102867. }
  102868. for(i = 0; i < 2; i++) {
  102869. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102870. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102871. }
  102872. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102873. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102874. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102875. }
  102876. for(i = 0; i < 2; i++) {
  102877. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102878. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102879. }
  102880. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102881. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102882. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102883. }
  102884. for(i = 0; i < 2; i++) {
  102885. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102886. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102887. }
  102888. for(i = 0; i < 2; i++)
  102889. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102890. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102891. return encoder;
  102892. }
  102893. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102894. {
  102895. unsigned i;
  102896. FLAC__ASSERT(0 != encoder);
  102897. FLAC__ASSERT(0 != encoder->protected_);
  102898. FLAC__ASSERT(0 != encoder->private_);
  102899. FLAC__ASSERT(0 != encoder->private_->frame);
  102900. encoder->private_->is_being_deleted = true;
  102901. (void)FLAC__stream_encoder_finish(encoder);
  102902. if(0 != encoder->private_->verify.decoder)
  102903. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102904. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102905. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102906. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102907. }
  102908. for(i = 0; i < 2; i++) {
  102909. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102910. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102911. }
  102912. for(i = 0; i < 2; i++)
  102913. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102914. FLAC__bitwriter_delete(encoder->private_->frame);
  102915. free(encoder->private_);
  102916. free(encoder->protected_);
  102917. free(encoder);
  102918. }
  102919. /***********************************************************************
  102920. *
  102921. * Public class methods
  102922. *
  102923. ***********************************************************************/
  102924. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102925. FLAC__StreamEncoder *encoder,
  102926. FLAC__StreamEncoderReadCallback read_callback,
  102927. FLAC__StreamEncoderWriteCallback write_callback,
  102928. FLAC__StreamEncoderSeekCallback seek_callback,
  102929. FLAC__StreamEncoderTellCallback tell_callback,
  102930. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102931. void *client_data,
  102932. FLAC__bool is_ogg
  102933. )
  102934. {
  102935. unsigned i;
  102936. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102937. FLAC__ASSERT(0 != encoder);
  102938. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102939. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102940. #if !FLAC__HAS_OGG
  102941. if(is_ogg)
  102942. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102943. #endif
  102944. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102945. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102946. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102947. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102948. if(encoder->protected_->channels != 2) {
  102949. encoder->protected_->do_mid_side_stereo = false;
  102950. encoder->protected_->loose_mid_side_stereo = false;
  102951. }
  102952. else if(!encoder->protected_->do_mid_side_stereo)
  102953. encoder->protected_->loose_mid_side_stereo = false;
  102954. if(encoder->protected_->bits_per_sample >= 32)
  102955. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102956. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102957. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102958. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102959. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102960. if(encoder->protected_->blocksize == 0) {
  102961. if(encoder->protected_->max_lpc_order == 0)
  102962. encoder->protected_->blocksize = 1152;
  102963. else
  102964. encoder->protected_->blocksize = 4096;
  102965. }
  102966. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102967. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102968. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102969. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102970. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102971. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102972. if(encoder->protected_->qlp_coeff_precision == 0) {
  102973. if(encoder->protected_->bits_per_sample < 16) {
  102974. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102975. /* @@@ until then we'll make a guess */
  102976. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102977. }
  102978. else if(encoder->protected_->bits_per_sample == 16) {
  102979. if(encoder->protected_->blocksize <= 192)
  102980. encoder->protected_->qlp_coeff_precision = 7;
  102981. else if(encoder->protected_->blocksize <= 384)
  102982. encoder->protected_->qlp_coeff_precision = 8;
  102983. else if(encoder->protected_->blocksize <= 576)
  102984. encoder->protected_->qlp_coeff_precision = 9;
  102985. else if(encoder->protected_->blocksize <= 1152)
  102986. encoder->protected_->qlp_coeff_precision = 10;
  102987. else if(encoder->protected_->blocksize <= 2304)
  102988. encoder->protected_->qlp_coeff_precision = 11;
  102989. else if(encoder->protected_->blocksize <= 4608)
  102990. encoder->protected_->qlp_coeff_precision = 12;
  102991. else
  102992. encoder->protected_->qlp_coeff_precision = 13;
  102993. }
  102994. else {
  102995. if(encoder->protected_->blocksize <= 384)
  102996. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102997. else if(encoder->protected_->blocksize <= 1152)
  102998. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102999. else
  103000. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  103001. }
  103002. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  103003. }
  103004. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  103005. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  103006. if(encoder->protected_->streamable_subset) {
  103007. if(
  103008. encoder->protected_->blocksize != 192 &&
  103009. encoder->protected_->blocksize != 576 &&
  103010. encoder->protected_->blocksize != 1152 &&
  103011. encoder->protected_->blocksize != 2304 &&
  103012. encoder->protected_->blocksize != 4608 &&
  103013. encoder->protected_->blocksize != 256 &&
  103014. encoder->protected_->blocksize != 512 &&
  103015. encoder->protected_->blocksize != 1024 &&
  103016. encoder->protected_->blocksize != 2048 &&
  103017. encoder->protected_->blocksize != 4096 &&
  103018. encoder->protected_->blocksize != 8192 &&
  103019. encoder->protected_->blocksize != 16384
  103020. )
  103021. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103022. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  103023. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103024. if(
  103025. encoder->protected_->bits_per_sample != 8 &&
  103026. encoder->protected_->bits_per_sample != 12 &&
  103027. encoder->protected_->bits_per_sample != 16 &&
  103028. encoder->protected_->bits_per_sample != 20 &&
  103029. encoder->protected_->bits_per_sample != 24
  103030. )
  103031. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103032. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103033. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103034. if(
  103035. encoder->protected_->sample_rate <= 48000 &&
  103036. (
  103037. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103038. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103039. )
  103040. ) {
  103041. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103042. }
  103043. }
  103044. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103045. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103046. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103047. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103048. #if FLAC__HAS_OGG
  103049. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103050. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103051. unsigned i;
  103052. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103053. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103054. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103055. for( ; i > 0; i--)
  103056. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103057. encoder->protected_->metadata[0] = vc;
  103058. break;
  103059. }
  103060. }
  103061. }
  103062. #endif
  103063. /* keep track of any SEEKTABLE block */
  103064. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103065. unsigned i;
  103066. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103067. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103068. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103069. break; /* take only the first one */
  103070. }
  103071. }
  103072. }
  103073. /* validate metadata */
  103074. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103075. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103076. metadata_has_seektable = false;
  103077. metadata_has_vorbis_comment = false;
  103078. metadata_picture_has_type1 = false;
  103079. metadata_picture_has_type2 = false;
  103080. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103081. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103082. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103083. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103084. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103085. if(metadata_has_seektable) /* only one is allowed */
  103086. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103087. metadata_has_seektable = true;
  103088. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103089. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103090. }
  103091. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103092. if(metadata_has_vorbis_comment) /* only one is allowed */
  103093. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103094. metadata_has_vorbis_comment = true;
  103095. }
  103096. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103097. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103098. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103099. }
  103100. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103101. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103102. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103103. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103104. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103105. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103106. metadata_picture_has_type1 = true;
  103107. /* standard icon must be 32x32 pixel PNG */
  103108. if(
  103109. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103110. (
  103111. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103112. m->data.picture.width != 32 ||
  103113. m->data.picture.height != 32
  103114. )
  103115. )
  103116. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103117. }
  103118. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103119. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103120. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103121. metadata_picture_has_type2 = true;
  103122. }
  103123. }
  103124. }
  103125. encoder->private_->input_capacity = 0;
  103126. for(i = 0; i < encoder->protected_->channels; i++) {
  103127. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103128. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103129. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103130. #endif
  103131. }
  103132. for(i = 0; i < 2; i++) {
  103133. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103134. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103135. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103136. #endif
  103137. }
  103138. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103139. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103140. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103141. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103142. #endif
  103143. for(i = 0; i < encoder->protected_->channels; i++) {
  103144. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103145. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103146. encoder->private_->best_subframe[i] = 0;
  103147. }
  103148. for(i = 0; i < 2; i++) {
  103149. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103150. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103151. encoder->private_->best_subframe_mid_side[i] = 0;
  103152. }
  103153. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103154. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103155. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103156. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103157. #else
  103158. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103159. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103160. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103161. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103162. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103163. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103164. 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);
  103165. #endif
  103166. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103167. encoder->private_->loose_mid_side_stereo_frames = 1;
  103168. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103169. encoder->private_->current_sample_number = 0;
  103170. encoder->private_->current_frame_number = 0;
  103171. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103172. 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? */
  103173. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103174. /*
  103175. * get the CPU info and set the function pointers
  103176. */
  103177. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103178. /* first default to the non-asm routines */
  103179. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103180. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103181. #endif
  103182. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103183. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103184. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103185. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103186. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103187. #endif
  103188. /* now override with asm where appropriate */
  103189. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103190. # ifndef FLAC__NO_ASM
  103191. if(encoder->private_->cpuinfo.use_asm) {
  103192. # ifdef FLAC__CPU_IA32
  103193. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103194. # ifdef FLAC__HAS_NASM
  103195. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103196. if(encoder->protected_->max_lpc_order < 4)
  103197. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103198. else if(encoder->protected_->max_lpc_order < 8)
  103199. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103200. else if(encoder->protected_->max_lpc_order < 12)
  103201. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103202. else
  103203. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103204. }
  103205. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103206. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103207. else
  103208. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103209. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103210. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103211. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103212. }
  103213. else {
  103214. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103215. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103216. }
  103217. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103218. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103219. # endif /* FLAC__HAS_NASM */
  103220. # endif /* FLAC__CPU_IA32 */
  103221. }
  103222. # endif /* !FLAC__NO_ASM */
  103223. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103224. /* finally override based on wide-ness if necessary */
  103225. if(encoder->private_->use_wide_by_block) {
  103226. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103227. }
  103228. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103229. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103230. #if FLAC__HAS_OGG
  103231. encoder->private_->is_ogg = is_ogg;
  103232. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103233. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103234. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103235. }
  103236. #endif
  103237. encoder->private_->read_callback = read_callback;
  103238. encoder->private_->write_callback = write_callback;
  103239. encoder->private_->seek_callback = seek_callback;
  103240. encoder->private_->tell_callback = tell_callback;
  103241. encoder->private_->metadata_callback = metadata_callback;
  103242. encoder->private_->client_data = client_data;
  103243. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103244. /* the above function sets the state for us in case of an error */
  103245. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103246. }
  103247. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103248. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103249. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103250. }
  103251. /*
  103252. * Set up the verify stuff if necessary
  103253. */
  103254. if(encoder->protected_->verify) {
  103255. /*
  103256. * First, set up the fifo which will hold the
  103257. * original signal to compare against
  103258. */
  103259. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103260. for(i = 0; i < encoder->protected_->channels; i++) {
  103261. 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))) {
  103262. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103263. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103264. }
  103265. }
  103266. encoder->private_->verify.input_fifo.tail = 0;
  103267. /*
  103268. * Now set up a stream decoder for verification
  103269. */
  103270. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103271. if(0 == encoder->private_->verify.decoder) {
  103272. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103273. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103274. }
  103275. 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) {
  103276. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103277. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103278. }
  103279. }
  103280. encoder->private_->verify.error_stats.absolute_sample = 0;
  103281. encoder->private_->verify.error_stats.frame_number = 0;
  103282. encoder->private_->verify.error_stats.channel = 0;
  103283. encoder->private_->verify.error_stats.sample = 0;
  103284. encoder->private_->verify.error_stats.expected = 0;
  103285. encoder->private_->verify.error_stats.got = 0;
  103286. /*
  103287. * These must be done before we write any metadata, because that
  103288. * calls the write_callback, which uses these values.
  103289. */
  103290. encoder->private_->first_seekpoint_to_check = 0;
  103291. encoder->private_->samples_written = 0;
  103292. encoder->protected_->streaminfo_offset = 0;
  103293. encoder->protected_->seektable_offset = 0;
  103294. encoder->protected_->audio_offset = 0;
  103295. /*
  103296. * write the stream header
  103297. */
  103298. if(encoder->protected_->verify)
  103299. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103300. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103301. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103302. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103303. }
  103304. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103305. /* the above function sets the state for us in case of an error */
  103306. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103307. }
  103308. /*
  103309. * write the STREAMINFO metadata block
  103310. */
  103311. if(encoder->protected_->verify)
  103312. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103313. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103314. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103315. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103316. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103317. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103318. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103319. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103320. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103321. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103322. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103323. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103324. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103325. if(encoder->protected_->do_md5)
  103326. FLAC__MD5Init(&encoder->private_->md5context);
  103327. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103328. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103329. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103330. }
  103331. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103332. /* the above function sets the state for us in case of an error */
  103333. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103334. }
  103335. /*
  103336. * Now that the STREAMINFO block is written, we can init this to an
  103337. * absurdly-high value...
  103338. */
  103339. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103340. /* ... and clear this to 0 */
  103341. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103342. /*
  103343. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103344. * if not, we will write an empty one (FLAC__add_metadata_block()
  103345. * automatically supplies the vendor string).
  103346. *
  103347. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103348. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103349. * true it will have already insured that the metadata list is properly
  103350. * ordered.)
  103351. */
  103352. if(!metadata_has_vorbis_comment) {
  103353. FLAC__StreamMetadata vorbis_comment;
  103354. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103355. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103356. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103357. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103358. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103359. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103360. vorbis_comment.data.vorbis_comment.comments = 0;
  103361. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103362. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103363. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103364. }
  103365. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103366. /* the above function sets the state for us in case of an error */
  103367. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103368. }
  103369. }
  103370. /*
  103371. * write the user's metadata blocks
  103372. */
  103373. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103374. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103375. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103376. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103377. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103378. }
  103379. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103380. /* the above function sets the state for us in case of an error */
  103381. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103382. }
  103383. }
  103384. /* now that all the metadata is written, we save the stream offset */
  103385. 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 */
  103386. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103387. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103388. }
  103389. if(encoder->protected_->verify)
  103390. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103391. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103392. }
  103393. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103394. FLAC__StreamEncoder *encoder,
  103395. FLAC__StreamEncoderWriteCallback write_callback,
  103396. FLAC__StreamEncoderSeekCallback seek_callback,
  103397. FLAC__StreamEncoderTellCallback tell_callback,
  103398. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103399. void *client_data
  103400. )
  103401. {
  103402. return init_stream_internal_enc(
  103403. encoder,
  103404. /*read_callback=*/0,
  103405. write_callback,
  103406. seek_callback,
  103407. tell_callback,
  103408. metadata_callback,
  103409. client_data,
  103410. /*is_ogg=*/false
  103411. );
  103412. }
  103413. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103414. FLAC__StreamEncoder *encoder,
  103415. FLAC__StreamEncoderReadCallback read_callback,
  103416. FLAC__StreamEncoderWriteCallback write_callback,
  103417. FLAC__StreamEncoderSeekCallback seek_callback,
  103418. FLAC__StreamEncoderTellCallback tell_callback,
  103419. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103420. void *client_data
  103421. )
  103422. {
  103423. return init_stream_internal_enc(
  103424. encoder,
  103425. read_callback,
  103426. write_callback,
  103427. seek_callback,
  103428. tell_callback,
  103429. metadata_callback,
  103430. client_data,
  103431. /*is_ogg=*/true
  103432. );
  103433. }
  103434. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103435. FLAC__StreamEncoder *encoder,
  103436. FILE *file,
  103437. FLAC__StreamEncoderProgressCallback progress_callback,
  103438. void *client_data,
  103439. FLAC__bool is_ogg
  103440. )
  103441. {
  103442. FLAC__StreamEncoderInitStatus init_status;
  103443. FLAC__ASSERT(0 != encoder);
  103444. FLAC__ASSERT(0 != file);
  103445. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103446. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103447. /* double protection */
  103448. if(file == 0) {
  103449. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103450. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103451. }
  103452. /*
  103453. * To make sure that our file does not go unclosed after an error, we
  103454. * must assign the FILE pointer before any further error can occur in
  103455. * this routine.
  103456. */
  103457. if(file == stdout)
  103458. file = get_binary_stdout_(); /* just to be safe */
  103459. encoder->private_->file = file;
  103460. encoder->private_->progress_callback = progress_callback;
  103461. encoder->private_->bytes_written = 0;
  103462. encoder->private_->samples_written = 0;
  103463. encoder->private_->frames_written = 0;
  103464. init_status = init_stream_internal_enc(
  103465. encoder,
  103466. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103467. file_write_callback_,
  103468. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103469. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103470. /*metadata_callback=*/0,
  103471. client_data,
  103472. is_ogg
  103473. );
  103474. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103475. /* the above function sets the state for us in case of an error */
  103476. return init_status;
  103477. }
  103478. {
  103479. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103480. FLAC__ASSERT(blocksize != 0);
  103481. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103482. }
  103483. return init_status;
  103484. }
  103485. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103486. FLAC__StreamEncoder *encoder,
  103487. FILE *file,
  103488. FLAC__StreamEncoderProgressCallback progress_callback,
  103489. void *client_data
  103490. )
  103491. {
  103492. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103493. }
  103494. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103495. FLAC__StreamEncoder *encoder,
  103496. FILE *file,
  103497. FLAC__StreamEncoderProgressCallback progress_callback,
  103498. void *client_data
  103499. )
  103500. {
  103501. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103502. }
  103503. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103504. FLAC__StreamEncoder *encoder,
  103505. const char *filename,
  103506. FLAC__StreamEncoderProgressCallback progress_callback,
  103507. void *client_data,
  103508. FLAC__bool is_ogg
  103509. )
  103510. {
  103511. FILE *file;
  103512. FLAC__ASSERT(0 != encoder);
  103513. /*
  103514. * To make sure that our file does not go unclosed after an error, we
  103515. * have to do the same entrance checks here that are later performed
  103516. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103517. */
  103518. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103519. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103520. file = filename? fopen(filename, "w+b") : stdout;
  103521. if(file == 0) {
  103522. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103523. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103524. }
  103525. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103526. }
  103527. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103528. FLAC__StreamEncoder *encoder,
  103529. const char *filename,
  103530. FLAC__StreamEncoderProgressCallback progress_callback,
  103531. void *client_data
  103532. )
  103533. {
  103534. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103535. }
  103536. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103537. FLAC__StreamEncoder *encoder,
  103538. const char *filename,
  103539. FLAC__StreamEncoderProgressCallback progress_callback,
  103540. void *client_data
  103541. )
  103542. {
  103543. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103544. }
  103545. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103546. {
  103547. FLAC__bool error = false;
  103548. FLAC__ASSERT(0 != encoder);
  103549. FLAC__ASSERT(0 != encoder->private_);
  103550. FLAC__ASSERT(0 != encoder->protected_);
  103551. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103552. return true;
  103553. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103554. if(encoder->private_->current_sample_number != 0) {
  103555. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103556. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103557. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103558. error = true;
  103559. }
  103560. }
  103561. if(encoder->protected_->do_md5)
  103562. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103563. if(!encoder->private_->is_being_deleted) {
  103564. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103565. if(encoder->private_->seek_callback) {
  103566. #if FLAC__HAS_OGG
  103567. if(encoder->private_->is_ogg)
  103568. update_ogg_metadata_(encoder);
  103569. else
  103570. #endif
  103571. update_metadata_(encoder);
  103572. /* check if an error occurred while updating metadata */
  103573. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103574. error = true;
  103575. }
  103576. if(encoder->private_->metadata_callback)
  103577. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103578. }
  103579. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103580. if(!error)
  103581. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103582. error = true;
  103583. }
  103584. }
  103585. if(0 != encoder->private_->file) {
  103586. if(encoder->private_->file != stdout)
  103587. fclose(encoder->private_->file);
  103588. encoder->private_->file = 0;
  103589. }
  103590. #if FLAC__HAS_OGG
  103591. if(encoder->private_->is_ogg)
  103592. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103593. #endif
  103594. free_(encoder);
  103595. set_defaults_enc(encoder);
  103596. if(!error)
  103597. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103598. return !error;
  103599. }
  103600. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103601. {
  103602. FLAC__ASSERT(0 != encoder);
  103603. FLAC__ASSERT(0 != encoder->private_);
  103604. FLAC__ASSERT(0 != encoder->protected_);
  103605. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103606. return false;
  103607. #if FLAC__HAS_OGG
  103608. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103609. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103610. return true;
  103611. #else
  103612. (void)value;
  103613. return false;
  103614. #endif
  103615. }
  103616. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103617. {
  103618. FLAC__ASSERT(0 != encoder);
  103619. FLAC__ASSERT(0 != encoder->private_);
  103620. FLAC__ASSERT(0 != encoder->protected_);
  103621. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103622. return false;
  103623. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103624. encoder->protected_->verify = value;
  103625. #endif
  103626. return true;
  103627. }
  103628. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103629. {
  103630. FLAC__ASSERT(0 != encoder);
  103631. FLAC__ASSERT(0 != encoder->private_);
  103632. FLAC__ASSERT(0 != encoder->protected_);
  103633. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103634. return false;
  103635. encoder->protected_->streamable_subset = value;
  103636. return true;
  103637. }
  103638. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103639. {
  103640. FLAC__ASSERT(0 != encoder);
  103641. FLAC__ASSERT(0 != encoder->private_);
  103642. FLAC__ASSERT(0 != encoder->protected_);
  103643. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103644. return false;
  103645. encoder->protected_->do_md5 = value;
  103646. return true;
  103647. }
  103648. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103649. {
  103650. FLAC__ASSERT(0 != encoder);
  103651. FLAC__ASSERT(0 != encoder->private_);
  103652. FLAC__ASSERT(0 != encoder->protected_);
  103653. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103654. return false;
  103655. encoder->protected_->channels = value;
  103656. return true;
  103657. }
  103658. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103659. {
  103660. FLAC__ASSERT(0 != encoder);
  103661. FLAC__ASSERT(0 != encoder->private_);
  103662. FLAC__ASSERT(0 != encoder->protected_);
  103663. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103664. return false;
  103665. encoder->protected_->bits_per_sample = value;
  103666. return true;
  103667. }
  103668. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103669. {
  103670. FLAC__ASSERT(0 != encoder);
  103671. FLAC__ASSERT(0 != encoder->private_);
  103672. FLAC__ASSERT(0 != encoder->protected_);
  103673. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103674. return false;
  103675. encoder->protected_->sample_rate = value;
  103676. return true;
  103677. }
  103678. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103679. {
  103680. FLAC__bool ok = true;
  103681. FLAC__ASSERT(0 != encoder);
  103682. FLAC__ASSERT(0 != encoder->private_);
  103683. FLAC__ASSERT(0 != encoder->protected_);
  103684. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103685. return false;
  103686. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103687. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103688. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103689. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103690. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103691. #if 0
  103692. /* was: */
  103693. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103694. /* but it's too hard to specify the string in a locale-specific way */
  103695. #else
  103696. encoder->protected_->num_apodizations = 1;
  103697. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103698. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103699. #endif
  103700. #endif
  103701. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103702. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103703. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103704. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103705. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103706. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103707. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103708. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103709. return ok;
  103710. }
  103711. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103712. {
  103713. FLAC__ASSERT(0 != encoder);
  103714. FLAC__ASSERT(0 != encoder->private_);
  103715. FLAC__ASSERT(0 != encoder->protected_);
  103716. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103717. return false;
  103718. encoder->protected_->blocksize = value;
  103719. return true;
  103720. }
  103721. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103722. {
  103723. FLAC__ASSERT(0 != encoder);
  103724. FLAC__ASSERT(0 != encoder->private_);
  103725. FLAC__ASSERT(0 != encoder->protected_);
  103726. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103727. return false;
  103728. encoder->protected_->do_mid_side_stereo = value;
  103729. return true;
  103730. }
  103731. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103732. {
  103733. FLAC__ASSERT(0 != encoder);
  103734. FLAC__ASSERT(0 != encoder->private_);
  103735. FLAC__ASSERT(0 != encoder->protected_);
  103736. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103737. return false;
  103738. encoder->protected_->loose_mid_side_stereo = value;
  103739. return true;
  103740. }
  103741. /*@@@@add to tests*/
  103742. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103743. {
  103744. FLAC__ASSERT(0 != encoder);
  103745. FLAC__ASSERT(0 != encoder->private_);
  103746. FLAC__ASSERT(0 != encoder->protected_);
  103747. FLAC__ASSERT(0 != specification);
  103748. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103749. return false;
  103750. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103751. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103752. #else
  103753. encoder->protected_->num_apodizations = 0;
  103754. while(1) {
  103755. const char *s = strchr(specification, ';');
  103756. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103757. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103758. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103759. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103760. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103761. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103762. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103763. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103764. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103765. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103766. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103767. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103768. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103769. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103770. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103771. if (stddev > 0.0 && stddev <= 0.5) {
  103772. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103773. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103774. }
  103775. }
  103776. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103777. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103778. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103779. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103780. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103781. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103782. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103783. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103784. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103785. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103786. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103787. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103788. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103789. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103790. if (p >= 0.0 && p <= 1.0) {
  103791. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103792. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103793. }
  103794. }
  103795. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103796. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103797. if (encoder->protected_->num_apodizations == 32)
  103798. break;
  103799. if (s)
  103800. specification = s+1;
  103801. else
  103802. break;
  103803. }
  103804. if(encoder->protected_->num_apodizations == 0) {
  103805. encoder->protected_->num_apodizations = 1;
  103806. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103807. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103808. }
  103809. #endif
  103810. return true;
  103811. }
  103812. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103813. {
  103814. FLAC__ASSERT(0 != encoder);
  103815. FLAC__ASSERT(0 != encoder->private_);
  103816. FLAC__ASSERT(0 != encoder->protected_);
  103817. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103818. return false;
  103819. encoder->protected_->max_lpc_order = value;
  103820. return true;
  103821. }
  103822. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103823. {
  103824. FLAC__ASSERT(0 != encoder);
  103825. FLAC__ASSERT(0 != encoder->private_);
  103826. FLAC__ASSERT(0 != encoder->protected_);
  103827. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103828. return false;
  103829. encoder->protected_->qlp_coeff_precision = value;
  103830. return true;
  103831. }
  103832. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103833. {
  103834. FLAC__ASSERT(0 != encoder);
  103835. FLAC__ASSERT(0 != encoder->private_);
  103836. FLAC__ASSERT(0 != encoder->protected_);
  103837. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103838. return false;
  103839. encoder->protected_->do_qlp_coeff_prec_search = value;
  103840. return true;
  103841. }
  103842. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103843. {
  103844. FLAC__ASSERT(0 != encoder);
  103845. FLAC__ASSERT(0 != encoder->private_);
  103846. FLAC__ASSERT(0 != encoder->protected_);
  103847. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103848. return false;
  103849. #if 0
  103850. /*@@@ deprecated: */
  103851. encoder->protected_->do_escape_coding = value;
  103852. #else
  103853. (void)value;
  103854. #endif
  103855. return true;
  103856. }
  103857. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103858. {
  103859. FLAC__ASSERT(0 != encoder);
  103860. FLAC__ASSERT(0 != encoder->private_);
  103861. FLAC__ASSERT(0 != encoder->protected_);
  103862. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103863. return false;
  103864. encoder->protected_->do_exhaustive_model_search = value;
  103865. return true;
  103866. }
  103867. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103868. {
  103869. FLAC__ASSERT(0 != encoder);
  103870. FLAC__ASSERT(0 != encoder->private_);
  103871. FLAC__ASSERT(0 != encoder->protected_);
  103872. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103873. return false;
  103874. encoder->protected_->min_residual_partition_order = value;
  103875. return true;
  103876. }
  103877. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103878. {
  103879. FLAC__ASSERT(0 != encoder);
  103880. FLAC__ASSERT(0 != encoder->private_);
  103881. FLAC__ASSERT(0 != encoder->protected_);
  103882. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103883. return false;
  103884. encoder->protected_->max_residual_partition_order = value;
  103885. return true;
  103886. }
  103887. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103888. {
  103889. FLAC__ASSERT(0 != encoder);
  103890. FLAC__ASSERT(0 != encoder->private_);
  103891. FLAC__ASSERT(0 != encoder->protected_);
  103892. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103893. return false;
  103894. #if 0
  103895. /*@@@ deprecated: */
  103896. encoder->protected_->rice_parameter_search_dist = value;
  103897. #else
  103898. (void)value;
  103899. #endif
  103900. return true;
  103901. }
  103902. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103903. {
  103904. FLAC__ASSERT(0 != encoder);
  103905. FLAC__ASSERT(0 != encoder->private_);
  103906. FLAC__ASSERT(0 != encoder->protected_);
  103907. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103908. return false;
  103909. encoder->protected_->total_samples_estimate = value;
  103910. return true;
  103911. }
  103912. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103913. {
  103914. FLAC__ASSERT(0 != encoder);
  103915. FLAC__ASSERT(0 != encoder->private_);
  103916. FLAC__ASSERT(0 != encoder->protected_);
  103917. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103918. return false;
  103919. if(0 == metadata)
  103920. num_blocks = 0;
  103921. if(0 == num_blocks)
  103922. metadata = 0;
  103923. /* realloc() does not do exactly what we want so... */
  103924. if(encoder->protected_->metadata) {
  103925. free(encoder->protected_->metadata);
  103926. encoder->protected_->metadata = 0;
  103927. encoder->protected_->num_metadata_blocks = 0;
  103928. }
  103929. if(num_blocks) {
  103930. FLAC__StreamMetadata **m;
  103931. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103932. return false;
  103933. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103934. encoder->protected_->metadata = m;
  103935. encoder->protected_->num_metadata_blocks = num_blocks;
  103936. }
  103937. #if FLAC__HAS_OGG
  103938. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103939. return false;
  103940. #endif
  103941. return true;
  103942. }
  103943. /*
  103944. * These three functions are not static, but not publically exposed in
  103945. * include/FLAC/ either. They are used by the test suite.
  103946. */
  103947. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103948. {
  103949. FLAC__ASSERT(0 != encoder);
  103950. FLAC__ASSERT(0 != encoder->private_);
  103951. FLAC__ASSERT(0 != encoder->protected_);
  103952. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103953. return false;
  103954. encoder->private_->disable_constant_subframes = value;
  103955. return true;
  103956. }
  103957. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103958. {
  103959. FLAC__ASSERT(0 != encoder);
  103960. FLAC__ASSERT(0 != encoder->private_);
  103961. FLAC__ASSERT(0 != encoder->protected_);
  103962. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103963. return false;
  103964. encoder->private_->disable_fixed_subframes = value;
  103965. return true;
  103966. }
  103967. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103968. {
  103969. FLAC__ASSERT(0 != encoder);
  103970. FLAC__ASSERT(0 != encoder->private_);
  103971. FLAC__ASSERT(0 != encoder->protected_);
  103972. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103973. return false;
  103974. encoder->private_->disable_verbatim_subframes = value;
  103975. return true;
  103976. }
  103977. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103978. {
  103979. FLAC__ASSERT(0 != encoder);
  103980. FLAC__ASSERT(0 != encoder->private_);
  103981. FLAC__ASSERT(0 != encoder->protected_);
  103982. return encoder->protected_->state;
  103983. }
  103984. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103985. {
  103986. FLAC__ASSERT(0 != encoder);
  103987. FLAC__ASSERT(0 != encoder->private_);
  103988. FLAC__ASSERT(0 != encoder->protected_);
  103989. if(encoder->protected_->verify)
  103990. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103991. else
  103992. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103993. }
  103994. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103995. {
  103996. FLAC__ASSERT(0 != encoder);
  103997. FLAC__ASSERT(0 != encoder->private_);
  103998. FLAC__ASSERT(0 != encoder->protected_);
  103999. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  104000. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  104001. else
  104002. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  104003. }
  104004. 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)
  104005. {
  104006. FLAC__ASSERT(0 != encoder);
  104007. FLAC__ASSERT(0 != encoder->private_);
  104008. FLAC__ASSERT(0 != encoder->protected_);
  104009. if(0 != absolute_sample)
  104010. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  104011. if(0 != frame_number)
  104012. *frame_number = encoder->private_->verify.error_stats.frame_number;
  104013. if(0 != channel)
  104014. *channel = encoder->private_->verify.error_stats.channel;
  104015. if(0 != sample)
  104016. *sample = encoder->private_->verify.error_stats.sample;
  104017. if(0 != expected)
  104018. *expected = encoder->private_->verify.error_stats.expected;
  104019. if(0 != got)
  104020. *got = encoder->private_->verify.error_stats.got;
  104021. }
  104022. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  104023. {
  104024. FLAC__ASSERT(0 != encoder);
  104025. FLAC__ASSERT(0 != encoder->private_);
  104026. FLAC__ASSERT(0 != encoder->protected_);
  104027. return encoder->protected_->verify;
  104028. }
  104029. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104030. {
  104031. FLAC__ASSERT(0 != encoder);
  104032. FLAC__ASSERT(0 != encoder->private_);
  104033. FLAC__ASSERT(0 != encoder->protected_);
  104034. return encoder->protected_->streamable_subset;
  104035. }
  104036. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104037. {
  104038. FLAC__ASSERT(0 != encoder);
  104039. FLAC__ASSERT(0 != encoder->private_);
  104040. FLAC__ASSERT(0 != encoder->protected_);
  104041. return encoder->protected_->do_md5;
  104042. }
  104043. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104044. {
  104045. FLAC__ASSERT(0 != encoder);
  104046. FLAC__ASSERT(0 != encoder->private_);
  104047. FLAC__ASSERT(0 != encoder->protected_);
  104048. return encoder->protected_->channels;
  104049. }
  104050. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104051. {
  104052. FLAC__ASSERT(0 != encoder);
  104053. FLAC__ASSERT(0 != encoder->private_);
  104054. FLAC__ASSERT(0 != encoder->protected_);
  104055. return encoder->protected_->bits_per_sample;
  104056. }
  104057. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104058. {
  104059. FLAC__ASSERT(0 != encoder);
  104060. FLAC__ASSERT(0 != encoder->private_);
  104061. FLAC__ASSERT(0 != encoder->protected_);
  104062. return encoder->protected_->sample_rate;
  104063. }
  104064. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104065. {
  104066. FLAC__ASSERT(0 != encoder);
  104067. FLAC__ASSERT(0 != encoder->private_);
  104068. FLAC__ASSERT(0 != encoder->protected_);
  104069. return encoder->protected_->blocksize;
  104070. }
  104071. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104072. {
  104073. FLAC__ASSERT(0 != encoder);
  104074. FLAC__ASSERT(0 != encoder->private_);
  104075. FLAC__ASSERT(0 != encoder->protected_);
  104076. return encoder->protected_->do_mid_side_stereo;
  104077. }
  104078. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104079. {
  104080. FLAC__ASSERT(0 != encoder);
  104081. FLAC__ASSERT(0 != encoder->private_);
  104082. FLAC__ASSERT(0 != encoder->protected_);
  104083. return encoder->protected_->loose_mid_side_stereo;
  104084. }
  104085. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104086. {
  104087. FLAC__ASSERT(0 != encoder);
  104088. FLAC__ASSERT(0 != encoder->private_);
  104089. FLAC__ASSERT(0 != encoder->protected_);
  104090. return encoder->protected_->max_lpc_order;
  104091. }
  104092. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104093. {
  104094. FLAC__ASSERT(0 != encoder);
  104095. FLAC__ASSERT(0 != encoder->private_);
  104096. FLAC__ASSERT(0 != encoder->protected_);
  104097. return encoder->protected_->qlp_coeff_precision;
  104098. }
  104099. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104100. {
  104101. FLAC__ASSERT(0 != encoder);
  104102. FLAC__ASSERT(0 != encoder->private_);
  104103. FLAC__ASSERT(0 != encoder->protected_);
  104104. return encoder->protected_->do_qlp_coeff_prec_search;
  104105. }
  104106. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104107. {
  104108. FLAC__ASSERT(0 != encoder);
  104109. FLAC__ASSERT(0 != encoder->private_);
  104110. FLAC__ASSERT(0 != encoder->protected_);
  104111. return encoder->protected_->do_escape_coding;
  104112. }
  104113. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104114. {
  104115. FLAC__ASSERT(0 != encoder);
  104116. FLAC__ASSERT(0 != encoder->private_);
  104117. FLAC__ASSERT(0 != encoder->protected_);
  104118. return encoder->protected_->do_exhaustive_model_search;
  104119. }
  104120. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104121. {
  104122. FLAC__ASSERT(0 != encoder);
  104123. FLAC__ASSERT(0 != encoder->private_);
  104124. FLAC__ASSERT(0 != encoder->protected_);
  104125. return encoder->protected_->min_residual_partition_order;
  104126. }
  104127. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104128. {
  104129. FLAC__ASSERT(0 != encoder);
  104130. FLAC__ASSERT(0 != encoder->private_);
  104131. FLAC__ASSERT(0 != encoder->protected_);
  104132. return encoder->protected_->max_residual_partition_order;
  104133. }
  104134. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104135. {
  104136. FLAC__ASSERT(0 != encoder);
  104137. FLAC__ASSERT(0 != encoder->private_);
  104138. FLAC__ASSERT(0 != encoder->protected_);
  104139. return encoder->protected_->rice_parameter_search_dist;
  104140. }
  104141. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104142. {
  104143. FLAC__ASSERT(0 != encoder);
  104144. FLAC__ASSERT(0 != encoder->private_);
  104145. FLAC__ASSERT(0 != encoder->protected_);
  104146. return encoder->protected_->total_samples_estimate;
  104147. }
  104148. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104149. {
  104150. unsigned i, j = 0, channel;
  104151. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104152. FLAC__ASSERT(0 != encoder);
  104153. FLAC__ASSERT(0 != encoder->private_);
  104154. FLAC__ASSERT(0 != encoder->protected_);
  104155. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104156. do {
  104157. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104158. if(encoder->protected_->verify)
  104159. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104160. for(channel = 0; channel < channels; channel++)
  104161. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104162. if(encoder->protected_->do_mid_side_stereo) {
  104163. FLAC__ASSERT(channels == 2);
  104164. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104165. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104166. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104167. 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' ! */
  104168. }
  104169. }
  104170. else
  104171. j += n;
  104172. encoder->private_->current_sample_number += n;
  104173. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104174. if(encoder->private_->current_sample_number > blocksize) {
  104175. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104176. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104177. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104178. return false;
  104179. /* move unprocessed overread samples to beginnings of arrays */
  104180. for(channel = 0; channel < channels; channel++)
  104181. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104182. if(encoder->protected_->do_mid_side_stereo) {
  104183. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104184. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104185. }
  104186. encoder->private_->current_sample_number = 1;
  104187. }
  104188. } while(j < samples);
  104189. return true;
  104190. }
  104191. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104192. {
  104193. unsigned i, j, k, channel;
  104194. FLAC__int32 x, mid, side;
  104195. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104196. FLAC__ASSERT(0 != encoder);
  104197. FLAC__ASSERT(0 != encoder->private_);
  104198. FLAC__ASSERT(0 != encoder->protected_);
  104199. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104200. j = k = 0;
  104201. /*
  104202. * we have several flavors of the same basic loop, optimized for
  104203. * different conditions:
  104204. */
  104205. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104206. /*
  104207. * stereo coding: unroll channel loop
  104208. */
  104209. do {
  104210. if(encoder->protected_->verify)
  104211. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104212. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104213. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104214. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104215. x = buffer[k++];
  104216. encoder->private_->integer_signal[1][i] = x;
  104217. mid += x;
  104218. side -= x;
  104219. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104220. encoder->private_->integer_signal_mid_side[1][i] = side;
  104221. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104222. }
  104223. encoder->private_->current_sample_number = i;
  104224. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104225. if(i > blocksize) {
  104226. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104227. return false;
  104228. /* move unprocessed overread samples to beginnings of arrays */
  104229. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104230. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104231. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104232. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104233. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104234. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104235. encoder->private_->current_sample_number = 1;
  104236. }
  104237. } while(j < samples);
  104238. }
  104239. else {
  104240. /*
  104241. * independent channel coding: buffer each channel in inner loop
  104242. */
  104243. do {
  104244. if(encoder->protected_->verify)
  104245. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104246. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104247. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104248. for(channel = 0; channel < channels; channel++)
  104249. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104250. }
  104251. encoder->private_->current_sample_number = i;
  104252. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104253. if(i > blocksize) {
  104254. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104255. return false;
  104256. /* move unprocessed overread samples to beginnings of arrays */
  104257. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104258. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104259. for(channel = 0; channel < channels; channel++)
  104260. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104261. encoder->private_->current_sample_number = 1;
  104262. }
  104263. } while(j < samples);
  104264. }
  104265. return true;
  104266. }
  104267. /***********************************************************************
  104268. *
  104269. * Private class methods
  104270. *
  104271. ***********************************************************************/
  104272. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104273. {
  104274. FLAC__ASSERT(0 != encoder);
  104275. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104276. encoder->protected_->verify = true;
  104277. #else
  104278. encoder->protected_->verify = false;
  104279. #endif
  104280. encoder->protected_->streamable_subset = true;
  104281. encoder->protected_->do_md5 = true;
  104282. encoder->protected_->do_mid_side_stereo = false;
  104283. encoder->protected_->loose_mid_side_stereo = false;
  104284. encoder->protected_->channels = 2;
  104285. encoder->protected_->bits_per_sample = 16;
  104286. encoder->protected_->sample_rate = 44100;
  104287. encoder->protected_->blocksize = 0;
  104288. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104289. encoder->protected_->num_apodizations = 1;
  104290. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104291. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104292. #endif
  104293. encoder->protected_->max_lpc_order = 0;
  104294. encoder->protected_->qlp_coeff_precision = 0;
  104295. encoder->protected_->do_qlp_coeff_prec_search = false;
  104296. encoder->protected_->do_exhaustive_model_search = false;
  104297. encoder->protected_->do_escape_coding = false;
  104298. encoder->protected_->min_residual_partition_order = 0;
  104299. encoder->protected_->max_residual_partition_order = 0;
  104300. encoder->protected_->rice_parameter_search_dist = 0;
  104301. encoder->protected_->total_samples_estimate = 0;
  104302. encoder->protected_->metadata = 0;
  104303. encoder->protected_->num_metadata_blocks = 0;
  104304. encoder->private_->seek_table = 0;
  104305. encoder->private_->disable_constant_subframes = false;
  104306. encoder->private_->disable_fixed_subframes = false;
  104307. encoder->private_->disable_verbatim_subframes = false;
  104308. #if FLAC__HAS_OGG
  104309. encoder->private_->is_ogg = false;
  104310. #endif
  104311. encoder->private_->read_callback = 0;
  104312. encoder->private_->write_callback = 0;
  104313. encoder->private_->seek_callback = 0;
  104314. encoder->private_->tell_callback = 0;
  104315. encoder->private_->metadata_callback = 0;
  104316. encoder->private_->progress_callback = 0;
  104317. encoder->private_->client_data = 0;
  104318. #if FLAC__HAS_OGG
  104319. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104320. #endif
  104321. }
  104322. void free_(FLAC__StreamEncoder *encoder)
  104323. {
  104324. unsigned i, channel;
  104325. FLAC__ASSERT(0 != encoder);
  104326. if(encoder->protected_->metadata) {
  104327. free(encoder->protected_->metadata);
  104328. encoder->protected_->metadata = 0;
  104329. encoder->protected_->num_metadata_blocks = 0;
  104330. }
  104331. for(i = 0; i < encoder->protected_->channels; i++) {
  104332. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104333. free(encoder->private_->integer_signal_unaligned[i]);
  104334. encoder->private_->integer_signal_unaligned[i] = 0;
  104335. }
  104336. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104337. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104338. free(encoder->private_->real_signal_unaligned[i]);
  104339. encoder->private_->real_signal_unaligned[i] = 0;
  104340. }
  104341. #endif
  104342. }
  104343. for(i = 0; i < 2; i++) {
  104344. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104345. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104346. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104347. }
  104348. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104349. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104350. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104351. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104352. }
  104353. #endif
  104354. }
  104355. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104356. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104357. if(0 != encoder->private_->window_unaligned[i]) {
  104358. free(encoder->private_->window_unaligned[i]);
  104359. encoder->private_->window_unaligned[i] = 0;
  104360. }
  104361. }
  104362. if(0 != encoder->private_->windowed_signal_unaligned) {
  104363. free(encoder->private_->windowed_signal_unaligned);
  104364. encoder->private_->windowed_signal_unaligned = 0;
  104365. }
  104366. #endif
  104367. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104368. for(i = 0; i < 2; i++) {
  104369. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104370. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104371. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104372. }
  104373. }
  104374. }
  104375. for(channel = 0; channel < 2; channel++) {
  104376. for(i = 0; i < 2; i++) {
  104377. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104378. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104379. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104380. }
  104381. }
  104382. }
  104383. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104384. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104385. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104386. }
  104387. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104388. free(encoder->private_->raw_bits_per_partition_unaligned);
  104389. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104390. }
  104391. if(encoder->protected_->verify) {
  104392. for(i = 0; i < encoder->protected_->channels; i++) {
  104393. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104394. free(encoder->private_->verify.input_fifo.data[i]);
  104395. encoder->private_->verify.input_fifo.data[i] = 0;
  104396. }
  104397. }
  104398. }
  104399. FLAC__bitwriter_free(encoder->private_->frame);
  104400. }
  104401. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104402. {
  104403. FLAC__bool ok;
  104404. unsigned i, channel;
  104405. FLAC__ASSERT(new_blocksize > 0);
  104406. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104407. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104408. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104409. if(new_blocksize <= encoder->private_->input_capacity)
  104410. return true;
  104411. ok = true;
  104412. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104413. * requires that the input arrays (in our case the integer signals)
  104414. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104415. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104416. */
  104417. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104418. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104419. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104420. encoder->private_->integer_signal[i] += 4;
  104421. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104422. #if 0 /* @@@ currently unused */
  104423. if(encoder->protected_->max_lpc_order > 0)
  104424. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104425. #endif
  104426. #endif
  104427. }
  104428. for(i = 0; ok && i < 2; i++) {
  104429. 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]);
  104430. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104431. encoder->private_->integer_signal_mid_side[i] += 4;
  104432. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104433. #if 0 /* @@@ currently unused */
  104434. if(encoder->protected_->max_lpc_order > 0)
  104435. 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]);
  104436. #endif
  104437. #endif
  104438. }
  104439. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104440. if(ok && encoder->protected_->max_lpc_order > 0) {
  104441. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104442. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104443. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104444. }
  104445. #endif
  104446. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104447. for(i = 0; ok && i < 2; i++) {
  104448. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104449. }
  104450. }
  104451. for(channel = 0; ok && channel < 2; channel++) {
  104452. for(i = 0; ok && i < 2; i++) {
  104453. 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]);
  104454. }
  104455. }
  104456. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104457. /*@@@ 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) */
  104458. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104459. if(encoder->protected_->do_escape_coding)
  104460. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104461. /* now adjust the windows if the blocksize has changed */
  104462. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104463. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104464. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104465. switch(encoder->protected_->apodizations[i].type) {
  104466. case FLAC__APODIZATION_BARTLETT:
  104467. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104468. break;
  104469. case FLAC__APODIZATION_BARTLETT_HANN:
  104470. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104471. break;
  104472. case FLAC__APODIZATION_BLACKMAN:
  104473. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104474. break;
  104475. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104476. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104477. break;
  104478. case FLAC__APODIZATION_CONNES:
  104479. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104480. break;
  104481. case FLAC__APODIZATION_FLATTOP:
  104482. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104483. break;
  104484. case FLAC__APODIZATION_GAUSS:
  104485. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104486. break;
  104487. case FLAC__APODIZATION_HAMMING:
  104488. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104489. break;
  104490. case FLAC__APODIZATION_HANN:
  104491. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104492. break;
  104493. case FLAC__APODIZATION_KAISER_BESSEL:
  104494. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104495. break;
  104496. case FLAC__APODIZATION_NUTTALL:
  104497. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104498. break;
  104499. case FLAC__APODIZATION_RECTANGLE:
  104500. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104501. break;
  104502. case FLAC__APODIZATION_TRIANGLE:
  104503. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104504. break;
  104505. case FLAC__APODIZATION_TUKEY:
  104506. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104507. break;
  104508. case FLAC__APODIZATION_WELCH:
  104509. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104510. break;
  104511. default:
  104512. FLAC__ASSERT(0);
  104513. /* double protection */
  104514. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104515. break;
  104516. }
  104517. }
  104518. }
  104519. #endif
  104520. if(ok)
  104521. encoder->private_->input_capacity = new_blocksize;
  104522. else
  104523. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104524. return ok;
  104525. }
  104526. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104527. {
  104528. const FLAC__byte *buffer;
  104529. size_t bytes;
  104530. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104531. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104532. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104533. return false;
  104534. }
  104535. if(encoder->protected_->verify) {
  104536. encoder->private_->verify.output.data = buffer;
  104537. encoder->private_->verify.output.bytes = bytes;
  104538. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104539. encoder->private_->verify.needs_magic_hack = true;
  104540. }
  104541. else {
  104542. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104543. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104544. FLAC__bitwriter_clear(encoder->private_->frame);
  104545. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104546. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104547. return false;
  104548. }
  104549. }
  104550. }
  104551. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104552. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104553. FLAC__bitwriter_clear(encoder->private_->frame);
  104554. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104555. return false;
  104556. }
  104557. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104558. FLAC__bitwriter_clear(encoder->private_->frame);
  104559. if(samples > 0) {
  104560. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104561. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104562. }
  104563. return true;
  104564. }
  104565. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104566. {
  104567. FLAC__StreamEncoderWriteStatus status;
  104568. FLAC__uint64 output_position = 0;
  104569. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104570. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104571. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104572. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104573. }
  104574. /*
  104575. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104576. */
  104577. if(samples == 0) {
  104578. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104579. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104580. encoder->protected_->streaminfo_offset = output_position;
  104581. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104582. encoder->protected_->seektable_offset = output_position;
  104583. }
  104584. /*
  104585. * Mark the current seek point if hit (if audio_offset == 0 that
  104586. * means we're still writing metadata and haven't hit the first
  104587. * frame yet)
  104588. */
  104589. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104590. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104591. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104592. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104593. FLAC__uint64 test_sample;
  104594. unsigned i;
  104595. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104596. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104597. if(test_sample > frame_last_sample) {
  104598. break;
  104599. }
  104600. else if(test_sample >= frame_first_sample) {
  104601. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104602. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104603. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104604. encoder->private_->first_seekpoint_to_check++;
  104605. /* DO NOT: "break;" and here's why:
  104606. * The seektable template may contain more than one target
  104607. * sample for any given frame; we will keep looping, generating
  104608. * duplicate seekpoints for them, and we'll clean it up later,
  104609. * just before writing the seektable back to the metadata.
  104610. */
  104611. }
  104612. else {
  104613. encoder->private_->first_seekpoint_to_check++;
  104614. }
  104615. }
  104616. }
  104617. #if FLAC__HAS_OGG
  104618. if(encoder->private_->is_ogg) {
  104619. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104620. &encoder->protected_->ogg_encoder_aspect,
  104621. buffer,
  104622. bytes,
  104623. samples,
  104624. encoder->private_->current_frame_number,
  104625. is_last_block,
  104626. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104627. encoder,
  104628. encoder->private_->client_data
  104629. );
  104630. }
  104631. else
  104632. #endif
  104633. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104634. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104635. encoder->private_->bytes_written += bytes;
  104636. encoder->private_->samples_written += samples;
  104637. /* we keep a high watermark on the number of frames written because
  104638. * when the encoder goes back to write metadata, 'current_frame'
  104639. * will drop back to 0.
  104640. */
  104641. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104642. }
  104643. else
  104644. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104645. return status;
  104646. }
  104647. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104648. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104649. {
  104650. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104651. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104652. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104653. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104654. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104655. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104656. FLAC__StreamEncoderSeekStatus seek_status;
  104657. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104658. /* All this is based on intimate knowledge of the stream header
  104659. * layout, but a change to the header format that would break this
  104660. * would also break all streams encoded in the previous format.
  104661. */
  104662. /*
  104663. * Write MD5 signature
  104664. */
  104665. {
  104666. const unsigned md5_offset =
  104667. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104668. (
  104669. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104670. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104671. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104672. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104673. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104674. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104675. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104676. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104677. ) / 8;
  104678. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104679. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104680. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104681. return;
  104682. }
  104683. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104684. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104685. return;
  104686. }
  104687. }
  104688. /*
  104689. * Write total samples
  104690. */
  104691. {
  104692. const unsigned total_samples_byte_offset =
  104693. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104694. (
  104695. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104696. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104697. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104698. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104699. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104700. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104701. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104702. - 4
  104703. ) / 8;
  104704. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104705. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104706. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104707. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104708. b[4] = (FLAC__byte)(samples & 0xFF);
  104709. 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) {
  104710. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104711. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104712. return;
  104713. }
  104714. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104715. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104716. return;
  104717. }
  104718. }
  104719. /*
  104720. * Write min/max framesize
  104721. */
  104722. {
  104723. const unsigned min_framesize_offset =
  104724. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104725. (
  104726. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104727. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104728. ) / 8;
  104729. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104730. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104731. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104732. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104733. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104734. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104735. 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) {
  104736. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104737. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104738. return;
  104739. }
  104740. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104741. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104742. return;
  104743. }
  104744. }
  104745. /*
  104746. * Write seektable
  104747. */
  104748. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104749. unsigned i;
  104750. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104751. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104752. 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) {
  104753. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104754. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104755. return;
  104756. }
  104757. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104758. FLAC__uint64 xx;
  104759. unsigned x;
  104760. xx = encoder->private_->seek_table->points[i].sample_number;
  104761. b[7] = (FLAC__byte)xx; xx >>= 8;
  104762. b[6] = (FLAC__byte)xx; xx >>= 8;
  104763. b[5] = (FLAC__byte)xx; xx >>= 8;
  104764. b[4] = (FLAC__byte)xx; xx >>= 8;
  104765. b[3] = (FLAC__byte)xx; xx >>= 8;
  104766. b[2] = (FLAC__byte)xx; xx >>= 8;
  104767. b[1] = (FLAC__byte)xx; xx >>= 8;
  104768. b[0] = (FLAC__byte)xx; xx >>= 8;
  104769. xx = encoder->private_->seek_table->points[i].stream_offset;
  104770. b[15] = (FLAC__byte)xx; xx >>= 8;
  104771. b[14] = (FLAC__byte)xx; xx >>= 8;
  104772. b[13] = (FLAC__byte)xx; xx >>= 8;
  104773. b[12] = (FLAC__byte)xx; xx >>= 8;
  104774. b[11] = (FLAC__byte)xx; xx >>= 8;
  104775. b[10] = (FLAC__byte)xx; xx >>= 8;
  104776. b[9] = (FLAC__byte)xx; xx >>= 8;
  104777. b[8] = (FLAC__byte)xx; xx >>= 8;
  104778. x = encoder->private_->seek_table->points[i].frame_samples;
  104779. b[17] = (FLAC__byte)x; x >>= 8;
  104780. b[16] = (FLAC__byte)x; x >>= 8;
  104781. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104782. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104783. return;
  104784. }
  104785. }
  104786. }
  104787. }
  104788. #if FLAC__HAS_OGG
  104789. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104790. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104791. {
  104792. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104793. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104794. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104795. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104796. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104797. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104798. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104799. FLAC__STREAM_SYNC_LENGTH
  104800. ;
  104801. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104802. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104803. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104804. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104805. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104806. ogg_page page;
  104807. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104808. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104809. /* Pre-check that client supports seeking, since we don't want the
  104810. * ogg_helper code to ever have to deal with this condition.
  104811. */
  104812. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104813. return;
  104814. /* All this is based on intimate knowledge of the stream header
  104815. * layout, but a change to the header format that would break this
  104816. * would also break all streams encoded in the previous format.
  104817. */
  104818. /**
  104819. ** Write STREAMINFO stats
  104820. **/
  104821. simple_ogg_page__init(&page);
  104822. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104823. simple_ogg_page__clear(&page);
  104824. return; /* state already set */
  104825. }
  104826. /*
  104827. * Write MD5 signature
  104828. */
  104829. {
  104830. const unsigned md5_offset =
  104831. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104832. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104833. (
  104834. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104835. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104836. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104837. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104838. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104839. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104840. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104841. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104842. ) / 8;
  104843. if(md5_offset + 16 > (unsigned)page.body_len) {
  104844. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104845. simple_ogg_page__clear(&page);
  104846. return;
  104847. }
  104848. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104849. }
  104850. /*
  104851. * Write total samples
  104852. */
  104853. {
  104854. const unsigned total_samples_byte_offset =
  104855. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104856. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104857. (
  104858. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104859. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104860. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104861. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104862. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104863. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104864. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104865. - 4
  104866. ) / 8;
  104867. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104868. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104869. simple_ogg_page__clear(&page);
  104870. return;
  104871. }
  104872. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104873. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104874. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104875. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104876. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104877. b[4] = (FLAC__byte)(samples & 0xFF);
  104878. memcpy(page.body + total_samples_byte_offset, b, 5);
  104879. }
  104880. /*
  104881. * Write min/max framesize
  104882. */
  104883. {
  104884. const unsigned min_framesize_offset =
  104885. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104886. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104887. (
  104888. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104889. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104890. ) / 8;
  104891. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104892. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104893. simple_ogg_page__clear(&page);
  104894. return;
  104895. }
  104896. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104897. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104898. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104899. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104900. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104901. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104902. memcpy(page.body + min_framesize_offset, b, 6);
  104903. }
  104904. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104905. simple_ogg_page__clear(&page);
  104906. return; /* state already set */
  104907. }
  104908. simple_ogg_page__clear(&page);
  104909. /*
  104910. * Write seektable
  104911. */
  104912. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104913. unsigned i;
  104914. FLAC__byte *p;
  104915. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104916. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104917. simple_ogg_page__init(&page);
  104918. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104919. simple_ogg_page__clear(&page);
  104920. return; /* state already set */
  104921. }
  104922. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104923. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104924. simple_ogg_page__clear(&page);
  104925. return;
  104926. }
  104927. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104928. FLAC__uint64 xx;
  104929. unsigned x;
  104930. xx = encoder->private_->seek_table->points[i].sample_number;
  104931. b[7] = (FLAC__byte)xx; xx >>= 8;
  104932. b[6] = (FLAC__byte)xx; xx >>= 8;
  104933. b[5] = (FLAC__byte)xx; xx >>= 8;
  104934. b[4] = (FLAC__byte)xx; xx >>= 8;
  104935. b[3] = (FLAC__byte)xx; xx >>= 8;
  104936. b[2] = (FLAC__byte)xx; xx >>= 8;
  104937. b[1] = (FLAC__byte)xx; xx >>= 8;
  104938. b[0] = (FLAC__byte)xx; xx >>= 8;
  104939. xx = encoder->private_->seek_table->points[i].stream_offset;
  104940. b[15] = (FLAC__byte)xx; xx >>= 8;
  104941. b[14] = (FLAC__byte)xx; xx >>= 8;
  104942. b[13] = (FLAC__byte)xx; xx >>= 8;
  104943. b[12] = (FLAC__byte)xx; xx >>= 8;
  104944. b[11] = (FLAC__byte)xx; xx >>= 8;
  104945. b[10] = (FLAC__byte)xx; xx >>= 8;
  104946. b[9] = (FLAC__byte)xx; xx >>= 8;
  104947. b[8] = (FLAC__byte)xx; xx >>= 8;
  104948. x = encoder->private_->seek_table->points[i].frame_samples;
  104949. b[17] = (FLAC__byte)x; x >>= 8;
  104950. b[16] = (FLAC__byte)x; x >>= 8;
  104951. memcpy(p, b, 18);
  104952. }
  104953. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104954. simple_ogg_page__clear(&page);
  104955. return; /* state already set */
  104956. }
  104957. simple_ogg_page__clear(&page);
  104958. }
  104959. }
  104960. #endif
  104961. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104962. {
  104963. FLAC__uint16 crc;
  104964. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104965. /*
  104966. * Accumulate raw signal to the MD5 signature
  104967. */
  104968. 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)) {
  104969. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104970. return false;
  104971. }
  104972. /*
  104973. * Process the frame header and subframes into the frame bitbuffer
  104974. */
  104975. if(!process_subframes_(encoder, is_fractional_block)) {
  104976. /* the above function sets the state for us in case of an error */
  104977. return false;
  104978. }
  104979. /*
  104980. * Zero-pad the frame to a byte_boundary
  104981. */
  104982. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104983. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104984. return false;
  104985. }
  104986. /*
  104987. * CRC-16 the whole thing
  104988. */
  104989. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104990. if(
  104991. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104992. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104993. ) {
  104994. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104995. return false;
  104996. }
  104997. /*
  104998. * Write it
  104999. */
  105000. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  105001. /* the above function sets the state for us in case of an error */
  105002. return false;
  105003. }
  105004. /*
  105005. * Get ready for the next frame
  105006. */
  105007. encoder->private_->current_sample_number = 0;
  105008. encoder->private_->current_frame_number++;
  105009. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  105010. return true;
  105011. }
  105012. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  105013. {
  105014. FLAC__FrameHeader frame_header;
  105015. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  105016. FLAC__bool do_independent, do_mid_side;
  105017. /*
  105018. * Calculate the min,max Rice partition orders
  105019. */
  105020. if(is_fractional_block) {
  105021. max_partition_order = 0;
  105022. }
  105023. else {
  105024. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105025. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105026. }
  105027. min_partition_order = min(min_partition_order, max_partition_order);
  105028. /*
  105029. * Setup the frame
  105030. */
  105031. frame_header.blocksize = encoder->protected_->blocksize;
  105032. frame_header.sample_rate = encoder->protected_->sample_rate;
  105033. frame_header.channels = encoder->protected_->channels;
  105034. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105035. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105036. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105037. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105038. /*
  105039. * Figure out what channel assignments to try
  105040. */
  105041. if(encoder->protected_->do_mid_side_stereo) {
  105042. if(encoder->protected_->loose_mid_side_stereo) {
  105043. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105044. do_independent = true;
  105045. do_mid_side = true;
  105046. }
  105047. else {
  105048. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105049. do_mid_side = !do_independent;
  105050. }
  105051. }
  105052. else {
  105053. do_independent = true;
  105054. do_mid_side = true;
  105055. }
  105056. }
  105057. else {
  105058. do_independent = true;
  105059. do_mid_side = false;
  105060. }
  105061. FLAC__ASSERT(do_independent || do_mid_side);
  105062. /*
  105063. * Check for wasted bits; set effective bps for each subframe
  105064. */
  105065. if(do_independent) {
  105066. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105067. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105068. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105069. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105070. }
  105071. }
  105072. if(do_mid_side) {
  105073. FLAC__ASSERT(encoder->protected_->channels == 2);
  105074. for(channel = 0; channel < 2; channel++) {
  105075. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105076. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105077. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105078. }
  105079. }
  105080. /*
  105081. * First do a normal encoding pass of each independent channel
  105082. */
  105083. if(do_independent) {
  105084. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105085. if(!
  105086. process_subframe_(
  105087. encoder,
  105088. min_partition_order,
  105089. max_partition_order,
  105090. &frame_header,
  105091. encoder->private_->subframe_bps[channel],
  105092. encoder->private_->integer_signal[channel],
  105093. encoder->private_->subframe_workspace_ptr[channel],
  105094. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105095. encoder->private_->residual_workspace[channel],
  105096. encoder->private_->best_subframe+channel,
  105097. encoder->private_->best_subframe_bits+channel
  105098. )
  105099. )
  105100. return false;
  105101. }
  105102. }
  105103. /*
  105104. * Now do mid and side channels if requested
  105105. */
  105106. if(do_mid_side) {
  105107. FLAC__ASSERT(encoder->protected_->channels == 2);
  105108. for(channel = 0; channel < 2; channel++) {
  105109. if(!
  105110. process_subframe_(
  105111. encoder,
  105112. min_partition_order,
  105113. max_partition_order,
  105114. &frame_header,
  105115. encoder->private_->subframe_bps_mid_side[channel],
  105116. encoder->private_->integer_signal_mid_side[channel],
  105117. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105118. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105119. encoder->private_->residual_workspace_mid_side[channel],
  105120. encoder->private_->best_subframe_mid_side+channel,
  105121. encoder->private_->best_subframe_bits_mid_side+channel
  105122. )
  105123. )
  105124. return false;
  105125. }
  105126. }
  105127. /*
  105128. * Compose the frame bitbuffer
  105129. */
  105130. if(do_mid_side) {
  105131. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105132. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105133. FLAC__ChannelAssignment channel_assignment;
  105134. FLAC__ASSERT(encoder->protected_->channels == 2);
  105135. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105136. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105137. }
  105138. else {
  105139. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105140. unsigned min_bits;
  105141. int ca;
  105142. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105143. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105144. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105145. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105146. FLAC__ASSERT(do_independent && do_mid_side);
  105147. /* We have to figure out which channel assignent results in the smallest frame */
  105148. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105149. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105150. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105151. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105152. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105153. min_bits = bits[channel_assignment];
  105154. for(ca = 1; ca <= 3; ca++) {
  105155. if(bits[ca] < min_bits) {
  105156. min_bits = bits[ca];
  105157. channel_assignment = (FLAC__ChannelAssignment)ca;
  105158. }
  105159. }
  105160. }
  105161. frame_header.channel_assignment = channel_assignment;
  105162. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105163. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105164. return false;
  105165. }
  105166. switch(channel_assignment) {
  105167. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105168. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105169. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105170. break;
  105171. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105172. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105173. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105174. break;
  105175. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105176. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105177. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105178. break;
  105179. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105180. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105181. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105182. break;
  105183. default:
  105184. FLAC__ASSERT(0);
  105185. }
  105186. switch(channel_assignment) {
  105187. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105188. left_bps = encoder->private_->subframe_bps [0];
  105189. right_bps = encoder->private_->subframe_bps [1];
  105190. break;
  105191. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105192. left_bps = encoder->private_->subframe_bps [0];
  105193. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105194. break;
  105195. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105196. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105197. right_bps = encoder->private_->subframe_bps [1];
  105198. break;
  105199. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105200. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105201. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105202. break;
  105203. default:
  105204. FLAC__ASSERT(0);
  105205. }
  105206. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105207. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105208. return false;
  105209. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105210. return false;
  105211. }
  105212. else {
  105213. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105214. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105215. return false;
  105216. }
  105217. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105218. 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)) {
  105219. /* the above function sets the state for us in case of an error */
  105220. return false;
  105221. }
  105222. }
  105223. }
  105224. if(encoder->protected_->loose_mid_side_stereo) {
  105225. encoder->private_->loose_mid_side_stereo_frame_count++;
  105226. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105227. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105228. }
  105229. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105230. return true;
  105231. }
  105232. FLAC__bool process_subframe_(
  105233. FLAC__StreamEncoder *encoder,
  105234. unsigned min_partition_order,
  105235. unsigned max_partition_order,
  105236. const FLAC__FrameHeader *frame_header,
  105237. unsigned subframe_bps,
  105238. const FLAC__int32 integer_signal[],
  105239. FLAC__Subframe *subframe[2],
  105240. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105241. FLAC__int32 *residual[2],
  105242. unsigned *best_subframe,
  105243. unsigned *best_bits
  105244. )
  105245. {
  105246. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105247. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105248. #else
  105249. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105250. #endif
  105251. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105252. FLAC__double lpc_residual_bits_per_sample;
  105253. 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 */
  105254. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105255. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105256. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105257. #endif
  105258. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105259. unsigned rice_parameter;
  105260. unsigned _candidate_bits, _best_bits;
  105261. unsigned _best_subframe;
  105262. /* only use RICE2 partitions if stream bps > 16 */
  105263. 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;
  105264. FLAC__ASSERT(frame_header->blocksize > 0);
  105265. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105266. _best_subframe = 0;
  105267. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105268. _best_bits = UINT_MAX;
  105269. else
  105270. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105271. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105272. unsigned signal_is_constant = false;
  105273. 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);
  105274. /* check for constant subframe */
  105275. if(
  105276. !encoder->private_->disable_constant_subframes &&
  105277. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105278. fixed_residual_bits_per_sample[1] == 0.0
  105279. #else
  105280. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105281. #endif
  105282. ) {
  105283. /* the above means it's possible all samples are the same value; now double-check it: */
  105284. unsigned i;
  105285. signal_is_constant = true;
  105286. for(i = 1; i < frame_header->blocksize; i++) {
  105287. if(integer_signal[0] != integer_signal[i]) {
  105288. signal_is_constant = false;
  105289. break;
  105290. }
  105291. }
  105292. }
  105293. if(signal_is_constant) {
  105294. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105295. if(_candidate_bits < _best_bits) {
  105296. _best_subframe = !_best_subframe;
  105297. _best_bits = _candidate_bits;
  105298. }
  105299. }
  105300. else {
  105301. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105302. /* encode fixed */
  105303. if(encoder->protected_->do_exhaustive_model_search) {
  105304. min_fixed_order = 0;
  105305. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105306. }
  105307. else {
  105308. min_fixed_order = max_fixed_order = guess_fixed_order;
  105309. }
  105310. if(max_fixed_order >= frame_header->blocksize)
  105311. max_fixed_order = frame_header->blocksize - 1;
  105312. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105313. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105314. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105315. continue; /* don't even try */
  105316. 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 */
  105317. #else
  105318. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105319. continue; /* don't even try */
  105320. 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 */
  105321. #endif
  105322. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105323. if(rice_parameter >= rice_parameter_limit) {
  105324. #ifdef DEBUG_VERBOSE
  105325. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105326. #endif
  105327. rice_parameter = rice_parameter_limit - 1;
  105328. }
  105329. _candidate_bits =
  105330. evaluate_fixed_subframe_(
  105331. encoder,
  105332. integer_signal,
  105333. residual[!_best_subframe],
  105334. encoder->private_->abs_residual_partition_sums,
  105335. encoder->private_->raw_bits_per_partition,
  105336. frame_header->blocksize,
  105337. subframe_bps,
  105338. fixed_order,
  105339. rice_parameter,
  105340. rice_parameter_limit,
  105341. min_partition_order,
  105342. max_partition_order,
  105343. encoder->protected_->do_escape_coding,
  105344. encoder->protected_->rice_parameter_search_dist,
  105345. subframe[!_best_subframe],
  105346. partitioned_rice_contents[!_best_subframe]
  105347. );
  105348. if(_candidate_bits < _best_bits) {
  105349. _best_subframe = !_best_subframe;
  105350. _best_bits = _candidate_bits;
  105351. }
  105352. }
  105353. }
  105354. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105355. /* encode lpc */
  105356. if(encoder->protected_->max_lpc_order > 0) {
  105357. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105358. max_lpc_order = frame_header->blocksize-1;
  105359. else
  105360. max_lpc_order = encoder->protected_->max_lpc_order;
  105361. if(max_lpc_order > 0) {
  105362. unsigned a;
  105363. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105364. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105365. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105366. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105367. if(autoc[0] != 0.0) {
  105368. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105369. if(encoder->protected_->do_exhaustive_model_search) {
  105370. min_lpc_order = 1;
  105371. }
  105372. else {
  105373. const unsigned guess_lpc_order =
  105374. FLAC__lpc_compute_best_order(
  105375. lpc_error,
  105376. max_lpc_order,
  105377. frame_header->blocksize,
  105378. subframe_bps + (
  105379. encoder->protected_->do_qlp_coeff_prec_search?
  105380. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105381. encoder->protected_->qlp_coeff_precision
  105382. )
  105383. );
  105384. min_lpc_order = max_lpc_order = guess_lpc_order;
  105385. }
  105386. if(max_lpc_order >= frame_header->blocksize)
  105387. max_lpc_order = frame_header->blocksize - 1;
  105388. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105389. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105390. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105391. continue; /* don't even try */
  105392. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105393. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105394. if(rice_parameter >= rice_parameter_limit) {
  105395. #ifdef DEBUG_VERBOSE
  105396. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105397. #endif
  105398. rice_parameter = rice_parameter_limit - 1;
  105399. }
  105400. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105401. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105402. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105403. if(subframe_bps <= 17) {
  105404. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105405. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105406. }
  105407. else
  105408. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105409. }
  105410. else {
  105411. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105412. }
  105413. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105414. _candidate_bits =
  105415. evaluate_lpc_subframe_(
  105416. encoder,
  105417. integer_signal,
  105418. residual[!_best_subframe],
  105419. encoder->private_->abs_residual_partition_sums,
  105420. encoder->private_->raw_bits_per_partition,
  105421. encoder->private_->lp_coeff[lpc_order-1],
  105422. frame_header->blocksize,
  105423. subframe_bps,
  105424. lpc_order,
  105425. qlp_coeff_precision,
  105426. rice_parameter,
  105427. rice_parameter_limit,
  105428. min_partition_order,
  105429. max_partition_order,
  105430. encoder->protected_->do_escape_coding,
  105431. encoder->protected_->rice_parameter_search_dist,
  105432. subframe[!_best_subframe],
  105433. partitioned_rice_contents[!_best_subframe]
  105434. );
  105435. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105436. if(_candidate_bits < _best_bits) {
  105437. _best_subframe = !_best_subframe;
  105438. _best_bits = _candidate_bits;
  105439. }
  105440. }
  105441. }
  105442. }
  105443. }
  105444. }
  105445. }
  105446. }
  105447. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105448. }
  105449. }
  105450. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105451. if(_best_bits == UINT_MAX) {
  105452. FLAC__ASSERT(_best_subframe == 0);
  105453. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105454. }
  105455. *best_subframe = _best_subframe;
  105456. *best_bits = _best_bits;
  105457. return true;
  105458. }
  105459. FLAC__bool add_subframe_(
  105460. FLAC__StreamEncoder *encoder,
  105461. unsigned blocksize,
  105462. unsigned subframe_bps,
  105463. const FLAC__Subframe *subframe,
  105464. FLAC__BitWriter *frame
  105465. )
  105466. {
  105467. switch(subframe->type) {
  105468. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105469. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105470. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105471. return false;
  105472. }
  105473. break;
  105474. case FLAC__SUBFRAME_TYPE_FIXED:
  105475. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105476. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105477. return false;
  105478. }
  105479. break;
  105480. case FLAC__SUBFRAME_TYPE_LPC:
  105481. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105482. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105483. return false;
  105484. }
  105485. break;
  105486. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105487. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105488. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105489. return false;
  105490. }
  105491. break;
  105492. default:
  105493. FLAC__ASSERT(0);
  105494. }
  105495. return true;
  105496. }
  105497. #define SPOTCHECK_ESTIMATE 0
  105498. #if SPOTCHECK_ESTIMATE
  105499. static void spotcheck_subframe_estimate_(
  105500. FLAC__StreamEncoder *encoder,
  105501. unsigned blocksize,
  105502. unsigned subframe_bps,
  105503. const FLAC__Subframe *subframe,
  105504. unsigned estimate
  105505. )
  105506. {
  105507. FLAC__bool ret;
  105508. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105509. if(frame == 0) {
  105510. fprintf(stderr, "EST: can't allocate frame\n");
  105511. return;
  105512. }
  105513. if(!FLAC__bitwriter_init(frame)) {
  105514. fprintf(stderr, "EST: can't init frame\n");
  105515. return;
  105516. }
  105517. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105518. FLAC__ASSERT(ret);
  105519. {
  105520. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105521. if(estimate != actual)
  105522. 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);
  105523. }
  105524. FLAC__bitwriter_delete(frame);
  105525. }
  105526. #endif
  105527. unsigned evaluate_constant_subframe_(
  105528. FLAC__StreamEncoder *encoder,
  105529. const FLAC__int32 signal,
  105530. unsigned blocksize,
  105531. unsigned subframe_bps,
  105532. FLAC__Subframe *subframe
  105533. )
  105534. {
  105535. unsigned estimate;
  105536. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105537. subframe->data.constant.value = signal;
  105538. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105539. #if SPOTCHECK_ESTIMATE
  105540. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105541. #else
  105542. (void)encoder, (void)blocksize;
  105543. #endif
  105544. return estimate;
  105545. }
  105546. unsigned evaluate_fixed_subframe_(
  105547. FLAC__StreamEncoder *encoder,
  105548. const FLAC__int32 signal[],
  105549. FLAC__int32 residual[],
  105550. FLAC__uint64 abs_residual_partition_sums[],
  105551. unsigned raw_bits_per_partition[],
  105552. unsigned blocksize,
  105553. unsigned subframe_bps,
  105554. unsigned order,
  105555. unsigned rice_parameter,
  105556. unsigned rice_parameter_limit,
  105557. unsigned min_partition_order,
  105558. unsigned max_partition_order,
  105559. FLAC__bool do_escape_coding,
  105560. unsigned rice_parameter_search_dist,
  105561. FLAC__Subframe *subframe,
  105562. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105563. )
  105564. {
  105565. unsigned i, residual_bits, estimate;
  105566. const unsigned residual_samples = blocksize - order;
  105567. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105568. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105569. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105570. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105571. subframe->data.fixed.residual = residual;
  105572. residual_bits =
  105573. find_best_partition_order_(
  105574. encoder->private_,
  105575. residual,
  105576. abs_residual_partition_sums,
  105577. raw_bits_per_partition,
  105578. residual_samples,
  105579. order,
  105580. rice_parameter,
  105581. rice_parameter_limit,
  105582. min_partition_order,
  105583. max_partition_order,
  105584. subframe_bps,
  105585. do_escape_coding,
  105586. rice_parameter_search_dist,
  105587. &subframe->data.fixed.entropy_coding_method
  105588. );
  105589. subframe->data.fixed.order = order;
  105590. for(i = 0; i < order; i++)
  105591. subframe->data.fixed.warmup[i] = signal[i];
  105592. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105593. #if SPOTCHECK_ESTIMATE
  105594. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105595. #endif
  105596. return estimate;
  105597. }
  105598. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105599. unsigned evaluate_lpc_subframe_(
  105600. FLAC__StreamEncoder *encoder,
  105601. const FLAC__int32 signal[],
  105602. FLAC__int32 residual[],
  105603. FLAC__uint64 abs_residual_partition_sums[],
  105604. unsigned raw_bits_per_partition[],
  105605. const FLAC__real lp_coeff[],
  105606. unsigned blocksize,
  105607. unsigned subframe_bps,
  105608. unsigned order,
  105609. unsigned qlp_coeff_precision,
  105610. unsigned rice_parameter,
  105611. unsigned rice_parameter_limit,
  105612. unsigned min_partition_order,
  105613. unsigned max_partition_order,
  105614. FLAC__bool do_escape_coding,
  105615. unsigned rice_parameter_search_dist,
  105616. FLAC__Subframe *subframe,
  105617. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105618. )
  105619. {
  105620. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105621. unsigned i, residual_bits, estimate;
  105622. int quantization, ret;
  105623. const unsigned residual_samples = blocksize - order;
  105624. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105625. if(subframe_bps <= 16) {
  105626. FLAC__ASSERT(order > 0);
  105627. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105628. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105629. }
  105630. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105631. if(ret != 0)
  105632. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105633. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105634. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105635. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105636. else
  105637. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105638. else
  105639. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105640. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105641. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105642. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105643. subframe->data.lpc.residual = residual;
  105644. residual_bits =
  105645. find_best_partition_order_(
  105646. encoder->private_,
  105647. residual,
  105648. abs_residual_partition_sums,
  105649. raw_bits_per_partition,
  105650. residual_samples,
  105651. order,
  105652. rice_parameter,
  105653. rice_parameter_limit,
  105654. min_partition_order,
  105655. max_partition_order,
  105656. subframe_bps,
  105657. do_escape_coding,
  105658. rice_parameter_search_dist,
  105659. &subframe->data.lpc.entropy_coding_method
  105660. );
  105661. subframe->data.lpc.order = order;
  105662. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105663. subframe->data.lpc.quantization_level = quantization;
  105664. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105665. for(i = 0; i < order; i++)
  105666. subframe->data.lpc.warmup[i] = signal[i];
  105667. 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;
  105668. #if SPOTCHECK_ESTIMATE
  105669. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105670. #endif
  105671. return estimate;
  105672. }
  105673. #endif
  105674. unsigned evaluate_verbatim_subframe_(
  105675. FLAC__StreamEncoder *encoder,
  105676. const FLAC__int32 signal[],
  105677. unsigned blocksize,
  105678. unsigned subframe_bps,
  105679. FLAC__Subframe *subframe
  105680. )
  105681. {
  105682. unsigned estimate;
  105683. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105684. subframe->data.verbatim.data = signal;
  105685. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105686. #if SPOTCHECK_ESTIMATE
  105687. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105688. #else
  105689. (void)encoder;
  105690. #endif
  105691. return estimate;
  105692. }
  105693. unsigned find_best_partition_order_(
  105694. FLAC__StreamEncoderPrivate *private_,
  105695. const FLAC__int32 residual[],
  105696. FLAC__uint64 abs_residual_partition_sums[],
  105697. unsigned raw_bits_per_partition[],
  105698. unsigned residual_samples,
  105699. unsigned predictor_order,
  105700. unsigned rice_parameter,
  105701. unsigned rice_parameter_limit,
  105702. unsigned min_partition_order,
  105703. unsigned max_partition_order,
  105704. unsigned bps,
  105705. FLAC__bool do_escape_coding,
  105706. unsigned rice_parameter_search_dist,
  105707. FLAC__EntropyCodingMethod *best_ecm
  105708. )
  105709. {
  105710. unsigned residual_bits, best_residual_bits = 0;
  105711. unsigned best_parameters_index = 0;
  105712. unsigned best_partition_order = 0;
  105713. const unsigned blocksize = residual_samples + predictor_order;
  105714. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105715. min_partition_order = min(min_partition_order, max_partition_order);
  105716. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105717. if(do_escape_coding)
  105718. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105719. {
  105720. int partition_order;
  105721. unsigned sum;
  105722. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105723. if(!
  105724. set_partitioned_rice_(
  105725. #ifdef EXACT_RICE_BITS_CALCULATION
  105726. residual,
  105727. #endif
  105728. abs_residual_partition_sums+sum,
  105729. raw_bits_per_partition+sum,
  105730. residual_samples,
  105731. predictor_order,
  105732. rice_parameter,
  105733. rice_parameter_limit,
  105734. rice_parameter_search_dist,
  105735. (unsigned)partition_order,
  105736. do_escape_coding,
  105737. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105738. &residual_bits
  105739. )
  105740. )
  105741. {
  105742. FLAC__ASSERT(best_residual_bits != 0);
  105743. break;
  105744. }
  105745. sum += 1u << partition_order;
  105746. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105747. best_residual_bits = residual_bits;
  105748. best_parameters_index = !best_parameters_index;
  105749. best_partition_order = partition_order;
  105750. }
  105751. }
  105752. }
  105753. best_ecm->data.partitioned_rice.order = best_partition_order;
  105754. {
  105755. /*
  105756. * We are allowed to de-const the pointer based on our special
  105757. * knowledge; it is const to the outside world.
  105758. */
  105759. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105760. unsigned partition;
  105761. /* save best parameters and raw_bits */
  105762. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105763. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105764. if(do_escape_coding)
  105765. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105766. /*
  105767. * Now need to check if the type should be changed to
  105768. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105769. * size of the rice parameters.
  105770. */
  105771. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105772. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105773. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105774. break;
  105775. }
  105776. }
  105777. }
  105778. return best_residual_bits;
  105779. }
  105780. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105781. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105782. const FLAC__int32 residual[],
  105783. FLAC__uint64 abs_residual_partition_sums[],
  105784. unsigned blocksize,
  105785. unsigned predictor_order,
  105786. unsigned min_partition_order,
  105787. unsigned max_partition_order
  105788. );
  105789. #endif
  105790. void precompute_partition_info_sums_(
  105791. const FLAC__int32 residual[],
  105792. FLAC__uint64 abs_residual_partition_sums[],
  105793. unsigned residual_samples,
  105794. unsigned predictor_order,
  105795. unsigned min_partition_order,
  105796. unsigned max_partition_order,
  105797. unsigned bps
  105798. )
  105799. {
  105800. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105801. unsigned partitions = 1u << max_partition_order;
  105802. FLAC__ASSERT(default_partition_samples > predictor_order);
  105803. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105804. /* slightly pessimistic but still catches all common cases */
  105805. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105806. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105807. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105808. return;
  105809. }
  105810. #endif
  105811. /* first do max_partition_order */
  105812. {
  105813. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105814. /* slightly pessimistic but still catches all common cases */
  105815. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105816. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105817. FLAC__uint32 abs_residual_partition_sum;
  105818. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105819. end += default_partition_samples;
  105820. abs_residual_partition_sum = 0;
  105821. for( ; residual_sample < end; residual_sample++)
  105822. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105823. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105824. }
  105825. }
  105826. else { /* have to pessimistically use 64 bits for accumulator */
  105827. FLAC__uint64 abs_residual_partition_sum;
  105828. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105829. end += default_partition_samples;
  105830. abs_residual_partition_sum = 0;
  105831. for( ; residual_sample < end; residual_sample++)
  105832. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105833. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105834. }
  105835. }
  105836. }
  105837. /* now merge partitions for lower orders */
  105838. {
  105839. unsigned from_partition = 0, to_partition = partitions;
  105840. int partition_order;
  105841. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105842. unsigned i;
  105843. partitions >>= 1;
  105844. for(i = 0; i < partitions; i++) {
  105845. abs_residual_partition_sums[to_partition++] =
  105846. abs_residual_partition_sums[from_partition ] +
  105847. abs_residual_partition_sums[from_partition+1];
  105848. from_partition += 2;
  105849. }
  105850. }
  105851. }
  105852. }
  105853. void precompute_partition_info_escapes_(
  105854. const FLAC__int32 residual[],
  105855. unsigned raw_bits_per_partition[],
  105856. unsigned residual_samples,
  105857. unsigned predictor_order,
  105858. unsigned min_partition_order,
  105859. unsigned max_partition_order
  105860. )
  105861. {
  105862. int partition_order;
  105863. unsigned from_partition, to_partition = 0;
  105864. const unsigned blocksize = residual_samples + predictor_order;
  105865. /* first do max_partition_order */
  105866. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105867. FLAC__int32 r;
  105868. FLAC__uint32 rmax;
  105869. unsigned partition, partition_sample, partition_samples, residual_sample;
  105870. const unsigned partitions = 1u << partition_order;
  105871. const unsigned default_partition_samples = blocksize >> partition_order;
  105872. FLAC__ASSERT(default_partition_samples > predictor_order);
  105873. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105874. partition_samples = default_partition_samples;
  105875. if(partition == 0)
  105876. partition_samples -= predictor_order;
  105877. rmax = 0;
  105878. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105879. r = residual[residual_sample++];
  105880. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105881. if(r < 0)
  105882. rmax |= ~r;
  105883. else
  105884. rmax |= r;
  105885. }
  105886. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105887. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105888. }
  105889. to_partition = partitions;
  105890. break; /*@@@ yuck, should remove the 'for' loop instead */
  105891. }
  105892. /* now merge partitions for lower orders */
  105893. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105894. unsigned m;
  105895. unsigned i;
  105896. const unsigned partitions = 1u << partition_order;
  105897. for(i = 0; i < partitions; i++) {
  105898. m = raw_bits_per_partition[from_partition];
  105899. from_partition++;
  105900. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105901. from_partition++;
  105902. to_partition++;
  105903. }
  105904. }
  105905. }
  105906. #ifdef EXACT_RICE_BITS_CALCULATION
  105907. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105908. const unsigned rice_parameter,
  105909. const unsigned partition_samples,
  105910. const FLAC__int32 *residual
  105911. )
  105912. {
  105913. unsigned i, partition_bits =
  105914. 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 */
  105915. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105916. ;
  105917. for(i = 0; i < partition_samples; i++)
  105918. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105919. return partition_bits;
  105920. }
  105921. #else
  105922. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105923. const unsigned rice_parameter,
  105924. const unsigned partition_samples,
  105925. const FLAC__uint64 abs_residual_partition_sum
  105926. )
  105927. {
  105928. return
  105929. 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 */
  105930. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105931. (
  105932. rice_parameter?
  105933. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105934. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105935. )
  105936. - (partition_samples >> 1)
  105937. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105938. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105939. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105940. * So the subtraction term tries to guess how many extra bits were contributed.
  105941. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105942. */
  105943. ;
  105944. }
  105945. #endif
  105946. FLAC__bool set_partitioned_rice_(
  105947. #ifdef EXACT_RICE_BITS_CALCULATION
  105948. const FLAC__int32 residual[],
  105949. #endif
  105950. const FLAC__uint64 abs_residual_partition_sums[],
  105951. const unsigned raw_bits_per_partition[],
  105952. const unsigned residual_samples,
  105953. const unsigned predictor_order,
  105954. const unsigned suggested_rice_parameter,
  105955. const unsigned rice_parameter_limit,
  105956. const unsigned rice_parameter_search_dist,
  105957. const unsigned partition_order,
  105958. const FLAC__bool search_for_escapes,
  105959. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105960. unsigned *bits
  105961. )
  105962. {
  105963. unsigned rice_parameter, partition_bits;
  105964. unsigned best_partition_bits, best_rice_parameter = 0;
  105965. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105966. unsigned *parameters, *raw_bits;
  105967. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105968. unsigned min_rice_parameter, max_rice_parameter;
  105969. #else
  105970. (void)rice_parameter_search_dist;
  105971. #endif
  105972. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105973. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105974. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105975. parameters = partitioned_rice_contents->parameters;
  105976. raw_bits = partitioned_rice_contents->raw_bits;
  105977. if(partition_order == 0) {
  105978. best_partition_bits = (unsigned)(-1);
  105979. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105980. if(rice_parameter_search_dist) {
  105981. if(suggested_rice_parameter < rice_parameter_search_dist)
  105982. min_rice_parameter = 0;
  105983. else
  105984. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105985. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105986. if(max_rice_parameter >= rice_parameter_limit) {
  105987. #ifdef DEBUG_VERBOSE
  105988. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105989. #endif
  105990. max_rice_parameter = rice_parameter_limit - 1;
  105991. }
  105992. }
  105993. else
  105994. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105995. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105996. #else
  105997. rice_parameter = suggested_rice_parameter;
  105998. #endif
  105999. #ifdef EXACT_RICE_BITS_CALCULATION
  106000. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  106001. #else
  106002. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  106003. #endif
  106004. if(partition_bits < best_partition_bits) {
  106005. best_rice_parameter = rice_parameter;
  106006. best_partition_bits = partition_bits;
  106007. }
  106008. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106009. }
  106010. #endif
  106011. if(search_for_escapes) {
  106012. 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;
  106013. if(partition_bits <= best_partition_bits) {
  106014. raw_bits[0] = raw_bits_per_partition[0];
  106015. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106016. best_partition_bits = partition_bits;
  106017. }
  106018. else
  106019. raw_bits[0] = 0;
  106020. }
  106021. parameters[0] = best_rice_parameter;
  106022. bits_ += best_partition_bits;
  106023. }
  106024. else {
  106025. unsigned partition, residual_sample;
  106026. unsigned partition_samples;
  106027. FLAC__uint64 mean, k;
  106028. const unsigned partitions = 1u << partition_order;
  106029. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106030. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106031. if(partition == 0) {
  106032. if(partition_samples <= predictor_order)
  106033. return false;
  106034. else
  106035. partition_samples -= predictor_order;
  106036. }
  106037. mean = abs_residual_partition_sums[partition];
  106038. /* we are basically calculating the size in bits of the
  106039. * average residual magnitude in the partition:
  106040. * rice_parameter = floor(log2(mean/partition_samples))
  106041. * 'mean' is not a good name for the variable, it is
  106042. * actually the sum of magnitudes of all residual values
  106043. * in the partition, so the actual mean is
  106044. * mean/partition_samples
  106045. */
  106046. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106047. ;
  106048. if(rice_parameter >= rice_parameter_limit) {
  106049. #ifdef DEBUG_VERBOSE
  106050. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106051. #endif
  106052. rice_parameter = rice_parameter_limit - 1;
  106053. }
  106054. best_partition_bits = (unsigned)(-1);
  106055. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106056. if(rice_parameter_search_dist) {
  106057. if(rice_parameter < rice_parameter_search_dist)
  106058. min_rice_parameter = 0;
  106059. else
  106060. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106061. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106062. if(max_rice_parameter >= rice_parameter_limit) {
  106063. #ifdef DEBUG_VERBOSE
  106064. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106065. #endif
  106066. max_rice_parameter = rice_parameter_limit - 1;
  106067. }
  106068. }
  106069. else
  106070. min_rice_parameter = max_rice_parameter = rice_parameter;
  106071. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106072. #endif
  106073. #ifdef EXACT_RICE_BITS_CALCULATION
  106074. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106075. #else
  106076. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106077. #endif
  106078. if(partition_bits < best_partition_bits) {
  106079. best_rice_parameter = rice_parameter;
  106080. best_partition_bits = partition_bits;
  106081. }
  106082. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106083. }
  106084. #endif
  106085. if(search_for_escapes) {
  106086. 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;
  106087. if(partition_bits <= best_partition_bits) {
  106088. raw_bits[partition] = raw_bits_per_partition[partition];
  106089. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106090. best_partition_bits = partition_bits;
  106091. }
  106092. else
  106093. raw_bits[partition] = 0;
  106094. }
  106095. parameters[partition] = best_rice_parameter;
  106096. bits_ += best_partition_bits;
  106097. residual_sample += partition_samples;
  106098. }
  106099. }
  106100. *bits = bits_;
  106101. return true;
  106102. }
  106103. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106104. {
  106105. unsigned i, shift;
  106106. FLAC__int32 x = 0;
  106107. for(i = 0; i < samples && !(x&1); i++)
  106108. x |= signal[i];
  106109. if(x == 0) {
  106110. shift = 0;
  106111. }
  106112. else {
  106113. for(shift = 0; !(x&1); shift++)
  106114. x >>= 1;
  106115. }
  106116. if(shift > 0) {
  106117. for(i = 0; i < samples; i++)
  106118. signal[i] >>= shift;
  106119. }
  106120. return shift;
  106121. }
  106122. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106123. {
  106124. unsigned channel;
  106125. for(channel = 0; channel < channels; channel++)
  106126. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106127. fifo->tail += wide_samples;
  106128. FLAC__ASSERT(fifo->tail <= fifo->size);
  106129. }
  106130. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106131. {
  106132. unsigned channel;
  106133. unsigned sample, wide_sample;
  106134. unsigned tail = fifo->tail;
  106135. sample = input_offset * channels;
  106136. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106137. for(channel = 0; channel < channels; channel++)
  106138. fifo->data[channel][tail] = input[sample++];
  106139. tail++;
  106140. }
  106141. fifo->tail = tail;
  106142. FLAC__ASSERT(fifo->tail <= fifo->size);
  106143. }
  106144. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106145. {
  106146. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106147. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106148. (void)decoder;
  106149. if(encoder->private_->verify.needs_magic_hack) {
  106150. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106151. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106152. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106153. encoder->private_->verify.needs_magic_hack = false;
  106154. }
  106155. else {
  106156. if(encoded_bytes == 0) {
  106157. /*
  106158. * If we get here, a FIFO underflow has occurred,
  106159. * which means there is a bug somewhere.
  106160. */
  106161. FLAC__ASSERT(0);
  106162. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106163. }
  106164. else if(encoded_bytes < *bytes)
  106165. *bytes = encoded_bytes;
  106166. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106167. encoder->private_->verify.output.data += *bytes;
  106168. encoder->private_->verify.output.bytes -= *bytes;
  106169. }
  106170. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106171. }
  106172. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106173. {
  106174. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106175. unsigned channel;
  106176. const unsigned channels = frame->header.channels;
  106177. const unsigned blocksize = frame->header.blocksize;
  106178. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106179. (void)decoder;
  106180. for(channel = 0; channel < channels; channel++) {
  106181. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106182. unsigned i, sample = 0;
  106183. FLAC__int32 expect = 0, got = 0;
  106184. for(i = 0; i < blocksize; i++) {
  106185. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106186. sample = i;
  106187. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106188. got = (FLAC__int32)buffer[channel][i];
  106189. break;
  106190. }
  106191. }
  106192. FLAC__ASSERT(i < blocksize);
  106193. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106194. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106195. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106196. encoder->private_->verify.error_stats.channel = channel;
  106197. encoder->private_->verify.error_stats.sample = sample;
  106198. encoder->private_->verify.error_stats.expected = expect;
  106199. encoder->private_->verify.error_stats.got = got;
  106200. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106201. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106202. }
  106203. }
  106204. /* dequeue the frame from the fifo */
  106205. encoder->private_->verify.input_fifo.tail -= blocksize;
  106206. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106207. for(channel = 0; channel < channels; channel++)
  106208. 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]));
  106209. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106210. }
  106211. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106212. {
  106213. (void)decoder, (void)metadata, (void)client_data;
  106214. }
  106215. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106216. {
  106217. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106218. (void)decoder, (void)status;
  106219. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106220. }
  106221. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106222. {
  106223. (void)client_data;
  106224. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106225. if (*bytes == 0) {
  106226. if (feof(encoder->private_->file))
  106227. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106228. else if (ferror(encoder->private_->file))
  106229. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106230. }
  106231. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106232. }
  106233. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106234. {
  106235. (void)client_data;
  106236. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106237. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106238. else
  106239. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106240. }
  106241. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106242. {
  106243. off_t offset;
  106244. (void)client_data;
  106245. offset = ftello(encoder->private_->file);
  106246. if(offset < 0) {
  106247. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106248. }
  106249. else {
  106250. *absolute_byte_offset = (FLAC__uint64)offset;
  106251. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106252. }
  106253. }
  106254. #ifdef FLAC__VALGRIND_TESTING
  106255. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106256. {
  106257. size_t ret = fwrite(ptr, size, nmemb, stream);
  106258. if(!ferror(stream))
  106259. fflush(stream);
  106260. return ret;
  106261. }
  106262. #else
  106263. #define local__fwrite fwrite
  106264. #endif
  106265. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106266. {
  106267. (void)client_data, (void)current_frame;
  106268. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106269. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106270. #if FLAC__HAS_OGG
  106271. /* We would like to be able to use 'samples > 0' in the
  106272. * clause here but currently because of the nature of our
  106273. * Ogg writing implementation, 'samples' is always 0 (see
  106274. * ogg_encoder_aspect.c). The downside is extra progress
  106275. * callbacks.
  106276. */
  106277. encoder->private_->is_ogg? true :
  106278. #endif
  106279. samples > 0
  106280. );
  106281. if(call_it) {
  106282. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106283. * because at this point in the callback chain, the stats
  106284. * have not been updated. Only after we return and control
  106285. * gets back to write_frame_() are the stats updated
  106286. */
  106287. 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);
  106288. }
  106289. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106290. }
  106291. else
  106292. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106293. }
  106294. /*
  106295. * This will forcibly set stdout to binary mode (for OSes that require it)
  106296. */
  106297. FILE *get_binary_stdout_(void)
  106298. {
  106299. /* if something breaks here it is probably due to the presence or
  106300. * absence of an underscore before the identifiers 'setmode',
  106301. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106302. */
  106303. #if defined _MSC_VER || defined __MINGW32__
  106304. _setmode(_fileno(stdout), _O_BINARY);
  106305. #elif defined __CYGWIN__
  106306. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106307. setmode(_fileno(stdout), _O_BINARY);
  106308. #elif defined __EMX__
  106309. setmode(fileno(stdout), O_BINARY);
  106310. #endif
  106311. return stdout;
  106312. }
  106313. #endif
  106314. /*** End of inlined file: stream_encoder.c ***/
  106315. /*** Start of inlined file: stream_encoder_framing.c ***/
  106316. /*** Start of inlined file: juce_FlacHeader.h ***/
  106317. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106318. // tasks..
  106319. #define VERSION "1.2.1"
  106320. #define FLAC__NO_DLL 1
  106321. #if JUCE_MSVC
  106322. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106323. #endif
  106324. #if JUCE_MAC
  106325. #define FLAC__SYS_DARWIN 1
  106326. #endif
  106327. /*** End of inlined file: juce_FlacHeader.h ***/
  106328. #if JUCE_USE_FLAC
  106329. #if HAVE_CONFIG_H
  106330. # include <config.h>
  106331. #endif
  106332. #include <stdio.h>
  106333. #include <string.h> /* for strlen() */
  106334. #ifdef max
  106335. #undef max
  106336. #endif
  106337. #define max(x,y) ((x)>(y)?(x):(y))
  106338. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106339. 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);
  106340. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106341. {
  106342. unsigned i, j;
  106343. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106344. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106345. return false;
  106346. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106347. return false;
  106348. /*
  106349. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106350. */
  106351. i = metadata->length;
  106352. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106353. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106354. i -= metadata->data.vorbis_comment.vendor_string.length;
  106355. i += vendor_string_length;
  106356. }
  106357. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106358. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106359. return false;
  106360. switch(metadata->type) {
  106361. case FLAC__METADATA_TYPE_STREAMINFO:
  106362. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106363. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106364. return false;
  106365. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106366. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106367. return false;
  106368. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106369. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106370. return false;
  106371. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106372. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106373. return false;
  106374. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106375. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106376. return false;
  106377. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106378. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106379. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106380. return false;
  106381. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106382. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106383. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106384. return false;
  106385. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106386. return false;
  106387. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106388. return false;
  106389. break;
  106390. case FLAC__METADATA_TYPE_PADDING:
  106391. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106392. return false;
  106393. break;
  106394. case FLAC__METADATA_TYPE_APPLICATION:
  106395. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106396. return false;
  106397. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106398. return false;
  106399. break;
  106400. case FLAC__METADATA_TYPE_SEEKTABLE:
  106401. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106402. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106403. return false;
  106404. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106405. return false;
  106406. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106407. return false;
  106408. }
  106409. break;
  106410. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106411. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106412. return false;
  106413. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106414. return false;
  106415. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106416. return false;
  106417. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106418. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106419. return false;
  106420. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106421. return false;
  106422. }
  106423. break;
  106424. case FLAC__METADATA_TYPE_CUESHEET:
  106425. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106426. 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))
  106427. return false;
  106428. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106429. return false;
  106430. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106431. return false;
  106432. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106433. return false;
  106434. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106435. return false;
  106436. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106437. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106438. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106439. return false;
  106440. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106441. return false;
  106442. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106443. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106444. return false;
  106445. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106446. return false;
  106447. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106448. return false;
  106449. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106450. return false;
  106451. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106452. return false;
  106453. for(j = 0; j < track->num_indices; j++) {
  106454. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106455. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106456. return false;
  106457. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106458. return false;
  106459. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106460. return false;
  106461. }
  106462. }
  106463. break;
  106464. case FLAC__METADATA_TYPE_PICTURE:
  106465. {
  106466. size_t len;
  106467. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106468. return false;
  106469. len = strlen(metadata->data.picture.mime_type);
  106470. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106471. return false;
  106472. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106473. return false;
  106474. len = strlen((const char *)metadata->data.picture.description);
  106475. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106476. return false;
  106477. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106478. return false;
  106479. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106480. return false;
  106481. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106482. return false;
  106483. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106484. return false;
  106485. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106486. return false;
  106487. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106488. return false;
  106489. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106490. return false;
  106491. }
  106492. break;
  106493. default:
  106494. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106495. return false;
  106496. break;
  106497. }
  106498. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106499. return true;
  106500. }
  106501. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106502. {
  106503. unsigned u, blocksize_hint, sample_rate_hint;
  106504. FLAC__byte crc;
  106505. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106506. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106507. return false;
  106508. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106509. return false;
  106510. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106511. return false;
  106512. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106513. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106514. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106515. blocksize_hint = 0;
  106516. switch(header->blocksize) {
  106517. case 192: u = 1; break;
  106518. case 576: u = 2; break;
  106519. case 1152: u = 3; break;
  106520. case 2304: u = 4; break;
  106521. case 4608: u = 5; break;
  106522. case 256: u = 8; break;
  106523. case 512: u = 9; break;
  106524. case 1024: u = 10; break;
  106525. case 2048: u = 11; break;
  106526. case 4096: u = 12; break;
  106527. case 8192: u = 13; break;
  106528. case 16384: u = 14; break;
  106529. case 32768: u = 15; break;
  106530. default:
  106531. if(header->blocksize <= 0x100)
  106532. blocksize_hint = u = 6;
  106533. else
  106534. blocksize_hint = u = 7;
  106535. break;
  106536. }
  106537. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106538. return false;
  106539. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106540. sample_rate_hint = 0;
  106541. switch(header->sample_rate) {
  106542. case 88200: u = 1; break;
  106543. case 176400: u = 2; break;
  106544. case 192000: u = 3; break;
  106545. case 8000: u = 4; break;
  106546. case 16000: u = 5; break;
  106547. case 22050: u = 6; break;
  106548. case 24000: u = 7; break;
  106549. case 32000: u = 8; break;
  106550. case 44100: u = 9; break;
  106551. case 48000: u = 10; break;
  106552. case 96000: u = 11; break;
  106553. default:
  106554. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106555. sample_rate_hint = u = 12;
  106556. else if(header->sample_rate % 10 == 0)
  106557. sample_rate_hint = u = 14;
  106558. else if(header->sample_rate <= 0xffff)
  106559. sample_rate_hint = u = 13;
  106560. else
  106561. u = 0;
  106562. break;
  106563. }
  106564. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106565. return false;
  106566. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106567. switch(header->channel_assignment) {
  106568. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106569. u = header->channels - 1;
  106570. break;
  106571. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106572. FLAC__ASSERT(header->channels == 2);
  106573. u = 8;
  106574. break;
  106575. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106576. FLAC__ASSERT(header->channels == 2);
  106577. u = 9;
  106578. break;
  106579. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106580. FLAC__ASSERT(header->channels == 2);
  106581. u = 10;
  106582. break;
  106583. default:
  106584. FLAC__ASSERT(0);
  106585. }
  106586. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106587. return false;
  106588. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106589. switch(header->bits_per_sample) {
  106590. case 8 : u = 1; break;
  106591. case 12: u = 2; break;
  106592. case 16: u = 4; break;
  106593. case 20: u = 5; break;
  106594. case 24: u = 6; break;
  106595. default: u = 0; break;
  106596. }
  106597. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106598. return false;
  106599. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106600. return false;
  106601. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106602. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106603. return false;
  106604. }
  106605. else {
  106606. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106607. return false;
  106608. }
  106609. if(blocksize_hint)
  106610. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106611. return false;
  106612. switch(sample_rate_hint) {
  106613. case 12:
  106614. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106615. return false;
  106616. break;
  106617. case 13:
  106618. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106619. return false;
  106620. break;
  106621. case 14:
  106622. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106623. return false;
  106624. break;
  106625. }
  106626. /* write the CRC */
  106627. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106628. return false;
  106629. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106630. return false;
  106631. return true;
  106632. }
  106633. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106634. {
  106635. FLAC__bool ok;
  106636. ok =
  106637. 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) &&
  106638. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106639. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106640. ;
  106641. return ok;
  106642. }
  106643. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106644. {
  106645. unsigned i;
  106646. 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))
  106647. return false;
  106648. if(wasted_bits)
  106649. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106650. return false;
  106651. for(i = 0; i < subframe->order; i++)
  106652. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106653. return false;
  106654. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106655. return false;
  106656. switch(subframe->entropy_coding_method.type) {
  106657. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106658. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106659. if(!add_residual_partitioned_rice_(
  106660. bw,
  106661. subframe->residual,
  106662. residual_samples,
  106663. subframe->order,
  106664. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106665. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106666. subframe->entropy_coding_method.data.partitioned_rice.order,
  106667. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106668. ))
  106669. return false;
  106670. break;
  106671. default:
  106672. FLAC__ASSERT(0);
  106673. }
  106674. return true;
  106675. }
  106676. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106677. {
  106678. unsigned i;
  106679. 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))
  106680. return false;
  106681. if(wasted_bits)
  106682. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106683. return false;
  106684. for(i = 0; i < subframe->order; i++)
  106685. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106686. return false;
  106687. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106688. return false;
  106689. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106690. return false;
  106691. for(i = 0; i < subframe->order; i++)
  106692. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106693. return false;
  106694. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106695. return false;
  106696. switch(subframe->entropy_coding_method.type) {
  106697. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106698. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106699. if(!add_residual_partitioned_rice_(
  106700. bw,
  106701. subframe->residual,
  106702. residual_samples,
  106703. subframe->order,
  106704. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106705. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106706. subframe->entropy_coding_method.data.partitioned_rice.order,
  106707. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106708. ))
  106709. return false;
  106710. break;
  106711. default:
  106712. FLAC__ASSERT(0);
  106713. }
  106714. return true;
  106715. }
  106716. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106717. {
  106718. unsigned i;
  106719. const FLAC__int32 *signal = subframe->data;
  106720. 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))
  106721. return false;
  106722. if(wasted_bits)
  106723. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106724. return false;
  106725. for(i = 0; i < samples; i++)
  106726. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106727. return false;
  106728. return true;
  106729. }
  106730. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106731. {
  106732. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106733. return false;
  106734. switch(method->type) {
  106735. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106736. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106737. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106738. return false;
  106739. break;
  106740. default:
  106741. FLAC__ASSERT(0);
  106742. }
  106743. return true;
  106744. }
  106745. 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)
  106746. {
  106747. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106748. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106749. if(partition_order == 0) {
  106750. unsigned i;
  106751. if(raw_bits[0] == 0) {
  106752. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106753. return false;
  106754. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106755. return false;
  106756. }
  106757. else {
  106758. FLAC__ASSERT(rice_parameters[0] == 0);
  106759. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106760. return false;
  106761. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106762. return false;
  106763. for(i = 0; i < residual_samples; i++) {
  106764. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106765. return false;
  106766. }
  106767. }
  106768. return true;
  106769. }
  106770. else {
  106771. unsigned i, j, k = 0, k_last = 0;
  106772. unsigned partition_samples;
  106773. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106774. for(i = 0; i < (1u<<partition_order); i++) {
  106775. partition_samples = default_partition_samples;
  106776. if(i == 0)
  106777. partition_samples -= predictor_order;
  106778. k += partition_samples;
  106779. if(raw_bits[i] == 0) {
  106780. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106781. return false;
  106782. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106783. return false;
  106784. }
  106785. else {
  106786. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106787. return false;
  106788. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106789. return false;
  106790. for(j = k_last; j < k; j++) {
  106791. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106792. return false;
  106793. }
  106794. }
  106795. k_last = k;
  106796. }
  106797. return true;
  106798. }
  106799. }
  106800. #endif
  106801. /*** End of inlined file: stream_encoder_framing.c ***/
  106802. /*** Start of inlined file: window_flac.c ***/
  106803. /*** Start of inlined file: juce_FlacHeader.h ***/
  106804. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106805. // tasks..
  106806. #define VERSION "1.2.1"
  106807. #define FLAC__NO_DLL 1
  106808. #if JUCE_MSVC
  106809. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106810. #endif
  106811. #if JUCE_MAC
  106812. #define FLAC__SYS_DARWIN 1
  106813. #endif
  106814. /*** End of inlined file: juce_FlacHeader.h ***/
  106815. #if JUCE_USE_FLAC
  106816. #if HAVE_CONFIG_H
  106817. # include <config.h>
  106818. #endif
  106819. #include <math.h>
  106820. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106821. #ifndef M_PI
  106822. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106823. #define M_PI 3.14159265358979323846
  106824. #endif
  106825. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106826. {
  106827. const FLAC__int32 N = L - 1;
  106828. FLAC__int32 n;
  106829. if (L & 1) {
  106830. for (n = 0; n <= N/2; n++)
  106831. window[n] = 2.0f * n / (float)N;
  106832. for (; n <= N; n++)
  106833. window[n] = 2.0f - 2.0f * n / (float)N;
  106834. }
  106835. else {
  106836. for (n = 0; n <= L/2-1; n++)
  106837. window[n] = 2.0f * n / (float)N;
  106838. for (; n <= N; n++)
  106839. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106840. }
  106841. }
  106842. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106843. {
  106844. const FLAC__int32 N = L - 1;
  106845. FLAC__int32 n;
  106846. for (n = 0; n < L; n++)
  106847. 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)));
  106848. }
  106849. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106850. {
  106851. const FLAC__int32 N = L - 1;
  106852. FLAC__int32 n;
  106853. for (n = 0; n < L; n++)
  106854. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106855. }
  106856. /* 4-term -92dB side-lobe */
  106857. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106858. {
  106859. const FLAC__int32 N = L - 1;
  106860. FLAC__int32 n;
  106861. for (n = 0; n <= N; n++)
  106862. 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));
  106863. }
  106864. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106865. {
  106866. const FLAC__int32 N = L - 1;
  106867. const double N2 = (double)N / 2.;
  106868. FLAC__int32 n;
  106869. for (n = 0; n <= N; n++) {
  106870. double k = ((double)n - N2) / N2;
  106871. k = 1.0f - k * k;
  106872. window[n] = (FLAC__real)(k * k);
  106873. }
  106874. }
  106875. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106876. {
  106877. const FLAC__int32 N = L - 1;
  106878. FLAC__int32 n;
  106879. for (n = 0; n < L; n++)
  106880. 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));
  106881. }
  106882. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106883. {
  106884. const FLAC__int32 N = L - 1;
  106885. const double N2 = (double)N / 2.;
  106886. FLAC__int32 n;
  106887. for (n = 0; n <= N; n++) {
  106888. const double k = ((double)n - N2) / (stddev * N2);
  106889. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106890. }
  106891. }
  106892. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106893. {
  106894. const FLAC__int32 N = L - 1;
  106895. FLAC__int32 n;
  106896. for (n = 0; n < L; n++)
  106897. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106898. }
  106899. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106900. {
  106901. const FLAC__int32 N = L - 1;
  106902. FLAC__int32 n;
  106903. for (n = 0; n < L; n++)
  106904. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106905. }
  106906. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106907. {
  106908. const FLAC__int32 N = L - 1;
  106909. FLAC__int32 n;
  106910. for (n = 0; n < L; n++)
  106911. 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));
  106912. }
  106913. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106914. {
  106915. const FLAC__int32 N = L - 1;
  106916. FLAC__int32 n;
  106917. for (n = 0; n < L; n++)
  106918. 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));
  106919. }
  106920. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106921. {
  106922. FLAC__int32 n;
  106923. for (n = 0; n < L; n++)
  106924. window[n] = 1.0f;
  106925. }
  106926. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106927. {
  106928. FLAC__int32 n;
  106929. if (L & 1) {
  106930. for (n = 1; n <= L+1/2; n++)
  106931. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106932. for (; n <= L; n++)
  106933. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106934. }
  106935. else {
  106936. for (n = 1; n <= L/2; n++)
  106937. window[n-1] = 2.0f * n / (float)L;
  106938. for (; n <= L; n++)
  106939. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106940. }
  106941. }
  106942. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106943. {
  106944. if (p <= 0.0)
  106945. FLAC__window_rectangle(window, L);
  106946. else if (p >= 1.0)
  106947. FLAC__window_hann(window, L);
  106948. else {
  106949. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106950. FLAC__int32 n;
  106951. /* start with rectangle... */
  106952. FLAC__window_rectangle(window, L);
  106953. /* ...replace ends with hann */
  106954. if (Np > 0) {
  106955. for (n = 0; n <= Np; n++) {
  106956. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106957. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106958. }
  106959. }
  106960. }
  106961. }
  106962. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106963. {
  106964. const FLAC__int32 N = L - 1;
  106965. const double N2 = (double)N / 2.;
  106966. FLAC__int32 n;
  106967. for (n = 0; n <= N; n++) {
  106968. const double k = ((double)n - N2) / N2;
  106969. window[n] = (FLAC__real)(1.0f - k * k);
  106970. }
  106971. }
  106972. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106973. #endif
  106974. /*** End of inlined file: window_flac.c ***/
  106975. #else
  106976. #include <FLAC/all.h>
  106977. #endif
  106978. }
  106979. #undef max
  106980. #undef min
  106981. BEGIN_JUCE_NAMESPACE
  106982. static const char* const flacFormatName = "FLAC file";
  106983. static const char* const flacExtensions[] = { ".flac", 0 };
  106984. class FlacReader : public AudioFormatReader
  106985. {
  106986. public:
  106987. FlacReader (InputStream* const in)
  106988. : AudioFormatReader (in, TRANS (flacFormatName)),
  106989. reservoir (2, 0),
  106990. reservoirStart (0),
  106991. samplesInReservoir (0),
  106992. scanningForLength (false)
  106993. {
  106994. using namespace FlacNamespace;
  106995. lengthInSamples = 0;
  106996. decoder = FLAC__stream_decoder_new();
  106997. ok = FLAC__stream_decoder_init_stream (decoder,
  106998. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106999. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  107000. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  107001. if (ok)
  107002. {
  107003. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107004. if (lengthInSamples == 0 && sampleRate > 0)
  107005. {
  107006. // the length hasn't been stored in the metadata, so we'll need to
  107007. // work it out the length the hard way, by scanning the whole file..
  107008. scanningForLength = true;
  107009. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  107010. scanningForLength = false;
  107011. const int64 tempLength = lengthInSamples;
  107012. FLAC__stream_decoder_reset (decoder);
  107013. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107014. lengthInSamples = tempLength;
  107015. }
  107016. }
  107017. }
  107018. ~FlacReader()
  107019. {
  107020. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  107021. }
  107022. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  107023. {
  107024. sampleRate = info.sample_rate;
  107025. bitsPerSample = info.bits_per_sample;
  107026. lengthInSamples = (unsigned int) info.total_samples;
  107027. numChannels = info.channels;
  107028. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107029. }
  107030. // returns the number of samples read
  107031. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107032. int64 startSampleInFile, int numSamples)
  107033. {
  107034. using namespace FlacNamespace;
  107035. if (! ok)
  107036. return false;
  107037. while (numSamples > 0)
  107038. {
  107039. if (startSampleInFile >= reservoirStart
  107040. && startSampleInFile < reservoirStart + samplesInReservoir)
  107041. {
  107042. const int num = (int) jmin ((int64) numSamples,
  107043. reservoirStart + samplesInReservoir - startSampleInFile);
  107044. jassert (num > 0);
  107045. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107046. if (destSamples[i] != 0)
  107047. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107048. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107049. sizeof (int) * num);
  107050. startOffsetInDestBuffer += num;
  107051. startSampleInFile += num;
  107052. numSamples -= num;
  107053. }
  107054. else
  107055. {
  107056. if (startSampleInFile >= (int) lengthInSamples)
  107057. {
  107058. samplesInReservoir = 0;
  107059. }
  107060. else if (startSampleInFile < reservoirStart
  107061. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107062. {
  107063. // had some problems with flac crashing if the read pos is aligned more
  107064. // accurately than this. Probably fixed in newer versions of the library, though.
  107065. reservoirStart = (int) (startSampleInFile & ~511);
  107066. samplesInReservoir = 0;
  107067. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107068. }
  107069. else
  107070. {
  107071. reservoirStart += samplesInReservoir;
  107072. samplesInReservoir = 0;
  107073. FLAC__stream_decoder_process_single (decoder);
  107074. }
  107075. if (samplesInReservoir == 0)
  107076. break;
  107077. }
  107078. }
  107079. if (numSamples > 0)
  107080. {
  107081. for (int i = numDestChannels; --i >= 0;)
  107082. if (destSamples[i] != 0)
  107083. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107084. sizeof (int) * numSamples);
  107085. }
  107086. return true;
  107087. }
  107088. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107089. {
  107090. if (scanningForLength)
  107091. {
  107092. lengthInSamples += numSamples;
  107093. }
  107094. else
  107095. {
  107096. if (numSamples > reservoir.getNumSamples())
  107097. reservoir.setSize (numChannels, numSamples, false, false, true);
  107098. const int bitsToShift = 32 - bitsPerSample;
  107099. for (int i = 0; i < (int) numChannels; ++i)
  107100. {
  107101. const FlacNamespace::FLAC__int32* src = buffer[i];
  107102. int n = i;
  107103. while (src == 0 && n > 0)
  107104. src = buffer [--n];
  107105. if (src != 0)
  107106. {
  107107. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107108. for (int j = 0; j < numSamples; ++j)
  107109. dest[j] = src[j] << bitsToShift;
  107110. }
  107111. }
  107112. samplesInReservoir = numSamples;
  107113. }
  107114. }
  107115. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107116. {
  107117. using namespace FlacNamespace;
  107118. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107119. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107120. }
  107121. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107122. {
  107123. using namespace FlacNamespace;
  107124. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107125. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107126. }
  107127. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107128. {
  107129. using namespace FlacNamespace;
  107130. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107131. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107132. }
  107133. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107134. {
  107135. using namespace FlacNamespace;
  107136. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107137. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107138. }
  107139. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107140. {
  107141. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107142. }
  107143. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107144. const FlacNamespace::FLAC__Frame* frame,
  107145. const FlacNamespace::FLAC__int32* const buffer[],
  107146. void* client_data)
  107147. {
  107148. using namespace FlacNamespace;
  107149. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107150. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107151. }
  107152. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107153. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107154. void* client_data)
  107155. {
  107156. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107157. }
  107158. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107159. {
  107160. }
  107161. private:
  107162. FlacNamespace::FLAC__StreamDecoder* decoder;
  107163. AudioSampleBuffer reservoir;
  107164. int reservoirStart, samplesInReservoir;
  107165. bool ok, scanningForLength;
  107166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  107167. };
  107168. class FlacWriter : public AudioFormatWriter
  107169. {
  107170. public:
  107171. FlacWriter (OutputStream* const out, double sampleRate_,
  107172. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107173. : AudioFormatWriter (out, TRANS (flacFormatName),
  107174. sampleRate_, numChannels_, bitsPerSample_)
  107175. {
  107176. using namespace FlacNamespace;
  107177. encoder = FLAC__stream_encoder_new();
  107178. if (qualityOptionIndex > 0)
  107179. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107180. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107181. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107182. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107183. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107184. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107185. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107186. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107187. ok = FLAC__stream_encoder_init_stream (encoder,
  107188. encodeWriteCallback, encodeSeekCallback,
  107189. encodeTellCallback, encodeMetadataCallback,
  107190. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107191. }
  107192. ~FlacWriter()
  107193. {
  107194. if (ok)
  107195. {
  107196. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107197. output->flush();
  107198. }
  107199. else
  107200. {
  107201. output = 0; // to stop the base class deleting this, as it needs to be returned
  107202. // to the caller of createWriter()
  107203. }
  107204. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107205. }
  107206. bool write (const int** samplesToWrite, int numSamples)
  107207. {
  107208. using namespace FlacNamespace;
  107209. if (! ok)
  107210. return false;
  107211. int* buf[3];
  107212. HeapBlock<int> temp;
  107213. const int bitsToShift = 32 - bitsPerSample;
  107214. if (bitsToShift > 0)
  107215. {
  107216. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107217. temp.malloc (numSamples * numChannelsToWrite);
  107218. buf[0] = temp.getData();
  107219. buf[1] = temp.getData() + numSamples;
  107220. buf[2] = 0;
  107221. for (int i = numChannelsToWrite; --i >= 0;)
  107222. if (samplesToWrite[i] != 0)
  107223. for (int j = 0; j < numSamples; ++j)
  107224. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107225. samplesToWrite = const_cast<const int**> (buf);
  107226. }
  107227. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  107228. }
  107229. bool writeData (const void* const data, const int size) const
  107230. {
  107231. return output->write (data, size);
  107232. }
  107233. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107234. {
  107235. using namespace FlacNamespace;
  107236. b += bytes;
  107237. for (int i = 0; i < bytes; ++i)
  107238. {
  107239. *(--b) = (FLAC__byte) (val & 0xff);
  107240. val >>= 8;
  107241. }
  107242. }
  107243. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107244. {
  107245. using namespace FlacNamespace;
  107246. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107247. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107248. const unsigned int channelsMinus1 = info.channels - 1;
  107249. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107250. packUint32 (info.min_blocksize, buffer, 2);
  107251. packUint32 (info.max_blocksize, buffer + 2, 2);
  107252. packUint32 (info.min_framesize, buffer + 4, 3);
  107253. packUint32 (info.max_framesize, buffer + 7, 3);
  107254. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107255. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107256. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107257. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107258. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107259. memcpy (buffer + 18, info.md5sum, 16);
  107260. const bool seekOk = output->setPosition (4);
  107261. (void) seekOk;
  107262. // if this fails, you've given it an output stream that can't seek! It needs
  107263. // to be able to seek back to write the header
  107264. jassert (seekOk);
  107265. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107266. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107267. }
  107268. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107269. const FlacNamespace::FLAC__byte buffer[],
  107270. size_t bytes,
  107271. unsigned int /*samples*/,
  107272. unsigned int /*current_frame*/,
  107273. void* client_data)
  107274. {
  107275. using namespace FlacNamespace;
  107276. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107277. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107278. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107279. }
  107280. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107281. {
  107282. using namespace FlacNamespace;
  107283. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107284. }
  107285. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107286. {
  107287. using namespace FlacNamespace;
  107288. if (client_data == 0)
  107289. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107290. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107291. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107292. }
  107293. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107294. {
  107295. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107296. }
  107297. bool ok;
  107298. private:
  107299. FlacNamespace::FLAC__StreamEncoder* encoder;
  107300. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  107301. };
  107302. FlacAudioFormat::FlacAudioFormat()
  107303. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107304. {
  107305. }
  107306. FlacAudioFormat::~FlacAudioFormat()
  107307. {
  107308. }
  107309. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107310. {
  107311. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107312. return Array <int> (rates);
  107313. }
  107314. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107315. {
  107316. const int depths[] = { 16, 24, 0 };
  107317. return Array <int> (depths);
  107318. }
  107319. bool FlacAudioFormat::canDoStereo() { return true; }
  107320. bool FlacAudioFormat::canDoMono() { return true; }
  107321. bool FlacAudioFormat::isCompressed() { return true; }
  107322. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107323. const bool deleteStreamIfOpeningFails)
  107324. {
  107325. ScopedPointer<FlacReader> r (new FlacReader (in));
  107326. if (r->sampleRate != 0)
  107327. return r.release();
  107328. if (! deleteStreamIfOpeningFails)
  107329. r->input = 0;
  107330. return 0;
  107331. }
  107332. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107333. double sampleRate,
  107334. unsigned int numberOfChannels,
  107335. int bitsPerSample,
  107336. const StringPairArray& /*metadataValues*/,
  107337. int qualityOptionIndex)
  107338. {
  107339. if (getPossibleBitDepths().contains (bitsPerSample))
  107340. {
  107341. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107342. if (w->ok)
  107343. return w.release();
  107344. }
  107345. return 0;
  107346. }
  107347. END_JUCE_NAMESPACE
  107348. #endif
  107349. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107350. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107351. #if JUCE_USE_OGGVORBIS
  107352. #if JUCE_MAC
  107353. #define __MACOSX__ 1
  107354. #endif
  107355. namespace OggVorbisNamespace
  107356. {
  107357. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107358. /*** Start of inlined file: vorbisenc.h ***/
  107359. #ifndef _OV_ENC_H_
  107360. #define _OV_ENC_H_
  107361. #ifdef __cplusplus
  107362. extern "C"
  107363. {
  107364. #endif /* __cplusplus */
  107365. /*** Start of inlined file: codec.h ***/
  107366. #ifndef _vorbis_codec_h_
  107367. #define _vorbis_codec_h_
  107368. #ifdef __cplusplus
  107369. extern "C"
  107370. {
  107371. #endif /* __cplusplus */
  107372. /*** Start of inlined file: ogg.h ***/
  107373. #ifndef _OGG_H
  107374. #define _OGG_H
  107375. #ifdef __cplusplus
  107376. extern "C" {
  107377. #endif
  107378. /*** Start of inlined file: os_types.h ***/
  107379. #ifndef _OS_TYPES_H
  107380. #define _OS_TYPES_H
  107381. /* make it easy on the folks that want to compile the libs with a
  107382. different malloc than stdlib */
  107383. #define _ogg_malloc malloc
  107384. #define _ogg_calloc calloc
  107385. #define _ogg_realloc realloc
  107386. #define _ogg_free free
  107387. #if defined(_WIN32)
  107388. # if defined(__CYGWIN__)
  107389. # include <_G_config.h>
  107390. typedef _G_int64_t ogg_int64_t;
  107391. typedef _G_int32_t ogg_int32_t;
  107392. typedef _G_uint32_t ogg_uint32_t;
  107393. typedef _G_int16_t ogg_int16_t;
  107394. typedef _G_uint16_t ogg_uint16_t;
  107395. # elif defined(__MINGW32__)
  107396. typedef short ogg_int16_t;
  107397. typedef unsigned short ogg_uint16_t;
  107398. typedef int ogg_int32_t;
  107399. typedef unsigned int ogg_uint32_t;
  107400. typedef long long ogg_int64_t;
  107401. typedef unsigned long long ogg_uint64_t;
  107402. # elif defined(__MWERKS__)
  107403. typedef long long ogg_int64_t;
  107404. typedef int ogg_int32_t;
  107405. typedef unsigned int ogg_uint32_t;
  107406. typedef short ogg_int16_t;
  107407. typedef unsigned short ogg_uint16_t;
  107408. # else
  107409. /* MSVC/Borland */
  107410. typedef __int64 ogg_int64_t;
  107411. typedef __int32 ogg_int32_t;
  107412. typedef unsigned __int32 ogg_uint32_t;
  107413. typedef __int16 ogg_int16_t;
  107414. typedef unsigned __int16 ogg_uint16_t;
  107415. # endif
  107416. #elif defined(__MACOS__)
  107417. # include <sys/types.h>
  107418. typedef SInt16 ogg_int16_t;
  107419. typedef UInt16 ogg_uint16_t;
  107420. typedef SInt32 ogg_int32_t;
  107421. typedef UInt32 ogg_uint32_t;
  107422. typedef SInt64 ogg_int64_t;
  107423. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107424. # include <sys/types.h>
  107425. typedef int16_t ogg_int16_t;
  107426. typedef u_int16_t ogg_uint16_t;
  107427. typedef int32_t ogg_int32_t;
  107428. typedef u_int32_t ogg_uint32_t;
  107429. typedef int64_t ogg_int64_t;
  107430. #elif defined(__BEOS__)
  107431. /* Be */
  107432. # include <inttypes.h>
  107433. typedef int16_t ogg_int16_t;
  107434. typedef u_int16_t ogg_uint16_t;
  107435. typedef int32_t ogg_int32_t;
  107436. typedef u_int32_t ogg_uint32_t;
  107437. typedef int64_t ogg_int64_t;
  107438. #elif defined (__EMX__)
  107439. /* OS/2 GCC */
  107440. typedef short ogg_int16_t;
  107441. typedef unsigned short ogg_uint16_t;
  107442. typedef int ogg_int32_t;
  107443. typedef unsigned int ogg_uint32_t;
  107444. typedef long long ogg_int64_t;
  107445. #elif defined (DJGPP)
  107446. /* DJGPP */
  107447. typedef short ogg_int16_t;
  107448. typedef int ogg_int32_t;
  107449. typedef unsigned int ogg_uint32_t;
  107450. typedef long long ogg_int64_t;
  107451. #elif defined(R5900)
  107452. /* PS2 EE */
  107453. typedef long ogg_int64_t;
  107454. typedef int ogg_int32_t;
  107455. typedef unsigned ogg_uint32_t;
  107456. typedef short ogg_int16_t;
  107457. #elif defined(__SYMBIAN32__)
  107458. /* Symbian GCC */
  107459. typedef signed short ogg_int16_t;
  107460. typedef unsigned short ogg_uint16_t;
  107461. typedef signed int ogg_int32_t;
  107462. typedef unsigned int ogg_uint32_t;
  107463. typedef long long int ogg_int64_t;
  107464. #else
  107465. # include <sys/types.h>
  107466. /*** Start of inlined file: config_types.h ***/
  107467. #ifndef __CONFIG_TYPES_H__
  107468. #define __CONFIG_TYPES_H__
  107469. typedef int16_t ogg_int16_t;
  107470. typedef unsigned short ogg_uint16_t;
  107471. typedef int32_t ogg_int32_t;
  107472. typedef unsigned int ogg_uint32_t;
  107473. typedef int64_t ogg_int64_t;
  107474. #endif
  107475. /*** End of inlined file: config_types.h ***/
  107476. #endif
  107477. #endif /* _OS_TYPES_H */
  107478. /*** End of inlined file: os_types.h ***/
  107479. typedef struct {
  107480. long endbyte;
  107481. int endbit;
  107482. unsigned char *buffer;
  107483. unsigned char *ptr;
  107484. long storage;
  107485. } oggpack_buffer;
  107486. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107487. typedef struct {
  107488. unsigned char *header;
  107489. long header_len;
  107490. unsigned char *body;
  107491. long body_len;
  107492. } ogg_page;
  107493. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107494. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107495. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107496. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107497. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107498. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107499. }
  107500. /* ogg_stream_state contains the current encode/decode state of a logical
  107501. Ogg bitstream **********************************************************/
  107502. typedef struct {
  107503. unsigned char *body_data; /* bytes from packet bodies */
  107504. long body_storage; /* storage elements allocated */
  107505. long body_fill; /* elements stored; fill mark */
  107506. long body_returned; /* elements of fill returned */
  107507. int *lacing_vals; /* The values that will go to the segment table */
  107508. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107509. this way, but it is simple coupled to the
  107510. lacing fifo */
  107511. long lacing_storage;
  107512. long lacing_fill;
  107513. long lacing_packet;
  107514. long lacing_returned;
  107515. unsigned char header[282]; /* working space for header encode */
  107516. int header_fill;
  107517. int e_o_s; /* set when we have buffered the last packet in the
  107518. logical bitstream */
  107519. int b_o_s; /* set after we've written the initial page
  107520. of a logical bitstream */
  107521. long serialno;
  107522. long pageno;
  107523. ogg_int64_t packetno; /* sequence number for decode; the framing
  107524. knows where there's a hole in the data,
  107525. but we need coupling so that the codec
  107526. (which is in a seperate abstraction
  107527. layer) also knows about the gap */
  107528. ogg_int64_t granulepos;
  107529. } ogg_stream_state;
  107530. /* ogg_packet is used to encapsulate the data and metadata belonging
  107531. to a single raw Ogg/Vorbis packet *************************************/
  107532. typedef struct {
  107533. unsigned char *packet;
  107534. long bytes;
  107535. long b_o_s;
  107536. long e_o_s;
  107537. ogg_int64_t granulepos;
  107538. ogg_int64_t packetno; /* sequence number for decode; the framing
  107539. knows where there's a hole in the data,
  107540. but we need coupling so that the codec
  107541. (which is in a seperate abstraction
  107542. layer) also knows about the gap */
  107543. } ogg_packet;
  107544. typedef struct {
  107545. unsigned char *data;
  107546. int storage;
  107547. int fill;
  107548. int returned;
  107549. int unsynced;
  107550. int headerbytes;
  107551. int bodybytes;
  107552. } ogg_sync_state;
  107553. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107554. extern void oggpack_writeinit(oggpack_buffer *b);
  107555. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107556. extern void oggpack_writealign(oggpack_buffer *b);
  107557. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107558. extern void oggpack_reset(oggpack_buffer *b);
  107559. extern void oggpack_writeclear(oggpack_buffer *b);
  107560. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107561. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107562. extern long oggpack_look(oggpack_buffer *b,int bits);
  107563. extern long oggpack_look1(oggpack_buffer *b);
  107564. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107565. extern void oggpack_adv1(oggpack_buffer *b);
  107566. extern long oggpack_read(oggpack_buffer *b,int bits);
  107567. extern long oggpack_read1(oggpack_buffer *b);
  107568. extern long oggpack_bytes(oggpack_buffer *b);
  107569. extern long oggpack_bits(oggpack_buffer *b);
  107570. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107571. extern void oggpackB_writeinit(oggpack_buffer *b);
  107572. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107573. extern void oggpackB_writealign(oggpack_buffer *b);
  107574. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107575. extern void oggpackB_reset(oggpack_buffer *b);
  107576. extern void oggpackB_writeclear(oggpack_buffer *b);
  107577. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107578. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107579. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107580. extern long oggpackB_look1(oggpack_buffer *b);
  107581. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107582. extern void oggpackB_adv1(oggpack_buffer *b);
  107583. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107584. extern long oggpackB_read1(oggpack_buffer *b);
  107585. extern long oggpackB_bytes(oggpack_buffer *b);
  107586. extern long oggpackB_bits(oggpack_buffer *b);
  107587. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107588. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107589. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107590. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107591. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107592. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107593. extern int ogg_sync_init(ogg_sync_state *oy);
  107594. extern int ogg_sync_clear(ogg_sync_state *oy);
  107595. extern int ogg_sync_reset(ogg_sync_state *oy);
  107596. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107597. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107598. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107599. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107600. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107601. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107602. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107603. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107604. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107605. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107606. extern int ogg_stream_clear(ogg_stream_state *os);
  107607. extern int ogg_stream_reset(ogg_stream_state *os);
  107608. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107609. extern int ogg_stream_destroy(ogg_stream_state *os);
  107610. extern int ogg_stream_eos(ogg_stream_state *os);
  107611. extern void ogg_page_checksum_set(ogg_page *og);
  107612. extern int ogg_page_version(ogg_page *og);
  107613. extern int ogg_page_continued(ogg_page *og);
  107614. extern int ogg_page_bos(ogg_page *og);
  107615. extern int ogg_page_eos(ogg_page *og);
  107616. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107617. extern int ogg_page_serialno(ogg_page *og);
  107618. extern long ogg_page_pageno(ogg_page *og);
  107619. extern int ogg_page_packets(ogg_page *og);
  107620. extern void ogg_packet_clear(ogg_packet *op);
  107621. #ifdef __cplusplus
  107622. }
  107623. #endif
  107624. #endif /* _OGG_H */
  107625. /*** End of inlined file: ogg.h ***/
  107626. typedef struct vorbis_info{
  107627. int version;
  107628. int channels;
  107629. long rate;
  107630. /* The below bitrate declarations are *hints*.
  107631. Combinations of the three values carry the following implications:
  107632. all three set to the same value:
  107633. implies a fixed rate bitstream
  107634. only nominal set:
  107635. implies a VBR stream that averages the nominal bitrate. No hard
  107636. upper/lower limit
  107637. upper and or lower set:
  107638. implies a VBR bitstream that obeys the bitrate limits. nominal
  107639. may also be set to give a nominal rate.
  107640. none set:
  107641. the coder does not care to speculate.
  107642. */
  107643. long bitrate_upper;
  107644. long bitrate_nominal;
  107645. long bitrate_lower;
  107646. long bitrate_window;
  107647. void *codec_setup;
  107648. } vorbis_info;
  107649. /* vorbis_dsp_state buffers the current vorbis audio
  107650. analysis/synthesis state. The DSP state belongs to a specific
  107651. logical bitstream ****************************************************/
  107652. typedef struct vorbis_dsp_state{
  107653. int analysisp;
  107654. vorbis_info *vi;
  107655. float **pcm;
  107656. float **pcmret;
  107657. int pcm_storage;
  107658. int pcm_current;
  107659. int pcm_returned;
  107660. int preextrapolate;
  107661. int eofflag;
  107662. long lW;
  107663. long W;
  107664. long nW;
  107665. long centerW;
  107666. ogg_int64_t granulepos;
  107667. ogg_int64_t sequence;
  107668. ogg_int64_t glue_bits;
  107669. ogg_int64_t time_bits;
  107670. ogg_int64_t floor_bits;
  107671. ogg_int64_t res_bits;
  107672. void *backend_state;
  107673. } vorbis_dsp_state;
  107674. typedef struct vorbis_block{
  107675. /* necessary stream state for linking to the framing abstraction */
  107676. float **pcm; /* this is a pointer into local storage */
  107677. oggpack_buffer opb;
  107678. long lW;
  107679. long W;
  107680. long nW;
  107681. int pcmend;
  107682. int mode;
  107683. int eofflag;
  107684. ogg_int64_t granulepos;
  107685. ogg_int64_t sequence;
  107686. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107687. /* local storage to avoid remallocing; it's up to the mapping to
  107688. structure it */
  107689. void *localstore;
  107690. long localtop;
  107691. long localalloc;
  107692. long totaluse;
  107693. struct alloc_chain *reap;
  107694. /* bitmetrics for the frame */
  107695. long glue_bits;
  107696. long time_bits;
  107697. long floor_bits;
  107698. long res_bits;
  107699. void *internal;
  107700. } vorbis_block;
  107701. /* vorbis_block is a single block of data to be processed as part of
  107702. the analysis/synthesis stream; it belongs to a specific logical
  107703. bitstream, but is independant from other vorbis_blocks belonging to
  107704. that logical bitstream. *************************************************/
  107705. struct alloc_chain{
  107706. void *ptr;
  107707. struct alloc_chain *next;
  107708. };
  107709. /* vorbis_info contains all the setup information specific to the
  107710. specific compression/decompression mode in progress (eg,
  107711. psychoacoustic settings, channel setup, options, codebook
  107712. etc). vorbis_info and substructures are in backends.h.
  107713. *********************************************************************/
  107714. /* the comments are not part of vorbis_info so that vorbis_info can be
  107715. static storage */
  107716. typedef struct vorbis_comment{
  107717. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107718. whatever vendor is set to in encode */
  107719. char **user_comments;
  107720. int *comment_lengths;
  107721. int comments;
  107722. char *vendor;
  107723. } vorbis_comment;
  107724. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107725. and produce a packet (see docs/analysis.txt). The packet is then
  107726. coded into a framed OggSquish bitstream by the second layer (see
  107727. docs/framing.txt). Decode is the reverse process; we sync/frame
  107728. the bitstream and extract individual packets, then decode the
  107729. packet back into PCM audio.
  107730. The extra framing/packetizing is used in streaming formats, such as
  107731. files. Over the net (such as with UDP), the framing and
  107732. packetization aren't necessary as they're provided by the transport
  107733. and the streaming layer is not used */
  107734. /* Vorbis PRIMITIVES: general ***************************************/
  107735. extern void vorbis_info_init(vorbis_info *vi);
  107736. extern void vorbis_info_clear(vorbis_info *vi);
  107737. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107738. extern void vorbis_comment_init(vorbis_comment *vc);
  107739. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107740. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107741. const char *tag, char *contents);
  107742. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107743. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107744. extern void vorbis_comment_clear(vorbis_comment *vc);
  107745. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107746. extern int vorbis_block_clear(vorbis_block *vb);
  107747. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107748. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107749. ogg_int64_t granulepos);
  107750. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107751. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107752. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107753. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107754. vorbis_comment *vc,
  107755. ogg_packet *op,
  107756. ogg_packet *op_comm,
  107757. ogg_packet *op_code);
  107758. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107759. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107760. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107761. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107762. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107763. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107764. ogg_packet *op);
  107765. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107766. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107767. ogg_packet *op);
  107768. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107769. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107770. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107771. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107772. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107773. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107774. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107775. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107776. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107777. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107778. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107779. /* Vorbis ERRORS and return codes ***********************************/
  107780. #define OV_FALSE -1
  107781. #define OV_EOF -2
  107782. #define OV_HOLE -3
  107783. #define OV_EREAD -128
  107784. #define OV_EFAULT -129
  107785. #define OV_EIMPL -130
  107786. #define OV_EINVAL -131
  107787. #define OV_ENOTVORBIS -132
  107788. #define OV_EBADHEADER -133
  107789. #define OV_EVERSION -134
  107790. #define OV_ENOTAUDIO -135
  107791. #define OV_EBADPACKET -136
  107792. #define OV_EBADLINK -137
  107793. #define OV_ENOSEEK -138
  107794. #ifdef __cplusplus
  107795. }
  107796. #endif /* __cplusplus */
  107797. #endif
  107798. /*** End of inlined file: codec.h ***/
  107799. extern int vorbis_encode_init(vorbis_info *vi,
  107800. long channels,
  107801. long rate,
  107802. long max_bitrate,
  107803. long nominal_bitrate,
  107804. long min_bitrate);
  107805. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107806. long channels,
  107807. long rate,
  107808. long max_bitrate,
  107809. long nominal_bitrate,
  107810. long min_bitrate);
  107811. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107812. long channels,
  107813. long rate,
  107814. float quality /* quality level from 0. (lo) to 1. (hi) */
  107815. );
  107816. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107817. long channels,
  107818. long rate,
  107819. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107820. );
  107821. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107822. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107823. /* deprecated rate management supported only for compatability */
  107824. #define OV_ECTL_RATEMANAGE_GET 0x10
  107825. #define OV_ECTL_RATEMANAGE_SET 0x11
  107826. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107827. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107828. struct ovectl_ratemanage_arg {
  107829. int management_active;
  107830. long bitrate_hard_min;
  107831. long bitrate_hard_max;
  107832. double bitrate_hard_window;
  107833. long bitrate_av_lo;
  107834. long bitrate_av_hi;
  107835. double bitrate_av_window;
  107836. double bitrate_av_window_center;
  107837. };
  107838. /* new rate setup */
  107839. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107840. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107841. struct ovectl_ratemanage2_arg {
  107842. int management_active;
  107843. long bitrate_limit_min_kbps;
  107844. long bitrate_limit_max_kbps;
  107845. long bitrate_limit_reservoir_bits;
  107846. double bitrate_limit_reservoir_bias;
  107847. long bitrate_average_kbps;
  107848. double bitrate_average_damping;
  107849. };
  107850. #define OV_ECTL_LOWPASS_GET 0x20
  107851. #define OV_ECTL_LOWPASS_SET 0x21
  107852. #define OV_ECTL_IBLOCK_GET 0x30
  107853. #define OV_ECTL_IBLOCK_SET 0x31
  107854. #ifdef __cplusplus
  107855. }
  107856. #endif /* __cplusplus */
  107857. #endif
  107858. /*** End of inlined file: vorbisenc.h ***/
  107859. /*** Start of inlined file: vorbisfile.h ***/
  107860. #ifndef _OV_FILE_H_
  107861. #define _OV_FILE_H_
  107862. #ifdef __cplusplus
  107863. extern "C"
  107864. {
  107865. #endif /* __cplusplus */
  107866. #include <stdio.h>
  107867. /* The function prototypes for the callbacks are basically the same as for
  107868. * the stdio functions fread, fseek, fclose, ftell.
  107869. * The one difference is that the FILE * arguments have been replaced with
  107870. * a void * - this is to be used as a pointer to whatever internal data these
  107871. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107872. *
  107873. * If you use other functions, check the docs for these functions and return
  107874. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107875. * unseekable
  107876. */
  107877. typedef struct {
  107878. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107879. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107880. int (*close_func) (void *datasource);
  107881. long (*tell_func) (void *datasource);
  107882. } ov_callbacks;
  107883. #define NOTOPEN 0
  107884. #define PARTOPEN 1
  107885. #define OPENED 2
  107886. #define STREAMSET 3
  107887. #define INITSET 4
  107888. typedef struct OggVorbis_File {
  107889. void *datasource; /* Pointer to a FILE *, etc. */
  107890. int seekable;
  107891. ogg_int64_t offset;
  107892. ogg_int64_t end;
  107893. ogg_sync_state oy;
  107894. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107895. stream appears */
  107896. int links;
  107897. ogg_int64_t *offsets;
  107898. ogg_int64_t *dataoffsets;
  107899. long *serialnos;
  107900. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107901. compatability; x2 size, stores both
  107902. beginning and end values */
  107903. vorbis_info *vi;
  107904. vorbis_comment *vc;
  107905. /* Decoding working state local storage */
  107906. ogg_int64_t pcm_offset;
  107907. int ready_state;
  107908. long current_serialno;
  107909. int current_link;
  107910. double bittrack;
  107911. double samptrack;
  107912. ogg_stream_state os; /* take physical pages, weld into a logical
  107913. stream of packets */
  107914. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107915. vorbis_block vb; /* local working space for packet->PCM decode */
  107916. ov_callbacks callbacks;
  107917. } OggVorbis_File;
  107918. extern int ov_clear(OggVorbis_File *vf);
  107919. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107920. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107921. char *initial, long ibytes, ov_callbacks callbacks);
  107922. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107923. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107924. char *initial, long ibytes, ov_callbacks callbacks);
  107925. extern int ov_test_open(OggVorbis_File *vf);
  107926. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107927. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107928. extern long ov_streams(OggVorbis_File *vf);
  107929. extern long ov_seekable(OggVorbis_File *vf);
  107930. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107931. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107932. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107933. extern double ov_time_total(OggVorbis_File *vf,int i);
  107934. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107935. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107936. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107937. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107938. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107939. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107940. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107941. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107942. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107943. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107944. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107945. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107946. extern double ov_time_tell(OggVorbis_File *vf);
  107947. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107948. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107949. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107950. int *bitstream);
  107951. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107952. int bigendianp,int word,int sgned,int *bitstream);
  107953. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107954. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107955. extern int ov_halfrate_p(OggVorbis_File *vf);
  107956. #ifdef __cplusplus
  107957. }
  107958. #endif /* __cplusplus */
  107959. #endif
  107960. /*** End of inlined file: vorbisfile.h ***/
  107961. /*** Start of inlined file: bitwise.c ***/
  107962. /* We're 'LSb' endian; if we write a word but read individual bits,
  107963. then we'll read the lsb first */
  107964. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107965. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107966. // tasks..
  107967. #if JUCE_MSVC
  107968. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107969. #endif
  107970. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107971. #if JUCE_USE_OGGVORBIS
  107972. #include <string.h>
  107973. #include <stdlib.h>
  107974. #define BUFFER_INCREMENT 256
  107975. static const unsigned long mask[]=
  107976. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107977. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107978. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107979. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107980. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107981. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107982. 0x3fffffff,0x7fffffff,0xffffffff };
  107983. static const unsigned int mask8B[]=
  107984. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107985. void oggpack_writeinit(oggpack_buffer *b){
  107986. memset(b,0,sizeof(*b));
  107987. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107988. b->buffer[0]='\0';
  107989. b->storage=BUFFER_INCREMENT;
  107990. }
  107991. void oggpackB_writeinit(oggpack_buffer *b){
  107992. oggpack_writeinit(b);
  107993. }
  107994. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107995. long bytes=bits>>3;
  107996. bits-=bytes*8;
  107997. b->ptr=b->buffer+bytes;
  107998. b->endbit=bits;
  107999. b->endbyte=bytes;
  108000. *b->ptr&=mask[bits];
  108001. }
  108002. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  108003. long bytes=bits>>3;
  108004. bits-=bytes*8;
  108005. b->ptr=b->buffer+bytes;
  108006. b->endbit=bits;
  108007. b->endbyte=bytes;
  108008. *b->ptr&=mask8B[bits];
  108009. }
  108010. /* Takes only up to 32 bits. */
  108011. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108012. if(b->endbyte+4>=b->storage){
  108013. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108014. b->storage+=BUFFER_INCREMENT;
  108015. b->ptr=b->buffer+b->endbyte;
  108016. }
  108017. value&=mask[bits];
  108018. bits+=b->endbit;
  108019. b->ptr[0]|=value<<b->endbit;
  108020. if(bits>=8){
  108021. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108022. if(bits>=16){
  108023. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108024. if(bits>=24){
  108025. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108026. if(bits>=32){
  108027. if(b->endbit)
  108028. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108029. else
  108030. b->ptr[4]=0;
  108031. }
  108032. }
  108033. }
  108034. }
  108035. b->endbyte+=bits/8;
  108036. b->ptr+=bits/8;
  108037. b->endbit=bits&7;
  108038. }
  108039. /* Takes only up to 32 bits. */
  108040. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108041. if(b->endbyte+4>=b->storage){
  108042. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108043. b->storage+=BUFFER_INCREMENT;
  108044. b->ptr=b->buffer+b->endbyte;
  108045. }
  108046. value=(value&mask[bits])<<(32-bits);
  108047. bits+=b->endbit;
  108048. b->ptr[0]|=value>>(24+b->endbit);
  108049. if(bits>=8){
  108050. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108051. if(bits>=16){
  108052. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108053. if(bits>=24){
  108054. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108055. if(bits>=32){
  108056. if(b->endbit)
  108057. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108058. else
  108059. b->ptr[4]=0;
  108060. }
  108061. }
  108062. }
  108063. }
  108064. b->endbyte+=bits/8;
  108065. b->ptr+=bits/8;
  108066. b->endbit=bits&7;
  108067. }
  108068. void oggpack_writealign(oggpack_buffer *b){
  108069. int bits=8-b->endbit;
  108070. if(bits<8)
  108071. oggpack_write(b,0,bits);
  108072. }
  108073. void oggpackB_writealign(oggpack_buffer *b){
  108074. int bits=8-b->endbit;
  108075. if(bits<8)
  108076. oggpackB_write(b,0,bits);
  108077. }
  108078. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108079. void *source,
  108080. long bits,
  108081. void (*w)(oggpack_buffer *,
  108082. unsigned long,
  108083. int),
  108084. int msb){
  108085. unsigned char *ptr=(unsigned char *)source;
  108086. long bytes=bits/8;
  108087. bits-=bytes*8;
  108088. if(b->endbit){
  108089. int i;
  108090. /* unaligned copy. Do it the hard way. */
  108091. for(i=0;i<bytes;i++)
  108092. w(b,(unsigned long)(ptr[i]),8);
  108093. }else{
  108094. /* aligned block copy */
  108095. if(b->endbyte+bytes+1>=b->storage){
  108096. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108097. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108098. b->ptr=b->buffer+b->endbyte;
  108099. }
  108100. memmove(b->ptr,source,bytes);
  108101. b->ptr+=bytes;
  108102. b->endbyte+=bytes;
  108103. *b->ptr=0;
  108104. }
  108105. if(bits){
  108106. if(msb)
  108107. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108108. else
  108109. w(b,(unsigned long)(ptr[bytes]),bits);
  108110. }
  108111. }
  108112. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108113. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108114. }
  108115. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108116. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108117. }
  108118. void oggpack_reset(oggpack_buffer *b){
  108119. b->ptr=b->buffer;
  108120. b->buffer[0]=0;
  108121. b->endbit=b->endbyte=0;
  108122. }
  108123. void oggpackB_reset(oggpack_buffer *b){
  108124. oggpack_reset(b);
  108125. }
  108126. void oggpack_writeclear(oggpack_buffer *b){
  108127. _ogg_free(b->buffer);
  108128. memset(b,0,sizeof(*b));
  108129. }
  108130. void oggpackB_writeclear(oggpack_buffer *b){
  108131. oggpack_writeclear(b);
  108132. }
  108133. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108134. memset(b,0,sizeof(*b));
  108135. b->buffer=b->ptr=buf;
  108136. b->storage=bytes;
  108137. }
  108138. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108139. oggpack_readinit(b,buf,bytes);
  108140. }
  108141. /* Read in bits without advancing the bitptr; bits <= 32 */
  108142. long oggpack_look(oggpack_buffer *b,int bits){
  108143. unsigned long ret;
  108144. unsigned long m=mask[bits];
  108145. bits+=b->endbit;
  108146. if(b->endbyte+4>=b->storage){
  108147. /* not the main path */
  108148. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108149. }
  108150. ret=b->ptr[0]>>b->endbit;
  108151. if(bits>8){
  108152. ret|=b->ptr[1]<<(8-b->endbit);
  108153. if(bits>16){
  108154. ret|=b->ptr[2]<<(16-b->endbit);
  108155. if(bits>24){
  108156. ret|=b->ptr[3]<<(24-b->endbit);
  108157. if(bits>32 && b->endbit)
  108158. ret|=b->ptr[4]<<(32-b->endbit);
  108159. }
  108160. }
  108161. }
  108162. return(m&ret);
  108163. }
  108164. /* Read in bits without advancing the bitptr; bits <= 32 */
  108165. long oggpackB_look(oggpack_buffer *b,int bits){
  108166. unsigned long ret;
  108167. int m=32-bits;
  108168. bits+=b->endbit;
  108169. if(b->endbyte+4>=b->storage){
  108170. /* not the main path */
  108171. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108172. }
  108173. ret=b->ptr[0]<<(24+b->endbit);
  108174. if(bits>8){
  108175. ret|=b->ptr[1]<<(16+b->endbit);
  108176. if(bits>16){
  108177. ret|=b->ptr[2]<<(8+b->endbit);
  108178. if(bits>24){
  108179. ret|=b->ptr[3]<<(b->endbit);
  108180. if(bits>32 && b->endbit)
  108181. ret|=b->ptr[4]>>(8-b->endbit);
  108182. }
  108183. }
  108184. }
  108185. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108186. }
  108187. long oggpack_look1(oggpack_buffer *b){
  108188. if(b->endbyte>=b->storage)return(-1);
  108189. return((b->ptr[0]>>b->endbit)&1);
  108190. }
  108191. long oggpackB_look1(oggpack_buffer *b){
  108192. if(b->endbyte>=b->storage)return(-1);
  108193. return((b->ptr[0]>>(7-b->endbit))&1);
  108194. }
  108195. void oggpack_adv(oggpack_buffer *b,int bits){
  108196. bits+=b->endbit;
  108197. b->ptr+=bits/8;
  108198. b->endbyte+=bits/8;
  108199. b->endbit=bits&7;
  108200. }
  108201. void oggpackB_adv(oggpack_buffer *b,int bits){
  108202. oggpack_adv(b,bits);
  108203. }
  108204. void oggpack_adv1(oggpack_buffer *b){
  108205. if(++(b->endbit)>7){
  108206. b->endbit=0;
  108207. b->ptr++;
  108208. b->endbyte++;
  108209. }
  108210. }
  108211. void oggpackB_adv1(oggpack_buffer *b){
  108212. oggpack_adv1(b);
  108213. }
  108214. /* bits <= 32 */
  108215. long oggpack_read(oggpack_buffer *b,int bits){
  108216. long ret;
  108217. unsigned long m=mask[bits];
  108218. bits+=b->endbit;
  108219. if(b->endbyte+4>=b->storage){
  108220. /* not the main path */
  108221. ret=-1L;
  108222. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108223. }
  108224. ret=b->ptr[0]>>b->endbit;
  108225. if(bits>8){
  108226. ret|=b->ptr[1]<<(8-b->endbit);
  108227. if(bits>16){
  108228. ret|=b->ptr[2]<<(16-b->endbit);
  108229. if(bits>24){
  108230. ret|=b->ptr[3]<<(24-b->endbit);
  108231. if(bits>32 && b->endbit){
  108232. ret|=b->ptr[4]<<(32-b->endbit);
  108233. }
  108234. }
  108235. }
  108236. }
  108237. ret&=m;
  108238. overflow:
  108239. b->ptr+=bits/8;
  108240. b->endbyte+=bits/8;
  108241. b->endbit=bits&7;
  108242. return(ret);
  108243. }
  108244. /* bits <= 32 */
  108245. long oggpackB_read(oggpack_buffer *b,int bits){
  108246. long ret;
  108247. long m=32-bits;
  108248. bits+=b->endbit;
  108249. if(b->endbyte+4>=b->storage){
  108250. /* not the main path */
  108251. ret=-1L;
  108252. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108253. }
  108254. ret=b->ptr[0]<<(24+b->endbit);
  108255. if(bits>8){
  108256. ret|=b->ptr[1]<<(16+b->endbit);
  108257. if(bits>16){
  108258. ret|=b->ptr[2]<<(8+b->endbit);
  108259. if(bits>24){
  108260. ret|=b->ptr[3]<<(b->endbit);
  108261. if(bits>32 && b->endbit)
  108262. ret|=b->ptr[4]>>(8-b->endbit);
  108263. }
  108264. }
  108265. }
  108266. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108267. overflow:
  108268. b->ptr+=bits/8;
  108269. b->endbyte+=bits/8;
  108270. b->endbit=bits&7;
  108271. return(ret);
  108272. }
  108273. long oggpack_read1(oggpack_buffer *b){
  108274. long ret;
  108275. if(b->endbyte>=b->storage){
  108276. /* not the main path */
  108277. ret=-1L;
  108278. goto overflow;
  108279. }
  108280. ret=(b->ptr[0]>>b->endbit)&1;
  108281. overflow:
  108282. b->endbit++;
  108283. if(b->endbit>7){
  108284. b->endbit=0;
  108285. b->ptr++;
  108286. b->endbyte++;
  108287. }
  108288. return(ret);
  108289. }
  108290. long oggpackB_read1(oggpack_buffer *b){
  108291. long ret;
  108292. if(b->endbyte>=b->storage){
  108293. /* not the main path */
  108294. ret=-1L;
  108295. goto overflow;
  108296. }
  108297. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108298. overflow:
  108299. b->endbit++;
  108300. if(b->endbit>7){
  108301. b->endbit=0;
  108302. b->ptr++;
  108303. b->endbyte++;
  108304. }
  108305. return(ret);
  108306. }
  108307. long oggpack_bytes(oggpack_buffer *b){
  108308. return(b->endbyte+(b->endbit+7)/8);
  108309. }
  108310. long oggpack_bits(oggpack_buffer *b){
  108311. return(b->endbyte*8+b->endbit);
  108312. }
  108313. long oggpackB_bytes(oggpack_buffer *b){
  108314. return oggpack_bytes(b);
  108315. }
  108316. long oggpackB_bits(oggpack_buffer *b){
  108317. return oggpack_bits(b);
  108318. }
  108319. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108320. return(b->buffer);
  108321. }
  108322. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108323. return oggpack_get_buffer(b);
  108324. }
  108325. /* Self test of the bitwise routines; everything else is based on
  108326. them, so they damned well better be solid. */
  108327. #ifdef _V_SELFTEST
  108328. #include <stdio.h>
  108329. static int ilog(unsigned int v){
  108330. int ret=0;
  108331. while(v){
  108332. ret++;
  108333. v>>=1;
  108334. }
  108335. return(ret);
  108336. }
  108337. oggpack_buffer o;
  108338. oggpack_buffer r;
  108339. void report(char *in){
  108340. fprintf(stderr,"%s",in);
  108341. exit(1);
  108342. }
  108343. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108344. long bytes,i;
  108345. unsigned char *buffer;
  108346. oggpack_reset(&o);
  108347. for(i=0;i<vals;i++)
  108348. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108349. buffer=oggpack_get_buffer(&o);
  108350. bytes=oggpack_bytes(&o);
  108351. if(bytes!=compsize)report("wrong number of bytes!\n");
  108352. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108353. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108354. report("wrote incorrect value!\n");
  108355. }
  108356. oggpack_readinit(&r,buffer,bytes);
  108357. for(i=0;i<vals;i++){
  108358. int tbit=bits?bits:ilog(b[i]);
  108359. if(oggpack_look(&r,tbit)==-1)
  108360. report("out of data!\n");
  108361. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108362. report("looked at incorrect value!\n");
  108363. if(tbit==1)
  108364. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108365. report("looked at single bit incorrect value!\n");
  108366. if(tbit==1){
  108367. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108368. report("read incorrect single bit value!\n");
  108369. }else{
  108370. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108371. report("read incorrect value!\n");
  108372. }
  108373. }
  108374. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108375. }
  108376. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108377. long bytes,i;
  108378. unsigned char *buffer;
  108379. oggpackB_reset(&o);
  108380. for(i=0;i<vals;i++)
  108381. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108382. buffer=oggpackB_get_buffer(&o);
  108383. bytes=oggpackB_bytes(&o);
  108384. if(bytes!=compsize)report("wrong number of bytes!\n");
  108385. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108386. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108387. report("wrote incorrect value!\n");
  108388. }
  108389. oggpackB_readinit(&r,buffer,bytes);
  108390. for(i=0;i<vals;i++){
  108391. int tbit=bits?bits:ilog(b[i]);
  108392. if(oggpackB_look(&r,tbit)==-1)
  108393. report("out of data!\n");
  108394. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108395. report("looked at incorrect value!\n");
  108396. if(tbit==1)
  108397. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108398. report("looked at single bit incorrect value!\n");
  108399. if(tbit==1){
  108400. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108401. report("read incorrect single bit value!\n");
  108402. }else{
  108403. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108404. report("read incorrect value!\n");
  108405. }
  108406. }
  108407. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108408. }
  108409. int main(void){
  108410. unsigned char *buffer;
  108411. long bytes,i;
  108412. static unsigned long testbuffer1[]=
  108413. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108414. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108415. int test1size=43;
  108416. static unsigned long testbuffer2[]=
  108417. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108418. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108419. 85525151,0,12321,1,349528352};
  108420. int test2size=21;
  108421. static unsigned long testbuffer3[]=
  108422. {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,
  108423. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108424. int test3size=56;
  108425. static unsigned long large[]=
  108426. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108427. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108428. 85525151,0,12321,1,2146528352};
  108429. int onesize=33;
  108430. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108431. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108432. 223,4};
  108433. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108434. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108435. 245,251,128};
  108436. int twosize=6;
  108437. static int two[6]={61,255,255,251,231,29};
  108438. static int twoB[6]={247,63,255,253,249,120};
  108439. int threesize=54;
  108440. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108441. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108442. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108443. 100,52,4,14,18,86,77,1};
  108444. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108445. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108446. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108447. 200,20,254,4,58,106,176,144,0};
  108448. int foursize=38;
  108449. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108450. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108451. 28,2,133,0,1};
  108452. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108453. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108454. 129,10,4,32};
  108455. int fivesize=45;
  108456. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108457. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108458. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108459. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108460. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108461. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108462. int sixsize=7;
  108463. static int six[7]={17,177,170,242,169,19,148};
  108464. static int sixB[7]={136,141,85,79,149,200,41};
  108465. /* Test read/write together */
  108466. /* Later we test against pregenerated bitstreams */
  108467. oggpack_writeinit(&o);
  108468. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108469. cliptest(testbuffer1,test1size,0,one,onesize);
  108470. fprintf(stderr,"ok.");
  108471. fprintf(stderr,"\nNull bit call (LSb): ");
  108472. cliptest(testbuffer3,test3size,0,two,twosize);
  108473. fprintf(stderr,"ok.");
  108474. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108475. cliptest(testbuffer2,test2size,0,three,threesize);
  108476. fprintf(stderr,"ok.");
  108477. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108478. oggpack_reset(&o);
  108479. for(i=0;i<test2size;i++)
  108480. oggpack_write(&o,large[i],32);
  108481. buffer=oggpack_get_buffer(&o);
  108482. bytes=oggpack_bytes(&o);
  108483. oggpack_readinit(&r,buffer,bytes);
  108484. for(i=0;i<test2size;i++){
  108485. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108486. if(oggpack_look(&r,32)!=large[i]){
  108487. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108488. oggpack_look(&r,32),large[i]);
  108489. report("read incorrect value!\n");
  108490. }
  108491. oggpack_adv(&r,32);
  108492. }
  108493. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108494. fprintf(stderr,"ok.");
  108495. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108496. cliptest(testbuffer1,test1size,7,four,foursize);
  108497. fprintf(stderr,"ok.");
  108498. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108499. cliptest(testbuffer2,test2size,17,five,fivesize);
  108500. fprintf(stderr,"ok.");
  108501. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108502. cliptest(testbuffer3,test3size,1,six,sixsize);
  108503. fprintf(stderr,"ok.");
  108504. fprintf(stderr,"\nTesting read past end (LSb): ");
  108505. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108506. for(i=0;i<64;i++){
  108507. if(oggpack_read(&r,1)!=0){
  108508. fprintf(stderr,"failed; got -1 prematurely.\n");
  108509. exit(1);
  108510. }
  108511. }
  108512. if(oggpack_look(&r,1)!=-1 ||
  108513. oggpack_read(&r,1)!=-1){
  108514. fprintf(stderr,"failed; read past end without -1.\n");
  108515. exit(1);
  108516. }
  108517. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108518. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108519. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108520. exit(1);
  108521. }
  108522. if(oggpack_look(&r,18)!=0 ||
  108523. oggpack_look(&r,18)!=0){
  108524. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108525. exit(1);
  108526. }
  108527. if(oggpack_look(&r,19)!=-1 ||
  108528. oggpack_look(&r,19)!=-1){
  108529. fprintf(stderr,"failed; read past end without -1.\n");
  108530. exit(1);
  108531. }
  108532. if(oggpack_look(&r,32)!=-1 ||
  108533. oggpack_look(&r,32)!=-1){
  108534. fprintf(stderr,"failed; read past end without -1.\n");
  108535. exit(1);
  108536. }
  108537. oggpack_writeclear(&o);
  108538. fprintf(stderr,"ok.\n");
  108539. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108540. /* Test read/write together */
  108541. /* Later we test against pregenerated bitstreams */
  108542. oggpackB_writeinit(&o);
  108543. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108544. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108545. fprintf(stderr,"ok.");
  108546. fprintf(stderr,"\nNull bit call (MSb): ");
  108547. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108548. fprintf(stderr,"ok.");
  108549. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108550. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108551. fprintf(stderr,"ok.");
  108552. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108553. oggpackB_reset(&o);
  108554. for(i=0;i<test2size;i++)
  108555. oggpackB_write(&o,large[i],32);
  108556. buffer=oggpackB_get_buffer(&o);
  108557. bytes=oggpackB_bytes(&o);
  108558. oggpackB_readinit(&r,buffer,bytes);
  108559. for(i=0;i<test2size;i++){
  108560. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108561. if(oggpackB_look(&r,32)!=large[i]){
  108562. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108563. oggpackB_look(&r,32),large[i]);
  108564. report("read incorrect value!\n");
  108565. }
  108566. oggpackB_adv(&r,32);
  108567. }
  108568. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108569. fprintf(stderr,"ok.");
  108570. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108571. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108572. fprintf(stderr,"ok.");
  108573. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108574. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108575. fprintf(stderr,"ok.");
  108576. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108577. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108578. fprintf(stderr,"ok.");
  108579. fprintf(stderr,"\nTesting read past end (MSb): ");
  108580. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108581. for(i=0;i<64;i++){
  108582. if(oggpackB_read(&r,1)!=0){
  108583. fprintf(stderr,"failed; got -1 prematurely.\n");
  108584. exit(1);
  108585. }
  108586. }
  108587. if(oggpackB_look(&r,1)!=-1 ||
  108588. oggpackB_read(&r,1)!=-1){
  108589. fprintf(stderr,"failed; read past end without -1.\n");
  108590. exit(1);
  108591. }
  108592. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108593. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108594. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108595. exit(1);
  108596. }
  108597. if(oggpackB_look(&r,18)!=0 ||
  108598. oggpackB_look(&r,18)!=0){
  108599. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108600. exit(1);
  108601. }
  108602. if(oggpackB_look(&r,19)!=-1 ||
  108603. oggpackB_look(&r,19)!=-1){
  108604. fprintf(stderr,"failed; read past end without -1.\n");
  108605. exit(1);
  108606. }
  108607. if(oggpackB_look(&r,32)!=-1 ||
  108608. oggpackB_look(&r,32)!=-1){
  108609. fprintf(stderr,"failed; read past end without -1.\n");
  108610. exit(1);
  108611. }
  108612. oggpackB_writeclear(&o);
  108613. fprintf(stderr,"ok.\n\n");
  108614. return(0);
  108615. }
  108616. #endif /* _V_SELFTEST */
  108617. #undef BUFFER_INCREMENT
  108618. #endif
  108619. /*** End of inlined file: bitwise.c ***/
  108620. /*** Start of inlined file: framing.c ***/
  108621. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108622. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108623. // tasks..
  108624. #if JUCE_MSVC
  108625. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108626. #endif
  108627. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108628. #if JUCE_USE_OGGVORBIS
  108629. #include <stdlib.h>
  108630. #include <string.h>
  108631. /* A complete description of Ogg framing exists in docs/framing.html */
  108632. int ogg_page_version(ogg_page *og){
  108633. return((int)(og->header[4]));
  108634. }
  108635. int ogg_page_continued(ogg_page *og){
  108636. return((int)(og->header[5]&0x01));
  108637. }
  108638. int ogg_page_bos(ogg_page *og){
  108639. return((int)(og->header[5]&0x02));
  108640. }
  108641. int ogg_page_eos(ogg_page *og){
  108642. return((int)(og->header[5]&0x04));
  108643. }
  108644. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108645. unsigned char *page=og->header;
  108646. ogg_int64_t granulepos=page[13]&(0xff);
  108647. granulepos= (granulepos<<8)|(page[12]&0xff);
  108648. granulepos= (granulepos<<8)|(page[11]&0xff);
  108649. granulepos= (granulepos<<8)|(page[10]&0xff);
  108650. granulepos= (granulepos<<8)|(page[9]&0xff);
  108651. granulepos= (granulepos<<8)|(page[8]&0xff);
  108652. granulepos= (granulepos<<8)|(page[7]&0xff);
  108653. granulepos= (granulepos<<8)|(page[6]&0xff);
  108654. return(granulepos);
  108655. }
  108656. int ogg_page_serialno(ogg_page *og){
  108657. return(og->header[14] |
  108658. (og->header[15]<<8) |
  108659. (og->header[16]<<16) |
  108660. (og->header[17]<<24));
  108661. }
  108662. long ogg_page_pageno(ogg_page *og){
  108663. return(og->header[18] |
  108664. (og->header[19]<<8) |
  108665. (og->header[20]<<16) |
  108666. (og->header[21]<<24));
  108667. }
  108668. /* returns the number of packets that are completed on this page (if
  108669. the leading packet is begun on a previous page, but ends on this
  108670. page, it's counted */
  108671. /* NOTE:
  108672. If a page consists of a packet begun on a previous page, and a new
  108673. packet begun (but not completed) on this page, the return will be:
  108674. ogg_page_packets(page) ==1,
  108675. ogg_page_continued(page) !=0
  108676. If a page happens to be a single packet that was begun on a
  108677. previous page, and spans to the next page (in the case of a three or
  108678. more page packet), the return will be:
  108679. ogg_page_packets(page) ==0,
  108680. ogg_page_continued(page) !=0
  108681. */
  108682. int ogg_page_packets(ogg_page *og){
  108683. int i,n=og->header[26],count=0;
  108684. for(i=0;i<n;i++)
  108685. if(og->header[27+i]<255)count++;
  108686. return(count);
  108687. }
  108688. #if 0
  108689. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108690. use the static init below) */
  108691. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108692. int i;
  108693. unsigned long r;
  108694. r = index << 24;
  108695. for (i=0; i<8; i++)
  108696. if (r & 0x80000000UL)
  108697. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108698. polynomial, although we use an
  108699. unreflected alg and an init/final
  108700. of 0, not 0xffffffff */
  108701. else
  108702. r<<=1;
  108703. return (r & 0xffffffffUL);
  108704. }
  108705. #endif
  108706. static const ogg_uint32_t crc_lookup[256]={
  108707. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108708. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108709. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108710. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108711. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108712. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108713. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108714. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108715. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108716. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108717. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108718. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108719. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108720. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108721. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108722. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108723. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108724. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108725. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108726. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108727. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108728. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108729. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108730. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108731. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108732. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108733. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108734. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108735. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108736. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108737. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108738. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108739. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108740. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108741. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108742. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108743. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108744. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108745. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108746. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108747. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108748. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108749. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108750. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108751. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108752. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108753. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108754. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108755. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108756. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108757. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108758. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108759. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108760. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108761. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108762. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108763. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108764. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108765. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108766. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108767. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108768. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108769. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108770. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108771. /* init the encode/decode logical stream state */
  108772. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108773. if(os){
  108774. memset(os,0,sizeof(*os));
  108775. os->body_storage=16*1024;
  108776. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108777. os->lacing_storage=1024;
  108778. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108779. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108780. os->serialno=serialno;
  108781. return(0);
  108782. }
  108783. return(-1);
  108784. }
  108785. /* _clear does not free os, only the non-flat storage within */
  108786. int ogg_stream_clear(ogg_stream_state *os){
  108787. if(os){
  108788. if(os->body_data)_ogg_free(os->body_data);
  108789. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108790. if(os->granule_vals)_ogg_free(os->granule_vals);
  108791. memset(os,0,sizeof(*os));
  108792. }
  108793. return(0);
  108794. }
  108795. int ogg_stream_destroy(ogg_stream_state *os){
  108796. if(os){
  108797. ogg_stream_clear(os);
  108798. _ogg_free(os);
  108799. }
  108800. return(0);
  108801. }
  108802. /* Helpers for ogg_stream_encode; this keeps the structure and
  108803. what's happening fairly clear */
  108804. static void _os_body_expand(ogg_stream_state *os,int needed){
  108805. if(os->body_storage<=os->body_fill+needed){
  108806. os->body_storage+=(needed+1024);
  108807. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108808. }
  108809. }
  108810. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108811. if(os->lacing_storage<=os->lacing_fill+needed){
  108812. os->lacing_storage+=(needed+32);
  108813. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108814. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108815. }
  108816. }
  108817. /* checksum the page */
  108818. /* Direct table CRC; note that this will be faster in the future if we
  108819. perform the checksum silmultaneously with other copies */
  108820. void ogg_page_checksum_set(ogg_page *og){
  108821. if(og){
  108822. ogg_uint32_t crc_reg=0;
  108823. int i;
  108824. /* safety; needed for API behavior, but not framing code */
  108825. og->header[22]=0;
  108826. og->header[23]=0;
  108827. og->header[24]=0;
  108828. og->header[25]=0;
  108829. for(i=0;i<og->header_len;i++)
  108830. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108831. for(i=0;i<og->body_len;i++)
  108832. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108833. og->header[22]=(unsigned char)(crc_reg&0xff);
  108834. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108835. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108836. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108837. }
  108838. }
  108839. /* submit data to the internal buffer of the framing engine */
  108840. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108841. int lacing_vals=op->bytes/255+1,i;
  108842. if(os->body_returned){
  108843. /* advance packet data according to the body_returned pointer. We
  108844. had to keep it around to return a pointer into the buffer last
  108845. call */
  108846. os->body_fill-=os->body_returned;
  108847. if(os->body_fill)
  108848. memmove(os->body_data,os->body_data+os->body_returned,
  108849. os->body_fill);
  108850. os->body_returned=0;
  108851. }
  108852. /* make sure we have the buffer storage */
  108853. _os_body_expand(os,op->bytes);
  108854. _os_lacing_expand(os,lacing_vals);
  108855. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108856. the liability of overly clean abstraction for the time being. It
  108857. will actually be fairly easy to eliminate the extra copy in the
  108858. future */
  108859. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108860. os->body_fill+=op->bytes;
  108861. /* Store lacing vals for this packet */
  108862. for(i=0;i<lacing_vals-1;i++){
  108863. os->lacing_vals[os->lacing_fill+i]=255;
  108864. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108865. }
  108866. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108867. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108868. /* flag the first segment as the beginning of the packet */
  108869. os->lacing_vals[os->lacing_fill]|= 0x100;
  108870. os->lacing_fill+=lacing_vals;
  108871. /* for the sake of completeness */
  108872. os->packetno++;
  108873. if(op->e_o_s)os->e_o_s=1;
  108874. return(0);
  108875. }
  108876. /* This will flush remaining packets into a page (returning nonzero),
  108877. even if there is not enough data to trigger a flush normally
  108878. (undersized page). If there are no packets or partial packets to
  108879. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108880. try to flush a normal sized page like ogg_stream_pageout; a call to
  108881. ogg_stream_flush does not guarantee that all packets have flushed.
  108882. Only a return value of 0 from ogg_stream_flush indicates all packet
  108883. data is flushed into pages.
  108884. since ogg_stream_flush will flush the last page in a stream even if
  108885. it's undersized, you almost certainly want to use ogg_stream_pageout
  108886. (and *not* ogg_stream_flush) unless you specifically need to flush
  108887. an page regardless of size in the middle of a stream. */
  108888. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108889. int i;
  108890. int vals=0;
  108891. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108892. int bytes=0;
  108893. long acc=0;
  108894. ogg_int64_t granule_pos=-1;
  108895. if(maxvals==0)return(0);
  108896. /* construct a page */
  108897. /* decide how many segments to include */
  108898. /* If this is the initial header case, the first page must only include
  108899. the initial header packet */
  108900. if(os->b_o_s==0){ /* 'initial header page' case */
  108901. granule_pos=0;
  108902. for(vals=0;vals<maxvals;vals++){
  108903. if((os->lacing_vals[vals]&0x0ff)<255){
  108904. vals++;
  108905. break;
  108906. }
  108907. }
  108908. }else{
  108909. for(vals=0;vals<maxvals;vals++){
  108910. if(acc>4096)break;
  108911. acc+=os->lacing_vals[vals]&0x0ff;
  108912. if((os->lacing_vals[vals]&0xff)<255)
  108913. granule_pos=os->granule_vals[vals];
  108914. }
  108915. }
  108916. /* construct the header in temp storage */
  108917. memcpy(os->header,"OggS",4);
  108918. /* stream structure version */
  108919. os->header[4]=0x00;
  108920. /* continued packet flag? */
  108921. os->header[5]=0x00;
  108922. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108923. /* first page flag? */
  108924. if(os->b_o_s==0)os->header[5]|=0x02;
  108925. /* last page flag? */
  108926. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108927. os->b_o_s=1;
  108928. /* 64 bits of PCM position */
  108929. for(i=6;i<14;i++){
  108930. os->header[i]=(unsigned char)(granule_pos&0xff);
  108931. granule_pos>>=8;
  108932. }
  108933. /* 32 bits of stream serial number */
  108934. {
  108935. long serialno=os->serialno;
  108936. for(i=14;i<18;i++){
  108937. os->header[i]=(unsigned char)(serialno&0xff);
  108938. serialno>>=8;
  108939. }
  108940. }
  108941. /* 32 bits of page counter (we have both counter and page header
  108942. because this val can roll over) */
  108943. if(os->pageno==-1)os->pageno=0; /* because someone called
  108944. stream_reset; this would be a
  108945. strange thing to do in an
  108946. encode stream, but it has
  108947. plausible uses */
  108948. {
  108949. long pageno=os->pageno++;
  108950. for(i=18;i<22;i++){
  108951. os->header[i]=(unsigned char)(pageno&0xff);
  108952. pageno>>=8;
  108953. }
  108954. }
  108955. /* zero for computation; filled in later */
  108956. os->header[22]=0;
  108957. os->header[23]=0;
  108958. os->header[24]=0;
  108959. os->header[25]=0;
  108960. /* segment table */
  108961. os->header[26]=(unsigned char)(vals&0xff);
  108962. for(i=0;i<vals;i++)
  108963. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108964. /* set pointers in the ogg_page struct */
  108965. og->header=os->header;
  108966. og->header_len=os->header_fill=vals+27;
  108967. og->body=os->body_data+os->body_returned;
  108968. og->body_len=bytes;
  108969. /* advance the lacing data and set the body_returned pointer */
  108970. os->lacing_fill-=vals;
  108971. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108972. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108973. os->body_returned+=bytes;
  108974. /* calculate the checksum */
  108975. ogg_page_checksum_set(og);
  108976. /* done */
  108977. return(1);
  108978. }
  108979. /* This constructs pages from buffered packet segments. The pointers
  108980. returned are to static buffers; do not free. The returned buffers are
  108981. good only until the next call (using the same ogg_stream_state) */
  108982. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108983. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108984. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108985. os->lacing_fill>=255 || /* 'segment table full' case */
  108986. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108987. return(ogg_stream_flush(os,og));
  108988. }
  108989. /* not enough data to construct a page and not end of stream */
  108990. return(0);
  108991. }
  108992. int ogg_stream_eos(ogg_stream_state *os){
  108993. return os->e_o_s;
  108994. }
  108995. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108996. /* This has two layers to place more of the multi-serialno and paging
  108997. control in the application's hands. First, we expose a data buffer
  108998. using ogg_sync_buffer(). The app either copies into the
  108999. buffer, or passes it directly to read(), etc. We then call
  109000. ogg_sync_wrote() to tell how many bytes we just added.
  109001. Pages are returned (pointers into the buffer in ogg_sync_state)
  109002. by ogg_sync_pageout(). The page is then submitted to
  109003. ogg_stream_pagein() along with the appropriate
  109004. ogg_stream_state* (ie, matching serialno). We then get raw
  109005. packets out calling ogg_stream_packetout() with a
  109006. ogg_stream_state. */
  109007. /* initialize the struct to a known state */
  109008. int ogg_sync_init(ogg_sync_state *oy){
  109009. if(oy){
  109010. memset(oy,0,sizeof(*oy));
  109011. }
  109012. return(0);
  109013. }
  109014. /* clear non-flat storage within */
  109015. int ogg_sync_clear(ogg_sync_state *oy){
  109016. if(oy){
  109017. if(oy->data)_ogg_free(oy->data);
  109018. ogg_sync_init(oy);
  109019. }
  109020. return(0);
  109021. }
  109022. int ogg_sync_destroy(ogg_sync_state *oy){
  109023. if(oy){
  109024. ogg_sync_clear(oy);
  109025. _ogg_free(oy);
  109026. }
  109027. return(0);
  109028. }
  109029. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109030. /* first, clear out any space that has been previously returned */
  109031. if(oy->returned){
  109032. oy->fill-=oy->returned;
  109033. if(oy->fill>0)
  109034. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109035. oy->returned=0;
  109036. }
  109037. if(size>oy->storage-oy->fill){
  109038. /* We need to extend the internal buffer */
  109039. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109040. if(oy->data)
  109041. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109042. else
  109043. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109044. oy->storage=newsize;
  109045. }
  109046. /* expose a segment at least as large as requested at the fill mark */
  109047. return((char *)oy->data+oy->fill);
  109048. }
  109049. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109050. if(oy->fill+bytes>oy->storage)return(-1);
  109051. oy->fill+=bytes;
  109052. return(0);
  109053. }
  109054. /* sync the stream. This is meant to be useful for finding page
  109055. boundaries.
  109056. return values for this:
  109057. -n) skipped n bytes
  109058. 0) page not ready; more data (no bytes skipped)
  109059. n) page synced at current location; page length n bytes
  109060. */
  109061. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109062. unsigned char *page=oy->data+oy->returned;
  109063. unsigned char *next;
  109064. long bytes=oy->fill-oy->returned;
  109065. if(oy->headerbytes==0){
  109066. int headerbytes,i;
  109067. if(bytes<27)return(0); /* not enough for a header */
  109068. /* verify capture pattern */
  109069. if(memcmp(page,"OggS",4))goto sync_fail;
  109070. headerbytes=page[26]+27;
  109071. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109072. /* count up body length in the segment table */
  109073. for(i=0;i<page[26];i++)
  109074. oy->bodybytes+=page[27+i];
  109075. oy->headerbytes=headerbytes;
  109076. }
  109077. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109078. /* The whole test page is buffered. Verify the checksum */
  109079. {
  109080. /* Grab the checksum bytes, set the header field to zero */
  109081. char chksum[4];
  109082. ogg_page log;
  109083. memcpy(chksum,page+22,4);
  109084. memset(page+22,0,4);
  109085. /* set up a temp page struct and recompute the checksum */
  109086. log.header=page;
  109087. log.header_len=oy->headerbytes;
  109088. log.body=page+oy->headerbytes;
  109089. log.body_len=oy->bodybytes;
  109090. ogg_page_checksum_set(&log);
  109091. /* Compare */
  109092. if(memcmp(chksum,page+22,4)){
  109093. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109094. at all) */
  109095. /* replace the computed checksum with the one actually read in */
  109096. memcpy(page+22,chksum,4);
  109097. /* Bad checksum. Lose sync */
  109098. goto sync_fail;
  109099. }
  109100. }
  109101. /* yes, have a whole page all ready to go */
  109102. {
  109103. unsigned char *page=oy->data+oy->returned;
  109104. long bytes;
  109105. if(og){
  109106. og->header=page;
  109107. og->header_len=oy->headerbytes;
  109108. og->body=page+oy->headerbytes;
  109109. og->body_len=oy->bodybytes;
  109110. }
  109111. oy->unsynced=0;
  109112. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109113. oy->headerbytes=0;
  109114. oy->bodybytes=0;
  109115. return(bytes);
  109116. }
  109117. sync_fail:
  109118. oy->headerbytes=0;
  109119. oy->bodybytes=0;
  109120. /* search for possible capture */
  109121. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109122. if(!next)
  109123. next=oy->data+oy->fill;
  109124. oy->returned=next-oy->data;
  109125. return(-(next-page));
  109126. }
  109127. /* sync the stream and get a page. Keep trying until we find a page.
  109128. Supress 'sync errors' after reporting the first.
  109129. return values:
  109130. -1) recapture (hole in data)
  109131. 0) need more data
  109132. 1) page returned
  109133. Returns pointers into buffered data; invalidated by next call to
  109134. _stream, _clear, _init, or _buffer */
  109135. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109136. /* all we need to do is verify a page at the head of the stream
  109137. buffer. If it doesn't verify, we look for the next potential
  109138. frame */
  109139. for(;;){
  109140. long ret=ogg_sync_pageseek(oy,og);
  109141. if(ret>0){
  109142. /* have a page */
  109143. return(1);
  109144. }
  109145. if(ret==0){
  109146. /* need more data */
  109147. return(0);
  109148. }
  109149. /* head did not start a synced page... skipped some bytes */
  109150. if(!oy->unsynced){
  109151. oy->unsynced=1;
  109152. return(-1);
  109153. }
  109154. /* loop. keep looking */
  109155. }
  109156. }
  109157. /* add the incoming page to the stream state; we decompose the page
  109158. into packet segments here as well. */
  109159. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109160. unsigned char *header=og->header;
  109161. unsigned char *body=og->body;
  109162. long bodysize=og->body_len;
  109163. int segptr=0;
  109164. int version=ogg_page_version(og);
  109165. int continued=ogg_page_continued(og);
  109166. int bos=ogg_page_bos(og);
  109167. int eos=ogg_page_eos(og);
  109168. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109169. int serialno=ogg_page_serialno(og);
  109170. long pageno=ogg_page_pageno(og);
  109171. int segments=header[26];
  109172. /* clean up 'returned data' */
  109173. {
  109174. long lr=os->lacing_returned;
  109175. long br=os->body_returned;
  109176. /* body data */
  109177. if(br){
  109178. os->body_fill-=br;
  109179. if(os->body_fill)
  109180. memmove(os->body_data,os->body_data+br,os->body_fill);
  109181. os->body_returned=0;
  109182. }
  109183. if(lr){
  109184. /* segment table */
  109185. if(os->lacing_fill-lr){
  109186. memmove(os->lacing_vals,os->lacing_vals+lr,
  109187. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109188. memmove(os->granule_vals,os->granule_vals+lr,
  109189. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109190. }
  109191. os->lacing_fill-=lr;
  109192. os->lacing_packet-=lr;
  109193. os->lacing_returned=0;
  109194. }
  109195. }
  109196. /* check the serial number */
  109197. if(serialno!=os->serialno)return(-1);
  109198. if(version>0)return(-1);
  109199. _os_lacing_expand(os,segments+1);
  109200. /* are we in sequence? */
  109201. if(pageno!=os->pageno){
  109202. int i;
  109203. /* unroll previous partial packet (if any) */
  109204. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109205. os->body_fill-=os->lacing_vals[i]&0xff;
  109206. os->lacing_fill=os->lacing_packet;
  109207. /* make a note of dropped data in segment table */
  109208. if(os->pageno!=-1){
  109209. os->lacing_vals[os->lacing_fill++]=0x400;
  109210. os->lacing_packet++;
  109211. }
  109212. }
  109213. /* are we a 'continued packet' page? If so, we may need to skip
  109214. some segments */
  109215. if(continued){
  109216. if(os->lacing_fill<1 ||
  109217. os->lacing_vals[os->lacing_fill-1]==0x400){
  109218. bos=0;
  109219. for(;segptr<segments;segptr++){
  109220. int val=header[27+segptr];
  109221. body+=val;
  109222. bodysize-=val;
  109223. if(val<255){
  109224. segptr++;
  109225. break;
  109226. }
  109227. }
  109228. }
  109229. }
  109230. if(bodysize){
  109231. _os_body_expand(os,bodysize);
  109232. memcpy(os->body_data+os->body_fill,body,bodysize);
  109233. os->body_fill+=bodysize;
  109234. }
  109235. {
  109236. int saved=-1;
  109237. while(segptr<segments){
  109238. int val=header[27+segptr];
  109239. os->lacing_vals[os->lacing_fill]=val;
  109240. os->granule_vals[os->lacing_fill]=-1;
  109241. if(bos){
  109242. os->lacing_vals[os->lacing_fill]|=0x100;
  109243. bos=0;
  109244. }
  109245. if(val<255)saved=os->lacing_fill;
  109246. os->lacing_fill++;
  109247. segptr++;
  109248. if(val<255)os->lacing_packet=os->lacing_fill;
  109249. }
  109250. /* set the granulepos on the last granuleval of the last full packet */
  109251. if(saved!=-1){
  109252. os->granule_vals[saved]=granulepos;
  109253. }
  109254. }
  109255. if(eos){
  109256. os->e_o_s=1;
  109257. if(os->lacing_fill>0)
  109258. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109259. }
  109260. os->pageno=pageno+1;
  109261. return(0);
  109262. }
  109263. /* clear things to an initial state. Good to call, eg, before seeking */
  109264. int ogg_sync_reset(ogg_sync_state *oy){
  109265. oy->fill=0;
  109266. oy->returned=0;
  109267. oy->unsynced=0;
  109268. oy->headerbytes=0;
  109269. oy->bodybytes=0;
  109270. return(0);
  109271. }
  109272. int ogg_stream_reset(ogg_stream_state *os){
  109273. os->body_fill=0;
  109274. os->body_returned=0;
  109275. os->lacing_fill=0;
  109276. os->lacing_packet=0;
  109277. os->lacing_returned=0;
  109278. os->header_fill=0;
  109279. os->e_o_s=0;
  109280. os->b_o_s=0;
  109281. os->pageno=-1;
  109282. os->packetno=0;
  109283. os->granulepos=0;
  109284. return(0);
  109285. }
  109286. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109287. ogg_stream_reset(os);
  109288. os->serialno=serialno;
  109289. return(0);
  109290. }
  109291. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109292. /* The last part of decode. We have the stream broken into packet
  109293. segments. Now we need to group them into packets (or return the
  109294. out of sync markers) */
  109295. int ptr=os->lacing_returned;
  109296. if(os->lacing_packet<=ptr)return(0);
  109297. if(os->lacing_vals[ptr]&0x400){
  109298. /* we need to tell the codec there's a gap; it might need to
  109299. handle previous packet dependencies. */
  109300. os->lacing_returned++;
  109301. os->packetno++;
  109302. return(-1);
  109303. }
  109304. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109305. to ask if there's a whole packet
  109306. waiting */
  109307. /* Gather the whole packet. We'll have no holes or a partial packet */
  109308. {
  109309. int size=os->lacing_vals[ptr]&0xff;
  109310. int bytes=size;
  109311. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109312. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109313. while(size==255){
  109314. int val=os->lacing_vals[++ptr];
  109315. size=val&0xff;
  109316. if(val&0x200)eos=0x200;
  109317. bytes+=size;
  109318. }
  109319. if(op){
  109320. op->e_o_s=eos;
  109321. op->b_o_s=bos;
  109322. op->packet=os->body_data+os->body_returned;
  109323. op->packetno=os->packetno;
  109324. op->granulepos=os->granule_vals[ptr];
  109325. op->bytes=bytes;
  109326. }
  109327. if(adv){
  109328. os->body_returned+=bytes;
  109329. os->lacing_returned=ptr+1;
  109330. os->packetno++;
  109331. }
  109332. }
  109333. return(1);
  109334. }
  109335. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109336. return _packetout(os,op,1);
  109337. }
  109338. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109339. return _packetout(os,op,0);
  109340. }
  109341. void ogg_packet_clear(ogg_packet *op) {
  109342. _ogg_free(op->packet);
  109343. memset(op, 0, sizeof(*op));
  109344. }
  109345. #ifdef _V_SELFTEST
  109346. #include <stdio.h>
  109347. ogg_stream_state os_en, os_de;
  109348. ogg_sync_state oy;
  109349. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109350. long j;
  109351. static int sequence=0;
  109352. static int lastno=0;
  109353. if(op->bytes!=len){
  109354. fprintf(stderr,"incorrect packet length!\n");
  109355. exit(1);
  109356. }
  109357. if(op->granulepos!=pos){
  109358. fprintf(stderr,"incorrect packet position!\n");
  109359. exit(1);
  109360. }
  109361. /* packet number just follows sequence/gap; adjust the input number
  109362. for that */
  109363. if(no==0){
  109364. sequence=0;
  109365. }else{
  109366. sequence++;
  109367. if(no>lastno+1)
  109368. sequence++;
  109369. }
  109370. lastno=no;
  109371. if(op->packetno!=sequence){
  109372. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109373. (long)(op->packetno),sequence);
  109374. exit(1);
  109375. }
  109376. /* Test data */
  109377. for(j=0;j<op->bytes;j++)
  109378. if(op->packet[j]!=((j+no)&0xff)){
  109379. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109380. j,op->packet[j],(j+no)&0xff);
  109381. exit(1);
  109382. }
  109383. }
  109384. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109385. long j;
  109386. /* Test data */
  109387. for(j=0;j<og->body_len;j++)
  109388. if(og->body[j]!=data[j]){
  109389. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109390. j,data[j],og->body[j]);
  109391. exit(1);
  109392. }
  109393. /* Test header */
  109394. for(j=0;j<og->header_len;j++){
  109395. if(og->header[j]!=header[j]){
  109396. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109397. for(j=0;j<header[26]+27;j++)
  109398. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109399. fprintf(stderr,"\n");
  109400. exit(1);
  109401. }
  109402. }
  109403. if(og->header_len!=header[26]+27){
  109404. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109405. og->header_len,header[26]+27);
  109406. exit(1);
  109407. }
  109408. }
  109409. void print_header(ogg_page *og){
  109410. int j;
  109411. fprintf(stderr,"\nHEADER:\n");
  109412. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109413. og->header[0],og->header[1],og->header[2],og->header[3],
  109414. (int)og->header[4],(int)og->header[5]);
  109415. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109416. (og->header[9]<<24)|(og->header[8]<<16)|
  109417. (og->header[7]<<8)|og->header[6],
  109418. (og->header[17]<<24)|(og->header[16]<<16)|
  109419. (og->header[15]<<8)|og->header[14],
  109420. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109421. (og->header[19]<<8)|og->header[18]);
  109422. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109423. (int)og->header[22],(int)og->header[23],
  109424. (int)og->header[24],(int)og->header[25],
  109425. (int)og->header[26]);
  109426. for(j=27;j<og->header_len;j++)
  109427. fprintf(stderr,"%d ",(int)og->header[j]);
  109428. fprintf(stderr,")\n\n");
  109429. }
  109430. void copy_page(ogg_page *og){
  109431. unsigned char *temp=_ogg_malloc(og->header_len);
  109432. memcpy(temp,og->header,og->header_len);
  109433. og->header=temp;
  109434. temp=_ogg_malloc(og->body_len);
  109435. memcpy(temp,og->body,og->body_len);
  109436. og->body=temp;
  109437. }
  109438. void free_page(ogg_page *og){
  109439. _ogg_free (og->header);
  109440. _ogg_free (og->body);
  109441. }
  109442. void error(void){
  109443. fprintf(stderr,"error!\n");
  109444. exit(1);
  109445. }
  109446. /* 17 only */
  109447. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109448. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109449. 0x01,0x02,0x03,0x04,0,0,0,0,
  109450. 0x15,0xed,0xec,0x91,
  109451. 1,
  109452. 17};
  109453. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109454. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109455. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109456. 0x01,0x02,0x03,0x04,0,0,0,0,
  109457. 0x59,0x10,0x6c,0x2c,
  109458. 1,
  109459. 17};
  109460. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109461. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109462. 0x01,0x02,0x03,0x04,1,0,0,0,
  109463. 0x89,0x33,0x85,0xce,
  109464. 13,
  109465. 254,255,0,255,1,255,245,255,255,0,
  109466. 255,255,90};
  109467. /* nil packets; beginning,middle,end */
  109468. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109469. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109470. 0x01,0x02,0x03,0x04,0,0,0,0,
  109471. 0xff,0x7b,0x23,0x17,
  109472. 1,
  109473. 0};
  109474. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109475. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109476. 0x01,0x02,0x03,0x04,1,0,0,0,
  109477. 0x5c,0x3f,0x66,0xcb,
  109478. 17,
  109479. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109480. 255,255,90,0};
  109481. /* large initial packet */
  109482. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109483. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109484. 0x01,0x02,0x03,0x04,0,0,0,0,
  109485. 0x01,0x27,0x31,0xaa,
  109486. 18,
  109487. 255,255,255,255,255,255,255,255,
  109488. 255,255,255,255,255,255,255,255,255,10};
  109489. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109490. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109491. 0x01,0x02,0x03,0x04,1,0,0,0,
  109492. 0x7f,0x4e,0x8a,0xd2,
  109493. 4,
  109494. 255,4,255,0};
  109495. /* continuing packet test */
  109496. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109497. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109498. 0x01,0x02,0x03,0x04,0,0,0,0,
  109499. 0xff,0x7b,0x23,0x17,
  109500. 1,
  109501. 0};
  109502. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109503. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109504. 0x01,0x02,0x03,0x04,1,0,0,0,
  109505. 0x54,0x05,0x51,0xc8,
  109506. 17,
  109507. 255,255,255,255,255,255,255,255,
  109508. 255,255,255,255,255,255,255,255,255};
  109509. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109510. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109511. 0x01,0x02,0x03,0x04,2,0,0,0,
  109512. 0xc8,0xc3,0xcb,0xed,
  109513. 5,
  109514. 10,255,4,255,0};
  109515. /* page with the 255 segment limit */
  109516. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109517. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109518. 0x01,0x02,0x03,0x04,0,0,0,0,
  109519. 0xff,0x7b,0x23,0x17,
  109520. 1,
  109521. 0};
  109522. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109523. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109524. 0x01,0x02,0x03,0x04,1,0,0,0,
  109525. 0xed,0x2a,0x2e,0xa7,
  109526. 255,
  109527. 10,10,10,10,10,10,10,10,
  109528. 10,10,10,10,10,10,10,10,
  109529. 10,10,10,10,10,10,10,10,
  109530. 10,10,10,10,10,10,10,10,
  109531. 10,10,10,10,10,10,10,10,
  109532. 10,10,10,10,10,10,10,10,
  109533. 10,10,10,10,10,10,10,10,
  109534. 10,10,10,10,10,10,10,10,
  109535. 10,10,10,10,10,10,10,10,
  109536. 10,10,10,10,10,10,10,10,
  109537. 10,10,10,10,10,10,10,10,
  109538. 10,10,10,10,10,10,10,10,
  109539. 10,10,10,10,10,10,10,10,
  109540. 10,10,10,10,10,10,10,10,
  109541. 10,10,10,10,10,10,10,10,
  109542. 10,10,10,10,10,10,10,10,
  109543. 10,10,10,10,10,10,10,10,
  109544. 10,10,10,10,10,10,10,10,
  109545. 10,10,10,10,10,10,10,10,
  109546. 10,10,10,10,10,10,10,10,
  109547. 10,10,10,10,10,10,10,10,
  109548. 10,10,10,10,10,10,10,10,
  109549. 10,10,10,10,10,10,10,10,
  109550. 10,10,10,10,10,10,10,10,
  109551. 10,10,10,10,10,10,10,10,
  109552. 10,10,10,10,10,10,10,10,
  109553. 10,10,10,10,10,10,10,10,
  109554. 10,10,10,10,10,10,10,10,
  109555. 10,10,10,10,10,10,10,10,
  109556. 10,10,10,10,10,10,10,10,
  109557. 10,10,10,10,10,10,10,10,
  109558. 10,10,10,10,10,10,10};
  109559. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109560. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109561. 0x01,0x02,0x03,0x04,2,0,0,0,
  109562. 0x6c,0x3b,0x82,0x3d,
  109563. 1,
  109564. 50};
  109565. /* packet that overspans over an entire page */
  109566. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109567. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109568. 0x01,0x02,0x03,0x04,0,0,0,0,
  109569. 0xff,0x7b,0x23,0x17,
  109570. 1,
  109571. 0};
  109572. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109573. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109574. 0x01,0x02,0x03,0x04,1,0,0,0,
  109575. 0x3c,0xd9,0x4d,0x3f,
  109576. 17,
  109577. 100,255,255,255,255,255,255,255,255,
  109578. 255,255,255,255,255,255,255,255};
  109579. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109580. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109581. 0x01,0x02,0x03,0x04,2,0,0,0,
  109582. 0x01,0xd2,0xe5,0xe5,
  109583. 17,
  109584. 255,255,255,255,255,255,255,255,
  109585. 255,255,255,255,255,255,255,255,255};
  109586. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109587. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109588. 0x01,0x02,0x03,0x04,3,0,0,0,
  109589. 0xef,0xdd,0x88,0xde,
  109590. 7,
  109591. 255,255,75,255,4,255,0};
  109592. /* packet that overspans over an entire page */
  109593. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109594. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109595. 0x01,0x02,0x03,0x04,0,0,0,0,
  109596. 0xff,0x7b,0x23,0x17,
  109597. 1,
  109598. 0};
  109599. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109600. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109601. 0x01,0x02,0x03,0x04,1,0,0,0,
  109602. 0x3c,0xd9,0x4d,0x3f,
  109603. 17,
  109604. 100,255,255,255,255,255,255,255,255,
  109605. 255,255,255,255,255,255,255,255};
  109606. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109607. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109608. 0x01,0x02,0x03,0x04,2,0,0,0,
  109609. 0xd4,0xe0,0x60,0xe5,
  109610. 1,0};
  109611. void test_pack(const int *pl, const int **headers, int byteskip,
  109612. int pageskip, int packetskip){
  109613. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109614. long inptr=0;
  109615. long outptr=0;
  109616. long deptr=0;
  109617. long depacket=0;
  109618. long granule_pos=7,pageno=0;
  109619. int i,j,packets,pageout=pageskip;
  109620. int eosflag=0;
  109621. int bosflag=0;
  109622. int byteskipcount=0;
  109623. ogg_stream_reset(&os_en);
  109624. ogg_stream_reset(&os_de);
  109625. ogg_sync_reset(&oy);
  109626. for(packets=0;packets<packetskip;packets++)
  109627. depacket+=pl[packets];
  109628. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109629. for(i=0;i<packets;i++){
  109630. /* construct a test packet */
  109631. ogg_packet op;
  109632. int len=pl[i];
  109633. op.packet=data+inptr;
  109634. op.bytes=len;
  109635. op.e_o_s=(pl[i+1]<0?1:0);
  109636. op.granulepos=granule_pos;
  109637. granule_pos+=1024;
  109638. for(j=0;j<len;j++)data[inptr++]=i+j;
  109639. /* submit the test packet */
  109640. ogg_stream_packetin(&os_en,&op);
  109641. /* retrieve any finished pages */
  109642. {
  109643. ogg_page og;
  109644. while(ogg_stream_pageout(&os_en,&og)){
  109645. /* We have a page. Check it carefully */
  109646. fprintf(stderr,"%ld, ",pageno);
  109647. if(headers[pageno]==NULL){
  109648. fprintf(stderr,"coded too many pages!\n");
  109649. exit(1);
  109650. }
  109651. check_page(data+outptr,headers[pageno],&og);
  109652. outptr+=og.body_len;
  109653. pageno++;
  109654. if(pageskip){
  109655. bosflag=1;
  109656. pageskip--;
  109657. deptr+=og.body_len;
  109658. }
  109659. /* have a complete page; submit it to sync/decode */
  109660. {
  109661. ogg_page og_de;
  109662. ogg_packet op_de,op_de2;
  109663. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109664. char *next=buf;
  109665. byteskipcount+=og.header_len;
  109666. if(byteskipcount>byteskip){
  109667. memcpy(next,og.header,byteskipcount-byteskip);
  109668. next+=byteskipcount-byteskip;
  109669. byteskipcount=byteskip;
  109670. }
  109671. byteskipcount+=og.body_len;
  109672. if(byteskipcount>byteskip){
  109673. memcpy(next,og.body,byteskipcount-byteskip);
  109674. next+=byteskipcount-byteskip;
  109675. byteskipcount=byteskip;
  109676. }
  109677. ogg_sync_wrote(&oy,next-buf);
  109678. while(1){
  109679. int ret=ogg_sync_pageout(&oy,&og_de);
  109680. if(ret==0)break;
  109681. if(ret<0)continue;
  109682. /* got a page. Happy happy. Verify that it's good. */
  109683. fprintf(stderr,"(%ld), ",pageout);
  109684. check_page(data+deptr,headers[pageout],&og_de);
  109685. deptr+=og_de.body_len;
  109686. pageout++;
  109687. /* submit it to deconstitution */
  109688. ogg_stream_pagein(&os_de,&og_de);
  109689. /* packets out? */
  109690. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109691. ogg_stream_packetpeek(&os_de,NULL);
  109692. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109693. /* verify peek and out match */
  109694. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109695. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109696. depacket);
  109697. exit(1);
  109698. }
  109699. /* verify the packet! */
  109700. /* check data */
  109701. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109702. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109703. depacket);
  109704. exit(1);
  109705. }
  109706. /* check bos flag */
  109707. if(bosflag==0 && op_de.b_o_s==0){
  109708. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109709. exit(1);
  109710. }
  109711. if(bosflag && op_de.b_o_s){
  109712. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109713. exit(1);
  109714. }
  109715. bosflag=1;
  109716. depacket+=op_de.bytes;
  109717. /* check eos flag */
  109718. if(eosflag){
  109719. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109720. exit(1);
  109721. }
  109722. if(op_de.e_o_s)eosflag=1;
  109723. /* check granulepos flag */
  109724. if(op_de.granulepos!=-1){
  109725. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109726. }
  109727. }
  109728. }
  109729. }
  109730. }
  109731. }
  109732. }
  109733. _ogg_free(data);
  109734. if(headers[pageno]!=NULL){
  109735. fprintf(stderr,"did not write last page!\n");
  109736. exit(1);
  109737. }
  109738. if(headers[pageout]!=NULL){
  109739. fprintf(stderr,"did not decode last page!\n");
  109740. exit(1);
  109741. }
  109742. if(inptr!=outptr){
  109743. fprintf(stderr,"encoded page data incomplete!\n");
  109744. exit(1);
  109745. }
  109746. if(inptr!=deptr){
  109747. fprintf(stderr,"decoded page data incomplete!\n");
  109748. exit(1);
  109749. }
  109750. if(inptr!=depacket){
  109751. fprintf(stderr,"decoded packet data incomplete!\n");
  109752. exit(1);
  109753. }
  109754. if(!eosflag){
  109755. fprintf(stderr,"Never got a packet with EOS set!\n");
  109756. exit(1);
  109757. }
  109758. fprintf(stderr,"ok.\n");
  109759. }
  109760. int main(void){
  109761. ogg_stream_init(&os_en,0x04030201);
  109762. ogg_stream_init(&os_de,0x04030201);
  109763. ogg_sync_init(&oy);
  109764. /* Exercise each code path in the framing code. Also verify that
  109765. the checksums are working. */
  109766. {
  109767. /* 17 only */
  109768. const int packets[]={17, -1};
  109769. const int *headret[]={head1_0,NULL};
  109770. fprintf(stderr,"testing single page encoding... ");
  109771. test_pack(packets,headret,0,0,0);
  109772. }
  109773. {
  109774. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109775. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109776. const int *headret[]={head1_1,head2_1,NULL};
  109777. fprintf(stderr,"testing basic page encoding... ");
  109778. test_pack(packets,headret,0,0,0);
  109779. }
  109780. {
  109781. /* nil packets; beginning,middle,end */
  109782. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109783. const int *headret[]={head1_2,head2_2,NULL};
  109784. fprintf(stderr,"testing basic nil packets... ");
  109785. test_pack(packets,headret,0,0,0);
  109786. }
  109787. {
  109788. /* large initial packet */
  109789. const int packets[]={4345,259,255,-1};
  109790. const int *headret[]={head1_3,head2_3,NULL};
  109791. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109792. test_pack(packets,headret,0,0,0);
  109793. }
  109794. {
  109795. /* continuing packet test */
  109796. const int packets[]={0,4345,259,255,-1};
  109797. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109798. fprintf(stderr,"testing single packet page span... ");
  109799. test_pack(packets,headret,0,0,0);
  109800. }
  109801. /* page with the 255 segment limit */
  109802. {
  109803. const int packets[]={0,10,10,10,10,10,10,10,10,
  109804. 10,10,10,10,10,10,10,10,
  109805. 10,10,10,10,10,10,10,10,
  109806. 10,10,10,10,10,10,10,10,
  109807. 10,10,10,10,10,10,10,10,
  109808. 10,10,10,10,10,10,10,10,
  109809. 10,10,10,10,10,10,10,10,
  109810. 10,10,10,10,10,10,10,10,
  109811. 10,10,10,10,10,10,10,10,
  109812. 10,10,10,10,10,10,10,10,
  109813. 10,10,10,10,10,10,10,10,
  109814. 10,10,10,10,10,10,10,10,
  109815. 10,10,10,10,10,10,10,10,
  109816. 10,10,10,10,10,10,10,10,
  109817. 10,10,10,10,10,10,10,10,
  109818. 10,10,10,10,10,10,10,10,
  109819. 10,10,10,10,10,10,10,10,
  109820. 10,10,10,10,10,10,10,10,
  109821. 10,10,10,10,10,10,10,10,
  109822. 10,10,10,10,10,10,10,10,
  109823. 10,10,10,10,10,10,10,10,
  109824. 10,10,10,10,10,10,10,10,
  109825. 10,10,10,10,10,10,10,10,
  109826. 10,10,10,10,10,10,10,10,
  109827. 10,10,10,10,10,10,10,10,
  109828. 10,10,10,10,10,10,10,10,
  109829. 10,10,10,10,10,10,10,10,
  109830. 10,10,10,10,10,10,10,10,
  109831. 10,10,10,10,10,10,10,10,
  109832. 10,10,10,10,10,10,10,10,
  109833. 10,10,10,10,10,10,10,10,
  109834. 10,10,10,10,10,10,10,50,-1};
  109835. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109836. fprintf(stderr,"testing max packet segments... ");
  109837. test_pack(packets,headret,0,0,0);
  109838. }
  109839. {
  109840. /* packet that overspans over an entire page */
  109841. const int packets[]={0,100,9000,259,255,-1};
  109842. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109843. fprintf(stderr,"testing very large packets... ");
  109844. test_pack(packets,headret,0,0,0);
  109845. }
  109846. {
  109847. /* test for the libogg 1.1.1 resync in large continuation bug
  109848. found by Josh Coalson) */
  109849. const int packets[]={0,100,9000,259,255,-1};
  109850. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109851. fprintf(stderr,"testing continuation resync in very large packets... ");
  109852. test_pack(packets,headret,100,2,3);
  109853. }
  109854. {
  109855. /* term only page. why not? */
  109856. const int packets[]={0,100,4080,-1};
  109857. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109858. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109859. test_pack(packets,headret,0,0,0);
  109860. }
  109861. {
  109862. /* build a bunch of pages for testing */
  109863. unsigned char *data=_ogg_malloc(1024*1024);
  109864. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109865. int inptr=0,i,j;
  109866. ogg_page og[5];
  109867. ogg_stream_reset(&os_en);
  109868. for(i=0;pl[i]!=-1;i++){
  109869. ogg_packet op;
  109870. int len=pl[i];
  109871. op.packet=data+inptr;
  109872. op.bytes=len;
  109873. op.e_o_s=(pl[i+1]<0?1:0);
  109874. op.granulepos=(i+1)*1000;
  109875. for(j=0;j<len;j++)data[inptr++]=i+j;
  109876. ogg_stream_packetin(&os_en,&op);
  109877. }
  109878. _ogg_free(data);
  109879. /* retrieve finished pages */
  109880. for(i=0;i<5;i++){
  109881. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109882. fprintf(stderr,"Too few pages output building sync tests!\n");
  109883. exit(1);
  109884. }
  109885. copy_page(&og[i]);
  109886. }
  109887. /* Test lost pages on pagein/packetout: no rollback */
  109888. {
  109889. ogg_page temp;
  109890. ogg_packet test;
  109891. fprintf(stderr,"Testing loss of pages... ");
  109892. ogg_sync_reset(&oy);
  109893. ogg_stream_reset(&os_de);
  109894. for(i=0;i<5;i++){
  109895. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109896. og[i].header_len);
  109897. ogg_sync_wrote(&oy,og[i].header_len);
  109898. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109899. ogg_sync_wrote(&oy,og[i].body_len);
  109900. }
  109901. ogg_sync_pageout(&oy,&temp);
  109902. ogg_stream_pagein(&os_de,&temp);
  109903. ogg_sync_pageout(&oy,&temp);
  109904. ogg_stream_pagein(&os_de,&temp);
  109905. ogg_sync_pageout(&oy,&temp);
  109906. /* skip */
  109907. ogg_sync_pageout(&oy,&temp);
  109908. ogg_stream_pagein(&os_de,&temp);
  109909. /* do we get the expected results/packets? */
  109910. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109911. checkpacket(&test,0,0,0);
  109912. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109913. checkpacket(&test,100,1,-1);
  109914. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109915. checkpacket(&test,4079,2,3000);
  109916. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109917. fprintf(stderr,"Error: loss of page did not return error\n");
  109918. exit(1);
  109919. }
  109920. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109921. checkpacket(&test,76,5,-1);
  109922. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109923. checkpacket(&test,34,6,-1);
  109924. fprintf(stderr,"ok.\n");
  109925. }
  109926. /* Test lost pages on pagein/packetout: rollback with continuation */
  109927. {
  109928. ogg_page temp;
  109929. ogg_packet test;
  109930. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109931. ogg_sync_reset(&oy);
  109932. ogg_stream_reset(&os_de);
  109933. for(i=0;i<5;i++){
  109934. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109935. og[i].header_len);
  109936. ogg_sync_wrote(&oy,og[i].header_len);
  109937. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109938. ogg_sync_wrote(&oy,og[i].body_len);
  109939. }
  109940. ogg_sync_pageout(&oy,&temp);
  109941. ogg_stream_pagein(&os_de,&temp);
  109942. ogg_sync_pageout(&oy,&temp);
  109943. ogg_stream_pagein(&os_de,&temp);
  109944. ogg_sync_pageout(&oy,&temp);
  109945. ogg_stream_pagein(&os_de,&temp);
  109946. ogg_sync_pageout(&oy,&temp);
  109947. /* skip */
  109948. ogg_sync_pageout(&oy,&temp);
  109949. ogg_stream_pagein(&os_de,&temp);
  109950. /* do we get the expected results/packets? */
  109951. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109952. checkpacket(&test,0,0,0);
  109953. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109954. checkpacket(&test,100,1,-1);
  109955. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109956. checkpacket(&test,4079,2,3000);
  109957. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109958. checkpacket(&test,2956,3,4000);
  109959. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109960. fprintf(stderr,"Error: loss of page did not return error\n");
  109961. exit(1);
  109962. }
  109963. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109964. checkpacket(&test,300,13,14000);
  109965. fprintf(stderr,"ok.\n");
  109966. }
  109967. /* the rest only test sync */
  109968. {
  109969. ogg_page og_de;
  109970. /* Test fractional page inputs: incomplete capture */
  109971. fprintf(stderr,"Testing sync on partial inputs... ");
  109972. ogg_sync_reset(&oy);
  109973. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109974. 3);
  109975. ogg_sync_wrote(&oy,3);
  109976. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109977. /* Test fractional page inputs: incomplete fixed header */
  109978. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109979. 20);
  109980. ogg_sync_wrote(&oy,20);
  109981. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109982. /* Test fractional page inputs: incomplete header */
  109983. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109984. 5);
  109985. ogg_sync_wrote(&oy,5);
  109986. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109987. /* Test fractional page inputs: incomplete body */
  109988. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109989. og[1].header_len-28);
  109990. ogg_sync_wrote(&oy,og[1].header_len-28);
  109991. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109992. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109993. ogg_sync_wrote(&oy,1000);
  109994. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109995. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109996. og[1].body_len-1000);
  109997. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109998. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109999. fprintf(stderr,"ok.\n");
  110000. }
  110001. /* Test fractional page inputs: page + incomplete capture */
  110002. {
  110003. ogg_page og_de;
  110004. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  110005. ogg_sync_reset(&oy);
  110006. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110007. og[1].header_len);
  110008. ogg_sync_wrote(&oy,og[1].header_len);
  110009. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110010. og[1].body_len);
  110011. ogg_sync_wrote(&oy,og[1].body_len);
  110012. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110013. 20);
  110014. ogg_sync_wrote(&oy,20);
  110015. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110016. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110017. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110018. og[1].header_len-20);
  110019. ogg_sync_wrote(&oy,og[1].header_len-20);
  110020. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110021. og[1].body_len);
  110022. ogg_sync_wrote(&oy,og[1].body_len);
  110023. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110024. fprintf(stderr,"ok.\n");
  110025. }
  110026. /* Test recapture: garbage + page */
  110027. {
  110028. ogg_page og_de;
  110029. fprintf(stderr,"Testing search for capture... ");
  110030. ogg_sync_reset(&oy);
  110031. /* 'garbage' */
  110032. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110033. og[1].body_len);
  110034. ogg_sync_wrote(&oy,og[1].body_len);
  110035. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110036. og[1].header_len);
  110037. ogg_sync_wrote(&oy,og[1].header_len);
  110038. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110039. og[1].body_len);
  110040. ogg_sync_wrote(&oy,og[1].body_len);
  110041. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110042. 20);
  110043. ogg_sync_wrote(&oy,20);
  110044. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110045. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110046. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110047. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110048. og[2].header_len-20);
  110049. ogg_sync_wrote(&oy,og[2].header_len-20);
  110050. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110051. og[2].body_len);
  110052. ogg_sync_wrote(&oy,og[2].body_len);
  110053. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110054. fprintf(stderr,"ok.\n");
  110055. }
  110056. /* Test recapture: page + garbage + page */
  110057. {
  110058. ogg_page og_de;
  110059. fprintf(stderr,"Testing recapture... ");
  110060. ogg_sync_reset(&oy);
  110061. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110062. og[1].header_len);
  110063. ogg_sync_wrote(&oy,og[1].header_len);
  110064. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110065. og[1].body_len);
  110066. ogg_sync_wrote(&oy,og[1].body_len);
  110067. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110068. og[2].header_len);
  110069. ogg_sync_wrote(&oy,og[2].header_len);
  110070. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110071. og[2].header_len);
  110072. ogg_sync_wrote(&oy,og[2].header_len);
  110073. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110074. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110075. og[2].body_len-5);
  110076. ogg_sync_wrote(&oy,og[2].body_len-5);
  110077. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110078. og[3].header_len);
  110079. ogg_sync_wrote(&oy,og[3].header_len);
  110080. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110081. og[3].body_len);
  110082. ogg_sync_wrote(&oy,og[3].body_len);
  110083. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110084. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110085. fprintf(stderr,"ok.\n");
  110086. }
  110087. /* Free page data that was previously copied */
  110088. {
  110089. for(i=0;i<5;i++){
  110090. free_page(&og[i]);
  110091. }
  110092. }
  110093. }
  110094. return(0);
  110095. }
  110096. #endif
  110097. #endif
  110098. /*** End of inlined file: framing.c ***/
  110099. /*** Start of inlined file: analysis.c ***/
  110100. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110101. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110102. // tasks..
  110103. #if JUCE_MSVC
  110104. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110105. #endif
  110106. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110107. #if JUCE_USE_OGGVORBIS
  110108. #include <stdio.h>
  110109. #include <string.h>
  110110. #include <math.h>
  110111. /*** Start of inlined file: codec_internal.h ***/
  110112. #ifndef _V_CODECI_H_
  110113. #define _V_CODECI_H_
  110114. /*** Start of inlined file: envelope.h ***/
  110115. #ifndef _V_ENVELOPE_
  110116. #define _V_ENVELOPE_
  110117. /*** Start of inlined file: mdct.h ***/
  110118. #ifndef _OGG_mdct_H_
  110119. #define _OGG_mdct_H_
  110120. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110121. #ifdef MDCT_INTEGERIZED
  110122. #define DATA_TYPE int
  110123. #define REG_TYPE register int
  110124. #define TRIGBITS 14
  110125. #define cPI3_8 6270
  110126. #define cPI2_8 11585
  110127. #define cPI1_8 15137
  110128. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110129. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110130. #define HALVE(x) ((x)>>1)
  110131. #else
  110132. #define DATA_TYPE float
  110133. #define REG_TYPE float
  110134. #define cPI3_8 .38268343236508977175F
  110135. #define cPI2_8 .70710678118654752441F
  110136. #define cPI1_8 .92387953251128675613F
  110137. #define FLOAT_CONV(x) (x)
  110138. #define MULT_NORM(x) (x)
  110139. #define HALVE(x) ((x)*.5f)
  110140. #endif
  110141. typedef struct {
  110142. int n;
  110143. int log2n;
  110144. DATA_TYPE *trig;
  110145. int *bitrev;
  110146. DATA_TYPE scale;
  110147. } mdct_lookup;
  110148. extern void mdct_init(mdct_lookup *lookup,int n);
  110149. extern void mdct_clear(mdct_lookup *l);
  110150. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110151. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110152. #endif
  110153. /*** End of inlined file: mdct.h ***/
  110154. #define VE_PRE 16
  110155. #define VE_WIN 4
  110156. #define VE_POST 2
  110157. #define VE_AMP (VE_PRE+VE_POST-1)
  110158. #define VE_BANDS 7
  110159. #define VE_NEARDC 15
  110160. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110161. #define VE_MAXSTRETCH 12 /* one-third full block */
  110162. typedef struct {
  110163. float ampbuf[VE_AMP];
  110164. int ampptr;
  110165. float nearDC[VE_NEARDC];
  110166. float nearDC_acc;
  110167. float nearDC_partialacc;
  110168. int nearptr;
  110169. } envelope_filter_state;
  110170. typedef struct {
  110171. int begin;
  110172. int end;
  110173. float *window;
  110174. float total;
  110175. } envelope_band;
  110176. typedef struct {
  110177. int ch;
  110178. int winlength;
  110179. int searchstep;
  110180. float minenergy;
  110181. mdct_lookup mdct;
  110182. float *mdct_win;
  110183. envelope_band band[VE_BANDS];
  110184. envelope_filter_state *filter;
  110185. int stretch;
  110186. int *mark;
  110187. long storage;
  110188. long current;
  110189. long curmark;
  110190. long cursor;
  110191. } envelope_lookup;
  110192. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110193. extern void _ve_envelope_clear(envelope_lookup *e);
  110194. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110195. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110196. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110197. #endif
  110198. /*** End of inlined file: envelope.h ***/
  110199. /*** Start of inlined file: codebook.h ***/
  110200. #ifndef _V_CODEBOOK_H_
  110201. #define _V_CODEBOOK_H_
  110202. /* This structure encapsulates huffman and VQ style encoding books; it
  110203. doesn't do anything specific to either.
  110204. valuelist/quantlist are nonNULL (and q_* significant) only if
  110205. there's entry->value mapping to be done.
  110206. If encode-side mapping must be done (and thus the entry needs to be
  110207. hunted), the auxiliary encode pointer will point to a decision
  110208. tree. This is true of both VQ and huffman, but is mostly useful
  110209. with VQ.
  110210. */
  110211. typedef struct static_codebook{
  110212. long dim; /* codebook dimensions (elements per vector) */
  110213. long entries; /* codebook entries */
  110214. long *lengthlist; /* codeword lengths in bits */
  110215. /* mapping ***************************************************************/
  110216. int maptype; /* 0=none
  110217. 1=implicitly populated values from map column
  110218. 2=listed arbitrary values */
  110219. /* The below does a linear, single monotonic sequence mapping. */
  110220. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110221. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110222. int q_quant; /* bits: 0 < quant <= 16 */
  110223. int q_sequencep; /* bitflag */
  110224. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110225. map == 2: list of dim*entries quantized entry vals
  110226. */
  110227. /* encode helpers ********************************************************/
  110228. struct encode_aux_nearestmatch *nearest_tree;
  110229. struct encode_aux_threshmatch *thresh_tree;
  110230. struct encode_aux_pigeonhole *pigeon_tree;
  110231. int allocedp;
  110232. } static_codebook;
  110233. /* this structures an arbitrary trained book to quickly find the
  110234. nearest cell match */
  110235. typedef struct encode_aux_nearestmatch{
  110236. /* pre-calculated partitioning tree */
  110237. long *ptr0;
  110238. long *ptr1;
  110239. long *p; /* decision points (each is an entry) */
  110240. long *q; /* decision points (each is an entry) */
  110241. long aux; /* number of tree entries */
  110242. long alloc;
  110243. } encode_aux_nearestmatch;
  110244. /* assumes a maptype of 1; encode side only, so that's OK */
  110245. typedef struct encode_aux_threshmatch{
  110246. float *quantthresh;
  110247. long *quantmap;
  110248. int quantvals;
  110249. int threshvals;
  110250. } encode_aux_threshmatch;
  110251. typedef struct encode_aux_pigeonhole{
  110252. float min;
  110253. float del;
  110254. int mapentries;
  110255. int quantvals;
  110256. long *pigeonmap;
  110257. long fittotal;
  110258. long *fitlist;
  110259. long *fitmap;
  110260. long *fitlength;
  110261. } encode_aux_pigeonhole;
  110262. typedef struct codebook{
  110263. long dim; /* codebook dimensions (elements per vector) */
  110264. long entries; /* codebook entries */
  110265. long used_entries; /* populated codebook entries */
  110266. const static_codebook *c;
  110267. /* for encode, the below are entry-ordered, fully populated */
  110268. /* for decode, the below are ordered by bitreversed codeword and only
  110269. used entries are populated */
  110270. float *valuelist; /* list of dim*entries actual entry values */
  110271. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110272. int *dec_index; /* only used if sparseness collapsed */
  110273. char *dec_codelengths;
  110274. ogg_uint32_t *dec_firsttable;
  110275. int dec_firsttablen;
  110276. int dec_maxlength;
  110277. } codebook;
  110278. extern void vorbis_staticbook_clear(static_codebook *b);
  110279. extern void vorbis_staticbook_destroy(static_codebook *b);
  110280. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110281. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110282. extern void vorbis_book_clear(codebook *b);
  110283. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110284. extern float *_book_logdist(const static_codebook *b,float *vals);
  110285. extern float _float32_unpack(long val);
  110286. extern long _float32_pack(float val);
  110287. extern int _best(codebook *book, float *a, int step);
  110288. extern int _ilog(unsigned int v);
  110289. extern long _book_maptype1_quantvals(const static_codebook *b);
  110290. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110291. extern long vorbis_book_codeword(codebook *book,int entry);
  110292. extern long vorbis_book_codelen(codebook *book,int entry);
  110293. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110294. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110295. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110296. extern int vorbis_book_errorv(codebook *book, float *a);
  110297. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110298. oggpack_buffer *b);
  110299. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110300. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110301. oggpack_buffer *b,int n);
  110302. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110303. oggpack_buffer *b,int n);
  110304. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110305. oggpack_buffer *b,int n);
  110306. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110307. long off,int ch,
  110308. oggpack_buffer *b,int n);
  110309. #endif
  110310. /*** End of inlined file: codebook.h ***/
  110311. #define BLOCKTYPE_IMPULSE 0
  110312. #define BLOCKTYPE_PADDING 1
  110313. #define BLOCKTYPE_TRANSITION 0
  110314. #define BLOCKTYPE_LONG 1
  110315. #define PACKETBLOBS 15
  110316. typedef struct vorbis_block_internal{
  110317. float **pcmdelay; /* this is a pointer into local storage */
  110318. float ampmax;
  110319. int blocktype;
  110320. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110321. blob [PACKETBLOBS/2] points to
  110322. the oggpack_buffer in the
  110323. main vorbis_block */
  110324. } vorbis_block_internal;
  110325. typedef void vorbis_look_floor;
  110326. typedef void vorbis_look_residue;
  110327. typedef void vorbis_look_transform;
  110328. /* mode ************************************************************/
  110329. typedef struct {
  110330. int blockflag;
  110331. int windowtype;
  110332. int transformtype;
  110333. int mapping;
  110334. } vorbis_info_mode;
  110335. typedef void vorbis_info_floor;
  110336. typedef void vorbis_info_residue;
  110337. typedef void vorbis_info_mapping;
  110338. /*** Start of inlined file: psy.h ***/
  110339. #ifndef _V_PSY_H_
  110340. #define _V_PSY_H_
  110341. /*** Start of inlined file: smallft.h ***/
  110342. #ifndef _V_SMFT_H_
  110343. #define _V_SMFT_H_
  110344. typedef struct {
  110345. int n;
  110346. float *trigcache;
  110347. int *splitcache;
  110348. } drft_lookup;
  110349. extern void drft_forward(drft_lookup *l,float *data);
  110350. extern void drft_backward(drft_lookup *l,float *data);
  110351. extern void drft_init(drft_lookup *l,int n);
  110352. extern void drft_clear(drft_lookup *l);
  110353. #endif
  110354. /*** End of inlined file: smallft.h ***/
  110355. /*** Start of inlined file: backends.h ***/
  110356. /* this is exposed up here because we need it for static modes.
  110357. Lookups for each backend aren't exposed because there's no reason
  110358. to do so */
  110359. #ifndef _vorbis_backend_h_
  110360. #define _vorbis_backend_h_
  110361. /* this would all be simpler/shorter with templates, but.... */
  110362. /* Floor backend generic *****************************************/
  110363. typedef struct{
  110364. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110365. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110366. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110367. void (*free_info) (vorbis_info_floor *);
  110368. void (*free_look) (vorbis_look_floor *);
  110369. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110370. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110371. void *buffer,float *);
  110372. } vorbis_func_floor;
  110373. typedef struct{
  110374. int order;
  110375. long rate;
  110376. long barkmap;
  110377. int ampbits;
  110378. int ampdB;
  110379. int numbooks; /* <= 16 */
  110380. int books[16];
  110381. float lessthan; /* encode-only config setting hacks for libvorbis */
  110382. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110383. } vorbis_info_floor0;
  110384. #define VIF_POSIT 63
  110385. #define VIF_CLASS 16
  110386. #define VIF_PARTS 31
  110387. typedef struct{
  110388. int partitions; /* 0 to 31 */
  110389. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110390. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110391. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110392. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110393. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110394. int mult; /* 1 2 3 or 4 */
  110395. int postlist[VIF_POSIT+2]; /* first two implicit */
  110396. /* encode side analysis parameters */
  110397. float maxover;
  110398. float maxunder;
  110399. float maxerr;
  110400. float twofitweight;
  110401. float twofitatten;
  110402. int n;
  110403. } vorbis_info_floor1;
  110404. /* Residue backend generic *****************************************/
  110405. typedef struct{
  110406. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110407. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110408. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110409. vorbis_info_residue *);
  110410. void (*free_info) (vorbis_info_residue *);
  110411. void (*free_look) (vorbis_look_residue *);
  110412. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110413. float **,int *,int);
  110414. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110415. vorbis_look_residue *,
  110416. float **,float **,int *,int,long **);
  110417. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110418. float **,int *,int);
  110419. } vorbis_func_residue;
  110420. typedef struct vorbis_info_residue0{
  110421. /* block-partitioned VQ coded straight residue */
  110422. long begin;
  110423. long end;
  110424. /* first stage (lossless partitioning) */
  110425. int grouping; /* group n vectors per partition */
  110426. int partitions; /* possible codebooks for a partition */
  110427. int groupbook; /* huffbook for partitioning */
  110428. int secondstages[64]; /* expanded out to pointers in lookup */
  110429. int booklist[256]; /* list of second stage books */
  110430. float classmetric1[64];
  110431. float classmetric2[64];
  110432. } vorbis_info_residue0;
  110433. /* Mapping backend generic *****************************************/
  110434. typedef struct{
  110435. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110436. oggpack_buffer *);
  110437. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110438. void (*free_info) (vorbis_info_mapping *);
  110439. int (*forward) (struct vorbis_block *vb);
  110440. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110441. } vorbis_func_mapping;
  110442. typedef struct vorbis_info_mapping0{
  110443. int submaps; /* <= 16 */
  110444. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110445. int floorsubmap[16]; /* [mux] submap to floors */
  110446. int residuesubmap[16]; /* [mux] submap to residue */
  110447. int coupling_steps;
  110448. int coupling_mag[256];
  110449. int coupling_ang[256];
  110450. } vorbis_info_mapping0;
  110451. #endif
  110452. /*** End of inlined file: backends.h ***/
  110453. #ifndef EHMER_MAX
  110454. #define EHMER_MAX 56
  110455. #endif
  110456. /* psychoacoustic setup ********************************************/
  110457. #define P_BANDS 17 /* 62Hz to 16kHz */
  110458. #define P_LEVELS 8 /* 30dB to 100dB */
  110459. #define P_LEVEL_0 30. /* 30 dB */
  110460. #define P_NOISECURVES 3
  110461. #define NOISE_COMPAND_LEVELS 40
  110462. typedef struct vorbis_info_psy{
  110463. int blockflag;
  110464. float ath_adjatt;
  110465. float ath_maxatt;
  110466. float tone_masteratt[P_NOISECURVES];
  110467. float tone_centerboost;
  110468. float tone_decay;
  110469. float tone_abs_limit;
  110470. float toneatt[P_BANDS];
  110471. int noisemaskp;
  110472. float noisemaxsupp;
  110473. float noisewindowlo;
  110474. float noisewindowhi;
  110475. int noisewindowlomin;
  110476. int noisewindowhimin;
  110477. int noisewindowfixed;
  110478. float noiseoff[P_NOISECURVES][P_BANDS];
  110479. float noisecompand[NOISE_COMPAND_LEVELS];
  110480. float max_curve_dB;
  110481. int normal_channel_p;
  110482. int normal_point_p;
  110483. int normal_start;
  110484. int normal_partition;
  110485. double normal_thresh;
  110486. } vorbis_info_psy;
  110487. typedef struct{
  110488. int eighth_octave_lines;
  110489. /* for block long/short tuning; encode only */
  110490. float preecho_thresh[VE_BANDS];
  110491. float postecho_thresh[VE_BANDS];
  110492. float stretch_penalty;
  110493. float preecho_minenergy;
  110494. float ampmax_att_per_sec;
  110495. /* channel coupling config */
  110496. int coupling_pkHz[PACKETBLOBS];
  110497. int coupling_pointlimit[2][PACKETBLOBS];
  110498. int coupling_prepointamp[PACKETBLOBS];
  110499. int coupling_postpointamp[PACKETBLOBS];
  110500. int sliding_lowpass[2][PACKETBLOBS];
  110501. } vorbis_info_psy_global;
  110502. typedef struct {
  110503. float ampmax;
  110504. int channels;
  110505. vorbis_info_psy_global *gi;
  110506. int coupling_pointlimit[2][P_NOISECURVES];
  110507. } vorbis_look_psy_global;
  110508. typedef struct {
  110509. int n;
  110510. struct vorbis_info_psy *vi;
  110511. float ***tonecurves;
  110512. float **noiseoffset;
  110513. float *ath;
  110514. long *octave; /* in n.ocshift format */
  110515. long *bark;
  110516. long firstoc;
  110517. long shiftoc;
  110518. int eighth_octave_lines; /* power of two, please */
  110519. int total_octave_lines;
  110520. long rate; /* cache it */
  110521. float m_val; /* Masking compensation value */
  110522. } vorbis_look_psy;
  110523. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110524. vorbis_info_psy_global *gi,int n,long rate);
  110525. extern void _vp_psy_clear(vorbis_look_psy *p);
  110526. extern void *_vi_psy_dup(void *source);
  110527. extern void _vi_psy_free(vorbis_info_psy *i);
  110528. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110529. extern void _vp_remove_floor(vorbis_look_psy *p,
  110530. float *mdct,
  110531. int *icodedflr,
  110532. float *residue,
  110533. int sliding_lowpass);
  110534. extern void _vp_noisemask(vorbis_look_psy *p,
  110535. float *logmdct,
  110536. float *logmask);
  110537. extern void _vp_tonemask(vorbis_look_psy *p,
  110538. float *logfft,
  110539. float *logmask,
  110540. float global_specmax,
  110541. float local_specmax);
  110542. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110543. float *noise,
  110544. float *tone,
  110545. int offset_select,
  110546. float *logmask,
  110547. float *mdct,
  110548. float *logmdct);
  110549. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110550. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110551. vorbis_info_psy_global *g,
  110552. vorbis_look_psy *p,
  110553. vorbis_info_mapping0 *vi,
  110554. float **mdct);
  110555. extern void _vp_couple(int blobno,
  110556. vorbis_info_psy_global *g,
  110557. vorbis_look_psy *p,
  110558. vorbis_info_mapping0 *vi,
  110559. float **res,
  110560. float **mag_memo,
  110561. int **mag_sort,
  110562. int **ifloor,
  110563. int *nonzero,
  110564. int sliding_lowpass);
  110565. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110566. float *in,float *out,int *sortedindex);
  110567. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110568. float *magnitudes,int *sortedindex);
  110569. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110570. vorbis_look_psy *p,
  110571. vorbis_info_mapping0 *vi,
  110572. float **mags);
  110573. extern void hf_reduction(vorbis_info_psy_global *g,
  110574. vorbis_look_psy *p,
  110575. vorbis_info_mapping0 *vi,
  110576. float **mdct);
  110577. #endif
  110578. /*** End of inlined file: psy.h ***/
  110579. /*** Start of inlined file: bitrate.h ***/
  110580. #ifndef _V_BITRATE_H_
  110581. #define _V_BITRATE_H_
  110582. /*** Start of inlined file: os.h ***/
  110583. #ifndef _OS_H
  110584. #define _OS_H
  110585. /********************************************************************
  110586. * *
  110587. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110588. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110589. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110590. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110591. * *
  110592. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110593. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110594. * *
  110595. ********************************************************************
  110596. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110597. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110598. ********************************************************************/
  110599. #ifdef HAVE_CONFIG_H
  110600. #include "config.h"
  110601. #endif
  110602. #include <math.h>
  110603. /*** Start of inlined file: misc.h ***/
  110604. #ifndef _V_RANDOM_H_
  110605. #define _V_RANDOM_H_
  110606. extern int analysis_noisy;
  110607. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110608. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110609. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110610. ogg_int64_t off);
  110611. #ifdef DEBUG_MALLOC
  110612. #define _VDBG_GRAPHFILE "malloc.m"
  110613. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110614. extern void _VDBG_free(void *ptr,char *file,long line);
  110615. #ifndef MISC_C
  110616. #undef _ogg_malloc
  110617. #undef _ogg_calloc
  110618. #undef _ogg_realloc
  110619. #undef _ogg_free
  110620. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110621. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110622. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110623. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110624. #endif
  110625. #endif
  110626. #endif
  110627. /*** End of inlined file: misc.h ***/
  110628. #ifndef _V_IFDEFJAIL_H_
  110629. # define _V_IFDEFJAIL_H_
  110630. # ifdef __GNUC__
  110631. # define STIN static __inline__
  110632. # elif _WIN32
  110633. # define STIN static __inline
  110634. # else
  110635. # define STIN static
  110636. # endif
  110637. #ifdef DJGPP
  110638. # define rint(x) (floor((x)+0.5f))
  110639. #endif
  110640. #ifndef M_PI
  110641. # define M_PI (3.1415926536f)
  110642. #endif
  110643. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110644. # include <malloc.h>
  110645. # define rint(x) (floor((x)+0.5f))
  110646. # define NO_FLOAT_MATH_LIB
  110647. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110648. #endif
  110649. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110650. void *_alloca(size_t size);
  110651. # define alloca _alloca
  110652. #endif
  110653. #ifndef FAST_HYPOT
  110654. # define FAST_HYPOT hypot
  110655. #endif
  110656. #endif
  110657. #ifdef HAVE_ALLOCA_H
  110658. # include <alloca.h>
  110659. #endif
  110660. #ifdef USE_MEMORY_H
  110661. # include <memory.h>
  110662. #endif
  110663. #ifndef min
  110664. # define min(x,y) ((x)>(y)?(y):(x))
  110665. #endif
  110666. #ifndef max
  110667. # define max(x,y) ((x)<(y)?(y):(x))
  110668. #endif
  110669. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110670. # define VORBIS_FPU_CONTROL
  110671. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110672. Because of encapsulation constraints (GCC can't see inside the asm
  110673. block and so we end up doing stupid things like a store/load that
  110674. is collectively a noop), we do it this way */
  110675. /* we must set up the fpu before this works!! */
  110676. typedef ogg_int16_t vorbis_fpu_control;
  110677. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110678. ogg_int16_t ret;
  110679. ogg_int16_t temp;
  110680. __asm__ __volatile__("fnstcw %0\n\t"
  110681. "movw %0,%%dx\n\t"
  110682. "orw $62463,%%dx\n\t"
  110683. "movw %%dx,%1\n\t"
  110684. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110685. *fpu=ret;
  110686. }
  110687. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110688. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110689. }
  110690. /* assumes the FPU is in round mode! */
  110691. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110692. we get extra fst/fld to
  110693. truncate precision */
  110694. int i;
  110695. __asm__("fistl %0": "=m"(i) : "t"(f));
  110696. return(i);
  110697. }
  110698. #endif
  110699. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110700. # define VORBIS_FPU_CONTROL
  110701. typedef ogg_int16_t vorbis_fpu_control;
  110702. static __inline int vorbis_ftoi(double f){
  110703. int i;
  110704. __asm{
  110705. fld f
  110706. fistp i
  110707. }
  110708. return i;
  110709. }
  110710. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110711. }
  110712. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110713. }
  110714. #endif
  110715. #ifndef VORBIS_FPU_CONTROL
  110716. typedef int vorbis_fpu_control;
  110717. static int vorbis_ftoi(double f){
  110718. return (int)(f+.5);
  110719. }
  110720. /* We don't have special code for this compiler/arch, so do it the slow way */
  110721. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110722. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110723. #endif
  110724. #endif /* _OS_H */
  110725. /*** End of inlined file: os.h ***/
  110726. /* encode side bitrate tracking */
  110727. typedef struct bitrate_manager_state {
  110728. int managed;
  110729. long avg_reservoir;
  110730. long minmax_reservoir;
  110731. long avg_bitsper;
  110732. long min_bitsper;
  110733. long max_bitsper;
  110734. long short_per_long;
  110735. double avgfloat;
  110736. vorbis_block *vb;
  110737. int choice;
  110738. } bitrate_manager_state;
  110739. typedef struct bitrate_manager_info{
  110740. long avg_rate;
  110741. long min_rate;
  110742. long max_rate;
  110743. long reservoir_bits;
  110744. double reservoir_bias;
  110745. double slew_damp;
  110746. } bitrate_manager_info;
  110747. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110748. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110749. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110750. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110751. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110752. #endif
  110753. /*** End of inlined file: bitrate.h ***/
  110754. static int ilog(unsigned int v){
  110755. int ret=0;
  110756. while(v){
  110757. ret++;
  110758. v>>=1;
  110759. }
  110760. return(ret);
  110761. }
  110762. static int ilog2(unsigned int v){
  110763. int ret=0;
  110764. if(v)--v;
  110765. while(v){
  110766. ret++;
  110767. v>>=1;
  110768. }
  110769. return(ret);
  110770. }
  110771. typedef struct private_state {
  110772. /* local lookup storage */
  110773. envelope_lookup *ve; /* envelope lookup */
  110774. int window[2];
  110775. vorbis_look_transform **transform[2]; /* block, type */
  110776. drft_lookup fft_look[2];
  110777. int modebits;
  110778. vorbis_look_floor **flr;
  110779. vorbis_look_residue **residue;
  110780. vorbis_look_psy *psy;
  110781. vorbis_look_psy_global *psy_g_look;
  110782. /* local storage, only used on the encoding side. This way the
  110783. application does not need to worry about freeing some packets'
  110784. memory and not others'; packet storage is always tracked.
  110785. Cleared next call to a _dsp_ function */
  110786. unsigned char *header;
  110787. unsigned char *header1;
  110788. unsigned char *header2;
  110789. bitrate_manager_state bms;
  110790. ogg_int64_t sample_count;
  110791. } private_state;
  110792. /* codec_setup_info contains all the setup information specific to the
  110793. specific compression/decompression mode in progress (eg,
  110794. psychoacoustic settings, channel setup, options, codebook
  110795. etc).
  110796. *********************************************************************/
  110797. /*** Start of inlined file: highlevel.h ***/
  110798. typedef struct highlevel_byblocktype {
  110799. double tone_mask_setting;
  110800. double tone_peaklimit_setting;
  110801. double noise_bias_setting;
  110802. double noise_compand_setting;
  110803. } highlevel_byblocktype;
  110804. typedef struct highlevel_encode_setup {
  110805. void *setup;
  110806. int set_in_stone;
  110807. double base_setting;
  110808. double long_setting;
  110809. double short_setting;
  110810. double impulse_noisetune;
  110811. int managed;
  110812. long bitrate_min;
  110813. long bitrate_av;
  110814. double bitrate_av_damp;
  110815. long bitrate_max;
  110816. long bitrate_reservoir;
  110817. double bitrate_reservoir_bias;
  110818. int impulse_block_p;
  110819. int noise_normalize_p;
  110820. double stereo_point_setting;
  110821. double lowpass_kHz;
  110822. double ath_floating_dB;
  110823. double ath_absolute_dB;
  110824. double amplitude_track_dBpersec;
  110825. double trigger_setting;
  110826. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110827. } highlevel_encode_setup;
  110828. /*** End of inlined file: highlevel.h ***/
  110829. typedef struct codec_setup_info {
  110830. /* Vorbis supports only short and long blocks, but allows the
  110831. encoder to choose the sizes */
  110832. long blocksizes[2];
  110833. /* modes are the primary means of supporting on-the-fly different
  110834. blocksizes, different channel mappings (LR or M/A),
  110835. different residue backends, etc. Each mode consists of a
  110836. blocksize flag and a mapping (along with the mapping setup */
  110837. int modes;
  110838. int maps;
  110839. int floors;
  110840. int residues;
  110841. int books;
  110842. int psys; /* encode only */
  110843. vorbis_info_mode *mode_param[64];
  110844. int map_type[64];
  110845. vorbis_info_mapping *map_param[64];
  110846. int floor_type[64];
  110847. vorbis_info_floor *floor_param[64];
  110848. int residue_type[64];
  110849. vorbis_info_residue *residue_param[64];
  110850. static_codebook *book_param[256];
  110851. codebook *fullbooks;
  110852. vorbis_info_psy *psy_param[4]; /* encode only */
  110853. vorbis_info_psy_global psy_g_param;
  110854. bitrate_manager_info bi;
  110855. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110856. highly redundant structure, but
  110857. improves clarity of program flow. */
  110858. int halfrate_flag; /* painless downsample for decode */
  110859. } codec_setup_info;
  110860. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110861. extern void _vp_global_free(vorbis_look_psy_global *look);
  110862. #endif
  110863. /*** End of inlined file: codec_internal.h ***/
  110864. /*** Start of inlined file: registry.h ***/
  110865. #ifndef _V_REG_H_
  110866. #define _V_REG_H_
  110867. #define VI_TRANSFORMB 1
  110868. #define VI_WINDOWB 1
  110869. #define VI_TIMEB 1
  110870. #define VI_FLOORB 2
  110871. #define VI_RESB 3
  110872. #define VI_MAPB 1
  110873. extern vorbis_func_floor *_floor_P[];
  110874. extern vorbis_func_residue *_residue_P[];
  110875. extern vorbis_func_mapping *_mapping_P[];
  110876. #endif
  110877. /*** End of inlined file: registry.h ***/
  110878. /*** Start of inlined file: scales.h ***/
  110879. #ifndef _V_SCALES_H_
  110880. #define _V_SCALES_H_
  110881. #include <math.h>
  110882. /* 20log10(x) */
  110883. #define VORBIS_IEEE_FLOAT32 1
  110884. #ifdef VORBIS_IEEE_FLOAT32
  110885. static float unitnorm(float x){
  110886. union {
  110887. ogg_uint32_t i;
  110888. float f;
  110889. } ix;
  110890. ix.f = x;
  110891. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110892. return ix.f;
  110893. }
  110894. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110895. static float todB(const float *x){
  110896. union {
  110897. ogg_uint32_t i;
  110898. float f;
  110899. } ix;
  110900. ix.f = *x;
  110901. ix.i = ix.i&0x7fffffff;
  110902. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110903. }
  110904. #define todB_nn(x) todB(x)
  110905. #else
  110906. static float unitnorm(float x){
  110907. if(x<0)return(-1.f);
  110908. return(1.f);
  110909. }
  110910. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110911. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110912. #endif
  110913. #define fromdB(x) (exp((x)*.11512925f))
  110914. /* The bark scale equations are approximations, since the original
  110915. table was somewhat hand rolled. The below are chosen to have the
  110916. best possible fit to the rolled tables, thus their somewhat odd
  110917. appearance (these are more accurate and over a longer range than
  110918. the oft-quoted bark equations found in the texts I have). The
  110919. approximations are valid from 0 - 30kHz (nyquist) or so.
  110920. all f in Hz, z in Bark */
  110921. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110922. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110923. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110924. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110925. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110926. 0.0 */
  110927. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110928. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110929. #endif
  110930. /*** End of inlined file: scales.h ***/
  110931. int analysis_noisy=1;
  110932. /* decides between modes, dispatches to the appropriate mapping. */
  110933. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110934. int ret,i;
  110935. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110936. vb->glue_bits=0;
  110937. vb->time_bits=0;
  110938. vb->floor_bits=0;
  110939. vb->res_bits=0;
  110940. /* first things first. Make sure encode is ready */
  110941. for(i=0;i<PACKETBLOBS;i++)
  110942. oggpack_reset(vbi->packetblob[i]);
  110943. /* we only have one mapping type (0), and we let the mapping code
  110944. itself figure out what soft mode to use. This allows easier
  110945. bitrate management */
  110946. if((ret=_mapping_P[0]->forward(vb)))
  110947. return(ret);
  110948. if(op){
  110949. if(vorbis_bitrate_managed(vb))
  110950. /* The app is using a bitmanaged mode... but not using the
  110951. bitrate management interface. */
  110952. return(OV_EINVAL);
  110953. op->packet=oggpack_get_buffer(&vb->opb);
  110954. op->bytes=oggpack_bytes(&vb->opb);
  110955. op->b_o_s=0;
  110956. op->e_o_s=vb->eofflag;
  110957. op->granulepos=vb->granulepos;
  110958. op->packetno=vb->sequence; /* for sake of completeness */
  110959. }
  110960. return(0);
  110961. }
  110962. /* there was no great place to put this.... */
  110963. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110964. int j;
  110965. FILE *of;
  110966. char buffer[80];
  110967. /* if(i==5870){*/
  110968. sprintf(buffer,"%s_%d.m",base,i);
  110969. of=fopen(buffer,"w");
  110970. if(!of)perror("failed to open data dump file");
  110971. for(j=0;j<n;j++){
  110972. if(bark){
  110973. float b=toBARK((4000.f*j/n)+.25);
  110974. fprintf(of,"%f ",b);
  110975. }else
  110976. if(off!=0)
  110977. fprintf(of,"%f ",(double)(j+off)/8000.);
  110978. else
  110979. fprintf(of,"%f ",(double)j);
  110980. if(dB){
  110981. float val;
  110982. if(v[j]==0.)
  110983. val=-140.;
  110984. else
  110985. val=todB(v+j);
  110986. fprintf(of,"%f\n",val);
  110987. }else{
  110988. fprintf(of,"%f\n",v[j]);
  110989. }
  110990. }
  110991. fclose(of);
  110992. /* } */
  110993. }
  110994. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110995. ogg_int64_t off){
  110996. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110997. }
  110998. #endif
  110999. /*** End of inlined file: analysis.c ***/
  111000. /*** Start of inlined file: bitrate.c ***/
  111001. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111002. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111003. // tasks..
  111004. #if JUCE_MSVC
  111005. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111006. #endif
  111007. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111008. #if JUCE_USE_OGGVORBIS
  111009. #include <stdlib.h>
  111010. #include <string.h>
  111011. #include <math.h>
  111012. /* compute bitrate tracking setup */
  111013. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111014. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111015. bitrate_manager_info *bi=&ci->bi;
  111016. memset(bm,0,sizeof(*bm));
  111017. if(bi && (bi->reservoir_bits>0)){
  111018. long ratesamples=vi->rate;
  111019. int halfsamples=ci->blocksizes[0]>>1;
  111020. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111021. bm->managed=1;
  111022. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111023. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111024. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111025. bm->avgfloat=PACKETBLOBS/2;
  111026. /* not a necessary fix, but one that leads to a more balanced
  111027. typical initialization */
  111028. {
  111029. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111030. bm->minmax_reservoir=desired_fill;
  111031. bm->avg_reservoir=desired_fill;
  111032. }
  111033. }
  111034. }
  111035. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111036. memset(bm,0,sizeof(*bm));
  111037. return;
  111038. }
  111039. int vorbis_bitrate_managed(vorbis_block *vb){
  111040. vorbis_dsp_state *vd=vb->vd;
  111041. private_state *b=(private_state*)vd->backend_state;
  111042. bitrate_manager_state *bm=&b->bms;
  111043. if(bm && bm->managed)return(1);
  111044. return(0);
  111045. }
  111046. /* finish taking in the block we just processed */
  111047. int vorbis_bitrate_addblock(vorbis_block *vb){
  111048. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111049. vorbis_dsp_state *vd=vb->vd;
  111050. private_state *b=(private_state*)vd->backend_state;
  111051. bitrate_manager_state *bm=&b->bms;
  111052. vorbis_info *vi=vd->vi;
  111053. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111054. bitrate_manager_info *bi=&ci->bi;
  111055. int choice=rint(bm->avgfloat);
  111056. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111057. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111058. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111059. int samples=ci->blocksizes[vb->W]>>1;
  111060. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111061. if(!bm->managed){
  111062. /* not a bitrate managed stream, but for API simplicity, we'll
  111063. buffer the packet to keep the code path clean */
  111064. if(bm->vb)return(-1); /* one has been submitted without
  111065. being claimed */
  111066. bm->vb=vb;
  111067. return(0);
  111068. }
  111069. bm->vb=vb;
  111070. /* look ahead for avg floater */
  111071. if(bm->avg_bitsper>0){
  111072. double slew=0.;
  111073. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111074. double slewlimit= 15./bi->slew_damp;
  111075. /* choosing a new floater:
  111076. if we're over target, we slew down
  111077. if we're under target, we slew up
  111078. choose slew as follows: look through packetblobs of this frame
  111079. and set slew as the first in the appropriate direction that
  111080. gives us the slew we want. This may mean no slew if delta is
  111081. already favorable.
  111082. Then limit slew to slew max */
  111083. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111084. while(choice>0 && this_bits>avg_target_bits &&
  111085. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111086. choice--;
  111087. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111088. }
  111089. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111090. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111091. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111092. choice++;
  111093. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111094. }
  111095. }
  111096. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111097. if(slew<-slewlimit)slew=-slewlimit;
  111098. if(slew>slewlimit)slew=slewlimit;
  111099. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111100. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111101. }
  111102. /* enforce min(if used) on the current floater (if used) */
  111103. if(bm->min_bitsper>0){
  111104. /* do we need to force the bitrate up? */
  111105. if(this_bits<min_target_bits){
  111106. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111107. choice++;
  111108. if(choice>=PACKETBLOBS)break;
  111109. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111110. }
  111111. }
  111112. }
  111113. /* enforce max (if used) on the current floater (if used) */
  111114. if(bm->max_bitsper>0){
  111115. /* do we need to force the bitrate down? */
  111116. if(this_bits>max_target_bits){
  111117. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111118. choice--;
  111119. if(choice<0)break;
  111120. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111121. }
  111122. }
  111123. }
  111124. /* Choice of packetblobs now made based on floater, and min/max
  111125. requirements. Now boundary check extreme choices */
  111126. if(choice<0){
  111127. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111128. frame will need to be truncated */
  111129. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111130. bm->choice=choice=0;
  111131. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111132. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111133. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111134. }
  111135. }else{
  111136. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111137. if(choice>=PACKETBLOBS)
  111138. choice=PACKETBLOBS-1;
  111139. bm->choice=choice;
  111140. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111141. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111142. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111143. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111144. }
  111145. /* now we have the final packet and the final packet size. Update statistics */
  111146. /* min and max reservoir */
  111147. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111148. if(max_target_bits>0 && this_bits>max_target_bits){
  111149. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111150. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111151. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111152. }else{
  111153. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111154. if(bm->minmax_reservoir>desired_fill){
  111155. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111156. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111157. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111158. }else{
  111159. bm->minmax_reservoir=desired_fill;
  111160. }
  111161. }else{
  111162. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111163. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111164. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111165. }else{
  111166. bm->minmax_reservoir=desired_fill;
  111167. }
  111168. }
  111169. }
  111170. }
  111171. /* avg reservoir */
  111172. if(bm->avg_bitsper>0){
  111173. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111174. bm->avg_reservoir+=this_bits-avg_target_bits;
  111175. }
  111176. return(0);
  111177. }
  111178. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111179. private_state *b=(private_state*)vd->backend_state;
  111180. bitrate_manager_state *bm=&b->bms;
  111181. vorbis_block *vb=bm->vb;
  111182. int choice=PACKETBLOBS/2;
  111183. if(!vb)return 0;
  111184. if(op){
  111185. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111186. if(vorbis_bitrate_managed(vb))
  111187. choice=bm->choice;
  111188. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111189. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111190. op->b_o_s=0;
  111191. op->e_o_s=vb->eofflag;
  111192. op->granulepos=vb->granulepos;
  111193. op->packetno=vb->sequence; /* for sake of completeness */
  111194. }
  111195. bm->vb=0;
  111196. return(1);
  111197. }
  111198. #endif
  111199. /*** End of inlined file: bitrate.c ***/
  111200. /*** Start of inlined file: block.c ***/
  111201. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111202. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111203. // tasks..
  111204. #if JUCE_MSVC
  111205. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111206. #endif
  111207. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111208. #if JUCE_USE_OGGVORBIS
  111209. #include <stdio.h>
  111210. #include <stdlib.h>
  111211. #include <string.h>
  111212. /*** Start of inlined file: window.h ***/
  111213. #ifndef _V_WINDOW_
  111214. #define _V_WINDOW_
  111215. extern float *_vorbis_window_get(int n);
  111216. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111217. int lW,int W,int nW);
  111218. #endif
  111219. /*** End of inlined file: window.h ***/
  111220. /*** Start of inlined file: lpc.h ***/
  111221. #ifndef _V_LPC_H_
  111222. #define _V_LPC_H_
  111223. /* simple linear scale LPC code */
  111224. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111225. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111226. float *data,long n);
  111227. #endif
  111228. /*** End of inlined file: lpc.h ***/
  111229. /* pcm accumulator examples (not exhaustive):
  111230. <-------------- lW ---------------->
  111231. <--------------- W ---------------->
  111232. : .....|..... _______________ |
  111233. : .''' | '''_--- | |\ |
  111234. :.....''' |_____--- '''......| | \_______|
  111235. :.................|__________________|_______|__|______|
  111236. |<------ Sl ------>| > Sr < |endW
  111237. |beginSl |endSl | |endSr
  111238. |beginW |endlW |beginSr
  111239. |< lW >|
  111240. <--------------- W ---------------->
  111241. | | .. ______________ |
  111242. | | ' `/ | ---_ |
  111243. |___.'___/`. | ---_____|
  111244. |_______|__|_______|_________________|
  111245. | >|Sl|< |<------ Sr ----->|endW
  111246. | | |endSl |beginSr |endSr
  111247. |beginW | |endlW
  111248. mult[0] |beginSl mult[n]
  111249. <-------------- lW ----------------->
  111250. |<--W-->|
  111251. : .............. ___ | |
  111252. : .''' |`/ \ | |
  111253. :.....''' |/`....\|...|
  111254. :.........................|___|___|___|
  111255. |Sl |Sr |endW
  111256. | | |endSr
  111257. | |beginSr
  111258. | |endSl
  111259. |beginSl
  111260. |beginW
  111261. */
  111262. /* block abstraction setup *********************************************/
  111263. #ifndef WORD_ALIGN
  111264. #define WORD_ALIGN 8
  111265. #endif
  111266. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111267. int i;
  111268. memset(vb,0,sizeof(*vb));
  111269. vb->vd=v;
  111270. vb->localalloc=0;
  111271. vb->localstore=NULL;
  111272. if(v->analysisp){
  111273. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111274. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111275. vbi->ampmax=-9999;
  111276. for(i=0;i<PACKETBLOBS;i++){
  111277. if(i==PACKETBLOBS/2){
  111278. vbi->packetblob[i]=&vb->opb;
  111279. }else{
  111280. vbi->packetblob[i]=
  111281. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111282. }
  111283. oggpack_writeinit(vbi->packetblob[i]);
  111284. }
  111285. }
  111286. return(0);
  111287. }
  111288. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111289. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111290. if(bytes+vb->localtop>vb->localalloc){
  111291. /* can't just _ogg_realloc... there are outstanding pointers */
  111292. if(vb->localstore){
  111293. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111294. vb->totaluse+=vb->localtop;
  111295. link->next=vb->reap;
  111296. link->ptr=vb->localstore;
  111297. vb->reap=link;
  111298. }
  111299. /* highly conservative */
  111300. vb->localalloc=bytes;
  111301. vb->localstore=_ogg_malloc(vb->localalloc);
  111302. vb->localtop=0;
  111303. }
  111304. {
  111305. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111306. vb->localtop+=bytes;
  111307. return ret;
  111308. }
  111309. }
  111310. /* reap the chain, pull the ripcord */
  111311. void _vorbis_block_ripcord(vorbis_block *vb){
  111312. /* reap the chain */
  111313. struct alloc_chain *reap=vb->reap;
  111314. while(reap){
  111315. struct alloc_chain *next=reap->next;
  111316. _ogg_free(reap->ptr);
  111317. memset(reap,0,sizeof(*reap));
  111318. _ogg_free(reap);
  111319. reap=next;
  111320. }
  111321. /* consolidate storage */
  111322. if(vb->totaluse){
  111323. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111324. vb->localalloc+=vb->totaluse;
  111325. vb->totaluse=0;
  111326. }
  111327. /* pull the ripcord */
  111328. vb->localtop=0;
  111329. vb->reap=NULL;
  111330. }
  111331. int vorbis_block_clear(vorbis_block *vb){
  111332. int i;
  111333. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111334. _vorbis_block_ripcord(vb);
  111335. if(vb->localstore)_ogg_free(vb->localstore);
  111336. if(vbi){
  111337. for(i=0;i<PACKETBLOBS;i++){
  111338. oggpack_writeclear(vbi->packetblob[i]);
  111339. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111340. }
  111341. _ogg_free(vbi);
  111342. }
  111343. memset(vb,0,sizeof(*vb));
  111344. return(0);
  111345. }
  111346. /* Analysis side code, but directly related to blocking. Thus it's
  111347. here and not in analysis.c (which is for analysis transforms only).
  111348. The init is here because some of it is shared */
  111349. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111350. int i;
  111351. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111352. private_state *b=NULL;
  111353. int hs;
  111354. if(ci==NULL) return 1;
  111355. hs=ci->halfrate_flag;
  111356. memset(v,0,sizeof(*v));
  111357. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111358. v->vi=vi;
  111359. b->modebits=ilog2(ci->modes);
  111360. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111361. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111362. /* MDCT is tranform 0 */
  111363. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111364. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111365. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111366. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111367. /* Vorbis I uses only window type 0 */
  111368. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111369. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111370. if(encp){ /* encode/decode differ here */
  111371. /* analysis always needs an fft */
  111372. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111373. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111374. /* finish the codebooks */
  111375. if(!ci->fullbooks){
  111376. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111377. for(i=0;i<ci->books;i++)
  111378. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111379. }
  111380. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111381. for(i=0;i<ci->psys;i++){
  111382. _vp_psy_init(b->psy+i,
  111383. ci->psy_param[i],
  111384. &ci->psy_g_param,
  111385. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111386. vi->rate);
  111387. }
  111388. v->analysisp=1;
  111389. }else{
  111390. /* finish the codebooks */
  111391. if(!ci->fullbooks){
  111392. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111393. for(i=0;i<ci->books;i++){
  111394. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111395. /* decode codebooks are now standalone after init */
  111396. vorbis_staticbook_destroy(ci->book_param[i]);
  111397. ci->book_param[i]=NULL;
  111398. }
  111399. }
  111400. }
  111401. /* initialize the storage vectors. blocksize[1] is small for encode,
  111402. but the correct size for decode */
  111403. v->pcm_storage=ci->blocksizes[1];
  111404. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111405. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111406. {
  111407. int i;
  111408. for(i=0;i<vi->channels;i++)
  111409. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111410. }
  111411. /* all 1 (large block) or 0 (small block) */
  111412. /* explicitly set for the sake of clarity */
  111413. v->lW=0; /* previous window size */
  111414. v->W=0; /* current window size */
  111415. /* all vector indexes */
  111416. v->centerW=ci->blocksizes[1]/2;
  111417. v->pcm_current=v->centerW;
  111418. /* initialize all the backend lookups */
  111419. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111420. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111421. for(i=0;i<ci->floors;i++)
  111422. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111423. look(v,ci->floor_param[i]);
  111424. for(i=0;i<ci->residues;i++)
  111425. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111426. look(v,ci->residue_param[i]);
  111427. return 0;
  111428. }
  111429. /* arbitrary settings and spec-mandated numbers get filled in here */
  111430. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111431. private_state *b=NULL;
  111432. if(_vds_shared_init(v,vi,1))return 1;
  111433. b=(private_state*)v->backend_state;
  111434. b->psy_g_look=_vp_global_look(vi);
  111435. /* Initialize the envelope state storage */
  111436. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111437. _ve_envelope_init(b->ve,vi);
  111438. vorbis_bitrate_init(vi,&b->bms);
  111439. /* compressed audio packets start after the headers
  111440. with sequence number 3 */
  111441. v->sequence=3;
  111442. return(0);
  111443. }
  111444. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111445. int i;
  111446. if(v){
  111447. vorbis_info *vi=v->vi;
  111448. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111449. private_state *b=(private_state*)v->backend_state;
  111450. if(b){
  111451. if(b->ve){
  111452. _ve_envelope_clear(b->ve);
  111453. _ogg_free(b->ve);
  111454. }
  111455. if(b->transform[0]){
  111456. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111457. _ogg_free(b->transform[0][0]);
  111458. _ogg_free(b->transform[0]);
  111459. }
  111460. if(b->transform[1]){
  111461. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111462. _ogg_free(b->transform[1][0]);
  111463. _ogg_free(b->transform[1]);
  111464. }
  111465. if(b->flr){
  111466. for(i=0;i<ci->floors;i++)
  111467. _floor_P[ci->floor_type[i]]->
  111468. free_look(b->flr[i]);
  111469. _ogg_free(b->flr);
  111470. }
  111471. if(b->residue){
  111472. for(i=0;i<ci->residues;i++)
  111473. _residue_P[ci->residue_type[i]]->
  111474. free_look(b->residue[i]);
  111475. _ogg_free(b->residue);
  111476. }
  111477. if(b->psy){
  111478. for(i=0;i<ci->psys;i++)
  111479. _vp_psy_clear(b->psy+i);
  111480. _ogg_free(b->psy);
  111481. }
  111482. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111483. vorbis_bitrate_clear(&b->bms);
  111484. drft_clear(&b->fft_look[0]);
  111485. drft_clear(&b->fft_look[1]);
  111486. }
  111487. if(v->pcm){
  111488. for(i=0;i<vi->channels;i++)
  111489. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111490. _ogg_free(v->pcm);
  111491. if(v->pcmret)_ogg_free(v->pcmret);
  111492. }
  111493. if(b){
  111494. /* free header, header1, header2 */
  111495. if(b->header)_ogg_free(b->header);
  111496. if(b->header1)_ogg_free(b->header1);
  111497. if(b->header2)_ogg_free(b->header2);
  111498. _ogg_free(b);
  111499. }
  111500. memset(v,0,sizeof(*v));
  111501. }
  111502. }
  111503. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111504. int i;
  111505. vorbis_info *vi=v->vi;
  111506. private_state *b=(private_state*)v->backend_state;
  111507. /* free header, header1, header2 */
  111508. if(b->header)_ogg_free(b->header);b->header=NULL;
  111509. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111510. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111511. /* Do we have enough storage space for the requested buffer? If not,
  111512. expand the PCM (and envelope) storage */
  111513. if(v->pcm_current+vals>=v->pcm_storage){
  111514. v->pcm_storage=v->pcm_current+vals*2;
  111515. for(i=0;i<vi->channels;i++){
  111516. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111517. }
  111518. }
  111519. for(i=0;i<vi->channels;i++)
  111520. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111521. return(v->pcmret);
  111522. }
  111523. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111524. int i;
  111525. int order=32;
  111526. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111527. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111528. long j;
  111529. v->preextrapolate=1;
  111530. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111531. for(i=0;i<v->vi->channels;i++){
  111532. /* need to run the extrapolation in reverse! */
  111533. for(j=0;j<v->pcm_current;j++)
  111534. work[j]=v->pcm[i][v->pcm_current-j-1];
  111535. /* prime as above */
  111536. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111537. /* run the predictor filter */
  111538. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111539. order,
  111540. work+v->pcm_current-v->centerW,
  111541. v->centerW);
  111542. for(j=0;j<v->pcm_current;j++)
  111543. v->pcm[i][v->pcm_current-j-1]=work[j];
  111544. }
  111545. }
  111546. }
  111547. /* call with val<=0 to set eof */
  111548. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111549. vorbis_info *vi=v->vi;
  111550. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111551. if(vals<=0){
  111552. int order=32;
  111553. int i;
  111554. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111555. /* if it wasn't done earlier (very short sample) */
  111556. if(!v->preextrapolate)
  111557. _preextrapolate_helper(v);
  111558. /* We're encoding the end of the stream. Just make sure we have
  111559. [at least] a few full blocks of zeroes at the end. */
  111560. /* actually, we don't want zeroes; that could drop a large
  111561. amplitude off a cliff, creating spread spectrum noise that will
  111562. suck to encode. Extrapolate for the sake of cleanliness. */
  111563. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111564. v->eofflag=v->pcm_current;
  111565. v->pcm_current+=ci->blocksizes[1]*3;
  111566. for(i=0;i<vi->channels;i++){
  111567. if(v->eofflag>order*2){
  111568. /* extrapolate with LPC to fill in */
  111569. long n;
  111570. /* make a predictor filter */
  111571. n=v->eofflag;
  111572. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111573. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111574. /* run the predictor filter */
  111575. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111576. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111577. }else{
  111578. /* not enough data to extrapolate (unlikely to happen due to
  111579. guarding the overlap, but bulletproof in case that
  111580. assumtion goes away). zeroes will do. */
  111581. memset(v->pcm[i]+v->eofflag,0,
  111582. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111583. }
  111584. }
  111585. }else{
  111586. if(v->pcm_current+vals>v->pcm_storage)
  111587. return(OV_EINVAL);
  111588. v->pcm_current+=vals;
  111589. /* we may want to reverse extrapolate the beginning of a stream
  111590. too... in case we're beginning on a cliff! */
  111591. /* clumsy, but simple. It only runs once, so simple is good. */
  111592. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111593. _preextrapolate_helper(v);
  111594. }
  111595. return(0);
  111596. }
  111597. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111598. the next block on which to continue analysis */
  111599. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111600. int i;
  111601. vorbis_info *vi=v->vi;
  111602. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111603. private_state *b=(private_state*)v->backend_state;
  111604. vorbis_look_psy_global *g=b->psy_g_look;
  111605. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111606. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111607. /* check to see if we're started... */
  111608. if(!v->preextrapolate)return(0);
  111609. /* check to see if we're done... */
  111610. if(v->eofflag==-1)return(0);
  111611. /* By our invariant, we have lW, W and centerW set. Search for
  111612. the next boundary so we can determine nW (the next window size)
  111613. which lets us compute the shape of the current block's window */
  111614. /* we do an envelope search even on a single blocksize; we may still
  111615. be throwing more bits at impulses, and envelope search handles
  111616. marking impulses too. */
  111617. {
  111618. long bp=_ve_envelope_search(v);
  111619. if(bp==-1){
  111620. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111621. full long block */
  111622. v->nW=0;
  111623. }else{
  111624. if(ci->blocksizes[0]==ci->blocksizes[1])
  111625. v->nW=0;
  111626. else
  111627. v->nW=bp;
  111628. }
  111629. }
  111630. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111631. {
  111632. /* center of next block + next block maximum right side. */
  111633. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111634. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111635. although this check is
  111636. less strict that the
  111637. _ve_envelope_search,
  111638. the search is not run
  111639. if we only use one
  111640. block size */
  111641. }
  111642. /* fill in the block. Note that for a short window, lW and nW are *short*
  111643. regardless of actual settings in the stream */
  111644. _vorbis_block_ripcord(vb);
  111645. vb->lW=v->lW;
  111646. vb->W=v->W;
  111647. vb->nW=v->nW;
  111648. if(v->W){
  111649. if(!v->lW || !v->nW){
  111650. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111651. /*fprintf(stderr,"-");*/
  111652. }else{
  111653. vbi->blocktype=BLOCKTYPE_LONG;
  111654. /*fprintf(stderr,"_");*/
  111655. }
  111656. }else{
  111657. if(_ve_envelope_mark(v)){
  111658. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111659. /*fprintf(stderr,"|");*/
  111660. }else{
  111661. vbi->blocktype=BLOCKTYPE_PADDING;
  111662. /*fprintf(stderr,".");*/
  111663. }
  111664. }
  111665. vb->vd=v;
  111666. vb->sequence=v->sequence++;
  111667. vb->granulepos=v->granulepos;
  111668. vb->pcmend=ci->blocksizes[v->W];
  111669. /* copy the vectors; this uses the local storage in vb */
  111670. /* this tracks 'strongest peak' for later psychoacoustics */
  111671. /* moved to the global psy state; clean this mess up */
  111672. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111673. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111674. vbi->ampmax=g->ampmax;
  111675. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111676. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111677. for(i=0;i<vi->channels;i++){
  111678. vbi->pcmdelay[i]=
  111679. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111680. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111681. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111682. /* before we added the delay
  111683. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111684. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111685. */
  111686. }
  111687. /* handle eof detection: eof==0 means that we've not yet received EOF
  111688. eof>0 marks the last 'real' sample in pcm[]
  111689. eof<0 'no more to do'; doesn't get here */
  111690. if(v->eofflag){
  111691. if(v->centerW>=v->eofflag){
  111692. v->eofflag=-1;
  111693. vb->eofflag=1;
  111694. return(1);
  111695. }
  111696. }
  111697. /* advance storage vectors and clean up */
  111698. {
  111699. int new_centerNext=ci->blocksizes[1]/2;
  111700. int movementW=centerNext-new_centerNext;
  111701. if(movementW>0){
  111702. _ve_envelope_shift(b->ve,movementW);
  111703. v->pcm_current-=movementW;
  111704. for(i=0;i<vi->channels;i++)
  111705. memmove(v->pcm[i],v->pcm[i]+movementW,
  111706. v->pcm_current*sizeof(*v->pcm[i]));
  111707. v->lW=v->W;
  111708. v->W=v->nW;
  111709. v->centerW=new_centerNext;
  111710. if(v->eofflag){
  111711. v->eofflag-=movementW;
  111712. if(v->eofflag<=0)v->eofflag=-1;
  111713. /* do not add padding to end of stream! */
  111714. if(v->centerW>=v->eofflag){
  111715. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111716. }else{
  111717. v->granulepos+=movementW;
  111718. }
  111719. }else{
  111720. v->granulepos+=movementW;
  111721. }
  111722. }
  111723. }
  111724. /* done */
  111725. return(1);
  111726. }
  111727. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111728. vorbis_info *vi=v->vi;
  111729. codec_setup_info *ci;
  111730. int hs;
  111731. if(!v->backend_state)return -1;
  111732. if(!vi)return -1;
  111733. ci=(codec_setup_info*) vi->codec_setup;
  111734. if(!ci)return -1;
  111735. hs=ci->halfrate_flag;
  111736. v->centerW=ci->blocksizes[1]>>(hs+1);
  111737. v->pcm_current=v->centerW>>hs;
  111738. v->pcm_returned=-1;
  111739. v->granulepos=-1;
  111740. v->sequence=-1;
  111741. v->eofflag=0;
  111742. ((private_state *)(v->backend_state))->sample_count=-1;
  111743. return(0);
  111744. }
  111745. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111746. if(_vds_shared_init(v,vi,0)) return 1;
  111747. vorbis_synthesis_restart(v);
  111748. return 0;
  111749. }
  111750. /* Unlike in analysis, the window is only partially applied for each
  111751. block. The time domain envelope is not yet handled at the point of
  111752. calling (as it relies on the previous block). */
  111753. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111754. vorbis_info *vi=v->vi;
  111755. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111756. private_state *b=(private_state*)v->backend_state;
  111757. int hs=ci->halfrate_flag;
  111758. int i,j;
  111759. if(!vb)return(OV_EINVAL);
  111760. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111761. v->lW=v->W;
  111762. v->W=vb->W;
  111763. v->nW=-1;
  111764. if((v->sequence==-1)||
  111765. (v->sequence+1 != vb->sequence)){
  111766. v->granulepos=-1; /* out of sequence; lose count */
  111767. b->sample_count=-1;
  111768. }
  111769. v->sequence=vb->sequence;
  111770. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111771. was called on block */
  111772. int n=ci->blocksizes[v->W]>>(hs+1);
  111773. int n0=ci->blocksizes[0]>>(hs+1);
  111774. int n1=ci->blocksizes[1]>>(hs+1);
  111775. int thisCenter;
  111776. int prevCenter;
  111777. v->glue_bits+=vb->glue_bits;
  111778. v->time_bits+=vb->time_bits;
  111779. v->floor_bits+=vb->floor_bits;
  111780. v->res_bits+=vb->res_bits;
  111781. if(v->centerW){
  111782. thisCenter=n1;
  111783. prevCenter=0;
  111784. }else{
  111785. thisCenter=0;
  111786. prevCenter=n1;
  111787. }
  111788. /* v->pcm is now used like a two-stage double buffer. We don't want
  111789. to have to constantly shift *or* adjust memory usage. Don't
  111790. accept a new block until the old is shifted out */
  111791. for(j=0;j<vi->channels;j++){
  111792. /* the overlap/add section */
  111793. if(v->lW){
  111794. if(v->W){
  111795. /* large/large */
  111796. float *w=_vorbis_window_get(b->window[1]-hs);
  111797. float *pcm=v->pcm[j]+prevCenter;
  111798. float *p=vb->pcm[j];
  111799. for(i=0;i<n1;i++)
  111800. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111801. }else{
  111802. /* large/small */
  111803. float *w=_vorbis_window_get(b->window[0]-hs);
  111804. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111805. float *p=vb->pcm[j];
  111806. for(i=0;i<n0;i++)
  111807. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111808. }
  111809. }else{
  111810. if(v->W){
  111811. /* small/large */
  111812. float *w=_vorbis_window_get(b->window[0]-hs);
  111813. float *pcm=v->pcm[j]+prevCenter;
  111814. float *p=vb->pcm[j]+n1/2-n0/2;
  111815. for(i=0;i<n0;i++)
  111816. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111817. for(;i<n1/2+n0/2;i++)
  111818. pcm[i]=p[i];
  111819. }else{
  111820. /* small/small */
  111821. float *w=_vorbis_window_get(b->window[0]-hs);
  111822. float *pcm=v->pcm[j]+prevCenter;
  111823. float *p=vb->pcm[j];
  111824. for(i=0;i<n0;i++)
  111825. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111826. }
  111827. }
  111828. /* the copy section */
  111829. {
  111830. float *pcm=v->pcm[j]+thisCenter;
  111831. float *p=vb->pcm[j]+n;
  111832. for(i=0;i<n;i++)
  111833. pcm[i]=p[i];
  111834. }
  111835. }
  111836. if(v->centerW)
  111837. v->centerW=0;
  111838. else
  111839. v->centerW=n1;
  111840. /* deal with initial packet state; we do this using the explicit
  111841. pcm_returned==-1 flag otherwise we're sensitive to first block
  111842. being short or long */
  111843. if(v->pcm_returned==-1){
  111844. v->pcm_returned=thisCenter;
  111845. v->pcm_current=thisCenter;
  111846. }else{
  111847. v->pcm_returned=prevCenter;
  111848. v->pcm_current=prevCenter+
  111849. ((ci->blocksizes[v->lW]/4+
  111850. ci->blocksizes[v->W]/4)>>hs);
  111851. }
  111852. }
  111853. /* track the frame number... This is for convenience, but also
  111854. making sure our last packet doesn't end with added padding. If
  111855. the last packet is partial, the number of samples we'll have to
  111856. return will be past the vb->granulepos.
  111857. This is not foolproof! It will be confused if we begin
  111858. decoding at the last page after a seek or hole. In that case,
  111859. we don't have a starting point to judge where the last frame
  111860. is. For this reason, vorbisfile will always try to make sure
  111861. it reads the last two marked pages in proper sequence */
  111862. if(b->sample_count==-1){
  111863. b->sample_count=0;
  111864. }else{
  111865. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111866. }
  111867. if(v->granulepos==-1){
  111868. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111869. v->granulepos=vb->granulepos;
  111870. /* is this a short page? */
  111871. if(b->sample_count>v->granulepos){
  111872. /* corner case; if this is both the first and last audio page,
  111873. then spec says the end is cut, not beginning */
  111874. if(vb->eofflag){
  111875. /* trim the end */
  111876. /* no preceeding granulepos; assume we started at zero (we'd
  111877. have to in a short single-page stream) */
  111878. /* granulepos could be -1 due to a seek, but that would result
  111879. in a long count, not short count */
  111880. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111881. }else{
  111882. /* trim the beginning */
  111883. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111884. if(v->pcm_returned>v->pcm_current)
  111885. v->pcm_returned=v->pcm_current;
  111886. }
  111887. }
  111888. }
  111889. }else{
  111890. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111891. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111892. if(v->granulepos>vb->granulepos){
  111893. long extra=v->granulepos-vb->granulepos;
  111894. if(extra)
  111895. if(vb->eofflag){
  111896. /* partial last frame. Strip the extra samples off */
  111897. v->pcm_current-=extra>>hs;
  111898. } /* else {Shouldn't happen *unless* the bitstream is out of
  111899. spec. Either way, believe the bitstream } */
  111900. } /* else {Shouldn't happen *unless* the bitstream is out of
  111901. spec. Either way, believe the bitstream } */
  111902. v->granulepos=vb->granulepos;
  111903. }
  111904. }
  111905. /* Update, cleanup */
  111906. if(vb->eofflag)v->eofflag=1;
  111907. return(0);
  111908. }
  111909. /* pcm==NULL indicates we just want the pending samples, no more */
  111910. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111911. vorbis_info *vi=v->vi;
  111912. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111913. if(pcm){
  111914. int i;
  111915. for(i=0;i<vi->channels;i++)
  111916. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111917. *pcm=v->pcmret;
  111918. }
  111919. return(v->pcm_current-v->pcm_returned);
  111920. }
  111921. return(0);
  111922. }
  111923. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111924. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111925. v->pcm_returned+=n;
  111926. return(0);
  111927. }
  111928. /* intended for use with a specific vorbisfile feature; we want access
  111929. to the [usually synthetic/postextrapolated] buffer and lapping at
  111930. the end of a decode cycle, specifically, a half-short-block worth.
  111931. This funtion works like pcmout above, except it will also expose
  111932. this implicit buffer data not normally decoded. */
  111933. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111934. vorbis_info *vi=v->vi;
  111935. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111936. int hs=ci->halfrate_flag;
  111937. int n=ci->blocksizes[v->W]>>(hs+1);
  111938. int n0=ci->blocksizes[0]>>(hs+1);
  111939. int n1=ci->blocksizes[1]>>(hs+1);
  111940. int i,j;
  111941. if(v->pcm_returned<0)return 0;
  111942. /* our returned data ends at pcm_returned; because the synthesis pcm
  111943. buffer is a two-fragment ring, that means our data block may be
  111944. fragmented by buffering, wrapping or a short block not filling
  111945. out a buffer. To simplify things, we unfragment if it's at all
  111946. possibly needed. Otherwise, we'd need to call lapout more than
  111947. once as well as hold additional dsp state. Opt for
  111948. simplicity. */
  111949. /* centerW was advanced by blockin; it would be the center of the
  111950. *next* block */
  111951. if(v->centerW==n1){
  111952. /* the data buffer wraps; swap the halves */
  111953. /* slow, sure, small */
  111954. for(j=0;j<vi->channels;j++){
  111955. float *p=v->pcm[j];
  111956. for(i=0;i<n1;i++){
  111957. float temp=p[i];
  111958. p[i]=p[i+n1];
  111959. p[i+n1]=temp;
  111960. }
  111961. }
  111962. v->pcm_current-=n1;
  111963. v->pcm_returned-=n1;
  111964. v->centerW=0;
  111965. }
  111966. /* solidify buffer into contiguous space */
  111967. if((v->lW^v->W)==1){
  111968. /* long/short or short/long */
  111969. for(j=0;j<vi->channels;j++){
  111970. float *s=v->pcm[j];
  111971. float *d=v->pcm[j]+(n1-n0)/2;
  111972. for(i=(n1+n0)/2-1;i>=0;--i)
  111973. d[i]=s[i];
  111974. }
  111975. v->pcm_returned+=(n1-n0)/2;
  111976. v->pcm_current+=(n1-n0)/2;
  111977. }else{
  111978. if(v->lW==0){
  111979. /* short/short */
  111980. for(j=0;j<vi->channels;j++){
  111981. float *s=v->pcm[j];
  111982. float *d=v->pcm[j]+n1-n0;
  111983. for(i=n0-1;i>=0;--i)
  111984. d[i]=s[i];
  111985. }
  111986. v->pcm_returned+=n1-n0;
  111987. v->pcm_current+=n1-n0;
  111988. }
  111989. }
  111990. if(pcm){
  111991. int i;
  111992. for(i=0;i<vi->channels;i++)
  111993. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111994. *pcm=v->pcmret;
  111995. }
  111996. return(n1+n-v->pcm_returned);
  111997. }
  111998. float *vorbis_window(vorbis_dsp_state *v,int W){
  111999. vorbis_info *vi=v->vi;
  112000. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112001. int hs=ci->halfrate_flag;
  112002. private_state *b=(private_state*)v->backend_state;
  112003. if(b->window[W]-1<0)return NULL;
  112004. return _vorbis_window_get(b->window[W]-hs);
  112005. }
  112006. #endif
  112007. /*** End of inlined file: block.c ***/
  112008. /*** Start of inlined file: codebook.c ***/
  112009. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112010. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112011. // tasks..
  112012. #if JUCE_MSVC
  112013. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112014. #endif
  112015. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112016. #if JUCE_USE_OGGVORBIS
  112017. #include <stdlib.h>
  112018. #include <string.h>
  112019. #include <math.h>
  112020. /* packs the given codebook into the bitstream **************************/
  112021. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112022. long i,j;
  112023. int ordered=0;
  112024. /* first the basic parameters */
  112025. oggpack_write(opb,0x564342,24);
  112026. oggpack_write(opb,c->dim,16);
  112027. oggpack_write(opb,c->entries,24);
  112028. /* pack the codewords. There are two packings; length ordered and
  112029. length random. Decide between the two now. */
  112030. for(i=1;i<c->entries;i++)
  112031. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112032. if(i==c->entries)ordered=1;
  112033. if(ordered){
  112034. /* length ordered. We only need to say how many codewords of
  112035. each length. The actual codewords are generated
  112036. deterministically */
  112037. long count=0;
  112038. oggpack_write(opb,1,1); /* ordered */
  112039. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112040. for(i=1;i<c->entries;i++){
  112041. long thisx=c->lengthlist[i];
  112042. long last=c->lengthlist[i-1];
  112043. if(thisx>last){
  112044. for(j=last;j<thisx;j++){
  112045. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112046. count=i;
  112047. }
  112048. }
  112049. }
  112050. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112051. }else{
  112052. /* length random. Again, we don't code the codeword itself, just
  112053. the length. This time, though, we have to encode each length */
  112054. oggpack_write(opb,0,1); /* unordered */
  112055. /* algortihmic mapping has use for 'unused entries', which we tag
  112056. here. The algorithmic mapping happens as usual, but the unused
  112057. entry has no codeword. */
  112058. for(i=0;i<c->entries;i++)
  112059. if(c->lengthlist[i]==0)break;
  112060. if(i==c->entries){
  112061. oggpack_write(opb,0,1); /* no unused entries */
  112062. for(i=0;i<c->entries;i++)
  112063. oggpack_write(opb,c->lengthlist[i]-1,5);
  112064. }else{
  112065. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112066. for(i=0;i<c->entries;i++){
  112067. if(c->lengthlist[i]==0){
  112068. oggpack_write(opb,0,1);
  112069. }else{
  112070. oggpack_write(opb,1,1);
  112071. oggpack_write(opb,c->lengthlist[i]-1,5);
  112072. }
  112073. }
  112074. }
  112075. }
  112076. /* is the entry number the desired return value, or do we have a
  112077. mapping? If we have a mapping, what type? */
  112078. oggpack_write(opb,c->maptype,4);
  112079. switch(c->maptype){
  112080. case 0:
  112081. /* no mapping */
  112082. break;
  112083. case 1:case 2:
  112084. /* implicitly populated value mapping */
  112085. /* explicitly populated value mapping */
  112086. if(!c->quantlist){
  112087. /* no quantlist? error */
  112088. return(-1);
  112089. }
  112090. /* values that define the dequantization */
  112091. oggpack_write(opb,c->q_min,32);
  112092. oggpack_write(opb,c->q_delta,32);
  112093. oggpack_write(opb,c->q_quant-1,4);
  112094. oggpack_write(opb,c->q_sequencep,1);
  112095. {
  112096. int quantvals;
  112097. switch(c->maptype){
  112098. case 1:
  112099. /* a single column of (c->entries/c->dim) quantized values for
  112100. building a full value list algorithmically (square lattice) */
  112101. quantvals=_book_maptype1_quantvals(c);
  112102. break;
  112103. case 2:
  112104. /* every value (c->entries*c->dim total) specified explicitly */
  112105. quantvals=c->entries*c->dim;
  112106. break;
  112107. default: /* NOT_REACHABLE */
  112108. quantvals=-1;
  112109. }
  112110. /* quantized values */
  112111. for(i=0;i<quantvals;i++)
  112112. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112113. }
  112114. break;
  112115. default:
  112116. /* error case; we don't have any other map types now */
  112117. return(-1);
  112118. }
  112119. return(0);
  112120. }
  112121. /* unpacks a codebook from the packet buffer into the codebook struct,
  112122. readies the codebook auxiliary structures for decode *************/
  112123. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112124. long i,j;
  112125. memset(s,0,sizeof(*s));
  112126. s->allocedp=1;
  112127. /* make sure alignment is correct */
  112128. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112129. /* first the basic parameters */
  112130. s->dim=oggpack_read(opb,16);
  112131. s->entries=oggpack_read(opb,24);
  112132. if(s->entries==-1)goto _eofout;
  112133. /* codeword ordering.... length ordered or unordered? */
  112134. switch((int)oggpack_read(opb,1)){
  112135. case 0:
  112136. /* unordered */
  112137. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112138. /* allocated but unused entries? */
  112139. if(oggpack_read(opb,1)){
  112140. /* yes, unused entries */
  112141. for(i=0;i<s->entries;i++){
  112142. if(oggpack_read(opb,1)){
  112143. long num=oggpack_read(opb,5);
  112144. if(num==-1)goto _eofout;
  112145. s->lengthlist[i]=num+1;
  112146. }else
  112147. s->lengthlist[i]=0;
  112148. }
  112149. }else{
  112150. /* all entries used; no tagging */
  112151. for(i=0;i<s->entries;i++){
  112152. long num=oggpack_read(opb,5);
  112153. if(num==-1)goto _eofout;
  112154. s->lengthlist[i]=num+1;
  112155. }
  112156. }
  112157. break;
  112158. case 1:
  112159. /* ordered */
  112160. {
  112161. long length=oggpack_read(opb,5)+1;
  112162. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112163. for(i=0;i<s->entries;){
  112164. long num=oggpack_read(opb,_ilog(s->entries-i));
  112165. if(num==-1)goto _eofout;
  112166. for(j=0;j<num && i<s->entries;j++,i++)
  112167. s->lengthlist[i]=length;
  112168. length++;
  112169. }
  112170. }
  112171. break;
  112172. default:
  112173. /* EOF */
  112174. return(-1);
  112175. }
  112176. /* Do we have a mapping to unpack? */
  112177. switch((s->maptype=oggpack_read(opb,4))){
  112178. case 0:
  112179. /* no mapping */
  112180. break;
  112181. case 1: case 2:
  112182. /* implicitly populated value mapping */
  112183. /* explicitly populated value mapping */
  112184. s->q_min=oggpack_read(opb,32);
  112185. s->q_delta=oggpack_read(opb,32);
  112186. s->q_quant=oggpack_read(opb,4)+1;
  112187. s->q_sequencep=oggpack_read(opb,1);
  112188. {
  112189. int quantvals=0;
  112190. switch(s->maptype){
  112191. case 1:
  112192. quantvals=_book_maptype1_quantvals(s);
  112193. break;
  112194. case 2:
  112195. quantvals=s->entries*s->dim;
  112196. break;
  112197. }
  112198. /* quantized values */
  112199. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112200. for(i=0;i<quantvals;i++)
  112201. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112202. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112203. }
  112204. break;
  112205. default:
  112206. goto _errout;
  112207. }
  112208. /* all set */
  112209. return(0);
  112210. _errout:
  112211. _eofout:
  112212. vorbis_staticbook_clear(s);
  112213. return(-1);
  112214. }
  112215. /* returns the number of bits ************************************************/
  112216. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112217. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112218. return(book->c->lengthlist[a]);
  112219. }
  112220. /* One the encode side, our vector writers are each designed for a
  112221. specific purpose, and the encoder is not flexible without modification:
  112222. The LSP vector coder uses a single stage nearest-match with no
  112223. interleave, so no step and no error return. This is specced by floor0
  112224. and doesn't change.
  112225. Residue0 encoding interleaves, uses multiple stages, and each stage
  112226. peels of a specific amount of resolution from a lattice (thus we want
  112227. to match by threshold, not nearest match). Residue doesn't *have* to
  112228. be encoded that way, but to change it, one will need to add more
  112229. infrastructure on the encode side (decode side is specced and simpler) */
  112230. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112231. /* returns entry number and *modifies a* to the quantization value *****/
  112232. int vorbis_book_errorv(codebook *book,float *a){
  112233. int dim=book->dim,k;
  112234. int best=_best(book,a,1);
  112235. for(k=0;k<dim;k++)
  112236. a[k]=(book->valuelist+best*dim)[k];
  112237. return(best);
  112238. }
  112239. /* returns the number of bits and *modifies a* to the quantization value *****/
  112240. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112241. int k,dim=book->dim;
  112242. for(k=0;k<dim;k++)
  112243. a[k]=(book->valuelist+best*dim)[k];
  112244. return(vorbis_book_encode(book,best,b));
  112245. }
  112246. /* the 'eliminate the decode tree' optimization actually requires the
  112247. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112248. (and one of the first places where carefully thought out design
  112249. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112250. to an MSb bitpacker), but not actually the huge hit it appears to
  112251. be. The first-stage decode table catches most words so that
  112252. bitreverse is not in the main execution path. */
  112253. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112254. int read=book->dec_maxlength;
  112255. long lo,hi;
  112256. long lok = oggpack_look(b,book->dec_firsttablen);
  112257. if (lok >= 0) {
  112258. long entry = book->dec_firsttable[lok];
  112259. if(entry&0x80000000UL){
  112260. lo=(entry>>15)&0x7fff;
  112261. hi=book->used_entries-(entry&0x7fff);
  112262. }else{
  112263. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112264. return(entry-1);
  112265. }
  112266. }else{
  112267. lo=0;
  112268. hi=book->used_entries;
  112269. }
  112270. lok = oggpack_look(b, read);
  112271. while(lok<0 && read>1)
  112272. lok = oggpack_look(b, --read);
  112273. if(lok<0)return -1;
  112274. /* bisect search for the codeword in the ordered list */
  112275. {
  112276. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112277. while(hi-lo>1){
  112278. long p=(hi-lo)>>1;
  112279. long test=book->codelist[lo+p]>testword;
  112280. lo+=p&(test-1);
  112281. hi-=p&(-test);
  112282. }
  112283. if(book->dec_codelengths[lo]<=read){
  112284. oggpack_adv(b, book->dec_codelengths[lo]);
  112285. return(lo);
  112286. }
  112287. }
  112288. oggpack_adv(b, read);
  112289. return(-1);
  112290. }
  112291. /* Decode side is specced and easier, because we don't need to find
  112292. matches using different criteria; we simply read and map. There are
  112293. two things we need to do 'depending':
  112294. We may need to support interleave. We don't really, but it's
  112295. convenient to do it here rather than rebuild the vector later.
  112296. Cascades may be additive or multiplicitive; this is not inherent in
  112297. the codebook, but set in the code using the codebook. Like
  112298. interleaving, it's easiest to do it here.
  112299. addmul==0 -> declarative (set the value)
  112300. addmul==1 -> additive
  112301. addmul==2 -> multiplicitive */
  112302. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112303. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112304. long packed_entry=decode_packed_entry_number(book,b);
  112305. if(packed_entry>=0)
  112306. return(book->dec_index[packed_entry]);
  112307. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112308. return(packed_entry);
  112309. }
  112310. /* returns 0 on OK or -1 on eof *************************************/
  112311. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112312. int step=n/book->dim;
  112313. long *entry = (long*)alloca(sizeof(*entry)*step);
  112314. float **t = (float**)alloca(sizeof(*t)*step);
  112315. int i,j,o;
  112316. for (i = 0; i < step; i++) {
  112317. entry[i]=decode_packed_entry_number(book,b);
  112318. if(entry[i]==-1)return(-1);
  112319. t[i] = book->valuelist+entry[i]*book->dim;
  112320. }
  112321. for(i=0,o=0;i<book->dim;i++,o+=step)
  112322. for (j=0;j<step;j++)
  112323. a[o+j]+=t[j][i];
  112324. return(0);
  112325. }
  112326. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112327. int i,j,entry;
  112328. float *t;
  112329. if(book->dim>8){
  112330. for(i=0;i<n;){
  112331. entry = decode_packed_entry_number(book,b);
  112332. if(entry==-1)return(-1);
  112333. t = book->valuelist+entry*book->dim;
  112334. for (j=0;j<book->dim;)
  112335. a[i++]+=t[j++];
  112336. }
  112337. }else{
  112338. for(i=0;i<n;){
  112339. entry = decode_packed_entry_number(book,b);
  112340. if(entry==-1)return(-1);
  112341. t = book->valuelist+entry*book->dim;
  112342. j=0;
  112343. switch((int)book->dim){
  112344. case 8:
  112345. a[i++]+=t[j++];
  112346. case 7:
  112347. a[i++]+=t[j++];
  112348. case 6:
  112349. a[i++]+=t[j++];
  112350. case 5:
  112351. a[i++]+=t[j++];
  112352. case 4:
  112353. a[i++]+=t[j++];
  112354. case 3:
  112355. a[i++]+=t[j++];
  112356. case 2:
  112357. a[i++]+=t[j++];
  112358. case 1:
  112359. a[i++]+=t[j++];
  112360. case 0:
  112361. break;
  112362. }
  112363. }
  112364. }
  112365. return(0);
  112366. }
  112367. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112368. int i,j,entry;
  112369. float *t;
  112370. for(i=0;i<n;){
  112371. entry = decode_packed_entry_number(book,b);
  112372. if(entry==-1)return(-1);
  112373. t = book->valuelist+entry*book->dim;
  112374. for (j=0;j<book->dim;)
  112375. a[i++]=t[j++];
  112376. }
  112377. return(0);
  112378. }
  112379. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112380. oggpack_buffer *b,int n){
  112381. long i,j,entry;
  112382. int chptr=0;
  112383. for(i=offset/ch;i<(offset+n)/ch;){
  112384. entry = decode_packed_entry_number(book,b);
  112385. if(entry==-1)return(-1);
  112386. {
  112387. const float *t = book->valuelist+entry*book->dim;
  112388. for (j=0;j<book->dim;j++){
  112389. a[chptr++][i]+=t[j];
  112390. if(chptr==ch){
  112391. chptr=0;
  112392. i++;
  112393. }
  112394. }
  112395. }
  112396. }
  112397. return(0);
  112398. }
  112399. #ifdef _V_SELFTEST
  112400. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112401. number of vectors through (keeping track of the quantized values),
  112402. and decode using the unpacked book. quantized version of in should
  112403. exactly equal out */
  112404. #include <stdio.h>
  112405. #include "vorbis/book/lsp20_0.vqh"
  112406. #include "vorbis/book/res0a_13.vqh"
  112407. #define TESTSIZE 40
  112408. float test1[TESTSIZE]={
  112409. 0.105939f,
  112410. 0.215373f,
  112411. 0.429117f,
  112412. 0.587974f,
  112413. 0.181173f,
  112414. 0.296583f,
  112415. 0.515707f,
  112416. 0.715261f,
  112417. 0.162327f,
  112418. 0.263834f,
  112419. 0.342876f,
  112420. 0.406025f,
  112421. 0.103571f,
  112422. 0.223561f,
  112423. 0.368513f,
  112424. 0.540313f,
  112425. 0.136672f,
  112426. 0.395882f,
  112427. 0.587183f,
  112428. 0.652476f,
  112429. 0.114338f,
  112430. 0.417300f,
  112431. 0.525486f,
  112432. 0.698679f,
  112433. 0.147492f,
  112434. 0.324481f,
  112435. 0.643089f,
  112436. 0.757582f,
  112437. 0.139556f,
  112438. 0.215795f,
  112439. 0.324559f,
  112440. 0.399387f,
  112441. 0.120236f,
  112442. 0.267420f,
  112443. 0.446940f,
  112444. 0.608760f,
  112445. 0.115587f,
  112446. 0.287234f,
  112447. 0.571081f,
  112448. 0.708603f,
  112449. };
  112450. float test3[TESTSIZE]={
  112451. 0,1,-2,3,4,-5,6,7,8,9,
  112452. 8,-2,7,-1,4,6,8,3,1,-9,
  112453. 10,11,12,13,14,15,26,17,18,19,
  112454. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112455. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112456. &_vq_book_res0a_13,NULL};
  112457. float *testvec[]={test1,test3};
  112458. int main(){
  112459. oggpack_buffer write;
  112460. oggpack_buffer read;
  112461. long ptr=0,i;
  112462. oggpack_writeinit(&write);
  112463. fprintf(stderr,"Testing codebook abstraction...:\n");
  112464. while(testlist[ptr]){
  112465. codebook c;
  112466. static_codebook s;
  112467. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112468. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112469. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112470. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112471. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112472. /* pack the codebook, write the testvector */
  112473. oggpack_reset(&write);
  112474. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112475. we can write */
  112476. vorbis_staticbook_pack(testlist[ptr],&write);
  112477. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112478. for(i=0;i<TESTSIZE;i+=c.dim){
  112479. int best=_best(&c,qv+i,1);
  112480. vorbis_book_encodev(&c,best,qv+i,&write);
  112481. }
  112482. vorbis_book_clear(&c);
  112483. fprintf(stderr,"OK.\n");
  112484. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112485. /* transfer the write data to a read buffer and unpack/read */
  112486. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112487. if(vorbis_staticbook_unpack(&read,&s)){
  112488. fprintf(stderr,"Error unpacking codebook.\n");
  112489. exit(1);
  112490. }
  112491. if(vorbis_book_init_decode(&c,&s)){
  112492. fprintf(stderr,"Error initializing codebook.\n");
  112493. exit(1);
  112494. }
  112495. for(i=0;i<TESTSIZE;i+=c.dim)
  112496. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112497. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112498. exit(1);
  112499. }
  112500. for(i=0;i<TESTSIZE;i++)
  112501. if(fabs(qv[i]-iv[i])>.000001){
  112502. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112503. iv[i],qv[i],i);
  112504. exit(1);
  112505. }
  112506. fprintf(stderr,"OK\n");
  112507. ptr++;
  112508. }
  112509. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112510. exit(0);
  112511. }
  112512. #endif
  112513. #endif
  112514. /*** End of inlined file: codebook.c ***/
  112515. /*** Start of inlined file: envelope.c ***/
  112516. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112517. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112518. // tasks..
  112519. #if JUCE_MSVC
  112520. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112521. #endif
  112522. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112523. #if JUCE_USE_OGGVORBIS
  112524. #include <stdlib.h>
  112525. #include <string.h>
  112526. #include <stdio.h>
  112527. #include <math.h>
  112528. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112529. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112530. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112531. int ch=vi->channels;
  112532. int i,j;
  112533. int n=e->winlength=128;
  112534. e->searchstep=64; /* not random */
  112535. e->minenergy=gi->preecho_minenergy;
  112536. e->ch=ch;
  112537. e->storage=128;
  112538. e->cursor=ci->blocksizes[1]/2;
  112539. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112540. mdct_init(&e->mdct,n);
  112541. for(i=0;i<n;i++){
  112542. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112543. e->mdct_win[i]*=e->mdct_win[i];
  112544. }
  112545. /* magic follows */
  112546. e->band[0].begin=2; e->band[0].end=4;
  112547. e->band[1].begin=4; e->band[1].end=5;
  112548. e->band[2].begin=6; e->band[2].end=6;
  112549. e->band[3].begin=9; e->band[3].end=8;
  112550. e->band[4].begin=13; e->band[4].end=8;
  112551. e->band[5].begin=17; e->band[5].end=8;
  112552. e->band[6].begin=22; e->band[6].end=8;
  112553. for(j=0;j<VE_BANDS;j++){
  112554. n=e->band[j].end;
  112555. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112556. for(i=0;i<n;i++){
  112557. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112558. e->band[j].total+=e->band[j].window[i];
  112559. }
  112560. e->band[j].total=1./e->band[j].total;
  112561. }
  112562. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112563. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112564. }
  112565. void _ve_envelope_clear(envelope_lookup *e){
  112566. int i;
  112567. mdct_clear(&e->mdct);
  112568. for(i=0;i<VE_BANDS;i++)
  112569. _ogg_free(e->band[i].window);
  112570. _ogg_free(e->mdct_win);
  112571. _ogg_free(e->filter);
  112572. _ogg_free(e->mark);
  112573. memset(e,0,sizeof(*e));
  112574. }
  112575. /* fairly straight threshhold-by-band based until we find something
  112576. that works better and isn't patented. */
  112577. static int _ve_amp(envelope_lookup *ve,
  112578. vorbis_info_psy_global *gi,
  112579. float *data,
  112580. envelope_band *bands,
  112581. envelope_filter_state *filters,
  112582. long pos){
  112583. long n=ve->winlength;
  112584. int ret=0;
  112585. long i,j;
  112586. float decay;
  112587. /* we want to have a 'minimum bar' for energy, else we're just
  112588. basing blocks on quantization noise that outweighs the signal
  112589. itself (for low power signals) */
  112590. float minV=ve->minenergy;
  112591. float *vec=(float*) alloca(n*sizeof(*vec));
  112592. /* stretch is used to gradually lengthen the number of windows
  112593. considered prevoius-to-potential-trigger */
  112594. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112595. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112596. if(penalty<0.f)penalty=0.f;
  112597. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112598. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112599. totalshift+pos*ve->searchstep);*/
  112600. /* window and transform */
  112601. for(i=0;i<n;i++)
  112602. vec[i]=data[i]*ve->mdct_win[i];
  112603. mdct_forward(&ve->mdct,vec,vec);
  112604. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112605. /* near-DC spreading function; this has nothing to do with
  112606. psychoacoustics, just sidelobe leakage and window size */
  112607. {
  112608. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112609. int ptr=filters->nearptr;
  112610. /* the accumulation is regularly refreshed from scratch to avoid
  112611. floating point creep */
  112612. if(ptr==0){
  112613. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112614. filters->nearDC_partialacc=temp;
  112615. }else{
  112616. decay=filters->nearDC_acc+=temp;
  112617. filters->nearDC_partialacc+=temp;
  112618. }
  112619. filters->nearDC_acc-=filters->nearDC[ptr];
  112620. filters->nearDC[ptr]=temp;
  112621. decay*=(1./(VE_NEARDC+1));
  112622. filters->nearptr++;
  112623. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112624. decay=todB(&decay)*.5-15.f;
  112625. }
  112626. /* perform spreading and limiting, also smooth the spectrum. yes,
  112627. the MDCT results in all real coefficients, but it still *behaves*
  112628. like real/imaginary pairs */
  112629. for(i=0;i<n/2;i+=2){
  112630. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112631. val=todB(&val)*.5f;
  112632. if(val<decay)val=decay;
  112633. if(val<minV)val=minV;
  112634. vec[i>>1]=val;
  112635. decay-=8.;
  112636. }
  112637. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112638. /* perform preecho/postecho triggering by band */
  112639. for(j=0;j<VE_BANDS;j++){
  112640. float acc=0.;
  112641. float valmax,valmin;
  112642. /* accumulate amplitude */
  112643. for(i=0;i<bands[j].end;i++)
  112644. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112645. acc*=bands[j].total;
  112646. /* convert amplitude to delta */
  112647. {
  112648. int p,thisx=filters[j].ampptr;
  112649. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112650. p=thisx;
  112651. p--;
  112652. if(p<0)p+=VE_AMP;
  112653. postmax=max(acc,filters[j].ampbuf[p]);
  112654. postmin=min(acc,filters[j].ampbuf[p]);
  112655. for(i=0;i<stretch;i++){
  112656. p--;
  112657. if(p<0)p+=VE_AMP;
  112658. premax=max(premax,filters[j].ampbuf[p]);
  112659. premin=min(premin,filters[j].ampbuf[p]);
  112660. }
  112661. valmin=postmin-premin;
  112662. valmax=postmax-premax;
  112663. /*filters[j].markers[pos]=valmax;*/
  112664. filters[j].ampbuf[thisx]=acc;
  112665. filters[j].ampptr++;
  112666. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112667. }
  112668. /* look at min/max, decide trigger */
  112669. if(valmax>gi->preecho_thresh[j]+penalty){
  112670. ret|=1;
  112671. ret|=4;
  112672. }
  112673. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112674. }
  112675. return(ret);
  112676. }
  112677. #if 0
  112678. static int seq=0;
  112679. static ogg_int64_t totalshift=-1024;
  112680. #endif
  112681. long _ve_envelope_search(vorbis_dsp_state *v){
  112682. vorbis_info *vi=v->vi;
  112683. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112684. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112685. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112686. long i,j;
  112687. int first=ve->current/ve->searchstep;
  112688. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112689. if(first<0)first=0;
  112690. /* make sure we have enough storage to match the PCM */
  112691. if(last+VE_WIN+VE_POST>ve->storage){
  112692. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112693. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112694. }
  112695. for(j=first;j<last;j++){
  112696. int ret=0;
  112697. ve->stretch++;
  112698. if(ve->stretch>VE_MAXSTRETCH*2)
  112699. ve->stretch=VE_MAXSTRETCH*2;
  112700. for(i=0;i<ve->ch;i++){
  112701. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112702. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112703. }
  112704. ve->mark[j+VE_POST]=0;
  112705. if(ret&1){
  112706. ve->mark[j]=1;
  112707. ve->mark[j+1]=1;
  112708. }
  112709. if(ret&2){
  112710. ve->mark[j]=1;
  112711. if(j>0)ve->mark[j-1]=1;
  112712. }
  112713. if(ret&4)ve->stretch=-1;
  112714. }
  112715. ve->current=last*ve->searchstep;
  112716. {
  112717. long centerW=v->centerW;
  112718. long testW=
  112719. centerW+
  112720. ci->blocksizes[v->W]/4+
  112721. ci->blocksizes[1]/2+
  112722. ci->blocksizes[0]/4;
  112723. j=ve->cursor;
  112724. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112725. working back one window */
  112726. if(j>=testW)return(1);
  112727. ve->cursor=j;
  112728. if(ve->mark[j/ve->searchstep]){
  112729. if(j>centerW){
  112730. #if 0
  112731. if(j>ve->curmark){
  112732. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112733. int l,m;
  112734. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112735. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112736. seq,
  112737. (totalshift+ve->cursor)/44100.,
  112738. (totalshift+j)/44100.);
  112739. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112740. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112741. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112742. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112743. for(m=0;m<VE_BANDS;m++){
  112744. char buf[80];
  112745. sprintf(buf,"delL%d",m);
  112746. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112747. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112748. }
  112749. for(m=0;m<VE_BANDS;m++){
  112750. char buf[80];
  112751. sprintf(buf,"delR%d",m);
  112752. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112753. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112754. }
  112755. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112756. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112757. seq++;
  112758. }
  112759. #endif
  112760. ve->curmark=j;
  112761. if(j>=testW)return(1);
  112762. return(0);
  112763. }
  112764. }
  112765. j+=ve->searchstep;
  112766. }
  112767. }
  112768. return(-1);
  112769. }
  112770. int _ve_envelope_mark(vorbis_dsp_state *v){
  112771. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112772. vorbis_info *vi=v->vi;
  112773. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112774. long centerW=v->centerW;
  112775. long beginW=centerW-ci->blocksizes[v->W]/4;
  112776. long endW=centerW+ci->blocksizes[v->W]/4;
  112777. if(v->W){
  112778. beginW-=ci->blocksizes[v->lW]/4;
  112779. endW+=ci->blocksizes[v->nW]/4;
  112780. }else{
  112781. beginW-=ci->blocksizes[0]/4;
  112782. endW+=ci->blocksizes[0]/4;
  112783. }
  112784. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112785. {
  112786. long first=beginW/ve->searchstep;
  112787. long last=endW/ve->searchstep;
  112788. long i;
  112789. for(i=first;i<last;i++)
  112790. if(ve->mark[i])return(1);
  112791. }
  112792. return(0);
  112793. }
  112794. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112795. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112796. ahead of ve->current */
  112797. int smallshift=shift/e->searchstep;
  112798. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112799. #if 0
  112800. for(i=0;i<VE_BANDS*e->ch;i++)
  112801. memmove(e->filter[i].markers,
  112802. e->filter[i].markers+smallshift,
  112803. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112804. totalshift+=shift;
  112805. #endif
  112806. e->current-=shift;
  112807. if(e->curmark>=0)
  112808. e->curmark-=shift;
  112809. e->cursor-=shift;
  112810. }
  112811. #endif
  112812. /*** End of inlined file: envelope.c ***/
  112813. /*** Start of inlined file: floor0.c ***/
  112814. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112815. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112816. // tasks..
  112817. #if JUCE_MSVC
  112818. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112819. #endif
  112820. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112821. #if JUCE_USE_OGGVORBIS
  112822. #include <stdlib.h>
  112823. #include <string.h>
  112824. #include <math.h>
  112825. /*** Start of inlined file: lsp.h ***/
  112826. #ifndef _V_LSP_H_
  112827. #define _V_LSP_H_
  112828. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112829. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112830. float *lsp,int m,
  112831. float amp,float ampoffset);
  112832. #endif
  112833. /*** End of inlined file: lsp.h ***/
  112834. #include <stdio.h>
  112835. typedef struct {
  112836. int ln;
  112837. int m;
  112838. int **linearmap;
  112839. int n[2];
  112840. vorbis_info_floor0 *vi;
  112841. long bits;
  112842. long frames;
  112843. } vorbis_look_floor0;
  112844. /***********************************************/
  112845. static void floor0_free_info(vorbis_info_floor *i){
  112846. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112847. if(info){
  112848. memset(info,0,sizeof(*info));
  112849. _ogg_free(info);
  112850. }
  112851. }
  112852. static void floor0_free_look(vorbis_look_floor *i){
  112853. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112854. if(look){
  112855. if(look->linearmap){
  112856. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112857. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112858. _ogg_free(look->linearmap);
  112859. }
  112860. memset(look,0,sizeof(*look));
  112861. _ogg_free(look);
  112862. }
  112863. }
  112864. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112865. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112866. int j;
  112867. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112868. info->order=oggpack_read(opb,8);
  112869. info->rate=oggpack_read(opb,16);
  112870. info->barkmap=oggpack_read(opb,16);
  112871. info->ampbits=oggpack_read(opb,6);
  112872. info->ampdB=oggpack_read(opb,8);
  112873. info->numbooks=oggpack_read(opb,4)+1;
  112874. if(info->order<1)goto err_out;
  112875. if(info->rate<1)goto err_out;
  112876. if(info->barkmap<1)goto err_out;
  112877. if(info->numbooks<1)goto err_out;
  112878. for(j=0;j<info->numbooks;j++){
  112879. info->books[j]=oggpack_read(opb,8);
  112880. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112881. }
  112882. return(info);
  112883. err_out:
  112884. floor0_free_info(info);
  112885. return(NULL);
  112886. }
  112887. /* initialize Bark scale and normalization lookups. We could do this
  112888. with static tables, but Vorbis allows a number of possible
  112889. combinations, so it's best to do it computationally.
  112890. The below is authoritative in terms of defining scale mapping.
  112891. Note that the scale depends on the sampling rate as well as the
  112892. linear block and mapping sizes */
  112893. static void floor0_map_lazy_init(vorbis_block *vb,
  112894. vorbis_info_floor *infoX,
  112895. vorbis_look_floor0 *look){
  112896. if(!look->linearmap[vb->W]){
  112897. vorbis_dsp_state *vd=vb->vd;
  112898. vorbis_info *vi=vd->vi;
  112899. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112900. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112901. int W=vb->W;
  112902. int n=ci->blocksizes[W]/2,j;
  112903. /* we choose a scaling constant so that:
  112904. floor(bark(rate/2-1)*C)=mapped-1
  112905. floor(bark(rate/2)*C)=mapped */
  112906. float scale=look->ln/toBARK(info->rate/2.f);
  112907. /* the mapping from a linear scale to a smaller bark scale is
  112908. straightforward. We do *not* make sure that the linear mapping
  112909. does not skip bark-scale bins; the decoder simply skips them and
  112910. the encoder may do what it wishes in filling them. They're
  112911. necessary in some mapping combinations to keep the scale spacing
  112912. accurate */
  112913. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112914. for(j=0;j<n;j++){
  112915. int val=floor( toBARK((info->rate/2.f)/n*j)
  112916. *scale); /* bark numbers represent band edges */
  112917. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112918. look->linearmap[W][j]=val;
  112919. }
  112920. look->linearmap[W][j]=-1;
  112921. look->n[W]=n;
  112922. }
  112923. }
  112924. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112925. vorbis_info_floor *i){
  112926. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112927. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112928. look->m=info->order;
  112929. look->ln=info->barkmap;
  112930. look->vi=info;
  112931. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112932. return look;
  112933. }
  112934. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112935. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112936. vorbis_info_floor0 *info=look->vi;
  112937. int j,k;
  112938. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112939. if(ampraw>0){ /* also handles the -1 out of data case */
  112940. long maxval=(1<<info->ampbits)-1;
  112941. float amp=(float)ampraw/maxval*info->ampdB;
  112942. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112943. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112944. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112945. codebook *b=ci->fullbooks+info->books[booknum];
  112946. float last=0.f;
  112947. /* the additional b->dim is a guard against any possible stack
  112948. smash; b->dim is provably more than we can overflow the
  112949. vector */
  112950. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112951. for(j=0;j<look->m;j+=b->dim)
  112952. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112953. for(j=0;j<look->m;){
  112954. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112955. last=lsp[j-1];
  112956. }
  112957. lsp[look->m]=amp;
  112958. return(lsp);
  112959. }
  112960. }
  112961. eop:
  112962. return(NULL);
  112963. }
  112964. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112965. void *memo,float *out){
  112966. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112967. vorbis_info_floor0 *info=look->vi;
  112968. floor0_map_lazy_init(vb,info,look);
  112969. if(memo){
  112970. float *lsp=(float *)memo;
  112971. float amp=lsp[look->m];
  112972. /* take the coefficients back to a spectral envelope curve */
  112973. vorbis_lsp_to_curve(out,
  112974. look->linearmap[vb->W],
  112975. look->n[vb->W],
  112976. look->ln,
  112977. lsp,look->m,amp,(float)info->ampdB);
  112978. return(1);
  112979. }
  112980. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112981. return(0);
  112982. }
  112983. /* export hooks */
  112984. vorbis_func_floor floor0_exportbundle={
  112985. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112986. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112987. };
  112988. #endif
  112989. /*** End of inlined file: floor0.c ***/
  112990. /*** Start of inlined file: floor1.c ***/
  112991. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112992. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112993. // tasks..
  112994. #if JUCE_MSVC
  112995. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112996. #endif
  112997. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112998. #if JUCE_USE_OGGVORBIS
  112999. #include <stdlib.h>
  113000. #include <string.h>
  113001. #include <math.h>
  113002. #include <stdio.h>
  113003. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  113004. typedef struct {
  113005. int sorted_index[VIF_POSIT+2];
  113006. int forward_index[VIF_POSIT+2];
  113007. int reverse_index[VIF_POSIT+2];
  113008. int hineighbor[VIF_POSIT];
  113009. int loneighbor[VIF_POSIT];
  113010. int posts;
  113011. int n;
  113012. int quant_q;
  113013. vorbis_info_floor1 *vi;
  113014. long phrasebits;
  113015. long postbits;
  113016. long frames;
  113017. } vorbis_look_floor1;
  113018. typedef struct lsfit_acc{
  113019. long x0;
  113020. long x1;
  113021. long xa;
  113022. long ya;
  113023. long x2a;
  113024. long y2a;
  113025. long xya;
  113026. long an;
  113027. } lsfit_acc;
  113028. /***********************************************/
  113029. static void floor1_free_info(vorbis_info_floor *i){
  113030. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113031. if(info){
  113032. memset(info,0,sizeof(*info));
  113033. _ogg_free(info);
  113034. }
  113035. }
  113036. static void floor1_free_look(vorbis_look_floor *i){
  113037. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113038. if(look){
  113039. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113040. (float)look->phrasebits/look->frames,
  113041. (float)look->postbits/look->frames,
  113042. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113043. memset(look,0,sizeof(*look));
  113044. _ogg_free(look);
  113045. }
  113046. }
  113047. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113048. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113049. int j,k;
  113050. int count=0;
  113051. int rangebits;
  113052. int maxposit=info->postlist[1];
  113053. int maxclass=-1;
  113054. /* save out partitions */
  113055. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113056. for(j=0;j<info->partitions;j++){
  113057. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113058. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113059. }
  113060. /* save out partition classes */
  113061. for(j=0;j<maxclass+1;j++){
  113062. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113063. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113064. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113065. for(k=0;k<(1<<info->class_subs[j]);k++)
  113066. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113067. }
  113068. /* save out the post list */
  113069. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113070. oggpack_write(opb,ilog2(maxposit),4);
  113071. rangebits=ilog2(maxposit);
  113072. for(j=0,k=0;j<info->partitions;j++){
  113073. count+=info->class_dim[info->partitionclass[j]];
  113074. for(;k<count;k++)
  113075. oggpack_write(opb,info->postlist[k+2],rangebits);
  113076. }
  113077. }
  113078. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113079. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113080. int j,k,count=0,maxclass=-1,rangebits;
  113081. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113082. /* read partitions */
  113083. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113084. for(j=0;j<info->partitions;j++){
  113085. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113086. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113087. }
  113088. /* read partition classes */
  113089. for(j=0;j<maxclass+1;j++){
  113090. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113091. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113092. if(info->class_subs[j]<0)
  113093. goto err_out;
  113094. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113095. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113096. goto err_out;
  113097. for(k=0;k<(1<<info->class_subs[j]);k++){
  113098. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113099. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113100. goto err_out;
  113101. }
  113102. }
  113103. /* read the post list */
  113104. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113105. rangebits=oggpack_read(opb,4);
  113106. for(j=0,k=0;j<info->partitions;j++){
  113107. count+=info->class_dim[info->partitionclass[j]];
  113108. for(;k<count;k++){
  113109. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113110. if(t<0 || t>=(1<<rangebits))
  113111. goto err_out;
  113112. }
  113113. }
  113114. info->postlist[0]=0;
  113115. info->postlist[1]=1<<rangebits;
  113116. return(info);
  113117. err_out:
  113118. floor1_free_info(info);
  113119. return(NULL);
  113120. }
  113121. static int JUCE_CDECL icomp(const void *a,const void *b){
  113122. return(**(int **)a-**(int **)b);
  113123. }
  113124. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113125. vorbis_info_floor *in){
  113126. int *sortpointer[VIF_POSIT+2];
  113127. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113128. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113129. int i,j,n=0;
  113130. look->vi=info;
  113131. look->n=info->postlist[1];
  113132. /* we drop each position value in-between already decoded values,
  113133. and use linear interpolation to predict each new value past the
  113134. edges. The positions are read in the order of the position
  113135. list... we precompute the bounding positions in the lookup. Of
  113136. course, the neighbors can change (if a position is declined), but
  113137. this is an initial mapping */
  113138. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113139. n+=2;
  113140. look->posts=n;
  113141. /* also store a sorted position index */
  113142. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113143. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113144. /* points from sort order back to range number */
  113145. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113146. /* points from range order to sorted position */
  113147. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113148. /* we actually need the post values too */
  113149. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113150. /* quantize values to multiplier spec */
  113151. switch(info->mult){
  113152. case 1: /* 1024 -> 256 */
  113153. look->quant_q=256;
  113154. break;
  113155. case 2: /* 1024 -> 128 */
  113156. look->quant_q=128;
  113157. break;
  113158. case 3: /* 1024 -> 86 */
  113159. look->quant_q=86;
  113160. break;
  113161. case 4: /* 1024 -> 64 */
  113162. look->quant_q=64;
  113163. break;
  113164. }
  113165. /* discover our neighbors for decode where we don't use fit flags
  113166. (that would push the neighbors outward) */
  113167. for(i=0;i<n-2;i++){
  113168. int lo=0;
  113169. int hi=1;
  113170. int lx=0;
  113171. int hx=look->n;
  113172. int currentx=info->postlist[i+2];
  113173. for(j=0;j<i+2;j++){
  113174. int x=info->postlist[j];
  113175. if(x>lx && x<currentx){
  113176. lo=j;
  113177. lx=x;
  113178. }
  113179. if(x<hx && x>currentx){
  113180. hi=j;
  113181. hx=x;
  113182. }
  113183. }
  113184. look->loneighbor[i]=lo;
  113185. look->hineighbor[i]=hi;
  113186. }
  113187. return(look);
  113188. }
  113189. static int render_point(int x0,int x1,int y0,int y1,int x){
  113190. y0&=0x7fff; /* mask off flag */
  113191. y1&=0x7fff;
  113192. {
  113193. int dy=y1-y0;
  113194. int adx=x1-x0;
  113195. int ady=abs(dy);
  113196. int err=ady*(x-x0);
  113197. int off=err/adx;
  113198. if(dy<0)return(y0-off);
  113199. return(y0+off);
  113200. }
  113201. }
  113202. static int vorbis_dBquant(const float *x){
  113203. int i= *x*7.3142857f+1023.5f;
  113204. if(i>1023)return(1023);
  113205. if(i<0)return(0);
  113206. return i;
  113207. }
  113208. static float FLOOR1_fromdB_LOOKUP[256]={
  113209. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113210. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113211. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113212. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113213. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113214. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113215. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113216. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113217. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113218. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113219. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113220. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113221. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113222. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113223. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113224. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113225. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113226. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113227. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113228. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113229. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113230. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113231. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113232. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113233. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113234. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113235. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113236. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113237. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113238. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113239. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113240. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113241. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113242. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113243. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113244. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113245. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113246. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113247. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113248. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113249. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113250. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113251. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113252. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113253. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113254. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113255. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113256. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113257. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113258. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113259. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113260. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113261. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113262. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113263. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113264. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113265. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113266. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113267. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113268. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113269. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113270. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113271. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113272. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113273. };
  113274. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113275. int dy=y1-y0;
  113276. int adx=x1-x0;
  113277. int ady=abs(dy);
  113278. int base=dy/adx;
  113279. int sy=(dy<0?base-1:base+1);
  113280. int x=x0;
  113281. int y=y0;
  113282. int err=0;
  113283. ady-=abs(base*adx);
  113284. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113285. while(++x<x1){
  113286. err=err+ady;
  113287. if(err>=adx){
  113288. err-=adx;
  113289. y+=sy;
  113290. }else{
  113291. y+=base;
  113292. }
  113293. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113294. }
  113295. }
  113296. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113297. int dy=y1-y0;
  113298. int adx=x1-x0;
  113299. int ady=abs(dy);
  113300. int base=dy/adx;
  113301. int sy=(dy<0?base-1:base+1);
  113302. int x=x0;
  113303. int y=y0;
  113304. int err=0;
  113305. ady-=abs(base*adx);
  113306. d[x]=y;
  113307. while(++x<x1){
  113308. err=err+ady;
  113309. if(err>=adx){
  113310. err-=adx;
  113311. y+=sy;
  113312. }else{
  113313. y+=base;
  113314. }
  113315. d[x]=y;
  113316. }
  113317. }
  113318. /* the floor has already been filtered to only include relevant sections */
  113319. static int accumulate_fit(const float *flr,const float *mdct,
  113320. int x0, int x1,lsfit_acc *a,
  113321. int n,vorbis_info_floor1 *info){
  113322. long i;
  113323. 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;
  113324. memset(a,0,sizeof(*a));
  113325. a->x0=x0;
  113326. a->x1=x1;
  113327. if(x1>=n)x1=n-1;
  113328. for(i=x0;i<=x1;i++){
  113329. int quantized=vorbis_dBquant(flr+i);
  113330. if(quantized){
  113331. if(mdct[i]+info->twofitatten>=flr[i]){
  113332. xa += i;
  113333. ya += quantized;
  113334. x2a += i*i;
  113335. y2a += quantized*quantized;
  113336. xya += i*quantized;
  113337. na++;
  113338. }else{
  113339. xb += i;
  113340. yb += quantized;
  113341. x2b += i*i;
  113342. y2b += quantized*quantized;
  113343. xyb += i*quantized;
  113344. nb++;
  113345. }
  113346. }
  113347. }
  113348. xb+=xa;
  113349. yb+=ya;
  113350. x2b+=x2a;
  113351. y2b+=y2a;
  113352. xyb+=xya;
  113353. nb+=na;
  113354. /* weight toward the actually used frequencies if we meet the threshhold */
  113355. {
  113356. int weight=nb*info->twofitweight/(na+1);
  113357. a->xa=xa*weight+xb;
  113358. a->ya=ya*weight+yb;
  113359. a->x2a=x2a*weight+x2b;
  113360. a->y2a=y2a*weight+y2b;
  113361. a->xya=xya*weight+xyb;
  113362. a->an=na*weight+nb;
  113363. }
  113364. return(na);
  113365. }
  113366. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113367. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113368. long x0=a[0].x0;
  113369. long x1=a[fits-1].x1;
  113370. for(i=0;i<fits;i++){
  113371. x+=a[i].xa;
  113372. y+=a[i].ya;
  113373. x2+=a[i].x2a;
  113374. y2+=a[i].y2a;
  113375. xy+=a[i].xya;
  113376. an+=a[i].an;
  113377. }
  113378. if(*y0>=0){
  113379. x+= x0;
  113380. y+= *y0;
  113381. x2+= x0 * x0;
  113382. y2+= *y0 * *y0;
  113383. xy+= *y0 * x0;
  113384. an++;
  113385. }
  113386. if(*y1>=0){
  113387. x+= x1;
  113388. y+= *y1;
  113389. x2+= x1 * x1;
  113390. y2+= *y1 * *y1;
  113391. xy+= *y1 * x1;
  113392. an++;
  113393. }
  113394. if(an){
  113395. /* need 64 bit multiplies, which C doesn't give portably as int */
  113396. double fx=x;
  113397. double fy=y;
  113398. double fx2=x2;
  113399. double fxy=xy;
  113400. double denom=1./(an*fx2-fx*fx);
  113401. double a=(fy*fx2-fxy*fx)*denom;
  113402. double b=(an*fxy-fx*fy)*denom;
  113403. *y0=rint(a+b*x0);
  113404. *y1=rint(a+b*x1);
  113405. /* limit to our range! */
  113406. if(*y0>1023)*y0=1023;
  113407. if(*y1>1023)*y1=1023;
  113408. if(*y0<0)*y0=0;
  113409. if(*y1<0)*y1=0;
  113410. }else{
  113411. *y0=0;
  113412. *y1=0;
  113413. }
  113414. }
  113415. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113416. long y=0;
  113417. int i;
  113418. for(i=0;i<fits && y==0;i++)
  113419. y+=a[i].ya;
  113420. *y0=*y1=y;
  113421. }*/
  113422. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113423. const float *mdct,
  113424. vorbis_info_floor1 *info){
  113425. int dy=y1-y0;
  113426. int adx=x1-x0;
  113427. int ady=abs(dy);
  113428. int base=dy/adx;
  113429. int sy=(dy<0?base-1:base+1);
  113430. int x=x0;
  113431. int y=y0;
  113432. int err=0;
  113433. int val=vorbis_dBquant(mask+x);
  113434. int mse=0;
  113435. int n=0;
  113436. ady-=abs(base*adx);
  113437. mse=(y-val);
  113438. mse*=mse;
  113439. n++;
  113440. if(mdct[x]+info->twofitatten>=mask[x]){
  113441. if(y+info->maxover<val)return(1);
  113442. if(y-info->maxunder>val)return(1);
  113443. }
  113444. while(++x<x1){
  113445. err=err+ady;
  113446. if(err>=adx){
  113447. err-=adx;
  113448. y+=sy;
  113449. }else{
  113450. y+=base;
  113451. }
  113452. val=vorbis_dBquant(mask+x);
  113453. mse+=((y-val)*(y-val));
  113454. n++;
  113455. if(mdct[x]+info->twofitatten>=mask[x]){
  113456. if(val){
  113457. if(y+info->maxover<val)return(1);
  113458. if(y-info->maxunder>val)return(1);
  113459. }
  113460. }
  113461. }
  113462. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113463. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113464. if(mse/n>info->maxerr)return(1);
  113465. return(0);
  113466. }
  113467. static int post_Y(int *A,int *B,int pos){
  113468. if(A[pos]<0)
  113469. return B[pos];
  113470. if(B[pos]<0)
  113471. return A[pos];
  113472. return (A[pos]+B[pos])>>1;
  113473. }
  113474. int *floor1_fit(vorbis_block *vb,void *look_,
  113475. const float *logmdct, /* in */
  113476. const float *logmask){
  113477. long i,j;
  113478. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113479. vorbis_info_floor1 *info=look->vi;
  113480. long n=look->n;
  113481. long posts=look->posts;
  113482. long nonzero=0;
  113483. lsfit_acc fits[VIF_POSIT+1];
  113484. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113485. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113486. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113487. int hineighbor[VIF_POSIT+2];
  113488. int *output=NULL;
  113489. int memo[VIF_POSIT+2];
  113490. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113491. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113492. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113493. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113494. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113495. /* quantize the relevant floor points and collect them into line fit
  113496. structures (one per minimal division) at the same time */
  113497. if(posts==0){
  113498. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113499. }else{
  113500. for(i=0;i<posts-1;i++)
  113501. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113502. look->sorted_index[i+1],fits+i,
  113503. n,info);
  113504. }
  113505. if(nonzero){
  113506. /* start by fitting the implicit base case.... */
  113507. int y0=-200;
  113508. int y1=-200;
  113509. fit_line(fits,posts-1,&y0,&y1);
  113510. fit_valueA[0]=y0;
  113511. fit_valueB[0]=y0;
  113512. fit_valueB[1]=y1;
  113513. fit_valueA[1]=y1;
  113514. /* Non degenerate case */
  113515. /* start progressive splitting. This is a greedy, non-optimal
  113516. algorithm, but simple and close enough to the best
  113517. answer. */
  113518. for(i=2;i<posts;i++){
  113519. int sortpos=look->reverse_index[i];
  113520. int ln=loneighbor[sortpos];
  113521. int hn=hineighbor[sortpos];
  113522. /* eliminate repeat searches of a particular range with a memo */
  113523. if(memo[ln]!=hn){
  113524. /* haven't performed this error search yet */
  113525. int lsortpos=look->reverse_index[ln];
  113526. int hsortpos=look->reverse_index[hn];
  113527. memo[ln]=hn;
  113528. {
  113529. /* A note: we want to bound/minimize *local*, not global, error */
  113530. int lx=info->postlist[ln];
  113531. int hx=info->postlist[hn];
  113532. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113533. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113534. if(ly==-1 || hy==-1){
  113535. exit(1);
  113536. }
  113537. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113538. /* outside error bounds/begin search area. Split it. */
  113539. int ly0=-200;
  113540. int ly1=-200;
  113541. int hy0=-200;
  113542. int hy1=-200;
  113543. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113544. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113545. /* store new edge values */
  113546. fit_valueB[ln]=ly0;
  113547. if(ln==0)fit_valueA[ln]=ly0;
  113548. fit_valueA[i]=ly1;
  113549. fit_valueB[i]=hy0;
  113550. fit_valueA[hn]=hy1;
  113551. if(hn==1)fit_valueB[hn]=hy1;
  113552. if(ly1>=0 || hy0>=0){
  113553. /* store new neighbor values */
  113554. for(j=sortpos-1;j>=0;j--)
  113555. if(hineighbor[j]==hn)
  113556. hineighbor[j]=i;
  113557. else
  113558. break;
  113559. for(j=sortpos+1;j<posts;j++)
  113560. if(loneighbor[j]==ln)
  113561. loneighbor[j]=i;
  113562. else
  113563. break;
  113564. }
  113565. }else{
  113566. fit_valueA[i]=-200;
  113567. fit_valueB[i]=-200;
  113568. }
  113569. }
  113570. }
  113571. }
  113572. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113573. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113574. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113575. /* fill in posts marked as not using a fit; we will zero
  113576. back out to 'unused' when encoding them so long as curve
  113577. interpolation doesn't force them into use */
  113578. for(i=2;i<posts;i++){
  113579. int ln=look->loneighbor[i-2];
  113580. int hn=look->hineighbor[i-2];
  113581. int x0=info->postlist[ln];
  113582. int x1=info->postlist[hn];
  113583. int y0=output[ln];
  113584. int y1=output[hn];
  113585. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113586. int vx=post_Y(fit_valueA,fit_valueB,i);
  113587. if(vx>=0 && predicted!=vx){
  113588. output[i]=vx;
  113589. }else{
  113590. output[i]= predicted|0x8000;
  113591. }
  113592. }
  113593. }
  113594. return(output);
  113595. }
  113596. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113597. int *A,int *B,
  113598. int del){
  113599. long i;
  113600. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113601. long posts=look->posts;
  113602. int *output=NULL;
  113603. if(A && B){
  113604. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113605. for(i=0;i<posts;i++){
  113606. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113607. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113608. }
  113609. }
  113610. return(output);
  113611. }
  113612. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113613. void*look_,
  113614. int *post,int *ilogmask){
  113615. long i,j;
  113616. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113617. vorbis_info_floor1 *info=look->vi;
  113618. long posts=look->posts;
  113619. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113620. int out[VIF_POSIT+2];
  113621. static_codebook **sbooks=ci->book_param;
  113622. codebook *books=ci->fullbooks;
  113623. static long seq=0;
  113624. /* quantize values to multiplier spec */
  113625. if(post){
  113626. for(i=0;i<posts;i++){
  113627. int val=post[i]&0x7fff;
  113628. switch(info->mult){
  113629. case 1: /* 1024 -> 256 */
  113630. val>>=2;
  113631. break;
  113632. case 2: /* 1024 -> 128 */
  113633. val>>=3;
  113634. break;
  113635. case 3: /* 1024 -> 86 */
  113636. val/=12;
  113637. break;
  113638. case 4: /* 1024 -> 64 */
  113639. val>>=4;
  113640. break;
  113641. }
  113642. post[i]=val | (post[i]&0x8000);
  113643. }
  113644. out[0]=post[0];
  113645. out[1]=post[1];
  113646. /* find prediction values for each post and subtract them */
  113647. for(i=2;i<posts;i++){
  113648. int ln=look->loneighbor[i-2];
  113649. int hn=look->hineighbor[i-2];
  113650. int x0=info->postlist[ln];
  113651. int x1=info->postlist[hn];
  113652. int y0=post[ln];
  113653. int y1=post[hn];
  113654. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113655. if((post[i]&0x8000) || (predicted==post[i])){
  113656. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113657. in interpolation */
  113658. out[i]=0;
  113659. }else{
  113660. int headroom=(look->quant_q-predicted<predicted?
  113661. look->quant_q-predicted:predicted);
  113662. int val=post[i]-predicted;
  113663. /* at this point the 'deviation' value is in the range +/- max
  113664. range, but the real, unique range can always be mapped to
  113665. only [0-maxrange). So we want to wrap the deviation into
  113666. this limited range, but do it in the way that least screws
  113667. an essentially gaussian probability distribution. */
  113668. if(val<0)
  113669. if(val<-headroom)
  113670. val=headroom-val-1;
  113671. else
  113672. val=-1-(val<<1);
  113673. else
  113674. if(val>=headroom)
  113675. val= val+headroom;
  113676. else
  113677. val<<=1;
  113678. out[i]=val;
  113679. post[ln]&=0x7fff;
  113680. post[hn]&=0x7fff;
  113681. }
  113682. }
  113683. /* we have everything we need. pack it out */
  113684. /* mark nontrivial floor */
  113685. oggpack_write(opb,1,1);
  113686. /* beginning/end post */
  113687. look->frames++;
  113688. look->postbits+=ilog(look->quant_q-1)*2;
  113689. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113690. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113691. /* partition by partition */
  113692. for(i=0,j=2;i<info->partitions;i++){
  113693. int classx=info->partitionclass[i];
  113694. int cdim=info->class_dim[classx];
  113695. int csubbits=info->class_subs[classx];
  113696. int csub=1<<csubbits;
  113697. int bookas[8]={0,0,0,0,0,0,0,0};
  113698. int cval=0;
  113699. int cshift=0;
  113700. int k,l;
  113701. /* generate the partition's first stage cascade value */
  113702. if(csubbits){
  113703. int maxval[8];
  113704. for(k=0;k<csub;k++){
  113705. int booknum=info->class_subbook[classx][k];
  113706. if(booknum<0){
  113707. maxval[k]=1;
  113708. }else{
  113709. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113710. }
  113711. }
  113712. for(k=0;k<cdim;k++){
  113713. for(l=0;l<csub;l++){
  113714. int val=out[j+k];
  113715. if(val<maxval[l]){
  113716. bookas[k]=l;
  113717. break;
  113718. }
  113719. }
  113720. cval|= bookas[k]<<cshift;
  113721. cshift+=csubbits;
  113722. }
  113723. /* write it */
  113724. look->phrasebits+=
  113725. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113726. #ifdef TRAIN_FLOOR1
  113727. {
  113728. FILE *of;
  113729. char buffer[80];
  113730. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113731. vb->pcmend/2,posts-2,class);
  113732. of=fopen(buffer,"a");
  113733. fprintf(of,"%d\n",cval);
  113734. fclose(of);
  113735. }
  113736. #endif
  113737. }
  113738. /* write post values */
  113739. for(k=0;k<cdim;k++){
  113740. int book=info->class_subbook[classx][bookas[k]];
  113741. if(book>=0){
  113742. /* hack to allow training with 'bad' books */
  113743. if(out[j+k]<(books+book)->entries)
  113744. look->postbits+=vorbis_book_encode(books+book,
  113745. out[j+k],opb);
  113746. /*else
  113747. fprintf(stderr,"+!");*/
  113748. #ifdef TRAIN_FLOOR1
  113749. {
  113750. FILE *of;
  113751. char buffer[80];
  113752. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113753. vb->pcmend/2,posts-2,class,bookas[k]);
  113754. of=fopen(buffer,"a");
  113755. fprintf(of,"%d\n",out[j+k]);
  113756. fclose(of);
  113757. }
  113758. #endif
  113759. }
  113760. }
  113761. j+=cdim;
  113762. }
  113763. {
  113764. /* generate quantized floor equivalent to what we'd unpack in decode */
  113765. /* render the lines */
  113766. int hx=0;
  113767. int lx=0;
  113768. int ly=post[0]*info->mult;
  113769. for(j=1;j<look->posts;j++){
  113770. int current=look->forward_index[j];
  113771. int hy=post[current]&0x7fff;
  113772. if(hy==post[current]){
  113773. hy*=info->mult;
  113774. hx=info->postlist[current];
  113775. render_line0(lx,hx,ly,hy,ilogmask);
  113776. lx=hx;
  113777. ly=hy;
  113778. }
  113779. }
  113780. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113781. seq++;
  113782. return(1);
  113783. }
  113784. }else{
  113785. oggpack_write(opb,0,1);
  113786. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113787. seq++;
  113788. return(0);
  113789. }
  113790. }
  113791. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113792. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113793. vorbis_info_floor1 *info=look->vi;
  113794. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113795. int i,j,k;
  113796. codebook *books=ci->fullbooks;
  113797. /* unpack wrapped/predicted values from stream */
  113798. if(oggpack_read(&vb->opb,1)==1){
  113799. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113800. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113801. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113802. /* partition by partition */
  113803. for(i=0,j=2;i<info->partitions;i++){
  113804. int classx=info->partitionclass[i];
  113805. int cdim=info->class_dim[classx];
  113806. int csubbits=info->class_subs[classx];
  113807. int csub=1<<csubbits;
  113808. int cval=0;
  113809. /* decode the partition's first stage cascade value */
  113810. if(csubbits){
  113811. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113812. if(cval==-1)goto eop;
  113813. }
  113814. for(k=0;k<cdim;k++){
  113815. int book=info->class_subbook[classx][cval&(csub-1)];
  113816. cval>>=csubbits;
  113817. if(book>=0){
  113818. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113819. goto eop;
  113820. }else{
  113821. fit_value[j+k]=0;
  113822. }
  113823. }
  113824. j+=cdim;
  113825. }
  113826. /* unwrap positive values and reconsitute via linear interpolation */
  113827. for(i=2;i<look->posts;i++){
  113828. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113829. info->postlist[look->hineighbor[i-2]],
  113830. fit_value[look->loneighbor[i-2]],
  113831. fit_value[look->hineighbor[i-2]],
  113832. info->postlist[i]);
  113833. int hiroom=look->quant_q-predicted;
  113834. int loroom=predicted;
  113835. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113836. int val=fit_value[i];
  113837. if(val){
  113838. if(val>=room){
  113839. if(hiroom>loroom){
  113840. val = val-loroom;
  113841. }else{
  113842. val = -1-(val-hiroom);
  113843. }
  113844. }else{
  113845. if(val&1){
  113846. val= -((val+1)>>1);
  113847. }else{
  113848. val>>=1;
  113849. }
  113850. }
  113851. fit_value[i]=val+predicted;
  113852. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113853. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113854. }else{
  113855. fit_value[i]=predicted|0x8000;
  113856. }
  113857. }
  113858. return(fit_value);
  113859. }
  113860. eop:
  113861. return(NULL);
  113862. }
  113863. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113864. float *out){
  113865. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113866. vorbis_info_floor1 *info=look->vi;
  113867. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113868. int n=ci->blocksizes[vb->W]/2;
  113869. int j;
  113870. if(memo){
  113871. /* render the lines */
  113872. int *fit_value=(int *)memo;
  113873. int hx=0;
  113874. int lx=0;
  113875. int ly=fit_value[0]*info->mult;
  113876. for(j=1;j<look->posts;j++){
  113877. int current=look->forward_index[j];
  113878. int hy=fit_value[current]&0x7fff;
  113879. if(hy==fit_value[current]){
  113880. hy*=info->mult;
  113881. hx=info->postlist[current];
  113882. render_line(lx,hx,ly,hy,out);
  113883. lx=hx;
  113884. ly=hy;
  113885. }
  113886. }
  113887. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113888. return(1);
  113889. }
  113890. memset(out,0,sizeof(*out)*n);
  113891. return(0);
  113892. }
  113893. /* export hooks */
  113894. vorbis_func_floor floor1_exportbundle={
  113895. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113896. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113897. };
  113898. #endif
  113899. /*** End of inlined file: floor1.c ***/
  113900. /*** Start of inlined file: info.c ***/
  113901. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113902. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113903. // tasks..
  113904. #if JUCE_MSVC
  113905. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113906. #endif
  113907. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113908. #if JUCE_USE_OGGVORBIS
  113909. /* general handling of the header and the vorbis_info structure (and
  113910. substructures) */
  113911. #include <stdlib.h>
  113912. #include <string.h>
  113913. #include <ctype.h>
  113914. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113915. while(bytes--){
  113916. oggpack_write(o,*s++,8);
  113917. }
  113918. }
  113919. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113920. while(bytes--){
  113921. *buf++=oggpack_read(o,8);
  113922. }
  113923. }
  113924. void vorbis_comment_init(vorbis_comment *vc){
  113925. memset(vc,0,sizeof(*vc));
  113926. }
  113927. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113928. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113929. (vc->comments+2)*sizeof(*vc->user_comments));
  113930. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113931. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113932. vc->comment_lengths[vc->comments]=strlen(comment);
  113933. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113934. strcpy(vc->user_comments[vc->comments], comment);
  113935. vc->comments++;
  113936. vc->user_comments[vc->comments]=NULL;
  113937. }
  113938. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113939. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113940. strcpy(comment, tag);
  113941. strcat(comment, "=");
  113942. strcat(comment, contents);
  113943. vorbis_comment_add(vc, comment);
  113944. }
  113945. /* This is more or less the same as strncasecmp - but that doesn't exist
  113946. * everywhere, and this is a fairly trivial function, so we include it */
  113947. static int tagcompare(const char *s1, const char *s2, int n){
  113948. int c=0;
  113949. while(c < n){
  113950. if(toupper(s1[c]) != toupper(s2[c]))
  113951. return !0;
  113952. c++;
  113953. }
  113954. return 0;
  113955. }
  113956. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113957. long i;
  113958. int found = 0;
  113959. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113960. char *fulltag = (char*)alloca(taglen+ 1);
  113961. strcpy(fulltag, tag);
  113962. strcat(fulltag, "=");
  113963. for(i=0;i<vc->comments;i++){
  113964. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113965. if(count == found)
  113966. /* We return a pointer to the data, not a copy */
  113967. return vc->user_comments[i] + taglen;
  113968. else
  113969. found++;
  113970. }
  113971. }
  113972. return NULL; /* didn't find anything */
  113973. }
  113974. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113975. int i,count=0;
  113976. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113977. char *fulltag = (char*)alloca(taglen+1);
  113978. strcpy(fulltag,tag);
  113979. strcat(fulltag, "=");
  113980. for(i=0;i<vc->comments;i++){
  113981. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113982. count++;
  113983. }
  113984. return count;
  113985. }
  113986. void vorbis_comment_clear(vorbis_comment *vc){
  113987. if(vc){
  113988. long i;
  113989. for(i=0;i<vc->comments;i++)
  113990. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113991. if(vc->user_comments)_ogg_free(vc->user_comments);
  113992. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113993. if(vc->vendor)_ogg_free(vc->vendor);
  113994. }
  113995. memset(vc,0,sizeof(*vc));
  113996. }
  113997. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113998. They may be equal, but short will never ge greater than long */
  113999. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  114000. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  114001. return ci ? ci->blocksizes[zo] : -1;
  114002. }
  114003. /* used by synthesis, which has a full, alloced vi */
  114004. void vorbis_info_init(vorbis_info *vi){
  114005. memset(vi,0,sizeof(*vi));
  114006. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  114007. }
  114008. void vorbis_info_clear(vorbis_info *vi){
  114009. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114010. int i;
  114011. if(ci){
  114012. for(i=0;i<ci->modes;i++)
  114013. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114014. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114015. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114016. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114017. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114018. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114019. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114020. for(i=0;i<ci->books;i++){
  114021. if(ci->book_param[i]){
  114022. /* knows if the book was not alloced */
  114023. vorbis_staticbook_destroy(ci->book_param[i]);
  114024. }
  114025. if(ci->fullbooks)
  114026. vorbis_book_clear(ci->fullbooks+i);
  114027. }
  114028. if(ci->fullbooks)
  114029. _ogg_free(ci->fullbooks);
  114030. for(i=0;i<ci->psys;i++)
  114031. _vi_psy_free(ci->psy_param[i]);
  114032. _ogg_free(ci);
  114033. }
  114034. memset(vi,0,sizeof(*vi));
  114035. }
  114036. /* Header packing/unpacking ********************************************/
  114037. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114038. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114039. if(!ci)return(OV_EFAULT);
  114040. vi->version=oggpack_read(opb,32);
  114041. if(vi->version!=0)return(OV_EVERSION);
  114042. vi->channels=oggpack_read(opb,8);
  114043. vi->rate=oggpack_read(opb,32);
  114044. vi->bitrate_upper=oggpack_read(opb,32);
  114045. vi->bitrate_nominal=oggpack_read(opb,32);
  114046. vi->bitrate_lower=oggpack_read(opb,32);
  114047. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114048. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114049. if(vi->rate<1)goto err_out;
  114050. if(vi->channels<1)goto err_out;
  114051. if(ci->blocksizes[0]<8)goto err_out;
  114052. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114053. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114054. return(0);
  114055. err_out:
  114056. vorbis_info_clear(vi);
  114057. return(OV_EBADHEADER);
  114058. }
  114059. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114060. int i;
  114061. int vendorlen=oggpack_read(opb,32);
  114062. if(vendorlen<0)goto err_out;
  114063. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114064. _v_readstring(opb,vc->vendor,vendorlen);
  114065. vc->comments=oggpack_read(opb,32);
  114066. if(vc->comments<0)goto err_out;
  114067. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114068. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114069. for(i=0;i<vc->comments;i++){
  114070. int len=oggpack_read(opb,32);
  114071. if(len<0)goto err_out;
  114072. vc->comment_lengths[i]=len;
  114073. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114074. _v_readstring(opb,vc->user_comments[i],len);
  114075. }
  114076. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114077. return(0);
  114078. err_out:
  114079. vorbis_comment_clear(vc);
  114080. return(OV_EBADHEADER);
  114081. }
  114082. /* all of the real encoding details are here. The modes, books,
  114083. everything */
  114084. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114085. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114086. int i;
  114087. if(!ci)return(OV_EFAULT);
  114088. /* codebooks */
  114089. ci->books=oggpack_read(opb,8)+1;
  114090. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114091. for(i=0;i<ci->books;i++){
  114092. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114093. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114094. }
  114095. /* time backend settings; hooks are unused */
  114096. {
  114097. int times=oggpack_read(opb,6)+1;
  114098. for(i=0;i<times;i++){
  114099. int test=oggpack_read(opb,16);
  114100. if(test<0 || test>=VI_TIMEB)goto err_out;
  114101. }
  114102. }
  114103. /* floor backend settings */
  114104. ci->floors=oggpack_read(opb,6)+1;
  114105. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114106. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114107. for(i=0;i<ci->floors;i++){
  114108. ci->floor_type[i]=oggpack_read(opb,16);
  114109. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114110. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114111. if(!ci->floor_param[i])goto err_out;
  114112. }
  114113. /* residue backend settings */
  114114. ci->residues=oggpack_read(opb,6)+1;
  114115. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114116. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114117. for(i=0;i<ci->residues;i++){
  114118. ci->residue_type[i]=oggpack_read(opb,16);
  114119. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114120. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114121. if(!ci->residue_param[i])goto err_out;
  114122. }
  114123. /* map backend settings */
  114124. ci->maps=oggpack_read(opb,6)+1;
  114125. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114126. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114127. for(i=0;i<ci->maps;i++){
  114128. ci->map_type[i]=oggpack_read(opb,16);
  114129. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114130. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114131. if(!ci->map_param[i])goto err_out;
  114132. }
  114133. /* mode settings */
  114134. ci->modes=oggpack_read(opb,6)+1;
  114135. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114136. for(i=0;i<ci->modes;i++){
  114137. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114138. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114139. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114140. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114141. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114142. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114143. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114144. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114145. }
  114146. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114147. return(0);
  114148. err_out:
  114149. vorbis_info_clear(vi);
  114150. return(OV_EBADHEADER);
  114151. }
  114152. /* The Vorbis header is in three packets; the initial small packet in
  114153. the first page that identifies basic parameters, a second packet
  114154. with bitstream comments and a third packet that holds the
  114155. codebook. */
  114156. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114157. oggpack_buffer opb;
  114158. if(op){
  114159. oggpack_readinit(&opb,op->packet,op->bytes);
  114160. /* Which of the three types of header is this? */
  114161. /* Also verify header-ness, vorbis */
  114162. {
  114163. char buffer[6];
  114164. int packtype=oggpack_read(&opb,8);
  114165. memset(buffer,0,6);
  114166. _v_readstring(&opb,buffer,6);
  114167. if(memcmp(buffer,"vorbis",6)){
  114168. /* not a vorbis header */
  114169. return(OV_ENOTVORBIS);
  114170. }
  114171. switch(packtype){
  114172. case 0x01: /* least significant *bit* is read first */
  114173. if(!op->b_o_s){
  114174. /* Not the initial packet */
  114175. return(OV_EBADHEADER);
  114176. }
  114177. if(vi->rate!=0){
  114178. /* previously initialized info header */
  114179. return(OV_EBADHEADER);
  114180. }
  114181. return(_vorbis_unpack_info(vi,&opb));
  114182. case 0x03: /* least significant *bit* is read first */
  114183. if(vi->rate==0){
  114184. /* um... we didn't get the initial header */
  114185. return(OV_EBADHEADER);
  114186. }
  114187. return(_vorbis_unpack_comment(vc,&opb));
  114188. case 0x05: /* least significant *bit* is read first */
  114189. if(vi->rate==0 || vc->vendor==NULL){
  114190. /* um... we didn;t get the initial header or comments yet */
  114191. return(OV_EBADHEADER);
  114192. }
  114193. return(_vorbis_unpack_books(vi,&opb));
  114194. default:
  114195. /* Not a valid vorbis header type */
  114196. return(OV_EBADHEADER);
  114197. break;
  114198. }
  114199. }
  114200. }
  114201. return(OV_EBADHEADER);
  114202. }
  114203. /* pack side **********************************************************/
  114204. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114205. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114206. if(!ci)return(OV_EFAULT);
  114207. /* preamble */
  114208. oggpack_write(opb,0x01,8);
  114209. _v_writestring(opb,"vorbis", 6);
  114210. /* basic information about the stream */
  114211. oggpack_write(opb,0x00,32);
  114212. oggpack_write(opb,vi->channels,8);
  114213. oggpack_write(opb,vi->rate,32);
  114214. oggpack_write(opb,vi->bitrate_upper,32);
  114215. oggpack_write(opb,vi->bitrate_nominal,32);
  114216. oggpack_write(opb,vi->bitrate_lower,32);
  114217. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114218. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114219. oggpack_write(opb,1,1);
  114220. return(0);
  114221. }
  114222. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114223. char temp[]="Xiph.Org libVorbis I 20050304";
  114224. int bytes = strlen(temp);
  114225. /* preamble */
  114226. oggpack_write(opb,0x03,8);
  114227. _v_writestring(opb,"vorbis", 6);
  114228. /* vendor */
  114229. oggpack_write(opb,bytes,32);
  114230. _v_writestring(opb,temp, bytes);
  114231. /* comments */
  114232. oggpack_write(opb,vc->comments,32);
  114233. if(vc->comments){
  114234. int i;
  114235. for(i=0;i<vc->comments;i++){
  114236. if(vc->user_comments[i]){
  114237. oggpack_write(opb,vc->comment_lengths[i],32);
  114238. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114239. }else{
  114240. oggpack_write(opb,0,32);
  114241. }
  114242. }
  114243. }
  114244. oggpack_write(opb,1,1);
  114245. return(0);
  114246. }
  114247. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114248. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114249. int i;
  114250. if(!ci)return(OV_EFAULT);
  114251. oggpack_write(opb,0x05,8);
  114252. _v_writestring(opb,"vorbis", 6);
  114253. /* books */
  114254. oggpack_write(opb,ci->books-1,8);
  114255. for(i=0;i<ci->books;i++)
  114256. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114257. /* times; hook placeholders */
  114258. oggpack_write(opb,0,6);
  114259. oggpack_write(opb,0,16);
  114260. /* floors */
  114261. oggpack_write(opb,ci->floors-1,6);
  114262. for(i=0;i<ci->floors;i++){
  114263. oggpack_write(opb,ci->floor_type[i],16);
  114264. if(_floor_P[ci->floor_type[i]]->pack)
  114265. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114266. else
  114267. goto err_out;
  114268. }
  114269. /* residues */
  114270. oggpack_write(opb,ci->residues-1,6);
  114271. for(i=0;i<ci->residues;i++){
  114272. oggpack_write(opb,ci->residue_type[i],16);
  114273. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114274. }
  114275. /* maps */
  114276. oggpack_write(opb,ci->maps-1,6);
  114277. for(i=0;i<ci->maps;i++){
  114278. oggpack_write(opb,ci->map_type[i],16);
  114279. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114280. }
  114281. /* modes */
  114282. oggpack_write(opb,ci->modes-1,6);
  114283. for(i=0;i<ci->modes;i++){
  114284. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114285. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114286. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114287. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114288. }
  114289. oggpack_write(opb,1,1);
  114290. return(0);
  114291. err_out:
  114292. return(-1);
  114293. }
  114294. int vorbis_commentheader_out(vorbis_comment *vc,
  114295. ogg_packet *op){
  114296. oggpack_buffer opb;
  114297. oggpack_writeinit(&opb);
  114298. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114299. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114300. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114301. op->bytes=oggpack_bytes(&opb);
  114302. op->b_o_s=0;
  114303. op->e_o_s=0;
  114304. op->granulepos=0;
  114305. op->packetno=1;
  114306. return 0;
  114307. }
  114308. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114309. vorbis_comment *vc,
  114310. ogg_packet *op,
  114311. ogg_packet *op_comm,
  114312. ogg_packet *op_code){
  114313. int ret=OV_EIMPL;
  114314. vorbis_info *vi=v->vi;
  114315. oggpack_buffer opb;
  114316. private_state *b=(private_state*)v->backend_state;
  114317. if(!b){
  114318. ret=OV_EFAULT;
  114319. goto err_out;
  114320. }
  114321. /* first header packet **********************************************/
  114322. oggpack_writeinit(&opb);
  114323. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114324. /* build the packet */
  114325. if(b->header)_ogg_free(b->header);
  114326. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114327. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114328. op->packet=b->header;
  114329. op->bytes=oggpack_bytes(&opb);
  114330. op->b_o_s=1;
  114331. op->e_o_s=0;
  114332. op->granulepos=0;
  114333. op->packetno=0;
  114334. /* second header packet (comments) **********************************/
  114335. oggpack_reset(&opb);
  114336. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114337. if(b->header1)_ogg_free(b->header1);
  114338. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114339. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114340. op_comm->packet=b->header1;
  114341. op_comm->bytes=oggpack_bytes(&opb);
  114342. op_comm->b_o_s=0;
  114343. op_comm->e_o_s=0;
  114344. op_comm->granulepos=0;
  114345. op_comm->packetno=1;
  114346. /* third header packet (modes/codebooks) ****************************/
  114347. oggpack_reset(&opb);
  114348. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114349. if(b->header2)_ogg_free(b->header2);
  114350. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114351. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114352. op_code->packet=b->header2;
  114353. op_code->bytes=oggpack_bytes(&opb);
  114354. op_code->b_o_s=0;
  114355. op_code->e_o_s=0;
  114356. op_code->granulepos=0;
  114357. op_code->packetno=2;
  114358. oggpack_writeclear(&opb);
  114359. return(0);
  114360. err_out:
  114361. oggpack_writeclear(&opb);
  114362. memset(op,0,sizeof(*op));
  114363. memset(op_comm,0,sizeof(*op_comm));
  114364. memset(op_code,0,sizeof(*op_code));
  114365. if(b->header)_ogg_free(b->header);
  114366. if(b->header1)_ogg_free(b->header1);
  114367. if(b->header2)_ogg_free(b->header2);
  114368. b->header=NULL;
  114369. b->header1=NULL;
  114370. b->header2=NULL;
  114371. return(ret);
  114372. }
  114373. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114374. if(granulepos>=0)
  114375. return((double)granulepos/v->vi->rate);
  114376. return(-1);
  114377. }
  114378. #endif
  114379. /*** End of inlined file: info.c ***/
  114380. /*** Start of inlined file: lpc.c ***/
  114381. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114382. are derived from code written by Jutta Degener and Carsten Bormann;
  114383. thus we include their copyright below. The entirety of this file
  114384. is freely redistributable on the condition that both of these
  114385. copyright notices are preserved without modification. */
  114386. /* Preserved Copyright: *********************************************/
  114387. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114388. Technische Universita"t Berlin
  114389. Any use of this software is permitted provided that this notice is not
  114390. removed and that neither the authors nor the Technische Universita"t
  114391. Berlin are deemed to have made any representations as to the
  114392. suitability of this software for any purpose nor are held responsible
  114393. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114394. THIS SOFTWARE.
  114395. As a matter of courtesy, the authors request to be informed about uses
  114396. this software has found, about bugs in this software, and about any
  114397. improvements that may be of general interest.
  114398. Berlin, 28.11.1994
  114399. Jutta Degener
  114400. Carsten Bormann
  114401. *********************************************************************/
  114402. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114403. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114404. // tasks..
  114405. #if JUCE_MSVC
  114406. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114407. #endif
  114408. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114409. #if JUCE_USE_OGGVORBIS
  114410. #include <stdlib.h>
  114411. #include <string.h>
  114412. #include <math.h>
  114413. /* Autocorrelation LPC coeff generation algorithm invented by
  114414. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114415. /* Input : n elements of time doamin data
  114416. Output: m lpc coefficients, excitation energy */
  114417. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114418. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114419. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114420. double error;
  114421. int i,j;
  114422. /* autocorrelation, p+1 lag coefficients */
  114423. j=m+1;
  114424. while(j--){
  114425. double d=0; /* double needed for accumulator depth */
  114426. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114427. aut[j]=d;
  114428. }
  114429. /* Generate lpc coefficients from autocorr values */
  114430. error=aut[0];
  114431. for(i=0;i<m;i++){
  114432. double r= -aut[i+1];
  114433. if(error==0){
  114434. memset(lpci,0,m*sizeof(*lpci));
  114435. return 0;
  114436. }
  114437. /* Sum up this iteration's reflection coefficient; note that in
  114438. Vorbis we don't save it. If anyone wants to recycle this code
  114439. and needs reflection coefficients, save the results of 'r' from
  114440. each iteration. */
  114441. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114442. r/=error;
  114443. /* Update LPC coefficients and total error */
  114444. lpc[i]=r;
  114445. for(j=0;j<i/2;j++){
  114446. double tmp=lpc[j];
  114447. lpc[j]+=r*lpc[i-1-j];
  114448. lpc[i-1-j]+=r*tmp;
  114449. }
  114450. if(i%2)lpc[j]+=lpc[j]*r;
  114451. error*=1.f-r*r;
  114452. }
  114453. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114454. /* we need the error value to know how big an impulse to hit the
  114455. filter with later */
  114456. return error;
  114457. }
  114458. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114459. float *data,long n){
  114460. /* in: coeff[0...m-1] LPC coefficients
  114461. prime[0...m-1] initial values (allocated size of n+m-1)
  114462. out: data[0...n-1] data samples */
  114463. long i,j,o,p;
  114464. float y;
  114465. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114466. if(!prime)
  114467. for(i=0;i<m;i++)
  114468. work[i]=0.f;
  114469. else
  114470. for(i=0;i<m;i++)
  114471. work[i]=prime[i];
  114472. for(i=0;i<n;i++){
  114473. y=0;
  114474. o=i;
  114475. p=m;
  114476. for(j=0;j<m;j++)
  114477. y-=work[o++]*coeff[--p];
  114478. data[i]=work[o]=y;
  114479. }
  114480. }
  114481. #endif
  114482. /*** End of inlined file: lpc.c ***/
  114483. /*** Start of inlined file: lsp.c ***/
  114484. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114485. an iterative root polisher (CACM algorithm 283). It *is* possible
  114486. to confuse this algorithm into not converging; that should only
  114487. happen with absurdly closely spaced roots (very sharp peaks in the
  114488. LPC f response) which in turn should be impossible in our use of
  114489. the code. If this *does* happen anyway, it's a bug in the floor
  114490. finder; find the cause of the confusion (probably a single bin
  114491. spike or accidental near-float-limit resolution problems) and
  114492. correct it. */
  114493. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114494. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114495. // tasks..
  114496. #if JUCE_MSVC
  114497. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114498. #endif
  114499. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114500. #if JUCE_USE_OGGVORBIS
  114501. #include <math.h>
  114502. #include <string.h>
  114503. #include <stdlib.h>
  114504. /*** Start of inlined file: lookup.h ***/
  114505. #ifndef _V_LOOKUP_H_
  114506. #ifdef FLOAT_LOOKUP
  114507. extern float vorbis_coslook(float a);
  114508. extern float vorbis_invsqlook(float a);
  114509. extern float vorbis_invsq2explook(int a);
  114510. extern float vorbis_fromdBlook(float a);
  114511. #endif
  114512. #ifdef INT_LOOKUP
  114513. extern long vorbis_invsqlook_i(long a,long e);
  114514. extern long vorbis_coslook_i(long a);
  114515. extern float vorbis_fromdBlook_i(long a);
  114516. #endif
  114517. #endif
  114518. /*** End of inlined file: lookup.h ***/
  114519. /* three possible LSP to f curve functions; the exact computation
  114520. (float), a lookup based float implementation, and an integer
  114521. implementation. The float lookup is likely the optimal choice on
  114522. any machine with an FPU. The integer implementation is *not* fixed
  114523. point (due to the need for a large dynamic range and thus a
  114524. seperately tracked exponent) and thus much more complex than the
  114525. relatively simple float implementations. It's mostly for future
  114526. work on a fully fixed point implementation for processors like the
  114527. ARM family. */
  114528. /* undefine both for the 'old' but more precise implementation */
  114529. #define FLOAT_LOOKUP
  114530. #undef INT_LOOKUP
  114531. #ifdef FLOAT_LOOKUP
  114532. /*** Start of inlined file: lookup.c ***/
  114533. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114534. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114535. // tasks..
  114536. #if JUCE_MSVC
  114537. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114538. #endif
  114539. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114540. #if JUCE_USE_OGGVORBIS
  114541. #include <math.h>
  114542. /*** Start of inlined file: lookup.h ***/
  114543. #ifndef _V_LOOKUP_H_
  114544. #ifdef FLOAT_LOOKUP
  114545. extern float vorbis_coslook(float a);
  114546. extern float vorbis_invsqlook(float a);
  114547. extern float vorbis_invsq2explook(int a);
  114548. extern float vorbis_fromdBlook(float a);
  114549. #endif
  114550. #ifdef INT_LOOKUP
  114551. extern long vorbis_invsqlook_i(long a,long e);
  114552. extern long vorbis_coslook_i(long a);
  114553. extern float vorbis_fromdBlook_i(long a);
  114554. #endif
  114555. #endif
  114556. /*** End of inlined file: lookup.h ***/
  114557. /*** Start of inlined file: lookup_data.h ***/
  114558. #ifndef _V_LOOKUP_DATA_H_
  114559. #ifdef FLOAT_LOOKUP
  114560. #define COS_LOOKUP_SZ 128
  114561. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114562. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114563. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114564. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114565. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114566. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114567. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114568. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114569. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114570. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114571. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114572. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114573. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114574. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114575. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114576. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114577. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114578. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114579. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114580. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114581. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114582. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114583. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114584. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114585. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114586. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114587. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114588. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114589. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114590. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114591. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114592. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114593. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114594. -1.0000000000000f,
  114595. };
  114596. #define INVSQ_LOOKUP_SZ 32
  114597. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114598. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114599. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114600. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114601. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114602. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114603. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114604. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114605. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114606. 1.000000000000f,
  114607. };
  114608. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114609. #define INVSQ2EXP_LOOKUP_MAX 32
  114610. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114611. INVSQ2EXP_LOOKUP_MIN+1]={
  114612. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114613. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114614. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114615. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114616. 256.f, 181.019336f, 128.f, 90.50966799f,
  114617. 64.f, 45.254834f, 32.f, 22.627417f,
  114618. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114619. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114620. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114621. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114622. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114623. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114624. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114625. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114626. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114627. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114628. 1.525878906e-05f,
  114629. };
  114630. #endif
  114631. #define FROMdB_LOOKUP_SZ 35
  114632. #define FROMdB2_LOOKUP_SZ 32
  114633. #define FROMdB_SHIFT 5
  114634. #define FROMdB2_SHIFT 3
  114635. #define FROMdB2_MASK 31
  114636. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114637. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114638. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114639. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114640. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114641. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114642. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114643. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114644. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114645. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114646. };
  114647. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114648. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114649. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114650. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114651. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114652. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114653. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114654. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114655. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114656. };
  114657. #ifdef INT_LOOKUP
  114658. #define INVSQ_LOOKUP_I_SHIFT 10
  114659. #define INVSQ_LOOKUP_I_MASK 1023
  114660. static long INVSQ_LOOKUP_I[64+1]={
  114661. 92682l, 91966l, 91267l, 90583l,
  114662. 89915l, 89261l, 88621l, 87995l,
  114663. 87381l, 86781l, 86192l, 85616l,
  114664. 85051l, 84497l, 83953l, 83420l,
  114665. 82897l, 82384l, 81880l, 81385l,
  114666. 80899l, 80422l, 79953l, 79492l,
  114667. 79039l, 78594l, 78156l, 77726l,
  114668. 77302l, 76885l, 76475l, 76072l,
  114669. 75674l, 75283l, 74898l, 74519l,
  114670. 74146l, 73778l, 73415l, 73058l,
  114671. 72706l, 72359l, 72016l, 71679l,
  114672. 71347l, 71019l, 70695l, 70376l,
  114673. 70061l, 69750l, 69444l, 69141l,
  114674. 68842l, 68548l, 68256l, 67969l,
  114675. 67685l, 67405l, 67128l, 66855l,
  114676. 66585l, 66318l, 66054l, 65794l,
  114677. 65536l,
  114678. };
  114679. #define COS_LOOKUP_I_SHIFT 9
  114680. #define COS_LOOKUP_I_MASK 511
  114681. #define COS_LOOKUP_I_SZ 128
  114682. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114683. 16384l, 16379l, 16364l, 16340l,
  114684. 16305l, 16261l, 16207l, 16143l,
  114685. 16069l, 15986l, 15893l, 15791l,
  114686. 15679l, 15557l, 15426l, 15286l,
  114687. 15137l, 14978l, 14811l, 14635l,
  114688. 14449l, 14256l, 14053l, 13842l,
  114689. 13623l, 13395l, 13160l, 12916l,
  114690. 12665l, 12406l, 12140l, 11866l,
  114691. 11585l, 11297l, 11003l, 10702l,
  114692. 10394l, 10080l, 9760l, 9434l,
  114693. 9102l, 8765l, 8423l, 8076l,
  114694. 7723l, 7366l, 7005l, 6639l,
  114695. 6270l, 5897l, 5520l, 5139l,
  114696. 4756l, 4370l, 3981l, 3590l,
  114697. 3196l, 2801l, 2404l, 2006l,
  114698. 1606l, 1205l, 804l, 402l,
  114699. 0l, -401l, -803l, -1204l,
  114700. -1605l, -2005l, -2403l, -2800l,
  114701. -3195l, -3589l, -3980l, -4369l,
  114702. -4755l, -5138l, -5519l, -5896l,
  114703. -6269l, -6638l, -7004l, -7365l,
  114704. -7722l, -8075l, -8422l, -8764l,
  114705. -9101l, -9433l, -9759l, -10079l,
  114706. -10393l, -10701l, -11002l, -11296l,
  114707. -11584l, -11865l, -12139l, -12405l,
  114708. -12664l, -12915l, -13159l, -13394l,
  114709. -13622l, -13841l, -14052l, -14255l,
  114710. -14448l, -14634l, -14810l, -14977l,
  114711. -15136l, -15285l, -15425l, -15556l,
  114712. -15678l, -15790l, -15892l, -15985l,
  114713. -16068l, -16142l, -16206l, -16260l,
  114714. -16304l, -16339l, -16363l, -16378l,
  114715. -16383l,
  114716. };
  114717. #endif
  114718. #endif
  114719. /*** End of inlined file: lookup_data.h ***/
  114720. #ifdef FLOAT_LOOKUP
  114721. /* interpolated lookup based cos function, domain 0 to PI only */
  114722. float vorbis_coslook(float a){
  114723. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114724. int i=vorbis_ftoi(d-.5);
  114725. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114726. }
  114727. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114728. float vorbis_invsqlook(float a){
  114729. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114730. int i=vorbis_ftoi(d-.5f);
  114731. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114732. }
  114733. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114734. float vorbis_invsq2explook(int a){
  114735. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114736. }
  114737. #include <stdio.h>
  114738. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114739. float vorbis_fromdBlook(float a){
  114740. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114741. return (i<0)?1.f:
  114742. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114743. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114744. }
  114745. #endif
  114746. #ifdef INT_LOOKUP
  114747. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114748. 16.16 format
  114749. returns in m.8 format */
  114750. long vorbis_invsqlook_i(long a,long e){
  114751. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114752. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114753. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114754. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114755. d)>>16); /* result 1.16 */
  114756. e+=32;
  114757. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114758. e=(e>>1)-8;
  114759. return(val>>e);
  114760. }
  114761. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114762. /* a is in n.12 format */
  114763. float vorbis_fromdBlook_i(long a){
  114764. int i=(-a)>>(12-FROMdB2_SHIFT);
  114765. return (i<0)?1.f:
  114766. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114767. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114768. }
  114769. /* interpolated lookup based cos function, domain 0 to PI only */
  114770. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114771. long vorbis_coslook_i(long a){
  114772. int i=a>>COS_LOOKUP_I_SHIFT;
  114773. int d=a&COS_LOOKUP_I_MASK;
  114774. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114775. COS_LOOKUP_I_SHIFT);
  114776. }
  114777. #endif
  114778. #endif
  114779. /*** End of inlined file: lookup.c ***/
  114780. /* catch this in the build system; we #include for
  114781. compilers (like gcc) that can't inline across
  114782. modules */
  114783. /* side effect: changes *lsp to cosines of lsp */
  114784. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114785. float amp,float ampoffset){
  114786. int i;
  114787. float wdel=M_PI/ln;
  114788. vorbis_fpu_control fpu;
  114789. (void) fpu; // to avoid an unused variable warning
  114790. vorbis_fpu_setround(&fpu);
  114791. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114792. i=0;
  114793. while(i<n){
  114794. int k=map[i];
  114795. int qexp;
  114796. float p=.7071067812f;
  114797. float q=.7071067812f;
  114798. float w=vorbis_coslook(wdel*k);
  114799. float *ftmp=lsp;
  114800. int c=m>>1;
  114801. do{
  114802. q*=ftmp[0]-w;
  114803. p*=ftmp[1]-w;
  114804. ftmp+=2;
  114805. }while(--c);
  114806. if(m&1){
  114807. /* odd order filter; slightly assymetric */
  114808. /* the last coefficient */
  114809. q*=ftmp[0]-w;
  114810. q*=q;
  114811. p*=p*(1.f-w*w);
  114812. }else{
  114813. /* even order filter; still symmetric */
  114814. q*=q*(1.f+w);
  114815. p*=p*(1.f-w);
  114816. }
  114817. q=frexp(p+q,&qexp);
  114818. q=vorbis_fromdBlook(amp*
  114819. vorbis_invsqlook(q)*
  114820. vorbis_invsq2explook(qexp+m)-
  114821. ampoffset);
  114822. do{
  114823. curve[i++]*=q;
  114824. }while(map[i]==k);
  114825. }
  114826. vorbis_fpu_restore(fpu);
  114827. }
  114828. #else
  114829. #ifdef INT_LOOKUP
  114830. /*** Start of inlined file: lookup.c ***/
  114831. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114832. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114833. // tasks..
  114834. #if JUCE_MSVC
  114835. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114836. #endif
  114837. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114838. #if JUCE_USE_OGGVORBIS
  114839. #include <math.h>
  114840. /*** Start of inlined file: lookup.h ***/
  114841. #ifndef _V_LOOKUP_H_
  114842. #ifdef FLOAT_LOOKUP
  114843. extern float vorbis_coslook(float a);
  114844. extern float vorbis_invsqlook(float a);
  114845. extern float vorbis_invsq2explook(int a);
  114846. extern float vorbis_fromdBlook(float a);
  114847. #endif
  114848. #ifdef INT_LOOKUP
  114849. extern long vorbis_invsqlook_i(long a,long e);
  114850. extern long vorbis_coslook_i(long a);
  114851. extern float vorbis_fromdBlook_i(long a);
  114852. #endif
  114853. #endif
  114854. /*** End of inlined file: lookup.h ***/
  114855. /*** Start of inlined file: lookup_data.h ***/
  114856. #ifndef _V_LOOKUP_DATA_H_
  114857. #ifdef FLOAT_LOOKUP
  114858. #define COS_LOOKUP_SZ 128
  114859. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114860. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114861. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114862. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114863. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114864. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114865. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114866. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114867. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114868. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114869. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114870. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114871. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114872. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114873. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114874. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114875. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114876. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114877. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114878. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114879. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114880. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114881. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114882. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114883. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114884. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114885. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114886. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114887. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114888. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114889. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114890. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114891. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114892. -1.0000000000000f,
  114893. };
  114894. #define INVSQ_LOOKUP_SZ 32
  114895. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114896. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114897. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114898. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114899. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114900. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114901. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114902. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114903. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114904. 1.000000000000f,
  114905. };
  114906. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114907. #define INVSQ2EXP_LOOKUP_MAX 32
  114908. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114909. INVSQ2EXP_LOOKUP_MIN+1]={
  114910. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114911. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114912. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114913. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114914. 256.f, 181.019336f, 128.f, 90.50966799f,
  114915. 64.f, 45.254834f, 32.f, 22.627417f,
  114916. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114917. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114918. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114919. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114920. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114921. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114922. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114923. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114924. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114925. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114926. 1.525878906e-05f,
  114927. };
  114928. #endif
  114929. #define FROMdB_LOOKUP_SZ 35
  114930. #define FROMdB2_LOOKUP_SZ 32
  114931. #define FROMdB_SHIFT 5
  114932. #define FROMdB2_SHIFT 3
  114933. #define FROMdB2_MASK 31
  114934. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114935. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114936. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114937. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114938. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114939. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114940. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114941. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114942. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114943. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114944. };
  114945. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114946. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114947. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114948. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114949. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114950. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114951. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114952. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114953. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114954. };
  114955. #ifdef INT_LOOKUP
  114956. #define INVSQ_LOOKUP_I_SHIFT 10
  114957. #define INVSQ_LOOKUP_I_MASK 1023
  114958. static long INVSQ_LOOKUP_I[64+1]={
  114959. 92682l, 91966l, 91267l, 90583l,
  114960. 89915l, 89261l, 88621l, 87995l,
  114961. 87381l, 86781l, 86192l, 85616l,
  114962. 85051l, 84497l, 83953l, 83420l,
  114963. 82897l, 82384l, 81880l, 81385l,
  114964. 80899l, 80422l, 79953l, 79492l,
  114965. 79039l, 78594l, 78156l, 77726l,
  114966. 77302l, 76885l, 76475l, 76072l,
  114967. 75674l, 75283l, 74898l, 74519l,
  114968. 74146l, 73778l, 73415l, 73058l,
  114969. 72706l, 72359l, 72016l, 71679l,
  114970. 71347l, 71019l, 70695l, 70376l,
  114971. 70061l, 69750l, 69444l, 69141l,
  114972. 68842l, 68548l, 68256l, 67969l,
  114973. 67685l, 67405l, 67128l, 66855l,
  114974. 66585l, 66318l, 66054l, 65794l,
  114975. 65536l,
  114976. };
  114977. #define COS_LOOKUP_I_SHIFT 9
  114978. #define COS_LOOKUP_I_MASK 511
  114979. #define COS_LOOKUP_I_SZ 128
  114980. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114981. 16384l, 16379l, 16364l, 16340l,
  114982. 16305l, 16261l, 16207l, 16143l,
  114983. 16069l, 15986l, 15893l, 15791l,
  114984. 15679l, 15557l, 15426l, 15286l,
  114985. 15137l, 14978l, 14811l, 14635l,
  114986. 14449l, 14256l, 14053l, 13842l,
  114987. 13623l, 13395l, 13160l, 12916l,
  114988. 12665l, 12406l, 12140l, 11866l,
  114989. 11585l, 11297l, 11003l, 10702l,
  114990. 10394l, 10080l, 9760l, 9434l,
  114991. 9102l, 8765l, 8423l, 8076l,
  114992. 7723l, 7366l, 7005l, 6639l,
  114993. 6270l, 5897l, 5520l, 5139l,
  114994. 4756l, 4370l, 3981l, 3590l,
  114995. 3196l, 2801l, 2404l, 2006l,
  114996. 1606l, 1205l, 804l, 402l,
  114997. 0l, -401l, -803l, -1204l,
  114998. -1605l, -2005l, -2403l, -2800l,
  114999. -3195l, -3589l, -3980l, -4369l,
  115000. -4755l, -5138l, -5519l, -5896l,
  115001. -6269l, -6638l, -7004l, -7365l,
  115002. -7722l, -8075l, -8422l, -8764l,
  115003. -9101l, -9433l, -9759l, -10079l,
  115004. -10393l, -10701l, -11002l, -11296l,
  115005. -11584l, -11865l, -12139l, -12405l,
  115006. -12664l, -12915l, -13159l, -13394l,
  115007. -13622l, -13841l, -14052l, -14255l,
  115008. -14448l, -14634l, -14810l, -14977l,
  115009. -15136l, -15285l, -15425l, -15556l,
  115010. -15678l, -15790l, -15892l, -15985l,
  115011. -16068l, -16142l, -16206l, -16260l,
  115012. -16304l, -16339l, -16363l, -16378l,
  115013. -16383l,
  115014. };
  115015. #endif
  115016. #endif
  115017. /*** End of inlined file: lookup_data.h ***/
  115018. #ifdef FLOAT_LOOKUP
  115019. /* interpolated lookup based cos function, domain 0 to PI only */
  115020. float vorbis_coslook(float a){
  115021. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115022. int i=vorbis_ftoi(d-.5);
  115023. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115024. }
  115025. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115026. float vorbis_invsqlook(float a){
  115027. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115028. int i=vorbis_ftoi(d-.5f);
  115029. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115030. }
  115031. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115032. float vorbis_invsq2explook(int a){
  115033. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115034. }
  115035. #include <stdio.h>
  115036. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115037. float vorbis_fromdBlook(float a){
  115038. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115039. return (i<0)?1.f:
  115040. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115041. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115042. }
  115043. #endif
  115044. #ifdef INT_LOOKUP
  115045. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115046. 16.16 format
  115047. returns in m.8 format */
  115048. long vorbis_invsqlook_i(long a,long e){
  115049. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115050. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115051. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115052. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115053. d)>>16); /* result 1.16 */
  115054. e+=32;
  115055. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115056. e=(e>>1)-8;
  115057. return(val>>e);
  115058. }
  115059. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115060. /* a is in n.12 format */
  115061. float vorbis_fromdBlook_i(long a){
  115062. int i=(-a)>>(12-FROMdB2_SHIFT);
  115063. return (i<0)?1.f:
  115064. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115065. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115066. }
  115067. /* interpolated lookup based cos function, domain 0 to PI only */
  115068. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115069. long vorbis_coslook_i(long a){
  115070. int i=a>>COS_LOOKUP_I_SHIFT;
  115071. int d=a&COS_LOOKUP_I_MASK;
  115072. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115073. COS_LOOKUP_I_SHIFT);
  115074. }
  115075. #endif
  115076. #endif
  115077. /*** End of inlined file: lookup.c ***/
  115078. /* catch this in the build system; we #include for
  115079. compilers (like gcc) that can't inline across
  115080. modules */
  115081. static int MLOOP_1[64]={
  115082. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115083. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115084. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115085. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115086. };
  115087. static int MLOOP_2[64]={
  115088. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115089. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115090. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115091. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115092. };
  115093. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115094. /* side effect: changes *lsp to cosines of lsp */
  115095. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115096. float amp,float ampoffset){
  115097. /* 0 <= m < 256 */
  115098. /* set up for using all int later */
  115099. int i;
  115100. int ampoffseti=rint(ampoffset*4096.f);
  115101. int ampi=rint(amp*16.f);
  115102. long *ilsp=alloca(m*sizeof(*ilsp));
  115103. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115104. i=0;
  115105. while(i<n){
  115106. int j,k=map[i];
  115107. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115108. unsigned long qi=46341;
  115109. int qexp=0,shift;
  115110. long wi=vorbis_coslook_i(k*65536/ln);
  115111. qi*=labs(ilsp[0]-wi);
  115112. pi*=labs(ilsp[1]-wi);
  115113. for(j=3;j<m;j+=2){
  115114. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115115. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115116. shift=MLOOP_3[(pi|qi)>>16];
  115117. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115118. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115119. qexp+=shift;
  115120. }
  115121. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115122. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115123. shift=MLOOP_3[(pi|qi)>>16];
  115124. /* pi,qi normalized collectively, both tracked using qexp */
  115125. if(m&1){
  115126. /* odd order filter; slightly assymetric */
  115127. /* the last coefficient */
  115128. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115129. pi=(pi>>shift)<<14;
  115130. qexp+=shift;
  115131. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115132. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115133. shift=MLOOP_3[(pi|qi)>>16];
  115134. pi>>=shift;
  115135. qi>>=shift;
  115136. qexp+=shift-14*((m+1)>>1);
  115137. pi=((pi*pi)>>16);
  115138. qi=((qi*qi)>>16);
  115139. qexp=qexp*2+m;
  115140. pi*=(1<<14)-((wi*wi)>>14);
  115141. qi+=pi>>14;
  115142. }else{
  115143. /* even order filter; still symmetric */
  115144. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115145. worth tracking step by step */
  115146. pi>>=shift;
  115147. qi>>=shift;
  115148. qexp+=shift-7*m;
  115149. pi=((pi*pi)>>16);
  115150. qi=((qi*qi)>>16);
  115151. qexp=qexp*2+m;
  115152. pi*=(1<<14)-wi;
  115153. qi*=(1<<14)+wi;
  115154. qi=(qi+pi)>>14;
  115155. }
  115156. /* we've let the normalization drift because it wasn't important;
  115157. however, for the lookup, things must be normalized again. We
  115158. need at most one right shift or a number of left shifts */
  115159. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115160. qi>>=1; qexp++;
  115161. }else
  115162. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115163. qi<<=1; qexp--;
  115164. }
  115165. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115166. vorbis_invsqlook_i(qi,qexp)-
  115167. /* m.8, m+n<=8 */
  115168. ampoffseti); /* 8.12[0] */
  115169. curve[i]*=amp;
  115170. while(map[++i]==k)curve[i]*=amp;
  115171. }
  115172. }
  115173. #else
  115174. /* old, nonoptimized but simple version for any poor sap who needs to
  115175. figure out what the hell this code does, or wants the other
  115176. fraction of a dB precision */
  115177. /* side effect: changes *lsp to cosines of lsp */
  115178. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115179. float amp,float ampoffset){
  115180. int i;
  115181. float wdel=M_PI/ln;
  115182. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115183. i=0;
  115184. while(i<n){
  115185. int j,k=map[i];
  115186. float p=.5f;
  115187. float q=.5f;
  115188. float w=2.f*cos(wdel*k);
  115189. for(j=1;j<m;j+=2){
  115190. q *= w-lsp[j-1];
  115191. p *= w-lsp[j];
  115192. }
  115193. if(j==m){
  115194. /* odd order filter; slightly assymetric */
  115195. /* the last coefficient */
  115196. q*=w-lsp[j-1];
  115197. p*=p*(4.f-w*w);
  115198. q*=q;
  115199. }else{
  115200. /* even order filter; still symmetric */
  115201. p*=p*(2.f-w);
  115202. q*=q*(2.f+w);
  115203. }
  115204. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115205. curve[i]*=q;
  115206. while(map[++i]==k)curve[i]*=q;
  115207. }
  115208. }
  115209. #endif
  115210. #endif
  115211. static void cheby(float *g, int ord) {
  115212. int i, j;
  115213. g[0] *= .5f;
  115214. for(i=2; i<= ord; i++) {
  115215. for(j=ord; j >= i; j--) {
  115216. g[j-2] -= g[j];
  115217. g[j] += g[j];
  115218. }
  115219. }
  115220. }
  115221. static int JUCE_CDECL comp(const void *a,const void *b){
  115222. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115223. }
  115224. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115225. but there are root sets for which it gets into limit cycles
  115226. (exacerbated by zero suppression) and fails. We can't afford to
  115227. fail, even if the failure is 1 in 100,000,000, so we now use
  115228. Laguerre and later polish with Newton-Raphson (which can then
  115229. afford to fail) */
  115230. #define EPSILON 10e-7
  115231. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115232. int i,m;
  115233. double lastdelta=0.f;
  115234. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115235. for(i=0;i<=ord;i++)defl[i]=a[i];
  115236. for(m=ord;m>0;m--){
  115237. double newx=0.f,delta;
  115238. /* iterate a root */
  115239. while(1){
  115240. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115241. /* eval the polynomial and its first two derivatives */
  115242. for(i=m;i>0;i--){
  115243. ppp = newx*ppp + pp;
  115244. pp = newx*pp + p;
  115245. p = newx*p + defl[i-1];
  115246. }
  115247. /* Laguerre's method */
  115248. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115249. if(denom<0)
  115250. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115251. if(pp>0){
  115252. denom = pp + sqrt(denom);
  115253. if(denom<EPSILON)denom=EPSILON;
  115254. }else{
  115255. denom = pp - sqrt(denom);
  115256. if(denom>-(EPSILON))denom=-(EPSILON);
  115257. }
  115258. delta = m*p/denom;
  115259. newx -= delta;
  115260. if(delta<0.f)delta*=-1;
  115261. if(fabs(delta/newx)<10e-12)break;
  115262. lastdelta=delta;
  115263. }
  115264. r[m-1]=newx;
  115265. /* forward deflation */
  115266. for(i=m;i>0;i--)
  115267. defl[i-1]+=newx*defl[i];
  115268. defl++;
  115269. }
  115270. return(0);
  115271. }
  115272. /* for spit-and-polish only */
  115273. static int Newton_Raphson(float *a,int ord,float *r){
  115274. int i, k, count=0;
  115275. double error=1.f;
  115276. double *root=(double*)alloca(ord*sizeof(*root));
  115277. for(i=0; i<ord;i++) root[i] = r[i];
  115278. while(error>1e-20){
  115279. error=0;
  115280. for(i=0; i<ord; i++) { /* Update each point. */
  115281. double pp=0.,delta;
  115282. double rooti=root[i];
  115283. double p=a[ord];
  115284. for(k=ord-1; k>= 0; k--) {
  115285. pp= pp* rooti + p;
  115286. p = p * rooti + a[k];
  115287. }
  115288. delta = p/pp;
  115289. root[i] -= delta;
  115290. error+= delta*delta;
  115291. }
  115292. if(count>40)return(-1);
  115293. count++;
  115294. }
  115295. /* Replaced the original bubble sort with a real sort. With your
  115296. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115297. for(i=0; i<ord;i++) r[i] = root[i];
  115298. return(0);
  115299. }
  115300. /* Convert lpc coefficients to lsp coefficients */
  115301. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115302. int order2=(m+1)>>1;
  115303. int g1_order,g2_order;
  115304. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115305. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115306. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115307. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115308. int i;
  115309. /* even and odd are slightly different base cases */
  115310. g1_order=(m+1)>>1;
  115311. g2_order=(m) >>1;
  115312. /* Compute the lengths of the x polynomials. */
  115313. /* Compute the first half of K & R F1 & F2 polynomials. */
  115314. /* Compute half of the symmetric and antisymmetric polynomials. */
  115315. /* Remove the roots at +1 and -1. */
  115316. g1[g1_order] = 1.f;
  115317. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115318. g2[g2_order] = 1.f;
  115319. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115320. if(g1_order>g2_order){
  115321. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115322. }else{
  115323. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115324. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115325. }
  115326. /* Convert into polynomials in cos(alpha) */
  115327. cheby(g1,g1_order);
  115328. cheby(g2,g2_order);
  115329. /* Find the roots of the 2 even polynomials.*/
  115330. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115331. Laguerre_With_Deflation(g2,g2_order,g2r))
  115332. return(-1);
  115333. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115334. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115335. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115336. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115337. for(i=0;i<g1_order;i++)
  115338. lsp[i*2] = acos(g1r[i]);
  115339. for(i=0;i<g2_order;i++)
  115340. lsp[i*2+1] = acos(g2r[i]);
  115341. return(0);
  115342. }
  115343. #endif
  115344. /*** End of inlined file: lsp.c ***/
  115345. /*** Start of inlined file: mapping0.c ***/
  115346. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115347. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115348. // tasks..
  115349. #if JUCE_MSVC
  115350. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115351. #endif
  115352. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115353. #if JUCE_USE_OGGVORBIS
  115354. #include <stdlib.h>
  115355. #include <stdio.h>
  115356. #include <string.h>
  115357. #include <math.h>
  115358. /* simplistic, wasteful way of doing this (unique lookup for each
  115359. mode/submapping); there should be a central repository for
  115360. identical lookups. That will require minor work, so I'm putting it
  115361. off as low priority.
  115362. Why a lookup for each backend in a given mode? Because the
  115363. blocksize is set by the mode, and low backend lookups may require
  115364. parameters from other areas of the mode/mapping */
  115365. static void mapping0_free_info(vorbis_info_mapping *i){
  115366. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115367. if(info){
  115368. memset(info,0,sizeof(*info));
  115369. _ogg_free(info);
  115370. }
  115371. }
  115372. static int ilog3(unsigned int v){
  115373. int ret=0;
  115374. if(v)--v;
  115375. while(v){
  115376. ret++;
  115377. v>>=1;
  115378. }
  115379. return(ret);
  115380. }
  115381. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115382. oggpack_buffer *opb){
  115383. int i;
  115384. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115385. /* another 'we meant to do it this way' hack... up to beta 4, we
  115386. packed 4 binary zeros here to signify one submapping in use. We
  115387. now redefine that to mean four bitflags that indicate use of
  115388. deeper features; bit0:submappings, bit1:coupling,
  115389. bit2,3:reserved. This is backward compatable with all actual uses
  115390. of the beta code. */
  115391. if(info->submaps>1){
  115392. oggpack_write(opb,1,1);
  115393. oggpack_write(opb,info->submaps-1,4);
  115394. }else
  115395. oggpack_write(opb,0,1);
  115396. if(info->coupling_steps>0){
  115397. oggpack_write(opb,1,1);
  115398. oggpack_write(opb,info->coupling_steps-1,8);
  115399. for(i=0;i<info->coupling_steps;i++){
  115400. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115401. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115402. }
  115403. }else
  115404. oggpack_write(opb,0,1);
  115405. oggpack_write(opb,0,2); /* 2,3:reserved */
  115406. /* we don't write the channel submappings if we only have one... */
  115407. if(info->submaps>1){
  115408. for(i=0;i<vi->channels;i++)
  115409. oggpack_write(opb,info->chmuxlist[i],4);
  115410. }
  115411. for(i=0;i<info->submaps;i++){
  115412. oggpack_write(opb,0,8); /* time submap unused */
  115413. oggpack_write(opb,info->floorsubmap[i],8);
  115414. oggpack_write(opb,info->residuesubmap[i],8);
  115415. }
  115416. }
  115417. /* also responsible for range checking */
  115418. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115419. int i;
  115420. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115421. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115422. memset(info,0,sizeof(*info));
  115423. if(oggpack_read(opb,1))
  115424. info->submaps=oggpack_read(opb,4)+1;
  115425. else
  115426. info->submaps=1;
  115427. if(oggpack_read(opb,1)){
  115428. info->coupling_steps=oggpack_read(opb,8)+1;
  115429. for(i=0;i<info->coupling_steps;i++){
  115430. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115431. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115432. if(testM<0 ||
  115433. testA<0 ||
  115434. testM==testA ||
  115435. testM>=vi->channels ||
  115436. testA>=vi->channels) goto err_out;
  115437. }
  115438. }
  115439. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115440. if(info->submaps>1){
  115441. for(i=0;i<vi->channels;i++){
  115442. info->chmuxlist[i]=oggpack_read(opb,4);
  115443. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115444. }
  115445. }
  115446. for(i=0;i<info->submaps;i++){
  115447. oggpack_read(opb,8); /* time submap unused */
  115448. info->floorsubmap[i]=oggpack_read(opb,8);
  115449. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115450. info->residuesubmap[i]=oggpack_read(opb,8);
  115451. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115452. }
  115453. return info;
  115454. err_out:
  115455. mapping0_free_info(info);
  115456. return(NULL);
  115457. }
  115458. #if 0
  115459. static long seq=0;
  115460. static ogg_int64_t total=0;
  115461. static float FLOOR1_fromdB_LOOKUP[256]={
  115462. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115463. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115464. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115465. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115466. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115467. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115468. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115469. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115470. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115471. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115472. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115473. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115474. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115475. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115476. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115477. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115478. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115479. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115480. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115481. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115482. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115483. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115484. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115485. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115486. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115487. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115488. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115489. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115490. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115491. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115492. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115493. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115494. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115495. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115496. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115497. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115498. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115499. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115500. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115501. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115502. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115503. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115504. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115505. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115506. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115507. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115508. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115509. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115510. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115511. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115512. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115513. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115514. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115515. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115516. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115517. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115518. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115519. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115520. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115521. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115522. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115523. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115524. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115525. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115526. };
  115527. #endif
  115528. extern int *floor1_fit(vorbis_block *vb,void *look,
  115529. const float *logmdct, /* in */
  115530. const float *logmask);
  115531. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115532. int *A,int *B,
  115533. int del);
  115534. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115535. void*look,
  115536. int *post,int *ilogmask);
  115537. static int mapping0_forward(vorbis_block *vb){
  115538. vorbis_dsp_state *vd=vb->vd;
  115539. vorbis_info *vi=vd->vi;
  115540. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115541. private_state *b=(private_state*)vb->vd->backend_state;
  115542. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115543. int n=vb->pcmend;
  115544. int i,j,k;
  115545. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115546. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115547. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115548. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115549. float global_ampmax=vbi->ampmax;
  115550. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115551. int blocktype=vbi->blocktype;
  115552. int modenumber=vb->W;
  115553. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115554. vorbis_look_psy *psy_look=
  115555. b->psy+blocktype+(vb->W?2:0);
  115556. vb->mode=modenumber;
  115557. for(i=0;i<vi->channels;i++){
  115558. float scale=4.f/n;
  115559. float scale_dB;
  115560. float *pcm =vb->pcm[i];
  115561. float *logfft =pcm;
  115562. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115563. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115564. todB estimation used on IEEE 754
  115565. compliant machines had a bug that
  115566. returned dB values about a third
  115567. of a decibel too high. The bug
  115568. was harmless because tunings
  115569. implicitly took that into
  115570. account. However, fixing the bug
  115571. in the estimator requires
  115572. changing all the tunings as well.
  115573. For now, it's easier to sync
  115574. things back up here, and
  115575. recalibrate the tunings in the
  115576. next major model upgrade. */
  115577. #if 0
  115578. if(vi->channels==2)
  115579. if(i==0)
  115580. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115581. else
  115582. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115583. #endif
  115584. /* window the PCM data */
  115585. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115586. #if 0
  115587. if(vi->channels==2)
  115588. if(i==0)
  115589. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115590. else
  115591. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115592. #endif
  115593. /* transform the PCM data */
  115594. /* only MDCT right now.... */
  115595. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115596. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115597. drft_forward(&b->fft_look[vb->W],pcm);
  115598. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115599. original todB estimation used on
  115600. IEEE 754 compliant machines had a
  115601. bug that returned dB values about
  115602. a third of a decibel too high.
  115603. The bug was harmless because
  115604. tunings implicitly took that into
  115605. account. However, fixing the bug
  115606. in the estimator requires
  115607. changing all the tunings as well.
  115608. For now, it's easier to sync
  115609. things back up here, and
  115610. recalibrate the tunings in the
  115611. next major model upgrade. */
  115612. local_ampmax[i]=logfft[0];
  115613. for(j=1;j<n-1;j+=2){
  115614. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115615. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115616. .345 is a hack; the original todB
  115617. estimation used on IEEE 754
  115618. compliant machines had a bug that
  115619. returned dB values about a third
  115620. of a decibel too high. The bug
  115621. was harmless because tunings
  115622. implicitly took that into
  115623. account. However, fixing the bug
  115624. in the estimator requires
  115625. changing all the tunings as well.
  115626. For now, it's easier to sync
  115627. things back up here, and
  115628. recalibrate the tunings in the
  115629. next major model upgrade. */
  115630. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115631. }
  115632. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115633. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115634. #if 0
  115635. if(vi->channels==2){
  115636. if(i==0){
  115637. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115638. }else{
  115639. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115640. }
  115641. }
  115642. #endif
  115643. }
  115644. {
  115645. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115646. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115647. for(i=0;i<vi->channels;i++){
  115648. /* the encoder setup assumes that all the modes used by any
  115649. specific bitrate tweaking use the same floor */
  115650. int submap=info->chmuxlist[i];
  115651. /* the following makes things clearer to *me* anyway */
  115652. float *mdct =gmdct[i];
  115653. float *logfft =vb->pcm[i];
  115654. float *logmdct =logfft+n/2;
  115655. float *logmask =logfft;
  115656. vb->mode=modenumber;
  115657. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115658. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115659. for(j=0;j<n/2;j++)
  115660. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115661. todB estimation used on IEEE 754
  115662. compliant machines had a bug that
  115663. returned dB values about a third
  115664. of a decibel too high. The bug
  115665. was harmless because tunings
  115666. implicitly took that into
  115667. account. However, fixing the bug
  115668. in the estimator requires
  115669. changing all the tunings as well.
  115670. For now, it's easier to sync
  115671. things back up here, and
  115672. recalibrate the tunings in the
  115673. next major model upgrade. */
  115674. #if 0
  115675. if(vi->channels==2){
  115676. if(i==0)
  115677. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115678. else
  115679. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115680. }else{
  115681. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115682. }
  115683. #endif
  115684. /* first step; noise masking. Not only does 'noise masking'
  115685. give us curves from which we can decide how much resolution
  115686. to give noise parts of the spectrum, it also implicitly hands
  115687. us a tonality estimate (the larger the value in the
  115688. 'noise_depth' vector, the more tonal that area is) */
  115689. _vp_noisemask(psy_look,
  115690. logmdct,
  115691. noise); /* noise does not have by-frequency offset
  115692. bias applied yet */
  115693. #if 0
  115694. if(vi->channels==2){
  115695. if(i==0)
  115696. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115697. else
  115698. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115699. }
  115700. #endif
  115701. /* second step: 'all the other crap'; all the stuff that isn't
  115702. computed/fit for bitrate management goes in the second psy
  115703. vector. This includes tone masking, peak limiting and ATH */
  115704. _vp_tonemask(psy_look,
  115705. logfft,
  115706. tone,
  115707. global_ampmax,
  115708. local_ampmax[i]);
  115709. #if 0
  115710. if(vi->channels==2){
  115711. if(i==0)
  115712. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115713. else
  115714. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115715. }
  115716. #endif
  115717. /* third step; we offset the noise vectors, overlay tone
  115718. masking. We then do a floor1-specific line fit. If we're
  115719. performing bitrate management, the line fit is performed
  115720. multiple times for up/down tweakage on demand. */
  115721. #if 0
  115722. {
  115723. float aotuv[psy_look->n];
  115724. #endif
  115725. _vp_offset_and_mix(psy_look,
  115726. noise,
  115727. tone,
  115728. 1,
  115729. logmask,
  115730. mdct,
  115731. logmdct);
  115732. #if 0
  115733. if(vi->channels==2){
  115734. if(i==0)
  115735. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115736. else
  115737. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115738. }
  115739. }
  115740. #endif
  115741. #if 0
  115742. if(vi->channels==2){
  115743. if(i==0)
  115744. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115745. else
  115746. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115747. }
  115748. #endif
  115749. /* this algorithm is hardwired to floor 1 for now; abort out if
  115750. we're *not* floor1. This won't happen unless someone has
  115751. broken the encode setup lib. Guard it anyway. */
  115752. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115753. floor_posts[i][PACKETBLOBS/2]=
  115754. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115755. logmdct,
  115756. logmask);
  115757. /* are we managing bitrate? If so, perform two more fits for
  115758. later rate tweaking (fits represent hi/lo) */
  115759. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115760. /* higher rate by way of lower noise curve */
  115761. _vp_offset_and_mix(psy_look,
  115762. noise,
  115763. tone,
  115764. 2,
  115765. logmask,
  115766. mdct,
  115767. logmdct);
  115768. #if 0
  115769. if(vi->channels==2){
  115770. if(i==0)
  115771. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115772. else
  115773. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115774. }
  115775. #endif
  115776. floor_posts[i][PACKETBLOBS-1]=
  115777. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115778. logmdct,
  115779. logmask);
  115780. /* lower rate by way of higher noise curve */
  115781. _vp_offset_and_mix(psy_look,
  115782. noise,
  115783. tone,
  115784. 0,
  115785. logmask,
  115786. mdct,
  115787. logmdct);
  115788. #if 0
  115789. if(vi->channels==2)
  115790. if(i==0)
  115791. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115792. else
  115793. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115794. #endif
  115795. floor_posts[i][0]=
  115796. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115797. logmdct,
  115798. logmask);
  115799. /* we also interpolate a range of intermediate curves for
  115800. intermediate rates */
  115801. for(k=1;k<PACKETBLOBS/2;k++)
  115802. floor_posts[i][k]=
  115803. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115804. floor_posts[i][0],
  115805. floor_posts[i][PACKETBLOBS/2],
  115806. k*65536/(PACKETBLOBS/2));
  115807. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115808. floor_posts[i][k]=
  115809. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115810. floor_posts[i][PACKETBLOBS/2],
  115811. floor_posts[i][PACKETBLOBS-1],
  115812. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115813. }
  115814. }
  115815. }
  115816. vbi->ampmax=global_ampmax;
  115817. /*
  115818. the next phases are performed once for vbr-only and PACKETBLOB
  115819. times for bitrate managed modes.
  115820. 1) encode actual mode being used
  115821. 2) encode the floor for each channel, compute coded mask curve/res
  115822. 3) normalize and couple.
  115823. 4) encode residue
  115824. 5) save packet bytes to the packetblob vector
  115825. */
  115826. /* iterate over the many masking curve fits we've created */
  115827. {
  115828. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115829. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115830. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115831. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115832. float **mag_memo;
  115833. int **mag_sort;
  115834. if(info->coupling_steps){
  115835. mag_memo=_vp_quantize_couple_memo(vb,
  115836. &ci->psy_g_param,
  115837. psy_look,
  115838. info,
  115839. gmdct);
  115840. mag_sort=_vp_quantize_couple_sort(vb,
  115841. psy_look,
  115842. info,
  115843. mag_memo);
  115844. hf_reduction(&ci->psy_g_param,
  115845. psy_look,
  115846. info,
  115847. mag_memo);
  115848. }
  115849. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115850. if(psy_look->vi->normal_channel_p){
  115851. for(i=0;i<vi->channels;i++){
  115852. float *mdct =gmdct[i];
  115853. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115854. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115855. }
  115856. }
  115857. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115858. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115859. k++){
  115860. oggpack_buffer *opb=vbi->packetblob[k];
  115861. /* start out our new packet blob with packet type and mode */
  115862. /* Encode the packet type */
  115863. oggpack_write(opb,0,1);
  115864. /* Encode the modenumber */
  115865. /* Encode frame mode, pre,post windowsize, then dispatch */
  115866. oggpack_write(opb,modenumber,b->modebits);
  115867. if(vb->W){
  115868. oggpack_write(opb,vb->lW,1);
  115869. oggpack_write(opb,vb->nW,1);
  115870. }
  115871. /* encode floor, compute masking curve, sep out residue */
  115872. for(i=0;i<vi->channels;i++){
  115873. int submap=info->chmuxlist[i];
  115874. float *mdct =gmdct[i];
  115875. float *res =vb->pcm[i];
  115876. int *ilogmask=ilogmaskch[i]=
  115877. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115878. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115879. floor_posts[i][k],
  115880. ilogmask);
  115881. #if 0
  115882. {
  115883. char buf[80];
  115884. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115885. float work[n/2];
  115886. for(j=0;j<n/2;j++)
  115887. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115888. _analysis_output(buf,seq,work,n/2,1,1,0);
  115889. }
  115890. #endif
  115891. _vp_remove_floor(psy_look,
  115892. mdct,
  115893. ilogmask,
  115894. res,
  115895. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115896. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115897. #if 0
  115898. {
  115899. char buf[80];
  115900. float work[n/2];
  115901. for(j=0;j<n/2;j++)
  115902. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115903. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115904. _analysis_output(buf,seq,work,n/2,1,1,0);
  115905. }
  115906. #endif
  115907. }
  115908. /* our iteration is now based on masking curve, not prequant and
  115909. coupling. Only one prequant/coupling step */
  115910. /* quantize/couple */
  115911. /* incomplete implementation that assumes the tree is all depth
  115912. one, or no tree at all */
  115913. if(info->coupling_steps){
  115914. _vp_couple(k,
  115915. &ci->psy_g_param,
  115916. psy_look,
  115917. info,
  115918. vb->pcm,
  115919. mag_memo,
  115920. mag_sort,
  115921. ilogmaskch,
  115922. nonzero,
  115923. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115924. }
  115925. /* classify and encode by submap */
  115926. for(i=0;i<info->submaps;i++){
  115927. int ch_in_bundle=0;
  115928. long **classifications;
  115929. int resnum=info->residuesubmap[i];
  115930. for(j=0;j<vi->channels;j++){
  115931. if(info->chmuxlist[j]==i){
  115932. zerobundle[ch_in_bundle]=0;
  115933. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115934. res_bundle[ch_in_bundle]=vb->pcm[j];
  115935. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115936. }
  115937. }
  115938. classifications=_residue_P[ci->residue_type[resnum]]->
  115939. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115940. _residue_P[ci->residue_type[resnum]]->
  115941. forward(opb,vb,b->residue[resnum],
  115942. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115943. }
  115944. /* ok, done encoding. Next protopacket. */
  115945. }
  115946. }
  115947. #if 0
  115948. seq++;
  115949. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115950. #endif
  115951. return(0);
  115952. }
  115953. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115954. vorbis_dsp_state *vd=vb->vd;
  115955. vorbis_info *vi=vd->vi;
  115956. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115957. private_state *b=(private_state*)vd->backend_state;
  115958. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115959. int i,j;
  115960. long n=vb->pcmend=ci->blocksizes[vb->W];
  115961. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115962. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115963. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115964. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115965. /* recover the spectral envelope; store it in the PCM vector for now */
  115966. for(i=0;i<vi->channels;i++){
  115967. int submap=info->chmuxlist[i];
  115968. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115969. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115970. if(floormemo[i])
  115971. nonzero[i]=1;
  115972. else
  115973. nonzero[i]=0;
  115974. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115975. }
  115976. /* channel coupling can 'dirty' the nonzero listing */
  115977. for(i=0;i<info->coupling_steps;i++){
  115978. if(nonzero[info->coupling_mag[i]] ||
  115979. nonzero[info->coupling_ang[i]]){
  115980. nonzero[info->coupling_mag[i]]=1;
  115981. nonzero[info->coupling_ang[i]]=1;
  115982. }
  115983. }
  115984. /* recover the residue into our working vectors */
  115985. for(i=0;i<info->submaps;i++){
  115986. int ch_in_bundle=0;
  115987. for(j=0;j<vi->channels;j++){
  115988. if(info->chmuxlist[j]==i){
  115989. if(nonzero[j])
  115990. zerobundle[ch_in_bundle]=1;
  115991. else
  115992. zerobundle[ch_in_bundle]=0;
  115993. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115994. }
  115995. }
  115996. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115997. inverse(vb,b->residue[info->residuesubmap[i]],
  115998. pcmbundle,zerobundle,ch_in_bundle);
  115999. }
  116000. /* channel coupling */
  116001. for(i=info->coupling_steps-1;i>=0;i--){
  116002. float *pcmM=vb->pcm[info->coupling_mag[i]];
  116003. float *pcmA=vb->pcm[info->coupling_ang[i]];
  116004. for(j=0;j<n/2;j++){
  116005. float mag=pcmM[j];
  116006. float ang=pcmA[j];
  116007. if(mag>0)
  116008. if(ang>0){
  116009. pcmM[j]=mag;
  116010. pcmA[j]=mag-ang;
  116011. }else{
  116012. pcmA[j]=mag;
  116013. pcmM[j]=mag+ang;
  116014. }
  116015. else
  116016. if(ang>0){
  116017. pcmM[j]=mag;
  116018. pcmA[j]=mag+ang;
  116019. }else{
  116020. pcmA[j]=mag;
  116021. pcmM[j]=mag-ang;
  116022. }
  116023. }
  116024. }
  116025. /* compute and apply spectral envelope */
  116026. for(i=0;i<vi->channels;i++){
  116027. float *pcm=vb->pcm[i];
  116028. int submap=info->chmuxlist[i];
  116029. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116030. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116031. floormemo[i],pcm);
  116032. }
  116033. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116034. /* only MDCT right now.... */
  116035. for(i=0;i<vi->channels;i++){
  116036. float *pcm=vb->pcm[i];
  116037. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116038. }
  116039. /* all done! */
  116040. return(0);
  116041. }
  116042. /* export hooks */
  116043. vorbis_func_mapping mapping0_exportbundle={
  116044. &mapping0_pack,
  116045. &mapping0_unpack,
  116046. &mapping0_free_info,
  116047. &mapping0_forward,
  116048. &mapping0_inverse
  116049. };
  116050. #endif
  116051. /*** End of inlined file: mapping0.c ***/
  116052. /*** Start of inlined file: mdct.c ***/
  116053. /* this can also be run as an integer transform by uncommenting a
  116054. define in mdct.h; the integerization is a first pass and although
  116055. it's likely stable for Vorbis, the dynamic range is constrained and
  116056. roundoff isn't done (so it's noisy). Consider it functional, but
  116057. only a starting point. There's no point on a machine with an FPU */
  116058. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116059. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116060. // tasks..
  116061. #if JUCE_MSVC
  116062. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116063. #endif
  116064. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116065. #if JUCE_USE_OGGVORBIS
  116066. #include <stdio.h>
  116067. #include <stdlib.h>
  116068. #include <string.h>
  116069. #include <math.h>
  116070. /* build lookups for trig functions; also pre-figure scaling and
  116071. some window function algebra. */
  116072. void mdct_init(mdct_lookup *lookup,int n){
  116073. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116074. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116075. int i;
  116076. int n2=n>>1;
  116077. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116078. lookup->n=n;
  116079. lookup->trig=T;
  116080. lookup->bitrev=bitrev;
  116081. /* trig lookups... */
  116082. for(i=0;i<n/4;i++){
  116083. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116084. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116085. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116086. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116087. }
  116088. for(i=0;i<n/8;i++){
  116089. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116090. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116091. }
  116092. /* bitreverse lookup... */
  116093. {
  116094. int mask=(1<<(log2n-1))-1,i,j;
  116095. int msb=1<<(log2n-2);
  116096. for(i=0;i<n/8;i++){
  116097. int acc=0;
  116098. for(j=0;msb>>j;j++)
  116099. if((msb>>j)&i)acc|=1<<j;
  116100. bitrev[i*2]=((~acc)&mask)-1;
  116101. bitrev[i*2+1]=acc;
  116102. }
  116103. }
  116104. lookup->scale=FLOAT_CONV(4.f/n);
  116105. }
  116106. /* 8 point butterfly (in place, 4 register) */
  116107. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116108. REG_TYPE r0 = x[6] + x[2];
  116109. REG_TYPE r1 = x[6] - x[2];
  116110. REG_TYPE r2 = x[4] + x[0];
  116111. REG_TYPE r3 = x[4] - x[0];
  116112. x[6] = r0 + r2;
  116113. x[4] = r0 - r2;
  116114. r0 = x[5] - x[1];
  116115. r2 = x[7] - x[3];
  116116. x[0] = r1 + r0;
  116117. x[2] = r1 - r0;
  116118. r0 = x[5] + x[1];
  116119. r1 = x[7] + x[3];
  116120. x[3] = r2 + r3;
  116121. x[1] = r2 - r3;
  116122. x[7] = r1 + r0;
  116123. x[5] = r1 - r0;
  116124. }
  116125. /* 16 point butterfly (in place, 4 register) */
  116126. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116127. REG_TYPE r0 = x[1] - x[9];
  116128. REG_TYPE r1 = x[0] - x[8];
  116129. x[8] += x[0];
  116130. x[9] += x[1];
  116131. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116132. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116133. r0 = x[3] - x[11];
  116134. r1 = x[10] - x[2];
  116135. x[10] += x[2];
  116136. x[11] += x[3];
  116137. x[2] = r0;
  116138. x[3] = r1;
  116139. r0 = x[12] - x[4];
  116140. r1 = x[13] - x[5];
  116141. x[12] += x[4];
  116142. x[13] += x[5];
  116143. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116144. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116145. r0 = x[14] - x[6];
  116146. r1 = x[15] - x[7];
  116147. x[14] += x[6];
  116148. x[15] += x[7];
  116149. x[6] = r0;
  116150. x[7] = r1;
  116151. mdct_butterfly_8(x);
  116152. mdct_butterfly_8(x+8);
  116153. }
  116154. /* 32 point butterfly (in place, 4 register) */
  116155. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116156. REG_TYPE r0 = x[30] - x[14];
  116157. REG_TYPE r1 = x[31] - x[15];
  116158. x[30] += x[14];
  116159. x[31] += x[15];
  116160. x[14] = r0;
  116161. x[15] = r1;
  116162. r0 = x[28] - x[12];
  116163. r1 = x[29] - x[13];
  116164. x[28] += x[12];
  116165. x[29] += x[13];
  116166. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116167. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116168. r0 = x[26] - x[10];
  116169. r1 = x[27] - x[11];
  116170. x[26] += x[10];
  116171. x[27] += x[11];
  116172. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116173. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116174. r0 = x[24] - x[8];
  116175. r1 = x[25] - x[9];
  116176. x[24] += x[8];
  116177. x[25] += x[9];
  116178. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116179. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116180. r0 = x[22] - x[6];
  116181. r1 = x[7] - x[23];
  116182. x[22] += x[6];
  116183. x[23] += x[7];
  116184. x[6] = r1;
  116185. x[7] = r0;
  116186. r0 = x[4] - x[20];
  116187. r1 = x[5] - x[21];
  116188. x[20] += x[4];
  116189. x[21] += x[5];
  116190. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116191. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116192. r0 = x[2] - x[18];
  116193. r1 = x[3] - x[19];
  116194. x[18] += x[2];
  116195. x[19] += x[3];
  116196. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116197. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116198. r0 = x[0] - x[16];
  116199. r1 = x[1] - x[17];
  116200. x[16] += x[0];
  116201. x[17] += x[1];
  116202. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116203. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116204. mdct_butterfly_16(x);
  116205. mdct_butterfly_16(x+16);
  116206. }
  116207. /* N point first stage butterfly (in place, 2 register) */
  116208. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116209. DATA_TYPE *x,
  116210. int points){
  116211. DATA_TYPE *x1 = x + points - 8;
  116212. DATA_TYPE *x2 = x + (points>>1) - 8;
  116213. REG_TYPE r0;
  116214. REG_TYPE r1;
  116215. do{
  116216. r0 = x1[6] - x2[6];
  116217. r1 = x1[7] - x2[7];
  116218. x1[6] += x2[6];
  116219. x1[7] += x2[7];
  116220. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116221. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116222. r0 = x1[4] - x2[4];
  116223. r1 = x1[5] - x2[5];
  116224. x1[4] += x2[4];
  116225. x1[5] += x2[5];
  116226. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116227. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116228. r0 = x1[2] - x2[2];
  116229. r1 = x1[3] - x2[3];
  116230. x1[2] += x2[2];
  116231. x1[3] += x2[3];
  116232. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116233. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116234. r0 = x1[0] - x2[0];
  116235. r1 = x1[1] - x2[1];
  116236. x1[0] += x2[0];
  116237. x1[1] += x2[1];
  116238. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116239. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116240. x1-=8;
  116241. x2-=8;
  116242. T+=16;
  116243. }while(x2>=x);
  116244. }
  116245. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116246. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116247. DATA_TYPE *x,
  116248. int points,
  116249. int trigint){
  116250. DATA_TYPE *x1 = x + points - 8;
  116251. DATA_TYPE *x2 = x + (points>>1) - 8;
  116252. REG_TYPE r0;
  116253. REG_TYPE r1;
  116254. do{
  116255. r0 = x1[6] - x2[6];
  116256. r1 = x1[7] - x2[7];
  116257. x1[6] += x2[6];
  116258. x1[7] += x2[7];
  116259. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116260. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116261. T+=trigint;
  116262. r0 = x1[4] - x2[4];
  116263. r1 = x1[5] - x2[5];
  116264. x1[4] += x2[4];
  116265. x1[5] += x2[5];
  116266. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116267. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116268. T+=trigint;
  116269. r0 = x1[2] - x2[2];
  116270. r1 = x1[3] - x2[3];
  116271. x1[2] += x2[2];
  116272. x1[3] += x2[3];
  116273. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116274. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116275. T+=trigint;
  116276. r0 = x1[0] - x2[0];
  116277. r1 = x1[1] - x2[1];
  116278. x1[0] += x2[0];
  116279. x1[1] += x2[1];
  116280. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116281. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116282. T+=trigint;
  116283. x1-=8;
  116284. x2-=8;
  116285. }while(x2>=x);
  116286. }
  116287. STIN void mdct_butterflies(mdct_lookup *init,
  116288. DATA_TYPE *x,
  116289. int points){
  116290. DATA_TYPE *T=init->trig;
  116291. int stages=init->log2n-5;
  116292. int i,j;
  116293. if(--stages>0){
  116294. mdct_butterfly_first(T,x,points);
  116295. }
  116296. for(i=1;--stages>0;i++){
  116297. for(j=0;j<(1<<i);j++)
  116298. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116299. }
  116300. for(j=0;j<points;j+=32)
  116301. mdct_butterfly_32(x+j);
  116302. }
  116303. void mdct_clear(mdct_lookup *l){
  116304. if(l){
  116305. if(l->trig)_ogg_free(l->trig);
  116306. if(l->bitrev)_ogg_free(l->bitrev);
  116307. memset(l,0,sizeof(*l));
  116308. }
  116309. }
  116310. STIN void mdct_bitreverse(mdct_lookup *init,
  116311. DATA_TYPE *x){
  116312. int n = init->n;
  116313. int *bit = init->bitrev;
  116314. DATA_TYPE *w0 = x;
  116315. DATA_TYPE *w1 = x = w0+(n>>1);
  116316. DATA_TYPE *T = init->trig+n;
  116317. do{
  116318. DATA_TYPE *x0 = x+bit[0];
  116319. DATA_TYPE *x1 = x+bit[1];
  116320. REG_TYPE r0 = x0[1] - x1[1];
  116321. REG_TYPE r1 = x0[0] + x1[0];
  116322. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116323. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116324. w1 -= 4;
  116325. r0 = HALVE(x0[1] + x1[1]);
  116326. r1 = HALVE(x0[0] - x1[0]);
  116327. w0[0] = r0 + r2;
  116328. w1[2] = r0 - r2;
  116329. w0[1] = r1 + r3;
  116330. w1[3] = r3 - r1;
  116331. x0 = x+bit[2];
  116332. x1 = x+bit[3];
  116333. r0 = x0[1] - x1[1];
  116334. r1 = x0[0] + x1[0];
  116335. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116336. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116337. r0 = HALVE(x0[1] + x1[1]);
  116338. r1 = HALVE(x0[0] - x1[0]);
  116339. w0[2] = r0 + r2;
  116340. w1[0] = r0 - r2;
  116341. w0[3] = r1 + r3;
  116342. w1[1] = r3 - r1;
  116343. T += 4;
  116344. bit += 4;
  116345. w0 += 4;
  116346. }while(w0<w1);
  116347. }
  116348. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116349. int n=init->n;
  116350. int n2=n>>1;
  116351. int n4=n>>2;
  116352. /* rotate */
  116353. DATA_TYPE *iX = in+n2-7;
  116354. DATA_TYPE *oX = out+n2+n4;
  116355. DATA_TYPE *T = init->trig+n4;
  116356. do{
  116357. oX -= 4;
  116358. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116359. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116360. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116361. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116362. iX -= 8;
  116363. T += 4;
  116364. }while(iX>=in);
  116365. iX = in+n2-8;
  116366. oX = out+n2+n4;
  116367. T = init->trig+n4;
  116368. do{
  116369. T -= 4;
  116370. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116371. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116372. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116373. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116374. iX -= 8;
  116375. oX += 4;
  116376. }while(iX>=in);
  116377. mdct_butterflies(init,out+n2,n2);
  116378. mdct_bitreverse(init,out);
  116379. /* roatate + window */
  116380. {
  116381. DATA_TYPE *oX1=out+n2+n4;
  116382. DATA_TYPE *oX2=out+n2+n4;
  116383. DATA_TYPE *iX =out;
  116384. T =init->trig+n2;
  116385. do{
  116386. oX1-=4;
  116387. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116388. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116389. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116390. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116391. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116392. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116393. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116394. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116395. oX2+=4;
  116396. iX += 8;
  116397. T += 8;
  116398. }while(iX<oX1);
  116399. iX=out+n2+n4;
  116400. oX1=out+n4;
  116401. oX2=oX1;
  116402. do{
  116403. oX1-=4;
  116404. iX-=4;
  116405. oX2[0] = -(oX1[3] = iX[3]);
  116406. oX2[1] = -(oX1[2] = iX[2]);
  116407. oX2[2] = -(oX1[1] = iX[1]);
  116408. oX2[3] = -(oX1[0] = iX[0]);
  116409. oX2+=4;
  116410. }while(oX2<iX);
  116411. iX=out+n2+n4;
  116412. oX1=out+n2+n4;
  116413. oX2=out+n2;
  116414. do{
  116415. oX1-=4;
  116416. oX1[0]= iX[3];
  116417. oX1[1]= iX[2];
  116418. oX1[2]= iX[1];
  116419. oX1[3]= iX[0];
  116420. iX+=4;
  116421. }while(oX1>oX2);
  116422. }
  116423. }
  116424. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116425. int n=init->n;
  116426. int n2=n>>1;
  116427. int n4=n>>2;
  116428. int n8=n>>3;
  116429. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116430. DATA_TYPE *w2=w+n2;
  116431. /* rotate */
  116432. /* window + rotate + step 1 */
  116433. REG_TYPE r0;
  116434. REG_TYPE r1;
  116435. DATA_TYPE *x0=in+n2+n4;
  116436. DATA_TYPE *x1=x0+1;
  116437. DATA_TYPE *T=init->trig+n2;
  116438. int i=0;
  116439. for(i=0;i<n8;i+=2){
  116440. x0 -=4;
  116441. T-=2;
  116442. r0= x0[2] + x1[0];
  116443. r1= x0[0] + x1[2];
  116444. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116445. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116446. x1 +=4;
  116447. }
  116448. x1=in+1;
  116449. for(;i<n2-n8;i+=2){
  116450. T-=2;
  116451. x0 -=4;
  116452. r0= x0[2] - x1[0];
  116453. r1= x0[0] - x1[2];
  116454. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116455. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116456. x1 +=4;
  116457. }
  116458. x0=in+n;
  116459. for(;i<n2;i+=2){
  116460. T-=2;
  116461. x0 -=4;
  116462. r0= -x0[2] - x1[0];
  116463. r1= -x0[0] - x1[2];
  116464. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116465. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116466. x1 +=4;
  116467. }
  116468. mdct_butterflies(init,w+n2,n2);
  116469. mdct_bitreverse(init,w);
  116470. /* roatate + window */
  116471. T=init->trig+n2;
  116472. x0=out+n2;
  116473. for(i=0;i<n4;i++){
  116474. x0--;
  116475. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116476. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116477. w+=2;
  116478. T+=2;
  116479. }
  116480. }
  116481. #endif
  116482. /*** End of inlined file: mdct.c ***/
  116483. /*** Start of inlined file: psy.c ***/
  116484. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116485. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116486. // tasks..
  116487. #if JUCE_MSVC
  116488. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116489. #endif
  116490. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116491. #if JUCE_USE_OGGVORBIS
  116492. #include <stdlib.h>
  116493. #include <math.h>
  116494. #include <string.h>
  116495. /*** Start of inlined file: masking.h ***/
  116496. #ifndef _V_MASKING_H_
  116497. #define _V_MASKING_H_
  116498. /* more detailed ATH; the bass if flat to save stressing the floor
  116499. overly for only a bin or two of savings. */
  116500. #define MAX_ATH 88
  116501. static float ATH[]={
  116502. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116503. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116504. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116505. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116506. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116507. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116508. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116509. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116510. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116511. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116512. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116513. };
  116514. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116515. replaced by an empirically collected data set. The previously
  116516. published values were, far too often, simply on crack. */
  116517. #define EHMER_OFFSET 16
  116518. #define EHMER_MAX 56
  116519. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116520. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116521. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116522. for collection of these curves) */
  116523. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116524. /* 62.5 Hz */
  116525. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116526. -60, -60, -60, -60, -62, -62, -65, -73,
  116527. -69, -68, -68, -67, -70, -70, -72, -74,
  116528. -75, -79, -79, -80, -83, -88, -93, -100,
  116529. -110, -999, -999, -999, -999, -999, -999, -999,
  116530. -999, -999, -999, -999, -999, -999, -999, -999,
  116531. -999, -999, -999, -999, -999, -999, -999, -999},
  116532. { -48, -48, -48, -48, -48, -48, -48, -48,
  116533. -48, -48, -48, -48, -48, -53, -61, -66,
  116534. -66, -68, -67, -70, -76, -76, -72, -73,
  116535. -75, -76, -78, -79, -83, -88, -93, -100,
  116536. -110, -999, -999, -999, -999, -999, -999, -999,
  116537. -999, -999, -999, -999, -999, -999, -999, -999,
  116538. -999, -999, -999, -999, -999, -999, -999, -999},
  116539. { -37, -37, -37, -37, -37, -37, -37, -37,
  116540. -38, -40, -42, -46, -48, -53, -55, -62,
  116541. -65, -58, -56, -56, -61, -60, -65, -67,
  116542. -69, -71, -77, -77, -78, -80, -82, -84,
  116543. -88, -93, -98, -106, -112, -999, -999, -999,
  116544. -999, -999, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -999, -999, -999, -999, -999},
  116546. { -25, -25, -25, -25, -25, -25, -25, -25,
  116547. -25, -26, -27, -29, -32, -38, -48, -52,
  116548. -52, -50, -48, -48, -51, -52, -54, -60,
  116549. -67, -67, -66, -68, -69, -73, -73, -76,
  116550. -80, -81, -81, -85, -85, -86, -88, -93,
  116551. -100, -110, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -999, -999, -999, -999, -999},
  116553. { -16, -16, -16, -16, -16, -16, -16, -16,
  116554. -17, -19, -20, -22, -26, -28, -31, -40,
  116555. -47, -39, -39, -40, -42, -43, -47, -51,
  116556. -57, -52, -55, -55, -60, -58, -62, -63,
  116557. -70, -67, -69, -72, -73, -77, -80, -82,
  116558. -83, -87, -90, -94, -98, -104, -115, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999},
  116560. { -8, -8, -8, -8, -8, -8, -8, -8,
  116561. -8, -8, -10, -11, -15, -19, -25, -30,
  116562. -34, -31, -30, -31, -29, -32, -35, -42,
  116563. -48, -42, -44, -46, -50, -50, -51, -52,
  116564. -59, -54, -55, -55, -58, -62, -63, -66,
  116565. -72, -73, -76, -75, -78, -80, -80, -81,
  116566. -84, -88, -90, -94, -98, -101, -106, -110}},
  116567. /* 88Hz */
  116568. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116569. -66, -66, -66, -66, -66, -67, -67, -67,
  116570. -76, -72, -71, -74, -76, -76, -75, -78,
  116571. -79, -79, -81, -83, -86, -89, -93, -97,
  116572. -100, -105, -110, -999, -999, -999, -999, -999,
  116573. -999, -999, -999, -999, -999, -999, -999, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999},
  116575. { -47, -47, -47, -47, -47, -47, -47, -47,
  116576. -47, -47, -47, -48, -51, -55, -59, -66,
  116577. -66, -66, -67, -66, -68, -69, -70, -74,
  116578. -79, -77, -77, -78, -80, -81, -82, -84,
  116579. -86, -88, -91, -95, -100, -108, -116, -999,
  116580. -999, -999, -999, -999, -999, -999, -999, -999,
  116581. -999, -999, -999, -999, -999, -999, -999, -999},
  116582. { -36, -36, -36, -36, -36, -36, -36, -36,
  116583. -36, -37, -37, -41, -44, -48, -51, -58,
  116584. -62, -60, -57, -59, -59, -60, -63, -65,
  116585. -72, -71, -70, -72, -74, -77, -76, -78,
  116586. -81, -81, -80, -83, -86, -91, -96, -100,
  116587. -105, -110, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -999, -999, -999},
  116589. { -28, -28, -28, -28, -28, -28, -28, -28,
  116590. -28, -30, -32, -32, -33, -35, -41, -49,
  116591. -50, -49, -47, -48, -48, -52, -51, -57,
  116592. -65, -61, -59, -61, -64, -69, -70, -74,
  116593. -77, -77, -78, -81, -84, -85, -87, -90,
  116594. -92, -96, -100, -107, -112, -999, -999, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999},
  116596. { -19, -19, -19, -19, -19, -19, -19, -19,
  116597. -20, -21, -23, -27, -30, -35, -36, -41,
  116598. -46, -44, -42, -40, -41, -41, -43, -48,
  116599. -55, -53, -52, -53, -56, -59, -58, -60,
  116600. -67, -66, -69, -71, -72, -75, -79, -81,
  116601. -84, -87, -90, -93, -97, -101, -107, -114,
  116602. -999, -999, -999, -999, -999, -999, -999, -999},
  116603. { -9, -9, -9, -9, -9, -9, -9, -9,
  116604. -11, -12, -12, -15, -16, -20, -23, -30,
  116605. -37, -34, -33, -34, -31, -32, -32, -38,
  116606. -47, -44, -41, -40, -47, -49, -46, -46,
  116607. -58, -50, -50, -54, -58, -62, -64, -67,
  116608. -67, -70, -72, -76, -79, -83, -87, -91,
  116609. -96, -100, -104, -110, -999, -999, -999, -999}},
  116610. /* 125 Hz */
  116611. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116612. -62, -62, -63, -64, -66, -67, -66, -68,
  116613. -75, -72, -76, -75, -76, -78, -79, -82,
  116614. -84, -85, -90, -94, -101, -110, -999, -999,
  116615. -999, -999, -999, -999, -999, -999, -999, -999,
  116616. -999, -999, -999, -999, -999, -999, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999},
  116618. { -59, -59, -59, -59, -59, -59, -59, -59,
  116619. -59, -59, -59, -60, -60, -61, -63, -66,
  116620. -71, -68, -70, -70, -71, -72, -72, -75,
  116621. -81, -78, -79, -82, -83, -86, -90, -97,
  116622. -103, -113, -999, -999, -999, -999, -999, -999,
  116623. -999, -999, -999, -999, -999, -999, -999, -999,
  116624. -999, -999, -999, -999, -999, -999, -999, -999},
  116625. { -53, -53, -53, -53, -53, -53, -53, -53,
  116626. -53, -54, -55, -57, -56, -57, -55, -61,
  116627. -65, -60, -60, -62, -63, -63, -66, -68,
  116628. -74, -73, -75, -75, -78, -80, -80, -82,
  116629. -85, -90, -96, -101, -108, -999, -999, -999,
  116630. -999, -999, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -999, -999, -999, -999, -999, -999},
  116632. { -46, -46, -46, -46, -46, -46, -46, -46,
  116633. -46, -46, -47, -47, -47, -47, -48, -51,
  116634. -57, -51, -49, -50, -51, -53, -54, -59,
  116635. -66, -60, -62, -67, -67, -70, -72, -75,
  116636. -76, -78, -81, -85, -88, -94, -97, -104,
  116637. -112, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -999, -999, -999, -999, -999, -999},
  116639. { -36, -36, -36, -36, -36, -36, -36, -36,
  116640. -39, -41, -42, -42, -39, -38, -41, -43,
  116641. -52, -44, -40, -39, -37, -37, -40, -47,
  116642. -54, -50, -48, -50, -55, -61, -59, -62,
  116643. -66, -66, -66, -69, -69, -73, -74, -74,
  116644. -75, -77, -79, -82, -87, -91, -95, -100,
  116645. -108, -115, -999, -999, -999, -999, -999, -999},
  116646. { -28, -26, -24, -22, -20, -20, -23, -29,
  116647. -30, -31, -28, -27, -28, -28, -28, -35,
  116648. -40, -33, -32, -29, -30, -30, -30, -37,
  116649. -45, -41, -37, -38, -45, -47, -47, -48,
  116650. -53, -49, -48, -50, -49, -49, -51, -52,
  116651. -58, -56, -57, -56, -60, -61, -62, -70,
  116652. -72, -74, -78, -83, -88, -93, -100, -106}},
  116653. /* 177 Hz */
  116654. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -110, -105, -100, -95, -91, -87, -83,
  116656. -80, -78, -76, -78, -78, -81, -83, -85,
  116657. -86, -85, -86, -87, -90, -97, -107, -999,
  116658. -999, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999},
  116661. {-999, -999, -999, -110, -105, -100, -95, -90,
  116662. -85, -81, -77, -73, -70, -67, -67, -68,
  116663. -75, -73, -70, -69, -70, -72, -75, -79,
  116664. -84, -83, -84, -86, -88, -89, -89, -93,
  116665. -98, -105, -112, -999, -999, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -999, -999, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999},
  116668. {-105, -100, -95, -90, -85, -80, -76, -71,
  116669. -68, -68, -65, -63, -63, -62, -62, -64,
  116670. -65, -64, -61, -62, -63, -64, -66, -68,
  116671. -73, -73, -74, -75, -76, -81, -83, -85,
  116672. -88, -89, -92, -95, -100, -108, -999, -999,
  116673. -999, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999},
  116675. { -80, -75, -71, -68, -65, -63, -62, -61,
  116676. -61, -61, -61, -59, -56, -57, -53, -50,
  116677. -58, -52, -50, -50, -52, -53, -54, -58,
  116678. -67, -63, -67, -68, -72, -75, -78, -80,
  116679. -81, -81, -82, -85, -89, -90, -93, -97,
  116680. -101, -107, -114, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -999, -999, -999, -999, -999},
  116682. { -65, -61, -59, -57, -56, -55, -55, -56,
  116683. -56, -57, -55, -53, -52, -47, -44, -44,
  116684. -50, -44, -41, -39, -39, -42, -40, -46,
  116685. -51, -49, -50, -53, -54, -63, -60, -61,
  116686. -62, -66, -66, -66, -70, -73, -74, -75,
  116687. -76, -75, -79, -85, -89, -91, -96, -102,
  116688. -110, -999, -999, -999, -999, -999, -999, -999},
  116689. { -52, -50, -49, -49, -48, -48, -48, -49,
  116690. -50, -50, -49, -46, -43, -39, -35, -33,
  116691. -38, -36, -32, -29, -32, -32, -32, -35,
  116692. -44, -39, -38, -38, -46, -50, -45, -46,
  116693. -53, -50, -50, -50, -54, -54, -53, -53,
  116694. -56, -57, -59, -66, -70, -72, -74, -79,
  116695. -83, -85, -90, -97, -114, -999, -999, -999}},
  116696. /* 250 Hz */
  116697. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116698. -100, -95, -90, -86, -80, -75, -75, -79,
  116699. -80, -79, -80, -81, -82, -88, -95, -103,
  116700. -110, -999, -999, -999, -999, -999, -999, -999,
  116701. -999, -999, -999, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999},
  116704. {-999, -999, -999, -999, -108, -103, -98, -93,
  116705. -88, -83, -79, -78, -75, -71, -67, -68,
  116706. -73, -73, -72, -73, -75, -77, -80, -82,
  116707. -88, -93, -100, -107, -114, -999, -999, -999,
  116708. -999, -999, -999, -999, -999, -999, -999, -999,
  116709. -999, -999, -999, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999},
  116711. {-999, -999, -999, -110, -105, -101, -96, -90,
  116712. -86, -81, -77, -73, -69, -66, -61, -62,
  116713. -66, -64, -62, -65, -66, -70, -72, -76,
  116714. -81, -80, -84, -90, -95, -102, -110, -999,
  116715. -999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -999, -999, -999},
  116718. {-999, -999, -999, -107, -103, -97, -92, -88,
  116719. -83, -79, -74, -70, -66, -59, -53, -58,
  116720. -62, -55, -54, -54, -54, -58, -61, -62,
  116721. -72, -70, -72, -75, -78, -80, -81, -80,
  116722. -83, -83, -88, -93, -100, -107, -115, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999},
  116725. {-999, -999, -999, -105, -100, -95, -90, -85,
  116726. -80, -75, -70, -66, -62, -56, -48, -44,
  116727. -48, -46, -46, -43, -46, -48, -48, -51,
  116728. -58, -58, -59, -60, -62, -62, -61, -61,
  116729. -65, -64, -65, -68, -70, -74, -75, -78,
  116730. -81, -86, -95, -110, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -999, -999, -999, -999},
  116732. {-999, -999, -105, -100, -95, -90, -85, -80,
  116733. -75, -70, -65, -61, -55, -49, -39, -33,
  116734. -40, -35, -32, -38, -40, -33, -35, -37,
  116735. -46, -41, -45, -44, -46, -42, -45, -46,
  116736. -52, -50, -50, -50, -54, -54, -55, -57,
  116737. -62, -64, -66, -68, -70, -76, -81, -90,
  116738. -100, -110, -999, -999, -999, -999, -999, -999}},
  116739. /* 354 hz */
  116740. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116741. -105, -98, -90, -85, -82, -83, -80, -78,
  116742. -84, -79, -80, -83, -87, -89, -91, -93,
  116743. -99, -106, -117, -999, -999, -999, -999, -999,
  116744. -999, -999, -999, -999, -999, -999, -999, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999},
  116747. {-999, -999, -999, -999, -999, -999, -999, -999,
  116748. -105, -98, -90, -85, -80, -75, -70, -68,
  116749. -74, -72, -74, -77, -80, -82, -85, -87,
  116750. -92, -89, -91, -95, -100, -106, -112, -999,
  116751. -999, -999, -999, -999, -999, -999, -999, -999,
  116752. -999, -999, -999, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999},
  116754. {-999, -999, -999, -999, -999, -999, -999, -999,
  116755. -105, -98, -90, -83, -75, -71, -63, -64,
  116756. -67, -62, -64, -67, -70, -73, -77, -81,
  116757. -84, -83, -85, -89, -90, -93, -98, -104,
  116758. -109, -114, -999, -999, -999, -999, -999, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999},
  116761. {-999, -999, -999, -999, -999, -999, -999, -999,
  116762. -103, -96, -88, -81, -75, -68, -58, -54,
  116763. -56, -54, -56, -56, -58, -60, -63, -66,
  116764. -74, -69, -72, -72, -75, -74, -77, -81,
  116765. -81, -82, -84, -87, -93, -96, -99, -104,
  116766. -110, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999},
  116768. {-999, -999, -999, -999, -999, -108, -102, -96,
  116769. -91, -85, -80, -74, -68, -60, -51, -46,
  116770. -48, -46, -43, -45, -47, -47, -49, -48,
  116771. -56, -53, -55, -58, -57, -63, -58, -60,
  116772. -66, -64, -67, -70, -70, -74, -77, -84,
  116773. -86, -89, -91, -93, -94, -101, -109, -118,
  116774. -999, -999, -999, -999, -999, -999, -999, -999},
  116775. {-999, -999, -999, -108, -103, -98, -93, -88,
  116776. -83, -78, -73, -68, -60, -53, -44, -35,
  116777. -38, -38, -34, -34, -36, -40, -41, -44,
  116778. -51, -45, -46, -47, -46, -54, -50, -49,
  116779. -50, -50, -50, -51, -54, -57, -58, -60,
  116780. -66, -66, -66, -64, -65, -68, -77, -82,
  116781. -87, -95, -110, -999, -999, -999, -999, -999}},
  116782. /* 500 Hz */
  116783. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116784. -107, -102, -97, -92, -87, -83, -78, -75,
  116785. -82, -79, -83, -85, -89, -92, -95, -98,
  116786. -101, -105, -109, -113, -999, -999, -999, -999,
  116787. -999, -999, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999},
  116790. {-999, -999, -999, -999, -999, -999, -999, -106,
  116791. -100, -95, -90, -86, -81, -78, -74, -69,
  116792. -74, -74, -76, -79, -83, -84, -86, -89,
  116793. -92, -97, -93, -100, -103, -107, -110, -999,
  116794. -999, -999, -999, -999, -999, -999, -999, -999,
  116795. -999, -999, -999, -999, -999, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999},
  116797. {-999, -999, -999, -999, -999, -999, -106, -100,
  116798. -95, -90, -87, -83, -80, -75, -69, -60,
  116799. -66, -66, -68, -70, -74, -78, -79, -81,
  116800. -81, -83, -84, -87, -93, -96, -99, -103,
  116801. -107, -110, -999, -999, -999, -999, -999, -999,
  116802. -999, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999},
  116804. {-999, -999, -999, -999, -999, -108, -103, -98,
  116805. -93, -89, -85, -82, -78, -71, -62, -55,
  116806. -58, -58, -54, -54, -55, -59, -61, -62,
  116807. -70, -66, -66, -67, -70, -72, -75, -78,
  116808. -84, -84, -84, -88, -91, -90, -95, -98,
  116809. -102, -103, -106, -110, -999, -999, -999, -999,
  116810. -999, -999, -999, -999, -999, -999, -999, -999},
  116811. {-999, -999, -999, -999, -108, -103, -98, -94,
  116812. -90, -87, -82, -79, -73, -67, -58, -47,
  116813. -50, -45, -41, -45, -48, -44, -44, -49,
  116814. -54, -51, -48, -47, -49, -50, -51, -57,
  116815. -58, -60, -63, -69, -70, -69, -71, -74,
  116816. -78, -82, -90, -95, -101, -105, -110, -999,
  116817. -999, -999, -999, -999, -999, -999, -999, -999},
  116818. {-999, -999, -999, -105, -101, -97, -93, -90,
  116819. -85, -80, -77, -72, -65, -56, -48, -37,
  116820. -40, -36, -34, -40, -50, -47, -38, -41,
  116821. -47, -38, -35, -39, -38, -43, -40, -45,
  116822. -50, -45, -44, -47, -50, -55, -48, -48,
  116823. -52, -66, -70, -76, -82, -90, -97, -105,
  116824. -110, -999, -999, -999, -999, -999, -999, -999}},
  116825. /* 707 Hz */
  116826. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -108, -103, -98, -93, -86, -79, -76,
  116828. -83, -81, -85, -87, -89, -93, -98, -102,
  116829. -107, -112, -999, -999, -999, -999, -999, -999,
  116830. -999, -999, -999, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999},
  116833. {-999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -108, -103, -98, -93, -86, -79, -71,
  116835. -77, -74, -77, -79, -81, -84, -85, -90,
  116836. -92, -93, -92, -98, -101, -108, -112, -999,
  116837. -999, -999, -999, -999, -999, -999, -999, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999},
  116840. {-999, -999, -999, -999, -999, -999, -999, -999,
  116841. -108, -103, -98, -93, -87, -78, -68, -65,
  116842. -66, -62, -65, -67, -70, -73, -75, -78,
  116843. -82, -82, -83, -84, -91, -93, -98, -102,
  116844. -106, -110, -999, -999, -999, -999, -999, -999,
  116845. -999, -999, -999, -999, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999},
  116847. {-999, -999, -999, -999, -999, -999, -999, -999,
  116848. -105, -100, -95, -90, -82, -74, -62, -57,
  116849. -58, -56, -51, -52, -52, -54, -54, -58,
  116850. -66, -59, -60, -63, -66, -69, -73, -79,
  116851. -83, -84, -80, -81, -81, -82, -88, -92,
  116852. -98, -105, -113, -999, -999, -999, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999},
  116854. {-999, -999, -999, -999, -999, -999, -999, -107,
  116855. -102, -97, -92, -84, -79, -69, -57, -47,
  116856. -52, -47, -44, -45, -50, -52, -42, -42,
  116857. -53, -43, -43, -48, -51, -56, -55, -52,
  116858. -57, -59, -61, -62, -67, -71, -78, -83,
  116859. -86, -94, -98, -103, -110, -999, -999, -999,
  116860. -999, -999, -999, -999, -999, -999, -999, -999},
  116861. {-999, -999, -999, -999, -999, -999, -105, -100,
  116862. -95, -90, -84, -78, -70, -61, -51, -41,
  116863. -40, -38, -40, -46, -52, -51, -41, -40,
  116864. -46, -40, -38, -38, -41, -46, -41, -46,
  116865. -47, -43, -43, -45, -41, -45, -56, -67,
  116866. -68, -83, -87, -90, -95, -102, -107, -113,
  116867. -999, -999, -999, -999, -999, -999, -999, -999}},
  116868. /* 1000 Hz */
  116869. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -109, -105, -101, -96, -91, -84, -77,
  116871. -82, -82, -85, -89, -94, -100, -106, -110,
  116872. -999, -999, -999, -999, -999, -999, -999, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999},
  116876. {-999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -106, -103, -98, -92, -85, -80, -71,
  116878. -75, -72, -76, -80, -84, -86, -89, -93,
  116879. -100, -107, -113, -999, -999, -999, -999, -999,
  116880. -999, -999, -999, -999, -999, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999},
  116883. {-999, -999, -999, -999, -999, -999, -999, -107,
  116884. -104, -101, -97, -92, -88, -84, -80, -64,
  116885. -66, -63, -64, -66, -69, -73, -77, -83,
  116886. -83, -86, -91, -98, -104, -111, -999, -999,
  116887. -999, -999, -999, -999, -999, -999, -999, -999,
  116888. -999, -999, -999, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999},
  116890. {-999, -999, -999, -999, -999, -999, -999, -107,
  116891. -104, -101, -97, -92, -90, -84, -74, -57,
  116892. -58, -52, -55, -54, -50, -52, -50, -52,
  116893. -63, -62, -69, -76, -77, -78, -78, -79,
  116894. -82, -88, -94, -100, -106, -111, -999, -999,
  116895. -999, -999, -999, -999, -999, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999},
  116897. {-999, -999, -999, -999, -999, -999, -106, -102,
  116898. -98, -95, -90, -85, -83, -78, -70, -50,
  116899. -50, -41, -44, -49, -47, -50, -50, -44,
  116900. -55, -46, -47, -48, -48, -54, -49, -49,
  116901. -58, -62, -71, -81, -87, -92, -97, -102,
  116902. -108, -114, -999, -999, -999, -999, -999, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999},
  116904. {-999, -999, -999, -999, -999, -999, -106, -102,
  116905. -98, -95, -90, -85, -83, -78, -70, -45,
  116906. -43, -41, -47, -50, -51, -50, -49, -45,
  116907. -47, -41, -44, -41, -39, -43, -38, -37,
  116908. -40, -41, -44, -50, -58, -65, -73, -79,
  116909. -85, -92, -97, -101, -105, -109, -113, -999,
  116910. -999, -999, -999, -999, -999, -999, -999, -999}},
  116911. /* 1414 Hz */
  116912. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -107, -100, -95, -87, -81,
  116914. -85, -83, -88, -93, -100, -107, -114, -999,
  116915. -999, -999, -999, -999, -999, -999, -999, -999,
  116916. -999, -999, -999, -999, -999, -999, -999, -999,
  116917. -999, -999, -999, -999, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999},
  116919. {-999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -107, -101, -95, -88, -83, -76,
  116921. -73, -72, -79, -84, -90, -95, -100, -105,
  116922. -110, -115, -999, -999, -999, -999, -999, -999,
  116923. -999, -999, -999, -999, -999, -999, -999, -999,
  116924. -999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999},
  116926. {-999, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -104, -98, -92, -87, -81, -70,
  116928. -65, -62, -67, -71, -74, -80, -85, -91,
  116929. -95, -99, -103, -108, -111, -114, -999, -999,
  116930. -999, -999, -999, -999, -999, -999, -999, -999,
  116931. -999, -999, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999},
  116933. {-999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -103, -97, -90, -85, -76, -60,
  116935. -56, -54, -60, -62, -61, -56, -63, -65,
  116936. -73, -74, -77, -75, -78, -81, -86, -87,
  116937. -88, -91, -94, -98, -103, -110, -999, -999,
  116938. -999, -999, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999},
  116940. {-999, -999, -999, -999, -999, -999, -999, -105,
  116941. -100, -97, -92, -86, -81, -79, -70, -57,
  116942. -51, -47, -51, -58, -60, -56, -53, -50,
  116943. -58, -52, -50, -50, -53, -55, -64, -69,
  116944. -71, -85, -82, -78, -81, -85, -95, -102,
  116945. -112, -999, -999, -999, -999, -999, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999},
  116947. {-999, -999, -999, -999, -999, -999, -999, -105,
  116948. -100, -97, -92, -85, -83, -79, -72, -49,
  116949. -40, -43, -43, -54, -56, -51, -50, -40,
  116950. -43, -38, -36, -35, -37, -38, -37, -44,
  116951. -54, -60, -57, -60, -70, -75, -84, -92,
  116952. -103, -112, -999, -999, -999, -999, -999, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999}},
  116954. /* 2000 Hz */
  116955. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -110, -102, -95, -89, -82,
  116957. -83, -84, -90, -92, -99, -107, -113, -999,
  116958. -999, -999, -999, -999, -999, -999, -999, -999,
  116959. -999, -999, -999, -999, -999, -999, -999, -999,
  116960. -999, -999, -999, -999, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999},
  116962. {-999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -107, -101, -95, -89, -83, -72,
  116964. -74, -78, -85, -88, -88, -90, -92, -98,
  116965. -105, -111, -999, -999, -999, -999, -999, -999,
  116966. -999, -999, -999, -999, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999},
  116969. {-999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -109, -103, -97, -93, -87, -81, -70,
  116971. -70, -67, -75, -73, -76, -79, -81, -83,
  116972. -88, -89, -97, -103, -110, -999, -999, -999,
  116973. -999, -999, -999, -999, -999, -999, -999, -999,
  116974. -999, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999},
  116976. {-999, -999, -999, -999, -999, -999, -999, -999,
  116977. -999, -107, -100, -94, -88, -83, -75, -63,
  116978. -59, -59, -63, -66, -60, -62, -67, -67,
  116979. -77, -76, -81, -88, -86, -92, -96, -102,
  116980. -109, -116, -999, -999, -999, -999, -999, -999,
  116981. -999, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999},
  116983. {-999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -105, -98, -92, -86, -81, -73, -56,
  116985. -52, -47, -55, -60, -58, -52, -51, -45,
  116986. -49, -50, -53, -54, -61, -71, -70, -69,
  116987. -78, -79, -87, -90, -96, -104, -112, -999,
  116988. -999, -999, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999},
  116990. {-999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -103, -96, -90, -86, -78, -70, -51,
  116992. -42, -47, -48, -55, -54, -54, -53, -42,
  116993. -35, -28, -33, -38, -37, -44, -47, -49,
  116994. -54, -63, -68, -78, -82, -89, -94, -99,
  116995. -104, -109, -114, -999, -999, -999, -999, -999,
  116996. -999, -999, -999, -999, -999, -999, -999, -999}},
  116997. /* 2828 Hz */
  116998. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -999, -110, -100, -90, -79,
  117000. -85, -81, -82, -82, -89, -94, -99, -103,
  117001. -109, -115, -999, -999, -999, -999, -999, -999,
  117002. -999, -999, -999, -999, -999, -999, -999, -999,
  117003. -999, -999, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999},
  117005. {-999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -105, -97, -85, -72,
  117007. -74, -70, -70, -70, -76, -85, -91, -93,
  117008. -97, -103, -109, -115, -999, -999, -999, -999,
  117009. -999, -999, -999, -999, -999, -999, -999, -999,
  117010. -999, -999, -999, -999, -999, -999, -999, -999,
  117011. -999, -999, -999, -999, -999, -999, -999, -999},
  117012. {-999, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -999, -999, -999, -112, -93, -81, -68,
  117014. -62, -60, -60, -57, -63, -70, -77, -82,
  117015. -90, -93, -98, -104, -109, -113, -999, -999,
  117016. -999, -999, -999, -999, -999, -999, -999, -999,
  117017. -999, -999, -999, -999, -999, -999, -999, -999,
  117018. -999, -999, -999, -999, -999, -999, -999, -999},
  117019. {-999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -999, -999, -113, -100, -93, -84, -63,
  117021. -58, -48, -53, -54, -52, -52, -57, -64,
  117022. -66, -76, -83, -81, -85, -85, -90, -95,
  117023. -98, -101, -103, -106, -108, -111, -999, -999,
  117024. -999, -999, -999, -999, -999, -999, -999, -999,
  117025. -999, -999, -999, -999, -999, -999, -999, -999},
  117026. {-999, -999, -999, -999, -999, -999, -999, -999,
  117027. -999, -999, -999, -105, -95, -86, -74, -53,
  117028. -50, -38, -43, -49, -43, -42, -39, -39,
  117029. -46, -52, -57, -56, -72, -69, -74, -81,
  117030. -87, -92, -94, -97, -99, -102, -105, -108,
  117031. -999, -999, -999, -999, -999, -999, -999, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999},
  117033. {-999, -999, -999, -999, -999, -999, -999, -999,
  117034. -999, -999, -108, -99, -90, -76, -66, -45,
  117035. -43, -41, -44, -47, -43, -47, -40, -30,
  117036. -31, -31, -39, -33, -40, -41, -43, -53,
  117037. -59, -70, -73, -77, -79, -82, -84, -87,
  117038. -999, -999, -999, -999, -999, -999, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999}},
  117040. /* 4000 Hz */
  117041. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -999, -110, -91, -76,
  117043. -75, -85, -93, -98, -104, -110, -999, -999,
  117044. -999, -999, -999, -999, -999, -999, -999, -999,
  117045. -999, -999, -999, -999, -999, -999, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999},
  117048. {-999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -110, -91, -70,
  117050. -70, -75, -86, -89, -94, -98, -101, -106,
  117051. -110, -999, -999, -999, -999, -999, -999, -999,
  117052. -999, -999, -999, -999, -999, -999, -999, -999,
  117053. -999, -999, -999, -999, -999, -999, -999, -999,
  117054. -999, -999, -999, -999, -999, -999, -999, -999},
  117055. {-999, -999, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -999, -110, -95, -80, -60,
  117057. -65, -64, -74, -83, -88, -91, -95, -99,
  117058. -103, -107, -110, -999, -999, -999, -999, -999,
  117059. -999, -999, -999, -999, -999, -999, -999, -999,
  117060. -999, -999, -999, -999, -999, -999, -999, -999,
  117061. -999, -999, -999, -999, -999, -999, -999, -999},
  117062. {-999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -999, -110, -95, -80, -58,
  117064. -55, -49, -66, -68, -71, -78, -78, -80,
  117065. -88, -85, -89, -97, -100, -105, -110, -999,
  117066. -999, -999, -999, -999, -999, -999, -999, -999,
  117067. -999, -999, -999, -999, -999, -999, -999, -999,
  117068. -999, -999, -999, -999, -999, -999, -999, -999},
  117069. {-999, -999, -999, -999, -999, -999, -999, -999,
  117070. -999, -999, -999, -999, -110, -95, -80, -53,
  117071. -52, -41, -59, -59, -49, -58, -56, -63,
  117072. -86, -79, -90, -93, -98, -103, -107, -112,
  117073. -999, -999, -999, -999, -999, -999, -999, -999,
  117074. -999, -999, -999, -999, -999, -999, -999, -999,
  117075. -999, -999, -999, -999, -999, -999, -999, -999},
  117076. {-999, -999, -999, -999, -999, -999, -999, -999,
  117077. -999, -999, -999, -110, -97, -91, -73, -45,
  117078. -40, -33, -53, -61, -49, -54, -50, -50,
  117079. -60, -52, -67, -74, -81, -92, -96, -100,
  117080. -105, -110, -999, -999, -999, -999, -999, -999,
  117081. -999, -999, -999, -999, -999, -999, -999, -999,
  117082. -999, -999, -999, -999, -999, -999, -999, -999}},
  117083. /* 5657 Hz */
  117084. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117085. -999, -999, -999, -113, -106, -99, -92, -77,
  117086. -80, -88, -97, -106, -115, -999, -999, -999,
  117087. -999, -999, -999, -999, -999, -999, -999, -999,
  117088. -999, -999, -999, -999, -999, -999, -999, -999,
  117089. -999, -999, -999, -999, -999, -999, -999, -999,
  117090. -999, -999, -999, -999, -999, -999, -999, -999},
  117091. {-999, -999, -999, -999, -999, -999, -999, -999,
  117092. -999, -999, -116, -109, -102, -95, -89, -74,
  117093. -72, -88, -87, -95, -102, -109, -116, -999,
  117094. -999, -999, -999, -999, -999, -999, -999, -999,
  117095. -999, -999, -999, -999, -999, -999, -999, -999,
  117096. -999, -999, -999, -999, -999, -999, -999, -999,
  117097. -999, -999, -999, -999, -999, -999, -999, -999},
  117098. {-999, -999, -999, -999, -999, -999, -999, -999,
  117099. -999, -999, -116, -109, -102, -95, -89, -75,
  117100. -66, -74, -77, -78, -86, -87, -90, -96,
  117101. -105, -115, -999, -999, -999, -999, -999, -999,
  117102. -999, -999, -999, -999, -999, -999, -999, -999,
  117103. -999, -999, -999, -999, -999, -999, -999, -999,
  117104. -999, -999, -999, -999, -999, -999, -999, -999},
  117105. {-999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -115, -108, -101, -94, -88, -66,
  117107. -56, -61, -70, -65, -78, -72, -83, -84,
  117108. -93, -98, -105, -110, -999, -999, -999, -999,
  117109. -999, -999, -999, -999, -999, -999, -999, -999,
  117110. -999, -999, -999, -999, -999, -999, -999, -999,
  117111. -999, -999, -999, -999, -999, -999, -999, -999},
  117112. {-999, -999, -999, -999, -999, -999, -999, -999,
  117113. -999, -999, -110, -105, -95, -89, -82, -57,
  117114. -52, -52, -59, -56, -59, -58, -69, -67,
  117115. -88, -82, -82, -89, -94, -100, -108, -999,
  117116. -999, -999, -999, -999, -999, -999, -999, -999,
  117117. -999, -999, -999, -999, -999, -999, -999, -999,
  117118. -999, -999, -999, -999, -999, -999, -999, -999},
  117119. {-999, -999, -999, -999, -999, -999, -999, -999,
  117120. -999, -110, -101, -96, -90, -83, -77, -54,
  117121. -43, -38, -50, -48, -52, -48, -42, -42,
  117122. -51, -52, -53, -59, -65, -71, -78, -85,
  117123. -95, -999, -999, -999, -999, -999, -999, -999,
  117124. -999, -999, -999, -999, -999, -999, -999, -999,
  117125. -999, -999, -999, -999, -999, -999, -999, -999}},
  117126. /* 8000 Hz */
  117127. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117128. -999, -999, -999, -999, -120, -105, -86, -68,
  117129. -78, -79, -90, -100, -110, -999, -999, -999,
  117130. -999, -999, -999, -999, -999, -999, -999, -999,
  117131. -999, -999, -999, -999, -999, -999, -999, -999,
  117132. -999, -999, -999, -999, -999, -999, -999, -999,
  117133. -999, -999, -999, -999, -999, -999, -999, -999},
  117134. {-999, -999, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -999, -999, -120, -105, -86, -66,
  117136. -73, -77, -88, -96, -105, -115, -999, -999,
  117137. -999, -999, -999, -999, -999, -999, -999, -999,
  117138. -999, -999, -999, -999, -999, -999, -999, -999,
  117139. -999, -999, -999, -999, -999, -999, -999, -999,
  117140. -999, -999, -999, -999, -999, -999, -999, -999},
  117141. {-999, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -999, -120, -105, -92, -80, -61,
  117143. -64, -68, -80, -87, -92, -100, -110, -999,
  117144. -999, -999, -999, -999, -999, -999, -999, -999,
  117145. -999, -999, -999, -999, -999, -999, -999, -999,
  117146. -999, -999, -999, -999, -999, -999, -999, -999,
  117147. -999, -999, -999, -999, -999, -999, -999, -999},
  117148. {-999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -999, -120, -104, -91, -79, -52,
  117150. -60, -54, -64, -69, -77, -80, -82, -84,
  117151. -85, -87, -88, -90, -999, -999, -999, -999,
  117152. -999, -999, -999, -999, -999, -999, -999, -999,
  117153. -999, -999, -999, -999, -999, -999, -999, -999,
  117154. -999, -999, -999, -999, -999, -999, -999, -999},
  117155. {-999, -999, -999, -999, -999, -999, -999, -999,
  117156. -999, -999, -999, -118, -100, -87, -77, -49,
  117157. -50, -44, -58, -61, -61, -67, -65, -62,
  117158. -62, -62, -65, -68, -999, -999, -999, -999,
  117159. -999, -999, -999, -999, -999, -999, -999, -999,
  117160. -999, -999, -999, -999, -999, -999, -999, -999,
  117161. -999, -999, -999, -999, -999, -999, -999, -999},
  117162. {-999, -999, -999, -999, -999, -999, -999, -999,
  117163. -999, -999, -999, -115, -98, -84, -62, -49,
  117164. -44, -38, -46, -49, -49, -46, -39, -37,
  117165. -39, -40, -42, -43, -999, -999, -999, -999,
  117166. -999, -999, -999, -999, -999, -999, -999, -999,
  117167. -999, -999, -999, -999, -999, -999, -999, -999,
  117168. -999, -999, -999, -999, -999, -999, -999, -999}},
  117169. /* 11314 Hz */
  117170. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117171. -999, -999, -999, -999, -999, -110, -88, -74,
  117172. -77, -82, -82, -85, -90, -94, -99, -104,
  117173. -999, -999, -999, -999, -999, -999, -999, -999,
  117174. -999, -999, -999, -999, -999, -999, -999, -999,
  117175. -999, -999, -999, -999, -999, -999, -999, -999,
  117176. -999, -999, -999, -999, -999, -999, -999, -999},
  117177. {-999, -999, -999, -999, -999, -999, -999, -999,
  117178. -999, -999, -999, -999, -999, -110, -88, -66,
  117179. -70, -81, -80, -81, -84, -88, -91, -93,
  117180. -999, -999, -999, -999, -999, -999, -999, -999,
  117181. -999, -999, -999, -999, -999, -999, -999, -999,
  117182. -999, -999, -999, -999, -999, -999, -999, -999,
  117183. -999, -999, -999, -999, -999, -999, -999, -999},
  117184. {-999, -999, -999, -999, -999, -999, -999, -999,
  117185. -999, -999, -999, -999, -999, -110, -88, -61,
  117186. -63, -70, -71, -74, -77, -80, -83, -85,
  117187. -999, -999, -999, -999, -999, -999, -999, -999,
  117188. -999, -999, -999, -999, -999, -999, -999, -999,
  117189. -999, -999, -999, -999, -999, -999, -999, -999,
  117190. -999, -999, -999, -999, -999, -999, -999, -999},
  117191. {-999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -999, -999, -110, -86, -62,
  117193. -63, -62, -62, -58, -52, -50, -50, -52,
  117194. -54, -999, -999, -999, -999, -999, -999, -999,
  117195. -999, -999, -999, -999, -999, -999, -999, -999,
  117196. -999, -999, -999, -999, -999, -999, -999, -999,
  117197. -999, -999, -999, -999, -999, -999, -999, -999},
  117198. {-999, -999, -999, -999, -999, -999, -999, -999,
  117199. -999, -999, -999, -999, -118, -108, -84, -53,
  117200. -50, -50, -50, -55, -47, -45, -40, -40,
  117201. -40, -999, -999, -999, -999, -999, -999, -999,
  117202. -999, -999, -999, -999, -999, -999, -999, -999,
  117203. -999, -999, -999, -999, -999, -999, -999, -999,
  117204. -999, -999, -999, -999, -999, -999, -999, -999},
  117205. {-999, -999, -999, -999, -999, -999, -999, -999,
  117206. -999, -999, -999, -999, -118, -100, -73, -43,
  117207. -37, -42, -43, -53, -38, -37, -35, -35,
  117208. -38, -999, -999, -999, -999, -999, -999, -999,
  117209. -999, -999, -999, -999, -999, -999, -999, -999,
  117210. -999, -999, -999, -999, -999, -999, -999, -999,
  117211. -999, -999, -999, -999, -999, -999, -999, -999}},
  117212. /* 16000 Hz */
  117213. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117214. -999, -999, -999, -110, -100, -91, -84, -74,
  117215. -80, -80, -80, -80, -80, -999, -999, -999,
  117216. -999, -999, -999, -999, -999, -999, -999, -999,
  117217. -999, -999, -999, -999, -999, -999, -999, -999,
  117218. -999, -999, -999, -999, -999, -999, -999, -999,
  117219. -999, -999, -999, -999, -999, -999, -999, -999},
  117220. {-999, -999, -999, -999, -999, -999, -999, -999,
  117221. -999, -999, -999, -110, -100, -91, -84, -74,
  117222. -68, -68, -68, -68, -68, -999, -999, -999,
  117223. -999, -999, -999, -999, -999, -999, -999, -999,
  117224. -999, -999, -999, -999, -999, -999, -999, -999,
  117225. -999, -999, -999, -999, -999, -999, -999, -999,
  117226. -999, -999, -999, -999, -999, -999, -999, -999},
  117227. {-999, -999, -999, -999, -999, -999, -999, -999,
  117228. -999, -999, -999, -110, -100, -86, -78, -70,
  117229. -60, -45, -30, -21, -999, -999, -999, -999,
  117230. -999, -999, -999, -999, -999, -999, -999, -999,
  117231. -999, -999, -999, -999, -999, -999, -999, -999,
  117232. -999, -999, -999, -999, -999, -999, -999, -999,
  117233. -999, -999, -999, -999, -999, -999, -999, -999},
  117234. {-999, -999, -999, -999, -999, -999, -999, -999,
  117235. -999, -999, -999, -110, -100, -87, -78, -67,
  117236. -48, -38, -29, -21, -999, -999, -999, -999,
  117237. -999, -999, -999, -999, -999, -999, -999, -999,
  117238. -999, -999, -999, -999, -999, -999, -999, -999,
  117239. -999, -999, -999, -999, -999, -999, -999, -999,
  117240. -999, -999, -999, -999, -999, -999, -999, -999},
  117241. {-999, -999, -999, -999, -999, -999, -999, -999,
  117242. -999, -999, -999, -110, -100, -86, -69, -56,
  117243. -45, -35, -33, -29, -999, -999, -999, -999,
  117244. -999, -999, -999, -999, -999, -999, -999, -999,
  117245. -999, -999, -999, -999, -999, -999, -999, -999,
  117246. -999, -999, -999, -999, -999, -999, -999, -999,
  117247. -999, -999, -999, -999, -999, -999, -999, -999},
  117248. {-999, -999, -999, -999, -999, -999, -999, -999,
  117249. -999, -999, -999, -110, -100, -83, -71, -48,
  117250. -27, -38, -37, -34, -999, -999, -999, -999,
  117251. -999, -999, -999, -999, -999, -999, -999, -999,
  117252. -999, -999, -999, -999, -999, -999, -999, -999,
  117253. -999, -999, -999, -999, -999, -999, -999, -999,
  117254. -999, -999, -999, -999, -999, -999, -999, -999}}
  117255. };
  117256. #endif
  117257. /*** End of inlined file: masking.h ***/
  117258. #define NEGINF -9999.f
  117259. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117260. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117261. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117262. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117263. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117264. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117265. look->channels=vi->channels;
  117266. look->ampmax=-9999.;
  117267. look->gi=gi;
  117268. return(look);
  117269. }
  117270. void _vp_global_free(vorbis_look_psy_global *look){
  117271. if(look){
  117272. memset(look,0,sizeof(*look));
  117273. _ogg_free(look);
  117274. }
  117275. }
  117276. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117277. if(i){
  117278. memset(i,0,sizeof(*i));
  117279. _ogg_free(i);
  117280. }
  117281. }
  117282. void _vi_psy_free(vorbis_info_psy *i){
  117283. if(i){
  117284. memset(i,0,sizeof(*i));
  117285. _ogg_free(i);
  117286. }
  117287. }
  117288. static void min_curve(float *c,
  117289. float *c2){
  117290. int i;
  117291. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117292. }
  117293. static void max_curve(float *c,
  117294. float *c2){
  117295. int i;
  117296. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117297. }
  117298. static void attenuate_curve(float *c,float att){
  117299. int i;
  117300. for(i=0;i<EHMER_MAX;i++)
  117301. c[i]+=att;
  117302. }
  117303. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117304. float center_boost, float center_decay_rate){
  117305. int i,j,k,m;
  117306. float ath[EHMER_MAX];
  117307. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117308. float athc[P_LEVELS][EHMER_MAX];
  117309. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117310. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117311. memset(workc,0,sizeof(workc));
  117312. for(i=0;i<P_BANDS;i++){
  117313. /* we add back in the ATH to avoid low level curves falling off to
  117314. -infinity and unnecessarily cutting off high level curves in the
  117315. curve limiting (last step). */
  117316. /* A half-band's settings must be valid over the whole band, and
  117317. it's better to mask too little than too much */
  117318. int ath_offset=i*4;
  117319. for(j=0;j<EHMER_MAX;j++){
  117320. float min=999.;
  117321. for(k=0;k<4;k++)
  117322. if(j+k+ath_offset<MAX_ATH){
  117323. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117324. }else{
  117325. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117326. }
  117327. ath[j]=min;
  117328. }
  117329. /* copy curves into working space, replicate the 50dB curve to 30
  117330. and 40, replicate the 100dB curve to 110 */
  117331. for(j=0;j<6;j++)
  117332. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117333. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117334. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117335. /* apply centered curve boost/decay */
  117336. for(j=0;j<P_LEVELS;j++){
  117337. for(k=0;k<EHMER_MAX;k++){
  117338. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117339. if(adj<0. && center_boost>0)adj=0.;
  117340. if(adj>0. && center_boost<0)adj=0.;
  117341. workc[i][j][k]+=adj;
  117342. }
  117343. }
  117344. /* normalize curves so the driving amplitude is 0dB */
  117345. /* make temp curves with the ATH overlayed */
  117346. for(j=0;j<P_LEVELS;j++){
  117347. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117348. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117349. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117350. max_curve(athc[j],workc[i][j]);
  117351. }
  117352. /* Now limit the louder curves.
  117353. the idea is this: We don't know what the playback attenuation
  117354. will be; 0dB SL moves every time the user twiddles the volume
  117355. knob. So that means we have to use a single 'most pessimal' curve
  117356. for all masking amplitudes, right? Wrong. The *loudest* sound
  117357. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117358. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117359. etc... */
  117360. for(j=1;j<P_LEVELS;j++){
  117361. min_curve(athc[j],athc[j-1]);
  117362. min_curve(workc[i][j],athc[j]);
  117363. }
  117364. }
  117365. for(i=0;i<P_BANDS;i++){
  117366. int hi_curve,lo_curve,bin;
  117367. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117368. /* low frequency curves are measured with greater resolution than
  117369. the MDCT/FFT will actually give us; we want the curve applied
  117370. to the tone data to be pessimistic and thus apply the minimum
  117371. masking possible for a given bin. That means that a single bin
  117372. could span more than one octave and that the curve will be a
  117373. composite of multiple octaves. It also may mean that a single
  117374. bin may span > an eighth of an octave and that the eighth
  117375. octave values may also be composited. */
  117376. /* which octave curves will we be compositing? */
  117377. bin=floor(fromOC(i*.5)/binHz);
  117378. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117379. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117380. if(lo_curve>i)lo_curve=i;
  117381. if(lo_curve<0)lo_curve=0;
  117382. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117383. for(m=0;m<P_LEVELS;m++){
  117384. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117385. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117386. /* render the curve into bins, then pull values back into curve.
  117387. The point is that any inherent subsampling aliasing results in
  117388. a safe minimum */
  117389. for(k=lo_curve;k<=hi_curve;k++){
  117390. int l=0;
  117391. for(j=0;j<EHMER_MAX;j++){
  117392. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117393. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117394. if(lo_bin<0)lo_bin=0;
  117395. if(lo_bin>n)lo_bin=n;
  117396. if(lo_bin<l)l=lo_bin;
  117397. if(hi_bin<0)hi_bin=0;
  117398. if(hi_bin>n)hi_bin=n;
  117399. for(;l<hi_bin && l<n;l++)
  117400. if(brute_buffer[l]>workc[k][m][j])
  117401. brute_buffer[l]=workc[k][m][j];
  117402. }
  117403. for(;l<n;l++)
  117404. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117405. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117406. }
  117407. /* be equally paranoid about being valid up to next half ocatve */
  117408. if(i+1<P_BANDS){
  117409. int l=0;
  117410. k=i+1;
  117411. for(j=0;j<EHMER_MAX;j++){
  117412. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117413. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117414. if(lo_bin<0)lo_bin=0;
  117415. if(lo_bin>n)lo_bin=n;
  117416. if(lo_bin<l)l=lo_bin;
  117417. if(hi_bin<0)hi_bin=0;
  117418. if(hi_bin>n)hi_bin=n;
  117419. for(;l<hi_bin && l<n;l++)
  117420. if(brute_buffer[l]>workc[k][m][j])
  117421. brute_buffer[l]=workc[k][m][j];
  117422. }
  117423. for(;l<n;l++)
  117424. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117425. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117426. }
  117427. for(j=0;j<EHMER_MAX;j++){
  117428. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117429. if(bin<0){
  117430. ret[i][m][j+2]=-999.;
  117431. }else{
  117432. if(bin>=n){
  117433. ret[i][m][j+2]=-999.;
  117434. }else{
  117435. ret[i][m][j+2]=brute_buffer[bin];
  117436. }
  117437. }
  117438. }
  117439. /* add fenceposts */
  117440. for(j=0;j<EHMER_OFFSET;j++)
  117441. if(ret[i][m][j+2]>-200.f)break;
  117442. ret[i][m][0]=j;
  117443. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117444. if(ret[i][m][j+2]>-200.f)
  117445. break;
  117446. ret[i][m][1]=j;
  117447. }
  117448. }
  117449. return(ret);
  117450. }
  117451. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117452. vorbis_info_psy_global *gi,int n,long rate){
  117453. long i,j,lo=-99,hi=1;
  117454. long maxoc;
  117455. memset(p,0,sizeof(*p));
  117456. p->eighth_octave_lines=gi->eighth_octave_lines;
  117457. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117458. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117459. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117460. p->total_octave_lines=maxoc-p->firstoc+1;
  117461. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117462. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117463. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117464. p->vi=vi;
  117465. p->n=n;
  117466. p->rate=rate;
  117467. /* AoTuV HF weighting */
  117468. p->m_val = 1.;
  117469. if(rate < 26000) p->m_val = 0;
  117470. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117471. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117472. /* set up the lookups for a given blocksize and sample rate */
  117473. for(i=0,j=0;i<MAX_ATH-1;i++){
  117474. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117475. float base=ATH[i];
  117476. if(j<endpos){
  117477. float delta=(ATH[i+1]-base)/(endpos-j);
  117478. for(;j<endpos && j<n;j++){
  117479. p->ath[j]=base+100.;
  117480. base+=delta;
  117481. }
  117482. }
  117483. }
  117484. for(i=0;i<n;i++){
  117485. float bark=toBARK(rate/(2*n)*i);
  117486. for(;lo+vi->noisewindowlomin<i &&
  117487. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117488. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117489. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117490. p->bark[i]=((lo-1)<<16)+(hi-1);
  117491. }
  117492. for(i=0;i<n;i++)
  117493. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117494. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117495. vi->tone_centerboost,vi->tone_decay);
  117496. /* set up rolling noise median */
  117497. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117498. for(i=0;i<P_NOISECURVES;i++)
  117499. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117500. for(i=0;i<n;i++){
  117501. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117502. int inthalfoc;
  117503. float del;
  117504. if(halfoc<0)halfoc=0;
  117505. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117506. inthalfoc=(int)halfoc;
  117507. del=halfoc-inthalfoc;
  117508. for(j=0;j<P_NOISECURVES;j++)
  117509. p->noiseoffset[j][i]=
  117510. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117511. p->vi->noiseoff[j][inthalfoc+1]*del;
  117512. }
  117513. #if 0
  117514. {
  117515. static int ls=0;
  117516. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117517. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117518. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117519. }
  117520. #endif
  117521. }
  117522. void _vp_psy_clear(vorbis_look_psy *p){
  117523. int i,j;
  117524. if(p){
  117525. if(p->ath)_ogg_free(p->ath);
  117526. if(p->octave)_ogg_free(p->octave);
  117527. if(p->bark)_ogg_free(p->bark);
  117528. if(p->tonecurves){
  117529. for(i=0;i<P_BANDS;i++){
  117530. for(j=0;j<P_LEVELS;j++){
  117531. _ogg_free(p->tonecurves[i][j]);
  117532. }
  117533. _ogg_free(p->tonecurves[i]);
  117534. }
  117535. _ogg_free(p->tonecurves);
  117536. }
  117537. if(p->noiseoffset){
  117538. for(i=0;i<P_NOISECURVES;i++){
  117539. _ogg_free(p->noiseoffset[i]);
  117540. }
  117541. _ogg_free(p->noiseoffset);
  117542. }
  117543. memset(p,0,sizeof(*p));
  117544. }
  117545. }
  117546. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117547. static void seed_curve(float *seed,
  117548. const float **curves,
  117549. float amp,
  117550. int oc, int n,
  117551. int linesper,float dBoffset){
  117552. int i,post1;
  117553. int seedptr;
  117554. const float *posts,*curve;
  117555. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117556. choice=max(choice,0);
  117557. choice=min(choice,P_LEVELS-1);
  117558. posts=curves[choice];
  117559. curve=posts+2;
  117560. post1=(int)posts[1];
  117561. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117562. for(i=posts[0];i<post1;i++){
  117563. if(seedptr>0){
  117564. float lin=amp+curve[i];
  117565. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117566. }
  117567. seedptr+=linesper;
  117568. if(seedptr>=n)break;
  117569. }
  117570. }
  117571. static void seed_loop(vorbis_look_psy *p,
  117572. const float ***curves,
  117573. const float *f,
  117574. const float *flr,
  117575. float *seed,
  117576. float specmax){
  117577. vorbis_info_psy *vi=p->vi;
  117578. long n=p->n,i;
  117579. float dBoffset=vi->max_curve_dB-specmax;
  117580. /* prime the working vector with peak values */
  117581. for(i=0;i<n;i++){
  117582. float max=f[i];
  117583. long oc=p->octave[i];
  117584. while(i+1<n && p->octave[i+1]==oc){
  117585. i++;
  117586. if(f[i]>max)max=f[i];
  117587. }
  117588. if(max+6.f>flr[i]){
  117589. oc=oc>>p->shiftoc;
  117590. if(oc>=P_BANDS)oc=P_BANDS-1;
  117591. if(oc<0)oc=0;
  117592. seed_curve(seed,
  117593. curves[oc],
  117594. max,
  117595. p->octave[i]-p->firstoc,
  117596. p->total_octave_lines,
  117597. p->eighth_octave_lines,
  117598. dBoffset);
  117599. }
  117600. }
  117601. }
  117602. static void seed_chase(float *seeds, int linesper, long n){
  117603. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117604. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117605. long stack=0;
  117606. long pos=0;
  117607. long i;
  117608. for(i=0;i<n;i++){
  117609. if(stack<2){
  117610. posstack[stack]=i;
  117611. ampstack[stack++]=seeds[i];
  117612. }else{
  117613. while(1){
  117614. if(seeds[i]<ampstack[stack-1]){
  117615. posstack[stack]=i;
  117616. ampstack[stack++]=seeds[i];
  117617. break;
  117618. }else{
  117619. if(i<posstack[stack-1]+linesper){
  117620. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117621. i<posstack[stack-2]+linesper){
  117622. /* we completely overlap, making stack-1 irrelevant. pop it */
  117623. stack--;
  117624. continue;
  117625. }
  117626. }
  117627. posstack[stack]=i;
  117628. ampstack[stack++]=seeds[i];
  117629. break;
  117630. }
  117631. }
  117632. }
  117633. }
  117634. /* the stack now contains only the positions that are relevant. Scan
  117635. 'em straight through */
  117636. for(i=0;i<stack;i++){
  117637. long endpos;
  117638. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117639. endpos=posstack[i+1];
  117640. }else{
  117641. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117642. discarded in short frames */
  117643. }
  117644. if(endpos>n)endpos=n;
  117645. for(;pos<endpos;pos++)
  117646. seeds[pos]=ampstack[i];
  117647. }
  117648. /* there. Linear time. I now remember this was on a problem set I
  117649. had in Grad Skool... I didn't solve it at the time ;-) */
  117650. }
  117651. /* bleaugh, this is more complicated than it needs to be */
  117652. #include<stdio.h>
  117653. static void max_seeds(vorbis_look_psy *p,
  117654. float *seed,
  117655. float *flr){
  117656. long n=p->total_octave_lines;
  117657. int linesper=p->eighth_octave_lines;
  117658. long linpos=0;
  117659. long pos;
  117660. seed_chase(seed,linesper,n); /* for masking */
  117661. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117662. while(linpos+1<p->n){
  117663. float minV=seed[pos];
  117664. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117665. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117666. while(pos+1<=end){
  117667. pos++;
  117668. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117669. minV=seed[pos];
  117670. }
  117671. end=pos+p->firstoc;
  117672. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117673. if(flr[linpos]<minV)flr[linpos]=minV;
  117674. }
  117675. {
  117676. float minV=seed[p->total_octave_lines-1];
  117677. for(;linpos<p->n;linpos++)
  117678. if(flr[linpos]<minV)flr[linpos]=minV;
  117679. }
  117680. }
  117681. static void bark_noise_hybridmp(int n,const long *b,
  117682. const float *f,
  117683. float *noise,
  117684. const float offset,
  117685. const int fixed){
  117686. float *N=(float*) alloca(n*sizeof(*N));
  117687. float *X=(float*) alloca(n*sizeof(*N));
  117688. float *XX=(float*) alloca(n*sizeof(*N));
  117689. float *Y=(float*) alloca(n*sizeof(*N));
  117690. float *XY=(float*) alloca(n*sizeof(*N));
  117691. float tN, tX, tXX, tY, tXY;
  117692. int i;
  117693. int lo, hi;
  117694. float R, A, B, D;
  117695. float w, x, y;
  117696. tN = tX = tXX = tY = tXY = 0.f;
  117697. y = f[0] + offset;
  117698. if (y < 1.f) y = 1.f;
  117699. w = y * y * .5;
  117700. tN += w;
  117701. tX += w;
  117702. tY += w * y;
  117703. N[0] = tN;
  117704. X[0] = tX;
  117705. XX[0] = tXX;
  117706. Y[0] = tY;
  117707. XY[0] = tXY;
  117708. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117709. y = f[i] + offset;
  117710. if (y < 1.f) y = 1.f;
  117711. w = y * y;
  117712. tN += w;
  117713. tX += w * x;
  117714. tXX += w * x * x;
  117715. tY += w * y;
  117716. tXY += w * x * y;
  117717. N[i] = tN;
  117718. X[i] = tX;
  117719. XX[i] = tXX;
  117720. Y[i] = tY;
  117721. XY[i] = tXY;
  117722. }
  117723. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117724. lo = b[i] >> 16;
  117725. if( lo>=0 ) break;
  117726. hi = b[i] & 0xffff;
  117727. tN = N[hi] + N[-lo];
  117728. tX = X[hi] - X[-lo];
  117729. tXX = XX[hi] + XX[-lo];
  117730. tY = Y[hi] + Y[-lo];
  117731. tXY = XY[hi] - XY[-lo];
  117732. A = tY * tXX - tX * tXY;
  117733. B = tN * tXY - tX * tY;
  117734. D = tN * tXX - tX * tX;
  117735. R = (A + x * B) / D;
  117736. if (R < 0.f)
  117737. R = 0.f;
  117738. noise[i] = R - offset;
  117739. }
  117740. for ( ;; i++, x += 1.f) {
  117741. lo = b[i] >> 16;
  117742. hi = b[i] & 0xffff;
  117743. if(hi>=n)break;
  117744. tN = N[hi] - N[lo];
  117745. tX = X[hi] - X[lo];
  117746. tXX = XX[hi] - XX[lo];
  117747. tY = Y[hi] - Y[lo];
  117748. tXY = XY[hi] - XY[lo];
  117749. A = tY * tXX - tX * tXY;
  117750. B = tN * tXY - tX * tY;
  117751. D = tN * tXX - tX * tX;
  117752. R = (A + x * B) / D;
  117753. if (R < 0.f) R = 0.f;
  117754. noise[i] = R - offset;
  117755. }
  117756. for ( ; i < n; i++, x += 1.f) {
  117757. R = (A + x * B) / D;
  117758. if (R < 0.f) R = 0.f;
  117759. noise[i] = R - offset;
  117760. }
  117761. if (fixed <= 0) return;
  117762. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117763. hi = i + fixed / 2;
  117764. lo = hi - fixed;
  117765. if(lo>=0)break;
  117766. tN = N[hi] + N[-lo];
  117767. tX = X[hi] - X[-lo];
  117768. tXX = XX[hi] + XX[-lo];
  117769. tY = Y[hi] + Y[-lo];
  117770. tXY = XY[hi] - XY[-lo];
  117771. A = tY * tXX - tX * tXY;
  117772. B = tN * tXY - tX * tY;
  117773. D = tN * tXX - tX * tX;
  117774. R = (A + x * B) / D;
  117775. if (R - offset < noise[i]) noise[i] = R - offset;
  117776. }
  117777. for ( ;; i++, x += 1.f) {
  117778. hi = i + fixed / 2;
  117779. lo = hi - fixed;
  117780. if(hi>=n)break;
  117781. tN = N[hi] - N[lo];
  117782. tX = X[hi] - X[lo];
  117783. tXX = XX[hi] - XX[lo];
  117784. tY = Y[hi] - Y[lo];
  117785. tXY = XY[hi] - XY[lo];
  117786. A = tY * tXX - tX * tXY;
  117787. B = tN * tXY - tX * tY;
  117788. D = tN * tXX - tX * tX;
  117789. R = (A + x * B) / D;
  117790. if (R - offset < noise[i]) noise[i] = R - offset;
  117791. }
  117792. for ( ; i < n; i++, x += 1.f) {
  117793. R = (A + x * B) / D;
  117794. if (R - offset < noise[i]) noise[i] = R - offset;
  117795. }
  117796. }
  117797. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117798. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117799. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117800. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117801. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117802. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117803. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117804. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117805. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117806. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117807. 973377.F, 913981.F, 858210.F, 805842.F,
  117808. 756669.F, 710497.F, 667142.F, 626433.F,
  117809. 588208.F, 552316.F, 518613.F, 486967.F,
  117810. 457252.F, 429351.F, 403152.F, 378551.F,
  117811. 355452.F, 333762.F, 313396.F, 294273.F,
  117812. 276316.F, 259455.F, 243623.F, 228757.F,
  117813. 214798.F, 201691.F, 189384.F, 177828.F,
  117814. 166977.F, 156788.F, 147221.F, 138237.F,
  117815. 129802.F, 121881.F, 114444.F, 107461.F,
  117816. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117817. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117818. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117819. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117820. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117821. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117822. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117823. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117824. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117825. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117826. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117827. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117828. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117829. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117830. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117831. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117832. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117833. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117834. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117835. 842.910F, 791.475F, 743.179F, 697.830F,
  117836. 655.249F, 615.265F, 577.722F, 542.469F,
  117837. 509.367F, 478.286F, 449.101F, 421.696F,
  117838. 395.964F, 371.803F, 349.115F, 327.812F,
  117839. 307.809F, 289.026F, 271.390F, 254.830F,
  117840. 239.280F, 224.679F, 210.969F, 198.096F,
  117841. 186.008F, 174.658F, 164.000F, 153.993F,
  117842. 144.596F, 135.773F, 127.488F, 119.708F,
  117843. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117844. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117845. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117846. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117847. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117848. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117849. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117850. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117851. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117852. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117853. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117854. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117855. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117856. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117857. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117858. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117859. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117860. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117861. 1.20790F, 1.13419F, 1.06499F, 1.F
  117862. };
  117863. void _vp_remove_floor(vorbis_look_psy *p,
  117864. float *mdct,
  117865. int *codedflr,
  117866. float *residue,
  117867. int sliding_lowpass){
  117868. int i,n=p->n;
  117869. if(sliding_lowpass>n)sliding_lowpass=n;
  117870. for(i=0;i<sliding_lowpass;i++){
  117871. residue[i]=
  117872. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117873. }
  117874. for(;i<n;i++)
  117875. residue[i]=0.;
  117876. }
  117877. void _vp_noisemask(vorbis_look_psy *p,
  117878. float *logmdct,
  117879. float *logmask){
  117880. int i,n=p->n;
  117881. float *work=(float*) alloca(n*sizeof(*work));
  117882. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117883. 140.,-1);
  117884. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117885. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117886. p->vi->noisewindowfixed);
  117887. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117888. #if 0
  117889. {
  117890. static int seq=0;
  117891. float work2[n];
  117892. for(i=0;i<n;i++){
  117893. work2[i]=logmask[i]+work[i];
  117894. }
  117895. if(seq&1)
  117896. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117897. else
  117898. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117899. if(seq&1)
  117900. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117901. else
  117902. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117903. seq++;
  117904. }
  117905. #endif
  117906. for(i=0;i<n;i++){
  117907. int dB=logmask[i]+.5;
  117908. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117909. if(dB<0)dB=0;
  117910. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117911. }
  117912. }
  117913. void _vp_tonemask(vorbis_look_psy *p,
  117914. float *logfft,
  117915. float *logmask,
  117916. float global_specmax,
  117917. float local_specmax){
  117918. int i,n=p->n;
  117919. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117920. float att=local_specmax+p->vi->ath_adjatt;
  117921. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117922. /* set the ATH (floating below localmax, not global max by a
  117923. specified att) */
  117924. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117925. for(i=0;i<n;i++)
  117926. logmask[i]=p->ath[i]+att;
  117927. /* tone masking */
  117928. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117929. max_seeds(p,seed,logmask);
  117930. }
  117931. void _vp_offset_and_mix(vorbis_look_psy *p,
  117932. float *noise,
  117933. float *tone,
  117934. int offset_select,
  117935. float *logmask,
  117936. float *mdct,
  117937. float *logmdct){
  117938. int i,n=p->n;
  117939. float de, coeffi, cx;/* AoTuV */
  117940. float toneatt=p->vi->tone_masteratt[offset_select];
  117941. cx = p->m_val;
  117942. for(i=0;i<n;i++){
  117943. float val= noise[i]+p->noiseoffset[offset_select][i];
  117944. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117945. logmask[i]=max(val,tone[i]+toneatt);
  117946. /* AoTuV */
  117947. /** @ M1 **
  117948. The following codes improve a noise problem.
  117949. A fundamental idea uses the value of masking and carries out
  117950. the relative compensation of the MDCT.
  117951. However, this code is not perfect and all noise problems cannot be solved.
  117952. by Aoyumi @ 2004/04/18
  117953. */
  117954. if(offset_select == 1) {
  117955. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117956. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117957. if(val > coeffi){
  117958. /* mdct value is > -17.2 dB below floor */
  117959. de = 1.0-((val-coeffi)*0.005*cx);
  117960. /* pro-rated attenuation:
  117961. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117962. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117963. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117964. etc... */
  117965. if(de < 0) de = 0.0001;
  117966. }else
  117967. /* mdct value is <= -17.2 dB below floor */
  117968. de = 1.0-((val-coeffi)*0.0003*cx);
  117969. /* pro-rated attenuation:
  117970. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117971. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117972. etc... */
  117973. mdct[i] *= de;
  117974. }
  117975. }
  117976. }
  117977. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117978. vorbis_info *vi=vd->vi;
  117979. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117980. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117981. int n=ci->blocksizes[vd->W]/2;
  117982. float secs=(float)n/vi->rate;
  117983. amp+=secs*gi->ampmax_att_per_sec;
  117984. if(amp<-9999)amp=-9999;
  117985. return(amp);
  117986. }
  117987. static void couple_lossless(float A, float B,
  117988. float *qA, float *qB){
  117989. int test1=fabs(*qA)>fabs(*qB);
  117990. test1-= fabs(*qA)<fabs(*qB);
  117991. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117992. if(test1==1){
  117993. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117994. }else{
  117995. float temp=*qB;
  117996. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117997. *qA=temp;
  117998. }
  117999. if(*qB>fabs(*qA)*1.9999f){
  118000. *qB= -fabs(*qA)*2.f;
  118001. *qA= -*qA;
  118002. }
  118003. }
  118004. static float hypot_lookup[32]={
  118005. -0.009935, -0.011245, -0.012726, -0.014397,
  118006. -0.016282, -0.018407, -0.020800, -0.023494,
  118007. -0.026522, -0.029923, -0.033737, -0.038010,
  118008. -0.042787, -0.048121, -0.054064, -0.060671,
  118009. -0.068000, -0.076109, -0.085054, -0.094892,
  118010. -0.105675, -0.117451, -0.130260, -0.144134,
  118011. -0.159093, -0.175146, -0.192286, -0.210490,
  118012. -0.229718, -0.249913, -0.271001, -0.292893};
  118013. static void precomputed_couple_point(float premag,
  118014. int floorA,int floorB,
  118015. float *mag, float *ang){
  118016. int test=(floorA>floorB)-1;
  118017. int offset=31-abs(floorA-floorB);
  118018. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118019. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118020. *mag=premag*floormag;
  118021. *ang=0.f;
  118022. }
  118023. /* just like below, this is currently set up to only do
  118024. single-step-depth coupling. Otherwise, we'd have to do more
  118025. copying (which will be inevitable later) */
  118026. /* doing the real circular magnitude calculation is audibly superior
  118027. to (A+B)/sqrt(2) */
  118028. static float dipole_hypot(float a, float b){
  118029. if(a>0.){
  118030. if(b>0.)return sqrt(a*a+b*b);
  118031. if(a>-b)return sqrt(a*a-b*b);
  118032. return -sqrt(b*b-a*a);
  118033. }
  118034. if(b<0.)return -sqrt(a*a+b*b);
  118035. if(-a>b)return -sqrt(a*a-b*b);
  118036. return sqrt(b*b-a*a);
  118037. }
  118038. static float round_hypot(float a, float b){
  118039. if(a>0.){
  118040. if(b>0.)return sqrt(a*a+b*b);
  118041. if(a>-b)return sqrt(a*a+b*b);
  118042. return -sqrt(b*b+a*a);
  118043. }
  118044. if(b<0.)return -sqrt(a*a+b*b);
  118045. if(-a>b)return -sqrt(a*a+b*b);
  118046. return sqrt(b*b+a*a);
  118047. }
  118048. /* revert to round hypot for now */
  118049. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118050. vorbis_info_psy_global *g,
  118051. vorbis_look_psy *p,
  118052. vorbis_info_mapping0 *vi,
  118053. float **mdct){
  118054. int i,j,n=p->n;
  118055. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118056. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118057. for(i=0;i<vi->coupling_steps;i++){
  118058. float *mdctM=mdct[vi->coupling_mag[i]];
  118059. float *mdctA=mdct[vi->coupling_ang[i]];
  118060. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118061. for(j=0;j<limit;j++)
  118062. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118063. for(;j<n;j++)
  118064. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118065. }
  118066. return(ret);
  118067. }
  118068. /* this is for per-channel noise normalization */
  118069. static int JUCE_CDECL apsort(const void *a, const void *b){
  118070. float f1=fabs(**(float**)a);
  118071. float f2=fabs(**(float**)b);
  118072. return (f1<f2)-(f1>f2);
  118073. }
  118074. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118075. vorbis_look_psy *p,
  118076. vorbis_info_mapping0 *vi,
  118077. float **mags){
  118078. if(p->vi->normal_point_p){
  118079. int i,j,k,n=p->n;
  118080. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118081. int partition=p->vi->normal_partition;
  118082. float **work=(float**) alloca(sizeof(*work)*partition);
  118083. for(i=0;i<vi->coupling_steps;i++){
  118084. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118085. for(j=0;j<n;j+=partition){
  118086. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118087. qsort(work,partition,sizeof(*work),apsort);
  118088. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118089. }
  118090. }
  118091. return(ret);
  118092. }
  118093. return(NULL);
  118094. }
  118095. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118096. float *magnitudes,int *sortedindex){
  118097. int i,j,n=p->n;
  118098. vorbis_info_psy *vi=p->vi;
  118099. int partition=vi->normal_partition;
  118100. float **work=(float**) alloca(sizeof(*work)*partition);
  118101. int start=vi->normal_start;
  118102. for(j=start;j<n;j+=partition){
  118103. if(j+partition>n)partition=n-j;
  118104. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118105. qsort(work,partition,sizeof(*work),apsort);
  118106. for(i=0;i<partition;i++){
  118107. sortedindex[i+j-start]=work[i]-magnitudes;
  118108. }
  118109. }
  118110. }
  118111. void _vp_noise_normalize(vorbis_look_psy *p,
  118112. float *in,float *out,int *sortedindex){
  118113. int flag=0,i,j=0,n=p->n;
  118114. vorbis_info_psy *vi=p->vi;
  118115. int partition=vi->normal_partition;
  118116. int start=vi->normal_start;
  118117. if(start>n)start=n;
  118118. if(vi->normal_channel_p){
  118119. for(;j<start;j++)
  118120. out[j]=rint(in[j]);
  118121. for(;j+partition<=n;j+=partition){
  118122. float acc=0.;
  118123. int k;
  118124. for(i=j;i<j+partition;i++)
  118125. acc+=in[i]*in[i];
  118126. for(i=0;i<partition;i++){
  118127. k=sortedindex[i+j-start];
  118128. if(in[k]*in[k]>=.25f){
  118129. out[k]=rint(in[k]);
  118130. acc-=in[k]*in[k];
  118131. flag=1;
  118132. }else{
  118133. if(acc<vi->normal_thresh)break;
  118134. out[k]=unitnorm(in[k]);
  118135. acc-=1.;
  118136. }
  118137. }
  118138. for(;i<partition;i++){
  118139. k=sortedindex[i+j-start];
  118140. out[k]=0.;
  118141. }
  118142. }
  118143. }
  118144. for(;j<n;j++)
  118145. out[j]=rint(in[j]);
  118146. }
  118147. void _vp_couple(int blobno,
  118148. vorbis_info_psy_global *g,
  118149. vorbis_look_psy *p,
  118150. vorbis_info_mapping0 *vi,
  118151. float **res,
  118152. float **mag_memo,
  118153. int **mag_sort,
  118154. int **ifloor,
  118155. int *nonzero,
  118156. int sliding_lowpass){
  118157. int i,j,k,n=p->n;
  118158. /* perform any requested channel coupling */
  118159. /* point stereo can only be used in a first stage (in this encoder)
  118160. because of the dependency on floor lookups */
  118161. for(i=0;i<vi->coupling_steps;i++){
  118162. /* once we're doing multistage coupling in which a channel goes
  118163. through more than one coupling step, the floor vector
  118164. magnitudes will also have to be recalculated an propogated
  118165. along with PCM. Right now, we're not (that will wait until 5.1
  118166. most likely), so the code isn't here yet. The memory management
  118167. here is all assuming single depth couplings anyway. */
  118168. /* make sure coupling a zero and a nonzero channel results in two
  118169. nonzero channels. */
  118170. if(nonzero[vi->coupling_mag[i]] ||
  118171. nonzero[vi->coupling_ang[i]]){
  118172. float *rM=res[vi->coupling_mag[i]];
  118173. float *rA=res[vi->coupling_ang[i]];
  118174. float *qM=rM+n;
  118175. float *qA=rA+n;
  118176. int *floorM=ifloor[vi->coupling_mag[i]];
  118177. int *floorA=ifloor[vi->coupling_ang[i]];
  118178. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118179. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118180. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118181. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118182. int pointlimit=limit;
  118183. nonzero[vi->coupling_mag[i]]=1;
  118184. nonzero[vi->coupling_ang[i]]=1;
  118185. /* The threshold of a stereo is changed with the size of n */
  118186. if(n > 1000)
  118187. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118188. for(j=0;j<p->n;j+=partition){
  118189. float acc=0.f;
  118190. for(k=0;k<partition;k++){
  118191. int l=k+j;
  118192. if(l<sliding_lowpass){
  118193. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118194. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118195. precomputed_couple_point(mag_memo[i][l],
  118196. floorM[l],floorA[l],
  118197. qM+l,qA+l);
  118198. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118199. }else{
  118200. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118201. }
  118202. }else{
  118203. qM[l]=0.;
  118204. qA[l]=0.;
  118205. }
  118206. }
  118207. if(p->vi->normal_point_p){
  118208. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118209. int l=mag_sort[i][j+k];
  118210. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118211. qM[l]=unitnorm(qM[l]);
  118212. acc-=1.f;
  118213. }
  118214. }
  118215. }
  118216. }
  118217. }
  118218. }
  118219. }
  118220. /* AoTuV */
  118221. /** @ M2 **
  118222. The boost problem by the combination of noise normalization and point stereo is eased.
  118223. However, this is a temporary patch.
  118224. by Aoyumi @ 2004/04/18
  118225. */
  118226. void hf_reduction(vorbis_info_psy_global *g,
  118227. vorbis_look_psy *p,
  118228. vorbis_info_mapping0 *vi,
  118229. float **mdct){
  118230. int i,j,n=p->n, de=0.3*p->m_val;
  118231. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118232. for(i=0; i<vi->coupling_steps; i++){
  118233. /* for(j=start; j<limit; j++){} // ???*/
  118234. for(j=limit; j<n; j++)
  118235. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118236. }
  118237. }
  118238. #endif
  118239. /*** End of inlined file: psy.c ***/
  118240. /*** Start of inlined file: registry.c ***/
  118241. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118242. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118243. // tasks..
  118244. #if JUCE_MSVC
  118245. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118246. #endif
  118247. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118248. #if JUCE_USE_OGGVORBIS
  118249. /* seems like major overkill now; the backend numbers will grow into
  118250. the infrastructure soon enough */
  118251. extern vorbis_func_floor floor0_exportbundle;
  118252. extern vorbis_func_floor floor1_exportbundle;
  118253. extern vorbis_func_residue residue0_exportbundle;
  118254. extern vorbis_func_residue residue1_exportbundle;
  118255. extern vorbis_func_residue residue2_exportbundle;
  118256. extern vorbis_func_mapping mapping0_exportbundle;
  118257. vorbis_func_floor *_floor_P[]={
  118258. &floor0_exportbundle,
  118259. &floor1_exportbundle,
  118260. };
  118261. vorbis_func_residue *_residue_P[]={
  118262. &residue0_exportbundle,
  118263. &residue1_exportbundle,
  118264. &residue2_exportbundle,
  118265. };
  118266. vorbis_func_mapping *_mapping_P[]={
  118267. &mapping0_exportbundle,
  118268. };
  118269. #endif
  118270. /*** End of inlined file: registry.c ***/
  118271. /*** Start of inlined file: res0.c ***/
  118272. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118273. encode/decode loops are coded for clarity and performance is not
  118274. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118275. it's slow. */
  118276. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118277. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118278. // tasks..
  118279. #if JUCE_MSVC
  118280. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118281. #endif
  118282. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118283. #if JUCE_USE_OGGVORBIS
  118284. #include <stdlib.h>
  118285. #include <string.h>
  118286. #include <math.h>
  118287. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118288. #include <stdio.h>
  118289. #endif
  118290. typedef struct {
  118291. vorbis_info_residue0 *info;
  118292. int parts;
  118293. int stages;
  118294. codebook *fullbooks;
  118295. codebook *phrasebook;
  118296. codebook ***partbooks;
  118297. int partvals;
  118298. int **decodemap;
  118299. long postbits;
  118300. long phrasebits;
  118301. long frames;
  118302. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118303. int train_seq;
  118304. long *training_data[8][64];
  118305. float training_max[8][64];
  118306. float training_min[8][64];
  118307. float tmin;
  118308. float tmax;
  118309. #endif
  118310. } vorbis_look_residue0;
  118311. void res0_free_info(vorbis_info_residue *i){
  118312. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118313. if(info){
  118314. memset(info,0,sizeof(*info));
  118315. _ogg_free(info);
  118316. }
  118317. }
  118318. void res0_free_look(vorbis_look_residue *i){
  118319. int j;
  118320. if(i){
  118321. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118322. #ifdef TRAIN_RES
  118323. {
  118324. int j,k,l;
  118325. for(j=0;j<look->parts;j++){
  118326. /*fprintf(stderr,"partition %d: ",j);*/
  118327. for(k=0;k<8;k++)
  118328. if(look->training_data[k][j]){
  118329. char buffer[80];
  118330. FILE *of;
  118331. codebook *statebook=look->partbooks[j][k];
  118332. /* long and short into the same bucket by current convention */
  118333. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118334. of=fopen(buffer,"a");
  118335. for(l=0;l<statebook->entries;l++)
  118336. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118337. fclose(of);
  118338. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118339. look->training_min[k][j],look->training_max[k][j]);*/
  118340. _ogg_free(look->training_data[k][j]);
  118341. look->training_data[k][j]=NULL;
  118342. }
  118343. /*fprintf(stderr,"\n");*/
  118344. }
  118345. }
  118346. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118347. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118348. (float)look->phrasebits/look->frames,
  118349. (float)look->postbits/look->frames,
  118350. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118351. #endif
  118352. /*vorbis_info_residue0 *info=look->info;
  118353. fprintf(stderr,
  118354. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118355. "(%g/frame) \n",look->frames,look->phrasebits,
  118356. look->resbitsflat,
  118357. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118358. for(j=0;j<look->parts;j++){
  118359. long acc=0;
  118360. fprintf(stderr,"\t[%d] == ",j);
  118361. for(k=0;k<look->stages;k++)
  118362. if((info->secondstages[j]>>k)&1){
  118363. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118364. acc+=look->resbits[j][k];
  118365. }
  118366. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118367. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118368. }
  118369. fprintf(stderr,"\n");*/
  118370. for(j=0;j<look->parts;j++)
  118371. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118372. _ogg_free(look->partbooks);
  118373. for(j=0;j<look->partvals;j++)
  118374. _ogg_free(look->decodemap[j]);
  118375. _ogg_free(look->decodemap);
  118376. memset(look,0,sizeof(*look));
  118377. _ogg_free(look);
  118378. }
  118379. }
  118380. static int icount(unsigned int v){
  118381. int ret=0;
  118382. while(v){
  118383. ret+=v&1;
  118384. v>>=1;
  118385. }
  118386. return(ret);
  118387. }
  118388. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118389. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118390. int j,acc=0;
  118391. oggpack_write(opb,info->begin,24);
  118392. oggpack_write(opb,info->end,24);
  118393. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118394. code with a partitioned book */
  118395. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118396. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118397. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118398. bitmask of one indicates this partition class has bits to write
  118399. this pass */
  118400. for(j=0;j<info->partitions;j++){
  118401. if(ilog(info->secondstages[j])>3){
  118402. /* yes, this is a minor hack due to not thinking ahead */
  118403. oggpack_write(opb,info->secondstages[j],3);
  118404. oggpack_write(opb,1,1);
  118405. oggpack_write(opb,info->secondstages[j]>>3,5);
  118406. }else
  118407. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118408. acc+=icount(info->secondstages[j]);
  118409. }
  118410. for(j=0;j<acc;j++)
  118411. oggpack_write(opb,info->booklist[j],8);
  118412. }
  118413. /* vorbis_info is for range checking */
  118414. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118415. int j,acc=0;
  118416. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118417. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118418. info->begin=oggpack_read(opb,24);
  118419. info->end=oggpack_read(opb,24);
  118420. info->grouping=oggpack_read(opb,24)+1;
  118421. info->partitions=oggpack_read(opb,6)+1;
  118422. info->groupbook=oggpack_read(opb,8);
  118423. for(j=0;j<info->partitions;j++){
  118424. int cascade=oggpack_read(opb,3);
  118425. if(oggpack_read(opb,1))
  118426. cascade|=(oggpack_read(opb,5)<<3);
  118427. info->secondstages[j]=cascade;
  118428. acc+=icount(cascade);
  118429. }
  118430. for(j=0;j<acc;j++)
  118431. info->booklist[j]=oggpack_read(opb,8);
  118432. if(info->groupbook>=ci->books)goto errout;
  118433. for(j=0;j<acc;j++)
  118434. if(info->booklist[j]>=ci->books)goto errout;
  118435. return(info);
  118436. errout:
  118437. res0_free_info(info);
  118438. return(NULL);
  118439. }
  118440. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118441. vorbis_info_residue *vr){
  118442. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118443. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118444. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118445. int j,k,acc=0;
  118446. int dim;
  118447. int maxstage=0;
  118448. look->info=info;
  118449. look->parts=info->partitions;
  118450. look->fullbooks=ci->fullbooks;
  118451. look->phrasebook=ci->fullbooks+info->groupbook;
  118452. dim=look->phrasebook->dim;
  118453. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118454. for(j=0;j<look->parts;j++){
  118455. int stages=ilog(info->secondstages[j]);
  118456. if(stages){
  118457. if(stages>maxstage)maxstage=stages;
  118458. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118459. for(k=0;k<stages;k++)
  118460. if(info->secondstages[j]&(1<<k)){
  118461. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118462. #ifdef TRAIN_RES
  118463. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118464. sizeof(***look->training_data));
  118465. #endif
  118466. }
  118467. }
  118468. }
  118469. look->partvals=rint(pow((float)look->parts,(float)dim));
  118470. look->stages=maxstage;
  118471. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118472. for(j=0;j<look->partvals;j++){
  118473. long val=j;
  118474. long mult=look->partvals/look->parts;
  118475. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118476. for(k=0;k<dim;k++){
  118477. long deco=val/mult;
  118478. val-=deco*mult;
  118479. mult/=look->parts;
  118480. look->decodemap[j][k]=deco;
  118481. }
  118482. }
  118483. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118484. {
  118485. static int train_seq=0;
  118486. look->train_seq=train_seq++;
  118487. }
  118488. #endif
  118489. return(look);
  118490. }
  118491. /* break an abstraction and copy some code for performance purposes */
  118492. static int local_book_besterror(codebook *book,float *a){
  118493. int dim=book->dim,i,k,o;
  118494. int best=0;
  118495. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118496. /* find the quant val of each scalar */
  118497. for(k=0,o=dim;k<dim;++k){
  118498. float val=a[--o];
  118499. i=tt->threshvals>>1;
  118500. if(val<tt->quantthresh[i]){
  118501. if(val<tt->quantthresh[i-1]){
  118502. for(--i;i>0;--i)
  118503. if(val>=tt->quantthresh[i-1])
  118504. break;
  118505. }
  118506. }else{
  118507. for(++i;i<tt->threshvals-1;++i)
  118508. if(val<tt->quantthresh[i])break;
  118509. }
  118510. best=(best*tt->quantvals)+tt->quantmap[i];
  118511. }
  118512. /* regular lattices are easy :-) */
  118513. if(book->c->lengthlist[best]<=0){
  118514. const static_codebook *c=book->c;
  118515. int i,j;
  118516. float bestf=0.f;
  118517. float *e=book->valuelist;
  118518. best=-1;
  118519. for(i=0;i<book->entries;i++){
  118520. if(c->lengthlist[i]>0){
  118521. float thisx=0.f;
  118522. for(j=0;j<dim;j++){
  118523. float val=(e[j]-a[j]);
  118524. thisx+=val*val;
  118525. }
  118526. if(best==-1 || thisx<bestf){
  118527. bestf=thisx;
  118528. best=i;
  118529. }
  118530. }
  118531. e+=dim;
  118532. }
  118533. }
  118534. {
  118535. float *ptr=book->valuelist+best*dim;
  118536. for(i=0;i<dim;i++)
  118537. *a++ -= *ptr++;
  118538. }
  118539. return(best);
  118540. }
  118541. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118542. codebook *book,long *acc){
  118543. int i,bits=0;
  118544. int dim=book->dim;
  118545. int step=n/dim;
  118546. for(i=0;i<step;i++){
  118547. int entry=local_book_besterror(book,vec+i*dim);
  118548. #ifdef TRAIN_RES
  118549. acc[entry]++;
  118550. #endif
  118551. bits+=vorbis_book_encode(book,entry,opb);
  118552. }
  118553. return(bits);
  118554. }
  118555. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118556. float **in,int ch){
  118557. long i,j,k;
  118558. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118559. vorbis_info_residue0 *info=look->info;
  118560. /* move all this setup out later */
  118561. int samples_per_partition=info->grouping;
  118562. int possible_partitions=info->partitions;
  118563. int n=info->end-info->begin;
  118564. int partvals=n/samples_per_partition;
  118565. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118566. float scale=100./samples_per_partition;
  118567. /* we find the partition type for each partition of each
  118568. channel. We'll go back and do the interleaved encoding in a
  118569. bit. For now, clarity */
  118570. for(i=0;i<ch;i++){
  118571. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118572. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118573. }
  118574. for(i=0;i<partvals;i++){
  118575. int offset=i*samples_per_partition+info->begin;
  118576. for(j=0;j<ch;j++){
  118577. float max=0.;
  118578. float ent=0.;
  118579. for(k=0;k<samples_per_partition;k++){
  118580. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118581. ent+=fabs(rint(in[j][offset+k]));
  118582. }
  118583. ent*=scale;
  118584. for(k=0;k<possible_partitions-1;k++)
  118585. if(max<=info->classmetric1[k] &&
  118586. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118587. break;
  118588. partword[j][i]=k;
  118589. }
  118590. }
  118591. #ifdef TRAIN_RESAUX
  118592. {
  118593. FILE *of;
  118594. char buffer[80];
  118595. for(i=0;i<ch;i++){
  118596. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118597. of=fopen(buffer,"a");
  118598. for(j=0;j<partvals;j++)
  118599. fprintf(of,"%ld, ",partword[i][j]);
  118600. fprintf(of,"\n");
  118601. fclose(of);
  118602. }
  118603. }
  118604. #endif
  118605. look->frames++;
  118606. return(partword);
  118607. }
  118608. /* designed for stereo or other modes where the partition size is an
  118609. integer multiple of the number of channels encoded in the current
  118610. submap */
  118611. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118612. int ch){
  118613. long i,j,k,l;
  118614. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118615. vorbis_info_residue0 *info=look->info;
  118616. /* move all this setup out later */
  118617. int samples_per_partition=info->grouping;
  118618. int possible_partitions=info->partitions;
  118619. int n=info->end-info->begin;
  118620. int partvals=n/samples_per_partition;
  118621. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118622. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118623. FILE *of;
  118624. char buffer[80];
  118625. #endif
  118626. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118627. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118628. for(i=0,l=info->begin/ch;i<partvals;i++){
  118629. float magmax=0.f;
  118630. float angmax=0.f;
  118631. for(j=0;j<samples_per_partition;j+=ch){
  118632. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118633. for(k=1;k<ch;k++)
  118634. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118635. l++;
  118636. }
  118637. for(j=0;j<possible_partitions-1;j++)
  118638. if(magmax<=info->classmetric1[j] &&
  118639. angmax<=info->classmetric2[j])
  118640. break;
  118641. partword[0][i]=j;
  118642. }
  118643. #ifdef TRAIN_RESAUX
  118644. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118645. of=fopen(buffer,"a");
  118646. for(i=0;i<partvals;i++)
  118647. fprintf(of,"%ld, ",partword[0][i]);
  118648. fprintf(of,"\n");
  118649. fclose(of);
  118650. #endif
  118651. look->frames++;
  118652. return(partword);
  118653. }
  118654. static int _01forward(oggpack_buffer *opb,
  118655. vorbis_block *vb,vorbis_look_residue *vl,
  118656. float **in,int ch,
  118657. long **partword,
  118658. int (*encode)(oggpack_buffer *,float *,int,
  118659. codebook *,long *)){
  118660. long i,j,k,s;
  118661. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118662. vorbis_info_residue0 *info=look->info;
  118663. /* move all this setup out later */
  118664. int samples_per_partition=info->grouping;
  118665. int possible_partitions=info->partitions;
  118666. int partitions_per_word=look->phrasebook->dim;
  118667. int n=info->end-info->begin;
  118668. int partvals=n/samples_per_partition;
  118669. long resbits[128];
  118670. long resvals[128];
  118671. #ifdef TRAIN_RES
  118672. for(i=0;i<ch;i++)
  118673. for(j=info->begin;j<info->end;j++){
  118674. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118675. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118676. }
  118677. #endif
  118678. memset(resbits,0,sizeof(resbits));
  118679. memset(resvals,0,sizeof(resvals));
  118680. /* we code the partition words for each channel, then the residual
  118681. words for a partition per channel until we've written all the
  118682. residual words for that partition word. Then write the next
  118683. partition channel words... */
  118684. for(s=0;s<look->stages;s++){
  118685. for(i=0;i<partvals;){
  118686. /* first we encode a partition codeword for each channel */
  118687. if(s==0){
  118688. for(j=0;j<ch;j++){
  118689. long val=partword[j][i];
  118690. for(k=1;k<partitions_per_word;k++){
  118691. val*=possible_partitions;
  118692. if(i+k<partvals)
  118693. val+=partword[j][i+k];
  118694. }
  118695. /* training hack */
  118696. if(val<look->phrasebook->entries)
  118697. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118698. #if 0 /*def TRAIN_RES*/
  118699. else
  118700. fprintf(stderr,"!");
  118701. #endif
  118702. }
  118703. }
  118704. /* now we encode interleaved residual values for the partitions */
  118705. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118706. long offset=i*samples_per_partition+info->begin;
  118707. for(j=0;j<ch;j++){
  118708. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118709. if(info->secondstages[partword[j][i]]&(1<<s)){
  118710. codebook *statebook=look->partbooks[partword[j][i]][s];
  118711. if(statebook){
  118712. int ret;
  118713. long *accumulator=NULL;
  118714. #ifdef TRAIN_RES
  118715. accumulator=look->training_data[s][partword[j][i]];
  118716. {
  118717. int l;
  118718. float *samples=in[j]+offset;
  118719. for(l=0;l<samples_per_partition;l++){
  118720. if(samples[l]<look->training_min[s][partword[j][i]])
  118721. look->training_min[s][partword[j][i]]=samples[l];
  118722. if(samples[l]>look->training_max[s][partword[j][i]])
  118723. look->training_max[s][partword[j][i]]=samples[l];
  118724. }
  118725. }
  118726. #endif
  118727. ret=encode(opb,in[j]+offset,samples_per_partition,
  118728. statebook,accumulator);
  118729. look->postbits+=ret;
  118730. resbits[partword[j][i]]+=ret;
  118731. }
  118732. }
  118733. }
  118734. }
  118735. }
  118736. }
  118737. /*{
  118738. long total=0;
  118739. long totalbits=0;
  118740. fprintf(stderr,"%d :: ",vb->mode);
  118741. for(k=0;k<possible_partitions;k++){
  118742. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118743. total+=resvals[k];
  118744. totalbits+=resbits[k];
  118745. }
  118746. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118747. }*/
  118748. return(0);
  118749. }
  118750. /* a truncated packet here just means 'stop working'; it's not an error */
  118751. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118752. float **in,int ch,
  118753. long (*decodepart)(codebook *, float *,
  118754. oggpack_buffer *,int)){
  118755. long i,j,k,l,s;
  118756. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118757. vorbis_info_residue0 *info=look->info;
  118758. /* move all this setup out later */
  118759. int samples_per_partition=info->grouping;
  118760. int partitions_per_word=look->phrasebook->dim;
  118761. int n=info->end-info->begin;
  118762. int partvals=n/samples_per_partition;
  118763. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118764. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118765. for(j=0;j<ch;j++)
  118766. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118767. for(s=0;s<look->stages;s++){
  118768. /* each loop decodes on partition codeword containing
  118769. partitions_pre_word partitions */
  118770. for(i=0,l=0;i<partvals;l++){
  118771. if(s==0){
  118772. /* fetch the partition word for each channel */
  118773. for(j=0;j<ch;j++){
  118774. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118775. if(temp==-1)goto eopbreak;
  118776. partword[j][l]=look->decodemap[temp];
  118777. if(partword[j][l]==NULL)goto errout;
  118778. }
  118779. }
  118780. /* now we decode residual values for the partitions */
  118781. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118782. for(j=0;j<ch;j++){
  118783. long offset=info->begin+i*samples_per_partition;
  118784. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118785. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118786. if(stagebook){
  118787. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118788. samples_per_partition)==-1)goto eopbreak;
  118789. }
  118790. }
  118791. }
  118792. }
  118793. }
  118794. errout:
  118795. eopbreak:
  118796. return(0);
  118797. }
  118798. #if 0
  118799. /* residue 0 and 1 are just slight variants of one another. 0 is
  118800. interleaved, 1 is not */
  118801. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118802. float **in,int *nonzero,int ch){
  118803. /* we encode only the nonzero parts of a bundle */
  118804. int i,used=0;
  118805. for(i=0;i<ch;i++)
  118806. if(nonzero[i])
  118807. in[used++]=in[i];
  118808. if(used)
  118809. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118810. return(_01class(vb,vl,in,used));
  118811. else
  118812. return(0);
  118813. }
  118814. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118815. float **in,float **out,int *nonzero,int ch,
  118816. long **partword){
  118817. /* we encode only the nonzero parts of a bundle */
  118818. int i,j,used=0,n=vb->pcmend/2;
  118819. for(i=0;i<ch;i++)
  118820. if(nonzero[i]){
  118821. if(out)
  118822. for(j=0;j<n;j++)
  118823. out[i][j]+=in[i][j];
  118824. in[used++]=in[i];
  118825. }
  118826. if(used){
  118827. int ret=_01forward(vb,vl,in,used,partword,
  118828. _interleaved_encodepart);
  118829. if(out){
  118830. used=0;
  118831. for(i=0;i<ch;i++)
  118832. if(nonzero[i]){
  118833. for(j=0;j<n;j++)
  118834. out[i][j]-=in[used][j];
  118835. used++;
  118836. }
  118837. }
  118838. return(ret);
  118839. }else{
  118840. return(0);
  118841. }
  118842. }
  118843. #endif
  118844. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118845. float **in,int *nonzero,int ch){
  118846. int i,used=0;
  118847. for(i=0;i<ch;i++)
  118848. if(nonzero[i])
  118849. in[used++]=in[i];
  118850. if(used)
  118851. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118852. else
  118853. return(0);
  118854. }
  118855. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118856. float **in,float **out,int *nonzero,int ch,
  118857. long **partword){
  118858. int i,j,used=0,n=vb->pcmend/2;
  118859. for(i=0;i<ch;i++)
  118860. if(nonzero[i]){
  118861. if(out)
  118862. for(j=0;j<n;j++)
  118863. out[i][j]+=in[i][j];
  118864. in[used++]=in[i];
  118865. }
  118866. if(used){
  118867. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118868. if(out){
  118869. used=0;
  118870. for(i=0;i<ch;i++)
  118871. if(nonzero[i]){
  118872. for(j=0;j<n;j++)
  118873. out[i][j]-=in[used][j];
  118874. used++;
  118875. }
  118876. }
  118877. return(ret);
  118878. }else{
  118879. return(0);
  118880. }
  118881. }
  118882. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118883. float **in,int *nonzero,int ch){
  118884. int i,used=0;
  118885. for(i=0;i<ch;i++)
  118886. if(nonzero[i])
  118887. in[used++]=in[i];
  118888. if(used)
  118889. return(_01class(vb,vl,in,used));
  118890. else
  118891. return(0);
  118892. }
  118893. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118894. float **in,int *nonzero,int ch){
  118895. int i,used=0;
  118896. for(i=0;i<ch;i++)
  118897. if(nonzero[i])
  118898. in[used++]=in[i];
  118899. if(used)
  118900. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118901. else
  118902. return(0);
  118903. }
  118904. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118905. float **in,int *nonzero,int ch){
  118906. int i,used=0;
  118907. for(i=0;i<ch;i++)
  118908. if(nonzero[i])used++;
  118909. if(used)
  118910. return(_2class(vb,vl,in,ch));
  118911. else
  118912. return(0);
  118913. }
  118914. /* res2 is slightly more different; all the channels are interleaved
  118915. into a single vector and encoded. */
  118916. int res2_forward(oggpack_buffer *opb,
  118917. vorbis_block *vb,vorbis_look_residue *vl,
  118918. float **in,float **out,int *nonzero,int ch,
  118919. long **partword){
  118920. long i,j,k,n=vb->pcmend/2,used=0;
  118921. /* don't duplicate the code; use a working vector hack for now and
  118922. reshape ourselves into a single channel res1 */
  118923. /* ugly; reallocs for each coupling pass :-( */
  118924. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118925. for(i=0;i<ch;i++){
  118926. float *pcm=in[i];
  118927. if(nonzero[i])used++;
  118928. for(j=0,k=i;j<n;j++,k+=ch)
  118929. work[k]=pcm[j];
  118930. }
  118931. if(used){
  118932. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118933. /* update the sofar vector */
  118934. if(out){
  118935. for(i=0;i<ch;i++){
  118936. float *pcm=in[i];
  118937. float *sofar=out[i];
  118938. for(j=0,k=i;j<n;j++,k+=ch)
  118939. sofar[j]+=pcm[j]-work[k];
  118940. }
  118941. }
  118942. return(ret);
  118943. }else{
  118944. return(0);
  118945. }
  118946. }
  118947. /* duplicate code here as speed is somewhat more important */
  118948. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118949. float **in,int *nonzero,int ch){
  118950. long i,k,l,s;
  118951. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118952. vorbis_info_residue0 *info=look->info;
  118953. /* move all this setup out later */
  118954. int samples_per_partition=info->grouping;
  118955. int partitions_per_word=look->phrasebook->dim;
  118956. int n=info->end-info->begin;
  118957. int partvals=n/samples_per_partition;
  118958. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118959. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118960. for(i=0;i<ch;i++)if(nonzero[i])break;
  118961. if(i==ch)return(0); /* no nonzero vectors */
  118962. for(s=0;s<look->stages;s++){
  118963. for(i=0,l=0;i<partvals;l++){
  118964. if(s==0){
  118965. /* fetch the partition word */
  118966. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118967. if(temp==-1)goto eopbreak;
  118968. partword[l]=look->decodemap[temp];
  118969. if(partword[l]==NULL)goto errout;
  118970. }
  118971. /* now we decode residual values for the partitions */
  118972. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118973. if(info->secondstages[partword[l][k]]&(1<<s)){
  118974. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118975. if(stagebook){
  118976. if(vorbis_book_decodevv_add(stagebook,in,
  118977. i*samples_per_partition+info->begin,ch,
  118978. &vb->opb,samples_per_partition)==-1)
  118979. goto eopbreak;
  118980. }
  118981. }
  118982. }
  118983. }
  118984. errout:
  118985. eopbreak:
  118986. return(0);
  118987. }
  118988. vorbis_func_residue residue0_exportbundle={
  118989. NULL,
  118990. &res0_unpack,
  118991. &res0_look,
  118992. &res0_free_info,
  118993. &res0_free_look,
  118994. NULL,
  118995. NULL,
  118996. &res0_inverse
  118997. };
  118998. vorbis_func_residue residue1_exportbundle={
  118999. &res0_pack,
  119000. &res0_unpack,
  119001. &res0_look,
  119002. &res0_free_info,
  119003. &res0_free_look,
  119004. &res1_class,
  119005. &res1_forward,
  119006. &res1_inverse
  119007. };
  119008. vorbis_func_residue residue2_exportbundle={
  119009. &res0_pack,
  119010. &res0_unpack,
  119011. &res0_look,
  119012. &res0_free_info,
  119013. &res0_free_look,
  119014. &res2_class,
  119015. &res2_forward,
  119016. &res2_inverse
  119017. };
  119018. #endif
  119019. /*** End of inlined file: res0.c ***/
  119020. /*** Start of inlined file: sharedbook.c ***/
  119021. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119022. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119023. // tasks..
  119024. #if JUCE_MSVC
  119025. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119026. #endif
  119027. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119028. #if JUCE_USE_OGGVORBIS
  119029. #include <stdlib.h>
  119030. #include <math.h>
  119031. #include <string.h>
  119032. /**** pack/unpack helpers ******************************************/
  119033. int _ilog(unsigned int v){
  119034. int ret=0;
  119035. while(v){
  119036. ret++;
  119037. v>>=1;
  119038. }
  119039. return(ret);
  119040. }
  119041. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119042. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119043. Why not IEEE? It's just not that important here. */
  119044. #define VQ_FEXP 10
  119045. #define VQ_FMAN 21
  119046. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119047. /* doesn't currently guard under/overflow */
  119048. long _float32_pack(float val){
  119049. int sign=0;
  119050. long exp;
  119051. long mant;
  119052. if(val<0){
  119053. sign=0x80000000;
  119054. val= -val;
  119055. }
  119056. exp= floor(log(val)/log(2.f));
  119057. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119058. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119059. return(sign|exp|mant);
  119060. }
  119061. float _float32_unpack(long val){
  119062. double mant=val&0x1fffff;
  119063. int sign=val&0x80000000;
  119064. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119065. if(sign)mant= -mant;
  119066. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119067. }
  119068. /* given a list of word lengths, generate a list of codewords. Works
  119069. for length ordered or unordered, always assigns the lowest valued
  119070. codewords first. Extended to handle unused entries (length 0) */
  119071. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119072. long i,j,count=0;
  119073. ogg_uint32_t marker[33];
  119074. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119075. memset(marker,0,sizeof(marker));
  119076. for(i=0;i<n;i++){
  119077. long length=l[i];
  119078. if(length>0){
  119079. ogg_uint32_t entry=marker[length];
  119080. /* when we claim a node for an entry, we also claim the nodes
  119081. below it (pruning off the imagined tree that may have dangled
  119082. from it) as well as blocking the use of any nodes directly
  119083. above for leaves */
  119084. /* update ourself */
  119085. if(length<32 && (entry>>length)){
  119086. /* error condition; the lengths must specify an overpopulated tree */
  119087. _ogg_free(r);
  119088. return(NULL);
  119089. }
  119090. r[count++]=entry;
  119091. /* Look to see if the next shorter marker points to the node
  119092. above. if so, update it and repeat. */
  119093. {
  119094. for(j=length;j>0;j--){
  119095. if(marker[j]&1){
  119096. /* have to jump branches */
  119097. if(j==1)
  119098. marker[1]++;
  119099. else
  119100. marker[j]=marker[j-1]<<1;
  119101. break; /* invariant says next upper marker would already
  119102. have been moved if it was on the same path */
  119103. }
  119104. marker[j]++;
  119105. }
  119106. }
  119107. /* prune the tree; the implicit invariant says all the longer
  119108. markers were dangling from our just-taken node. Dangle them
  119109. from our *new* node. */
  119110. for(j=length+1;j<33;j++)
  119111. if((marker[j]>>1) == entry){
  119112. entry=marker[j];
  119113. marker[j]=marker[j-1]<<1;
  119114. }else
  119115. break;
  119116. }else
  119117. if(sparsecount==0)count++;
  119118. }
  119119. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119120. endian */
  119121. for(i=0,count=0;i<n;i++){
  119122. ogg_uint32_t temp=0;
  119123. for(j=0;j<l[i];j++){
  119124. temp<<=1;
  119125. temp|=(r[count]>>j)&1;
  119126. }
  119127. if(sparsecount){
  119128. if(l[i])
  119129. r[count++]=temp;
  119130. }else
  119131. r[count++]=temp;
  119132. }
  119133. return(r);
  119134. }
  119135. /* there might be a straightforward one-line way to do the below
  119136. that's portable and totally safe against roundoff, but I haven't
  119137. thought of it. Therefore, we opt on the side of caution */
  119138. long _book_maptype1_quantvals(const static_codebook *b){
  119139. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119140. /* the above *should* be reliable, but we'll not assume that FP is
  119141. ever reliable when bitstream sync is at stake; verify via integer
  119142. means that vals really is the greatest value of dim for which
  119143. vals^b->bim <= b->entries */
  119144. /* treat the above as an initial guess */
  119145. while(1){
  119146. long acc=1;
  119147. long acc1=1;
  119148. int i;
  119149. for(i=0;i<b->dim;i++){
  119150. acc*=vals;
  119151. acc1*=vals+1;
  119152. }
  119153. if(acc<=b->entries && acc1>b->entries){
  119154. return(vals);
  119155. }else{
  119156. if(acc>b->entries){
  119157. vals--;
  119158. }else{
  119159. vals++;
  119160. }
  119161. }
  119162. }
  119163. }
  119164. /* unpack the quantized list of values for encode/decode ***********/
  119165. /* we need to deal with two map types: in map type 1, the values are
  119166. generated algorithmically (each column of the vector counts through
  119167. the values in the quant vector). in map type 2, all the values came
  119168. in in an explicit list. Both value lists must be unpacked */
  119169. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119170. long j,k,count=0;
  119171. if(b->maptype==1 || b->maptype==2){
  119172. int quantvals;
  119173. float mindel=_float32_unpack(b->q_min);
  119174. float delta=_float32_unpack(b->q_delta);
  119175. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119176. /* maptype 1 and 2 both use a quantized value vector, but
  119177. different sizes */
  119178. switch(b->maptype){
  119179. case 1:
  119180. /* most of the time, entries%dimensions == 0, but we need to be
  119181. well defined. We define that the possible vales at each
  119182. scalar is values == entries/dim. If entries%dim != 0, we'll
  119183. have 'too few' values (values*dim<entries), which means that
  119184. we'll have 'left over' entries; left over entries use zeroed
  119185. values (and are wasted). So don't generate codebooks like
  119186. that */
  119187. quantvals=_book_maptype1_quantvals(b);
  119188. for(j=0;j<b->entries;j++){
  119189. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119190. float last=0.f;
  119191. int indexdiv=1;
  119192. for(k=0;k<b->dim;k++){
  119193. int index= (j/indexdiv)%quantvals;
  119194. float val=b->quantlist[index];
  119195. val=fabs(val)*delta+mindel+last;
  119196. if(b->q_sequencep)last=val;
  119197. if(sparsemap)
  119198. r[sparsemap[count]*b->dim+k]=val;
  119199. else
  119200. r[count*b->dim+k]=val;
  119201. indexdiv*=quantvals;
  119202. }
  119203. count++;
  119204. }
  119205. }
  119206. break;
  119207. case 2:
  119208. for(j=0;j<b->entries;j++){
  119209. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119210. float last=0.f;
  119211. for(k=0;k<b->dim;k++){
  119212. float val=b->quantlist[j*b->dim+k];
  119213. val=fabs(val)*delta+mindel+last;
  119214. if(b->q_sequencep)last=val;
  119215. if(sparsemap)
  119216. r[sparsemap[count]*b->dim+k]=val;
  119217. else
  119218. r[count*b->dim+k]=val;
  119219. }
  119220. count++;
  119221. }
  119222. }
  119223. break;
  119224. }
  119225. return(r);
  119226. }
  119227. return(NULL);
  119228. }
  119229. void vorbis_staticbook_clear(static_codebook *b){
  119230. if(b->allocedp){
  119231. if(b->quantlist)_ogg_free(b->quantlist);
  119232. if(b->lengthlist)_ogg_free(b->lengthlist);
  119233. if(b->nearest_tree){
  119234. _ogg_free(b->nearest_tree->ptr0);
  119235. _ogg_free(b->nearest_tree->ptr1);
  119236. _ogg_free(b->nearest_tree->p);
  119237. _ogg_free(b->nearest_tree->q);
  119238. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119239. _ogg_free(b->nearest_tree);
  119240. }
  119241. if(b->thresh_tree){
  119242. _ogg_free(b->thresh_tree->quantthresh);
  119243. _ogg_free(b->thresh_tree->quantmap);
  119244. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119245. _ogg_free(b->thresh_tree);
  119246. }
  119247. memset(b,0,sizeof(*b));
  119248. }
  119249. }
  119250. void vorbis_staticbook_destroy(static_codebook *b){
  119251. if(b->allocedp){
  119252. vorbis_staticbook_clear(b);
  119253. _ogg_free(b);
  119254. }
  119255. }
  119256. void vorbis_book_clear(codebook *b){
  119257. /* static book is not cleared; we're likely called on the lookup and
  119258. the static codebook belongs to the info struct */
  119259. if(b->valuelist)_ogg_free(b->valuelist);
  119260. if(b->codelist)_ogg_free(b->codelist);
  119261. if(b->dec_index)_ogg_free(b->dec_index);
  119262. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119263. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119264. memset(b,0,sizeof(*b));
  119265. }
  119266. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119267. memset(c,0,sizeof(*c));
  119268. c->c=s;
  119269. c->entries=s->entries;
  119270. c->used_entries=s->entries;
  119271. c->dim=s->dim;
  119272. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119273. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119274. return(0);
  119275. }
  119276. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119277. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119278. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119279. }
  119280. /* decode codebook arrangement is more heavily optimized than encode */
  119281. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119282. int i,j,n=0,tabn;
  119283. int *sortindex;
  119284. memset(c,0,sizeof(*c));
  119285. /* count actually used entries */
  119286. for(i=0;i<s->entries;i++)
  119287. if(s->lengthlist[i]>0)
  119288. n++;
  119289. c->entries=s->entries;
  119290. c->used_entries=n;
  119291. c->dim=s->dim;
  119292. /* two different remappings go on here.
  119293. First, we collapse the likely sparse codebook down only to
  119294. actually represented values/words. This collapsing needs to be
  119295. indexed as map-valueless books are used to encode original entry
  119296. positions as integers.
  119297. Second, we reorder all vectors, including the entry index above,
  119298. by sorted bitreversed codeword to allow treeless decode. */
  119299. {
  119300. /* perform sort */
  119301. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119302. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119303. if(codes==NULL)goto err_out;
  119304. for(i=0;i<n;i++){
  119305. codes[i]=ogg_bitreverse(codes[i]);
  119306. codep[i]=codes+i;
  119307. }
  119308. qsort(codep,n,sizeof(*codep),sort32a);
  119309. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119310. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119311. /* the index is a reverse index */
  119312. for(i=0;i<n;i++){
  119313. int position=codep[i]-codes;
  119314. sortindex[position]=i;
  119315. }
  119316. for(i=0;i<n;i++)
  119317. c->codelist[sortindex[i]]=codes[i];
  119318. _ogg_free(codes);
  119319. }
  119320. c->valuelist=_book_unquantize(s,n,sortindex);
  119321. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119322. for(n=0,i=0;i<s->entries;i++)
  119323. if(s->lengthlist[i]>0)
  119324. c->dec_index[sortindex[n++]]=i;
  119325. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119326. for(n=0,i=0;i<s->entries;i++)
  119327. if(s->lengthlist[i]>0)
  119328. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119329. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119330. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119331. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119332. tabn=1<<c->dec_firsttablen;
  119333. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119334. c->dec_maxlength=0;
  119335. for(i=0;i<n;i++){
  119336. if(c->dec_maxlength<c->dec_codelengths[i])
  119337. c->dec_maxlength=c->dec_codelengths[i];
  119338. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119339. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119340. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119341. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119342. }
  119343. }
  119344. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119345. hints for the non-direct-hits */
  119346. {
  119347. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119348. long lo=0,hi=0;
  119349. for(i=0;i<tabn;i++){
  119350. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119351. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119352. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119353. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119354. /* we only actually have 15 bits per hint to play with here.
  119355. In order to overflow gracefully (nothing breaks, efficiency
  119356. just drops), encode as the difference from the extremes. */
  119357. {
  119358. unsigned long loval=lo;
  119359. unsigned long hival=n-hi;
  119360. if(loval>0x7fff)loval=0x7fff;
  119361. if(hival>0x7fff)hival=0x7fff;
  119362. c->dec_firsttable[ogg_bitreverse(word)]=
  119363. 0x80000000UL | (loval<<15) | hival;
  119364. }
  119365. }
  119366. }
  119367. }
  119368. return(0);
  119369. err_out:
  119370. vorbis_book_clear(c);
  119371. return(-1);
  119372. }
  119373. static float _dist(int el,float *ref, float *b,int step){
  119374. int i;
  119375. float acc=0.f;
  119376. for(i=0;i<el;i++){
  119377. float val=(ref[i]-b[i*step]);
  119378. acc+=val*val;
  119379. }
  119380. return(acc);
  119381. }
  119382. int _best(codebook *book, float *a, int step){
  119383. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119384. #if 0
  119385. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119386. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119387. #endif
  119388. int dim=book->dim;
  119389. int k,o;
  119390. /*int savebest=-1;
  119391. float saverr;*/
  119392. /* do we have a threshhold encode hint? */
  119393. if(tt){
  119394. int index=0,i;
  119395. /* find the quant val of each scalar */
  119396. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119397. i=tt->threshvals>>1;
  119398. if(a[o]<tt->quantthresh[i]){
  119399. for(;i>0;i--)
  119400. if(a[o]>=tt->quantthresh[i-1])
  119401. break;
  119402. }else{
  119403. for(i++;i<tt->threshvals-1;i++)
  119404. if(a[o]<tt->quantthresh[i])break;
  119405. }
  119406. index=(index*tt->quantvals)+tt->quantmap[i];
  119407. }
  119408. /* regular lattices are easy :-) */
  119409. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119410. use a decision tree after all
  119411. and fall through*/
  119412. return(index);
  119413. }
  119414. #if 0
  119415. /* do we have a pigeonhole encode hint? */
  119416. if(pt){
  119417. const static_codebook *c=book->c;
  119418. int i,besti=-1;
  119419. float best=0.f;
  119420. int entry=0;
  119421. /* dealing with sequentialness is a pain in the ass */
  119422. if(c->q_sequencep){
  119423. int pv;
  119424. long mul=1;
  119425. float qlast=0;
  119426. for(k=0,o=0;k<dim;k++,o+=step){
  119427. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119428. if(pv<0 || pv>=pt->mapentries)break;
  119429. entry+=pt->pigeonmap[pv]*mul;
  119430. mul*=pt->quantvals;
  119431. qlast+=pv*pt->del+pt->min;
  119432. }
  119433. }else{
  119434. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119435. int pv=(int)((a[o]-pt->min)/pt->del);
  119436. if(pv<0 || pv>=pt->mapentries)break;
  119437. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119438. }
  119439. }
  119440. /* must be within the pigeonholable range; if we quant outside (or
  119441. in an entry that we define no list for), brute force it */
  119442. if(k==dim && pt->fitlength[entry]){
  119443. /* search the abbreviated list */
  119444. long *list=pt->fitlist+pt->fitmap[entry];
  119445. for(i=0;i<pt->fitlength[entry];i++){
  119446. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119447. if(besti==-1 || this<best){
  119448. best=this;
  119449. besti=list[i];
  119450. }
  119451. }
  119452. return(besti);
  119453. }
  119454. }
  119455. if(nt){
  119456. /* optimized using the decision tree */
  119457. while(1){
  119458. float c=0.f;
  119459. float *p=book->valuelist+nt->p[ptr];
  119460. float *q=book->valuelist+nt->q[ptr];
  119461. for(k=0,o=0;k<dim;k++,o+=step)
  119462. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119463. if(c>0.f) /* in A */
  119464. ptr= -nt->ptr0[ptr];
  119465. else /* in B */
  119466. ptr= -nt->ptr1[ptr];
  119467. if(ptr<=0)break;
  119468. }
  119469. return(-ptr);
  119470. }
  119471. #endif
  119472. /* brute force it! */
  119473. {
  119474. const static_codebook *c=book->c;
  119475. int i,besti=-1;
  119476. float best=0.f;
  119477. float *e=book->valuelist;
  119478. for(i=0;i<book->entries;i++){
  119479. if(c->lengthlist[i]>0){
  119480. float thisx=_dist(dim,e,a,step);
  119481. if(besti==-1 || thisx<best){
  119482. best=thisx;
  119483. besti=i;
  119484. }
  119485. }
  119486. e+=dim;
  119487. }
  119488. /*if(savebest!=-1 && savebest!=besti){
  119489. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119490. "original:");
  119491. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119492. fprintf(stderr,"\n"
  119493. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119494. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119495. (book->valuelist+savebest*dim)[i]);
  119496. fprintf(stderr,"\n"
  119497. "bruteforce (entry %d, err %g):",besti,best);
  119498. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119499. (book->valuelist+besti*dim)[i]);
  119500. fprintf(stderr,"\n");
  119501. }*/
  119502. return(besti);
  119503. }
  119504. }
  119505. long vorbis_book_codeword(codebook *book,int entry){
  119506. if(book->c) /* only use with encode; decode optimizations are
  119507. allowed to break this */
  119508. return book->codelist[entry];
  119509. return -1;
  119510. }
  119511. long vorbis_book_codelen(codebook *book,int entry){
  119512. if(book->c) /* only use with encode; decode optimizations are
  119513. allowed to break this */
  119514. return book->c->lengthlist[entry];
  119515. return -1;
  119516. }
  119517. #ifdef _V_SELFTEST
  119518. /* Unit tests of the dequantizer; this stuff will be OK
  119519. cross-platform, I simply want to be sure that special mapping cases
  119520. actually work properly; a bug could go unnoticed for a while */
  119521. #include <stdio.h>
  119522. /* cases:
  119523. no mapping
  119524. full, explicit mapping
  119525. algorithmic mapping
  119526. nonsequential
  119527. sequential
  119528. */
  119529. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119530. static long partial_quantlist1[]={0,7,2};
  119531. /* no mapping */
  119532. static_codebook test1={
  119533. 4,16,
  119534. NULL,
  119535. 0,
  119536. 0,0,0,0,
  119537. NULL,
  119538. NULL,NULL
  119539. };
  119540. static float *test1_result=NULL;
  119541. /* linear, full mapping, nonsequential */
  119542. static_codebook test2={
  119543. 4,3,
  119544. NULL,
  119545. 2,
  119546. -533200896,1611661312,4,0,
  119547. full_quantlist1,
  119548. NULL,NULL
  119549. };
  119550. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119551. /* linear, full mapping, sequential */
  119552. static_codebook test3={
  119553. 4,3,
  119554. NULL,
  119555. 2,
  119556. -533200896,1611661312,4,1,
  119557. full_quantlist1,
  119558. NULL,NULL
  119559. };
  119560. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119561. /* linear, algorithmic mapping, nonsequential */
  119562. static_codebook test4={
  119563. 3,27,
  119564. NULL,
  119565. 1,
  119566. -533200896,1611661312,4,0,
  119567. partial_quantlist1,
  119568. NULL,NULL
  119569. };
  119570. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119571. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119572. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119573. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119574. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119575. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119576. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119577. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119578. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119579. /* linear, algorithmic mapping, sequential */
  119580. static_codebook test5={
  119581. 3,27,
  119582. NULL,
  119583. 1,
  119584. -533200896,1611661312,4,1,
  119585. partial_quantlist1,
  119586. NULL,NULL
  119587. };
  119588. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119589. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119590. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119591. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119592. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119593. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119594. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119595. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119596. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119597. void run_test(static_codebook *b,float *comp){
  119598. float *out=_book_unquantize(b,b->entries,NULL);
  119599. int i;
  119600. if(comp){
  119601. if(!out){
  119602. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119603. exit(1);
  119604. }
  119605. for(i=0;i<b->entries*b->dim;i++)
  119606. if(fabs(out[i]-comp[i])>.0001){
  119607. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119608. "position %d, %g != %g\n",i,out[i],comp[i]);
  119609. exit(1);
  119610. }
  119611. }else{
  119612. if(out){
  119613. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119614. " correct result should have been NULL\n");
  119615. exit(1);
  119616. }
  119617. }
  119618. }
  119619. int main(){
  119620. /* run the nine dequant tests, and compare to the hand-rolled results */
  119621. fprintf(stderr,"Dequant test 1... ");
  119622. run_test(&test1,test1_result);
  119623. fprintf(stderr,"OK\nDequant test 2... ");
  119624. run_test(&test2,test2_result);
  119625. fprintf(stderr,"OK\nDequant test 3... ");
  119626. run_test(&test3,test3_result);
  119627. fprintf(stderr,"OK\nDequant test 4... ");
  119628. run_test(&test4,test4_result);
  119629. fprintf(stderr,"OK\nDequant test 5... ");
  119630. run_test(&test5,test5_result);
  119631. fprintf(stderr,"OK\n\n");
  119632. return(0);
  119633. }
  119634. #endif
  119635. #endif
  119636. /*** End of inlined file: sharedbook.c ***/
  119637. /*** Start of inlined file: smallft.c ***/
  119638. /* FFT implementation from OggSquish, minus cosine transforms,
  119639. * minus all but radix 2/4 case. In Vorbis we only need this
  119640. * cut-down version.
  119641. *
  119642. * To do more than just power-of-two sized vectors, see the full
  119643. * version I wrote for NetLib.
  119644. *
  119645. * Note that the packing is a little strange; rather than the FFT r/i
  119646. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119647. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119648. * FORTRAN version
  119649. */
  119650. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119651. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119652. // tasks..
  119653. #if JUCE_MSVC
  119654. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119655. #endif
  119656. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119657. #if JUCE_USE_OGGVORBIS
  119658. #include <stdlib.h>
  119659. #include <string.h>
  119660. #include <math.h>
  119661. static void drfti1(int n, float *wa, int *ifac){
  119662. static int ntryh[4] = { 4,2,3,5 };
  119663. static float tpi = 6.28318530717958648f;
  119664. float arg,argh,argld,fi;
  119665. int ntry=0,i,j=-1;
  119666. int k1, l1, l2, ib;
  119667. int ld, ii, ip, is, nq, nr;
  119668. int ido, ipm, nfm1;
  119669. int nl=n;
  119670. int nf=0;
  119671. L101:
  119672. j++;
  119673. if (j < 4)
  119674. ntry=ntryh[j];
  119675. else
  119676. ntry+=2;
  119677. L104:
  119678. nq=nl/ntry;
  119679. nr=nl-ntry*nq;
  119680. if (nr!=0) goto L101;
  119681. nf++;
  119682. ifac[nf+1]=ntry;
  119683. nl=nq;
  119684. if(ntry!=2)goto L107;
  119685. if(nf==1)goto L107;
  119686. for (i=1;i<nf;i++){
  119687. ib=nf-i+1;
  119688. ifac[ib+1]=ifac[ib];
  119689. }
  119690. ifac[2] = 2;
  119691. L107:
  119692. if(nl!=1)goto L104;
  119693. ifac[0]=n;
  119694. ifac[1]=nf;
  119695. argh=tpi/n;
  119696. is=0;
  119697. nfm1=nf-1;
  119698. l1=1;
  119699. if(nfm1==0)return;
  119700. for (k1=0;k1<nfm1;k1++){
  119701. ip=ifac[k1+2];
  119702. ld=0;
  119703. l2=l1*ip;
  119704. ido=n/l2;
  119705. ipm=ip-1;
  119706. for (j=0;j<ipm;j++){
  119707. ld+=l1;
  119708. i=is;
  119709. argld=(float)ld*argh;
  119710. fi=0.f;
  119711. for (ii=2;ii<ido;ii+=2){
  119712. fi+=1.f;
  119713. arg=fi*argld;
  119714. wa[i++]=cos(arg);
  119715. wa[i++]=sin(arg);
  119716. }
  119717. is+=ido;
  119718. }
  119719. l1=l2;
  119720. }
  119721. }
  119722. static void fdrffti(int n, float *wsave, int *ifac){
  119723. if (n == 1) return;
  119724. drfti1(n, wsave+n, ifac);
  119725. }
  119726. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119727. int i,k;
  119728. float ti2,tr2;
  119729. int t0,t1,t2,t3,t4,t5,t6;
  119730. t1=0;
  119731. t0=(t2=l1*ido);
  119732. t3=ido<<1;
  119733. for(k=0;k<l1;k++){
  119734. ch[t1<<1]=cc[t1]+cc[t2];
  119735. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119736. t1+=ido;
  119737. t2+=ido;
  119738. }
  119739. if(ido<2)return;
  119740. if(ido==2)goto L105;
  119741. t1=0;
  119742. t2=t0;
  119743. for(k=0;k<l1;k++){
  119744. t3=t2;
  119745. t4=(t1<<1)+(ido<<1);
  119746. t5=t1;
  119747. t6=t1+t1;
  119748. for(i=2;i<ido;i+=2){
  119749. t3+=2;
  119750. t4-=2;
  119751. t5+=2;
  119752. t6+=2;
  119753. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119754. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119755. ch[t6]=cc[t5]+ti2;
  119756. ch[t4]=ti2-cc[t5];
  119757. ch[t6-1]=cc[t5-1]+tr2;
  119758. ch[t4-1]=cc[t5-1]-tr2;
  119759. }
  119760. t1+=ido;
  119761. t2+=ido;
  119762. }
  119763. if(ido%2==1)return;
  119764. L105:
  119765. t3=(t2=(t1=ido)-1);
  119766. t2+=t0;
  119767. for(k=0;k<l1;k++){
  119768. ch[t1]=-cc[t2];
  119769. ch[t1-1]=cc[t3];
  119770. t1+=ido<<1;
  119771. t2+=ido;
  119772. t3+=ido;
  119773. }
  119774. }
  119775. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119776. float *wa2,float *wa3){
  119777. static float hsqt2 = .70710678118654752f;
  119778. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119779. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119780. t0=l1*ido;
  119781. t1=t0;
  119782. t4=t1<<1;
  119783. t2=t1+(t1<<1);
  119784. t3=0;
  119785. for(k=0;k<l1;k++){
  119786. tr1=cc[t1]+cc[t2];
  119787. tr2=cc[t3]+cc[t4];
  119788. ch[t5=t3<<2]=tr1+tr2;
  119789. ch[(ido<<2)+t5-1]=tr2-tr1;
  119790. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119791. ch[t5]=cc[t2]-cc[t1];
  119792. t1+=ido;
  119793. t2+=ido;
  119794. t3+=ido;
  119795. t4+=ido;
  119796. }
  119797. if(ido<2)return;
  119798. if(ido==2)goto L105;
  119799. t1=0;
  119800. for(k=0;k<l1;k++){
  119801. t2=t1;
  119802. t4=t1<<2;
  119803. t5=(t6=ido<<1)+t4;
  119804. for(i=2;i<ido;i+=2){
  119805. t3=(t2+=2);
  119806. t4+=2;
  119807. t5-=2;
  119808. t3+=t0;
  119809. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119810. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119811. t3+=t0;
  119812. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119813. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119814. t3+=t0;
  119815. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119816. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119817. tr1=cr2+cr4;
  119818. tr4=cr4-cr2;
  119819. ti1=ci2+ci4;
  119820. ti4=ci2-ci4;
  119821. ti2=cc[t2]+ci3;
  119822. ti3=cc[t2]-ci3;
  119823. tr2=cc[t2-1]+cr3;
  119824. tr3=cc[t2-1]-cr3;
  119825. ch[t4-1]=tr1+tr2;
  119826. ch[t4]=ti1+ti2;
  119827. ch[t5-1]=tr3-ti4;
  119828. ch[t5]=tr4-ti3;
  119829. ch[t4+t6-1]=ti4+tr3;
  119830. ch[t4+t6]=tr4+ti3;
  119831. ch[t5+t6-1]=tr2-tr1;
  119832. ch[t5+t6]=ti1-ti2;
  119833. }
  119834. t1+=ido;
  119835. }
  119836. if(ido&1)return;
  119837. L105:
  119838. t2=(t1=t0+ido-1)+(t0<<1);
  119839. t3=ido<<2;
  119840. t4=ido;
  119841. t5=ido<<1;
  119842. t6=ido;
  119843. for(k=0;k<l1;k++){
  119844. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119845. tr1=hsqt2*(cc[t1]-cc[t2]);
  119846. ch[t4-1]=tr1+cc[t6-1];
  119847. ch[t4+t5-1]=cc[t6-1]-tr1;
  119848. ch[t4]=ti1-cc[t1+t0];
  119849. ch[t4+t5]=ti1+cc[t1+t0];
  119850. t1+=ido;
  119851. t2+=ido;
  119852. t4+=t3;
  119853. t6+=ido;
  119854. }
  119855. }
  119856. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119857. float *c2,float *ch,float *ch2,float *wa){
  119858. static float tpi=6.283185307179586f;
  119859. int idij,ipph,i,j,k,l,ic,ik,is;
  119860. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119861. float dc2,ai1,ai2,ar1,ar2,ds2;
  119862. int nbd;
  119863. float dcp,arg,dsp,ar1h,ar2h;
  119864. int idp2,ipp2;
  119865. arg=tpi/(float)ip;
  119866. dcp=cos(arg);
  119867. dsp=sin(arg);
  119868. ipph=(ip+1)>>1;
  119869. ipp2=ip;
  119870. idp2=ido;
  119871. nbd=(ido-1)>>1;
  119872. t0=l1*ido;
  119873. t10=ip*ido;
  119874. if(ido==1)goto L119;
  119875. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119876. t1=0;
  119877. for(j=1;j<ip;j++){
  119878. t1+=t0;
  119879. t2=t1;
  119880. for(k=0;k<l1;k++){
  119881. ch[t2]=c1[t2];
  119882. t2+=ido;
  119883. }
  119884. }
  119885. is=-ido;
  119886. t1=0;
  119887. if(nbd>l1){
  119888. for(j=1;j<ip;j++){
  119889. t1+=t0;
  119890. is+=ido;
  119891. t2= -ido+t1;
  119892. for(k=0;k<l1;k++){
  119893. idij=is-1;
  119894. t2+=ido;
  119895. t3=t2;
  119896. for(i=2;i<ido;i+=2){
  119897. idij+=2;
  119898. t3+=2;
  119899. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119900. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119901. }
  119902. }
  119903. }
  119904. }else{
  119905. for(j=1;j<ip;j++){
  119906. is+=ido;
  119907. idij=is-1;
  119908. t1+=t0;
  119909. t2=t1;
  119910. for(i=2;i<ido;i+=2){
  119911. idij+=2;
  119912. t2+=2;
  119913. t3=t2;
  119914. for(k=0;k<l1;k++){
  119915. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119916. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119917. t3+=ido;
  119918. }
  119919. }
  119920. }
  119921. }
  119922. t1=0;
  119923. t2=ipp2*t0;
  119924. if(nbd<l1){
  119925. for(j=1;j<ipph;j++){
  119926. t1+=t0;
  119927. t2-=t0;
  119928. t3=t1;
  119929. t4=t2;
  119930. for(i=2;i<ido;i+=2){
  119931. t3+=2;
  119932. t4+=2;
  119933. t5=t3-ido;
  119934. t6=t4-ido;
  119935. for(k=0;k<l1;k++){
  119936. t5+=ido;
  119937. t6+=ido;
  119938. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119939. c1[t6-1]=ch[t5]-ch[t6];
  119940. c1[t5]=ch[t5]+ch[t6];
  119941. c1[t6]=ch[t6-1]-ch[t5-1];
  119942. }
  119943. }
  119944. }
  119945. }else{
  119946. for(j=1;j<ipph;j++){
  119947. t1+=t0;
  119948. t2-=t0;
  119949. t3=t1;
  119950. t4=t2;
  119951. for(k=0;k<l1;k++){
  119952. t5=t3;
  119953. t6=t4;
  119954. for(i=2;i<ido;i+=2){
  119955. t5+=2;
  119956. t6+=2;
  119957. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119958. c1[t6-1]=ch[t5]-ch[t6];
  119959. c1[t5]=ch[t5]+ch[t6];
  119960. c1[t6]=ch[t6-1]-ch[t5-1];
  119961. }
  119962. t3+=ido;
  119963. t4+=ido;
  119964. }
  119965. }
  119966. }
  119967. L119:
  119968. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119969. t1=0;
  119970. t2=ipp2*idl1;
  119971. for(j=1;j<ipph;j++){
  119972. t1+=t0;
  119973. t2-=t0;
  119974. t3=t1-ido;
  119975. t4=t2-ido;
  119976. for(k=0;k<l1;k++){
  119977. t3+=ido;
  119978. t4+=ido;
  119979. c1[t3]=ch[t3]+ch[t4];
  119980. c1[t4]=ch[t4]-ch[t3];
  119981. }
  119982. }
  119983. ar1=1.f;
  119984. ai1=0.f;
  119985. t1=0;
  119986. t2=ipp2*idl1;
  119987. t3=(ip-1)*idl1;
  119988. for(l=1;l<ipph;l++){
  119989. t1+=idl1;
  119990. t2-=idl1;
  119991. ar1h=dcp*ar1-dsp*ai1;
  119992. ai1=dcp*ai1+dsp*ar1;
  119993. ar1=ar1h;
  119994. t4=t1;
  119995. t5=t2;
  119996. t6=t3;
  119997. t7=idl1;
  119998. for(ik=0;ik<idl1;ik++){
  119999. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  120000. ch2[t5++]=ai1*c2[t6++];
  120001. }
  120002. dc2=ar1;
  120003. ds2=ai1;
  120004. ar2=ar1;
  120005. ai2=ai1;
  120006. t4=idl1;
  120007. t5=(ipp2-1)*idl1;
  120008. for(j=2;j<ipph;j++){
  120009. t4+=idl1;
  120010. t5-=idl1;
  120011. ar2h=dc2*ar2-ds2*ai2;
  120012. ai2=dc2*ai2+ds2*ar2;
  120013. ar2=ar2h;
  120014. t6=t1;
  120015. t7=t2;
  120016. t8=t4;
  120017. t9=t5;
  120018. for(ik=0;ik<idl1;ik++){
  120019. ch2[t6++]+=ar2*c2[t8++];
  120020. ch2[t7++]+=ai2*c2[t9++];
  120021. }
  120022. }
  120023. }
  120024. t1=0;
  120025. for(j=1;j<ipph;j++){
  120026. t1+=idl1;
  120027. t2=t1;
  120028. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120029. }
  120030. if(ido<l1)goto L132;
  120031. t1=0;
  120032. t2=0;
  120033. for(k=0;k<l1;k++){
  120034. t3=t1;
  120035. t4=t2;
  120036. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120037. t1+=ido;
  120038. t2+=t10;
  120039. }
  120040. goto L135;
  120041. L132:
  120042. for(i=0;i<ido;i++){
  120043. t1=i;
  120044. t2=i;
  120045. for(k=0;k<l1;k++){
  120046. cc[t2]=ch[t1];
  120047. t1+=ido;
  120048. t2+=t10;
  120049. }
  120050. }
  120051. L135:
  120052. t1=0;
  120053. t2=ido<<1;
  120054. t3=0;
  120055. t4=ipp2*t0;
  120056. for(j=1;j<ipph;j++){
  120057. t1+=t2;
  120058. t3+=t0;
  120059. t4-=t0;
  120060. t5=t1;
  120061. t6=t3;
  120062. t7=t4;
  120063. for(k=0;k<l1;k++){
  120064. cc[t5-1]=ch[t6];
  120065. cc[t5]=ch[t7];
  120066. t5+=t10;
  120067. t6+=ido;
  120068. t7+=ido;
  120069. }
  120070. }
  120071. if(ido==1)return;
  120072. if(nbd<l1)goto L141;
  120073. t1=-ido;
  120074. t3=0;
  120075. t4=0;
  120076. t5=ipp2*t0;
  120077. for(j=1;j<ipph;j++){
  120078. t1+=t2;
  120079. t3+=t2;
  120080. t4+=t0;
  120081. t5-=t0;
  120082. t6=t1;
  120083. t7=t3;
  120084. t8=t4;
  120085. t9=t5;
  120086. for(k=0;k<l1;k++){
  120087. for(i=2;i<ido;i+=2){
  120088. ic=idp2-i;
  120089. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120090. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120091. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120092. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120093. }
  120094. t6+=t10;
  120095. t7+=t10;
  120096. t8+=ido;
  120097. t9+=ido;
  120098. }
  120099. }
  120100. return;
  120101. L141:
  120102. t1=-ido;
  120103. t3=0;
  120104. t4=0;
  120105. t5=ipp2*t0;
  120106. for(j=1;j<ipph;j++){
  120107. t1+=t2;
  120108. t3+=t2;
  120109. t4+=t0;
  120110. t5-=t0;
  120111. for(i=2;i<ido;i+=2){
  120112. t6=idp2+t1-i;
  120113. t7=i+t3;
  120114. t8=i+t4;
  120115. t9=i+t5;
  120116. for(k=0;k<l1;k++){
  120117. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120118. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120119. cc[t7]=ch[t8]+ch[t9];
  120120. cc[t6]=ch[t9]-ch[t8];
  120121. t6+=t10;
  120122. t7+=t10;
  120123. t8+=ido;
  120124. t9+=ido;
  120125. }
  120126. }
  120127. }
  120128. }
  120129. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120130. int i,k1,l1,l2;
  120131. int na,kh,nf;
  120132. int ip,iw,ido,idl1,ix2,ix3;
  120133. nf=ifac[1];
  120134. na=1;
  120135. l2=n;
  120136. iw=n;
  120137. for(k1=0;k1<nf;k1++){
  120138. kh=nf-k1;
  120139. ip=ifac[kh+1];
  120140. l1=l2/ip;
  120141. ido=n/l2;
  120142. idl1=ido*l1;
  120143. iw-=(ip-1)*ido;
  120144. na=1-na;
  120145. if(ip!=4)goto L102;
  120146. ix2=iw+ido;
  120147. ix3=ix2+ido;
  120148. if(na!=0)
  120149. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120150. else
  120151. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120152. goto L110;
  120153. L102:
  120154. if(ip!=2)goto L104;
  120155. if(na!=0)goto L103;
  120156. dradf2(ido,l1,c,ch,wa+iw-1);
  120157. goto L110;
  120158. L103:
  120159. dradf2(ido,l1,ch,c,wa+iw-1);
  120160. goto L110;
  120161. L104:
  120162. if(ido==1)na=1-na;
  120163. if(na!=0)goto L109;
  120164. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120165. na=1;
  120166. goto L110;
  120167. L109:
  120168. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120169. na=0;
  120170. L110:
  120171. l2=l1;
  120172. }
  120173. if(na==1)return;
  120174. for(i=0;i<n;i++)c[i]=ch[i];
  120175. }
  120176. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120177. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120178. float ti2,tr2;
  120179. t0=l1*ido;
  120180. t1=0;
  120181. t2=0;
  120182. t3=(ido<<1)-1;
  120183. for(k=0;k<l1;k++){
  120184. ch[t1]=cc[t2]+cc[t3+t2];
  120185. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120186. t2=(t1+=ido)<<1;
  120187. }
  120188. if(ido<2)return;
  120189. if(ido==2)goto L105;
  120190. t1=0;
  120191. t2=0;
  120192. for(k=0;k<l1;k++){
  120193. t3=t1;
  120194. t5=(t4=t2)+(ido<<1);
  120195. t6=t0+t1;
  120196. for(i=2;i<ido;i+=2){
  120197. t3+=2;
  120198. t4+=2;
  120199. t5-=2;
  120200. t6+=2;
  120201. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120202. tr2=cc[t4-1]-cc[t5-1];
  120203. ch[t3]=cc[t4]-cc[t5];
  120204. ti2=cc[t4]+cc[t5];
  120205. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120206. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120207. }
  120208. t2=(t1+=ido)<<1;
  120209. }
  120210. if(ido%2==1)return;
  120211. L105:
  120212. t1=ido-1;
  120213. t2=ido-1;
  120214. for(k=0;k<l1;k++){
  120215. ch[t1]=cc[t2]+cc[t2];
  120216. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120217. t1+=ido;
  120218. t2+=ido<<1;
  120219. }
  120220. }
  120221. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120222. float *wa2){
  120223. static float taur = -.5f;
  120224. static float taui = .8660254037844386f;
  120225. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120226. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120227. t0=l1*ido;
  120228. t1=0;
  120229. t2=t0<<1;
  120230. t3=ido<<1;
  120231. t4=ido+(ido<<1);
  120232. t5=0;
  120233. for(k=0;k<l1;k++){
  120234. tr2=cc[t3-1]+cc[t3-1];
  120235. cr2=cc[t5]+(taur*tr2);
  120236. ch[t1]=cc[t5]+tr2;
  120237. ci3=taui*(cc[t3]+cc[t3]);
  120238. ch[t1+t0]=cr2-ci3;
  120239. ch[t1+t2]=cr2+ci3;
  120240. t1+=ido;
  120241. t3+=t4;
  120242. t5+=t4;
  120243. }
  120244. if(ido==1)return;
  120245. t1=0;
  120246. t3=ido<<1;
  120247. for(k=0;k<l1;k++){
  120248. t7=t1+(t1<<1);
  120249. t6=(t5=t7+t3);
  120250. t8=t1;
  120251. t10=(t9=t1+t0)+t0;
  120252. for(i=2;i<ido;i+=2){
  120253. t5+=2;
  120254. t6-=2;
  120255. t7+=2;
  120256. t8+=2;
  120257. t9+=2;
  120258. t10+=2;
  120259. tr2=cc[t5-1]+cc[t6-1];
  120260. cr2=cc[t7-1]+(taur*tr2);
  120261. ch[t8-1]=cc[t7-1]+tr2;
  120262. ti2=cc[t5]-cc[t6];
  120263. ci2=cc[t7]+(taur*ti2);
  120264. ch[t8]=cc[t7]+ti2;
  120265. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120266. ci3=taui*(cc[t5]+cc[t6]);
  120267. dr2=cr2-ci3;
  120268. dr3=cr2+ci3;
  120269. di2=ci2+cr3;
  120270. di3=ci2-cr3;
  120271. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120272. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120273. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120274. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120275. }
  120276. t1+=ido;
  120277. }
  120278. }
  120279. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120280. float *wa2,float *wa3){
  120281. static float sqrt2=1.414213562373095f;
  120282. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120283. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120284. t0=l1*ido;
  120285. t1=0;
  120286. t2=ido<<2;
  120287. t3=0;
  120288. t6=ido<<1;
  120289. for(k=0;k<l1;k++){
  120290. t4=t3+t6;
  120291. t5=t1;
  120292. tr3=cc[t4-1]+cc[t4-1];
  120293. tr4=cc[t4]+cc[t4];
  120294. tr1=cc[t3]-cc[(t4+=t6)-1];
  120295. tr2=cc[t3]+cc[t4-1];
  120296. ch[t5]=tr2+tr3;
  120297. ch[t5+=t0]=tr1-tr4;
  120298. ch[t5+=t0]=tr2-tr3;
  120299. ch[t5+=t0]=tr1+tr4;
  120300. t1+=ido;
  120301. t3+=t2;
  120302. }
  120303. if(ido<2)return;
  120304. if(ido==2)goto L105;
  120305. t1=0;
  120306. for(k=0;k<l1;k++){
  120307. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120308. t7=t1;
  120309. for(i=2;i<ido;i+=2){
  120310. t2+=2;
  120311. t3+=2;
  120312. t4-=2;
  120313. t5-=2;
  120314. t7+=2;
  120315. ti1=cc[t2]+cc[t5];
  120316. ti2=cc[t2]-cc[t5];
  120317. ti3=cc[t3]-cc[t4];
  120318. tr4=cc[t3]+cc[t4];
  120319. tr1=cc[t2-1]-cc[t5-1];
  120320. tr2=cc[t2-1]+cc[t5-1];
  120321. ti4=cc[t3-1]-cc[t4-1];
  120322. tr3=cc[t3-1]+cc[t4-1];
  120323. ch[t7-1]=tr2+tr3;
  120324. cr3=tr2-tr3;
  120325. ch[t7]=ti2+ti3;
  120326. ci3=ti2-ti3;
  120327. cr2=tr1-tr4;
  120328. cr4=tr1+tr4;
  120329. ci2=ti1+ti4;
  120330. ci4=ti1-ti4;
  120331. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120332. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120333. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120334. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120335. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120336. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120337. }
  120338. t1+=ido;
  120339. }
  120340. if(ido%2 == 1)return;
  120341. L105:
  120342. t1=ido;
  120343. t2=ido<<2;
  120344. t3=ido-1;
  120345. t4=ido+(ido<<1);
  120346. for(k=0;k<l1;k++){
  120347. t5=t3;
  120348. ti1=cc[t1]+cc[t4];
  120349. ti2=cc[t4]-cc[t1];
  120350. tr1=cc[t1-1]-cc[t4-1];
  120351. tr2=cc[t1-1]+cc[t4-1];
  120352. ch[t5]=tr2+tr2;
  120353. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120354. ch[t5+=t0]=ti2+ti2;
  120355. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120356. t3+=ido;
  120357. t1+=t2;
  120358. t4+=t2;
  120359. }
  120360. }
  120361. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120362. float *c2,float *ch,float *ch2,float *wa){
  120363. static float tpi=6.283185307179586f;
  120364. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120365. t11,t12;
  120366. float dc2,ai1,ai2,ar1,ar2,ds2;
  120367. int nbd;
  120368. float dcp,arg,dsp,ar1h,ar2h;
  120369. int ipp2;
  120370. t10=ip*ido;
  120371. t0=l1*ido;
  120372. arg=tpi/(float)ip;
  120373. dcp=cos(arg);
  120374. dsp=sin(arg);
  120375. nbd=(ido-1)>>1;
  120376. ipp2=ip;
  120377. ipph=(ip+1)>>1;
  120378. if(ido<l1)goto L103;
  120379. t1=0;
  120380. t2=0;
  120381. for(k=0;k<l1;k++){
  120382. t3=t1;
  120383. t4=t2;
  120384. for(i=0;i<ido;i++){
  120385. ch[t3]=cc[t4];
  120386. t3++;
  120387. t4++;
  120388. }
  120389. t1+=ido;
  120390. t2+=t10;
  120391. }
  120392. goto L106;
  120393. L103:
  120394. t1=0;
  120395. for(i=0;i<ido;i++){
  120396. t2=t1;
  120397. t3=t1;
  120398. for(k=0;k<l1;k++){
  120399. ch[t2]=cc[t3];
  120400. t2+=ido;
  120401. t3+=t10;
  120402. }
  120403. t1++;
  120404. }
  120405. L106:
  120406. t1=0;
  120407. t2=ipp2*t0;
  120408. t7=(t5=ido<<1);
  120409. for(j=1;j<ipph;j++){
  120410. t1+=t0;
  120411. t2-=t0;
  120412. t3=t1;
  120413. t4=t2;
  120414. t6=t5;
  120415. for(k=0;k<l1;k++){
  120416. ch[t3]=cc[t6-1]+cc[t6-1];
  120417. ch[t4]=cc[t6]+cc[t6];
  120418. t3+=ido;
  120419. t4+=ido;
  120420. t6+=t10;
  120421. }
  120422. t5+=t7;
  120423. }
  120424. if (ido == 1)goto L116;
  120425. if(nbd<l1)goto L112;
  120426. t1=0;
  120427. t2=ipp2*t0;
  120428. t7=0;
  120429. for(j=1;j<ipph;j++){
  120430. t1+=t0;
  120431. t2-=t0;
  120432. t3=t1;
  120433. t4=t2;
  120434. t7+=(ido<<1);
  120435. t8=t7;
  120436. for(k=0;k<l1;k++){
  120437. t5=t3;
  120438. t6=t4;
  120439. t9=t8;
  120440. t11=t8;
  120441. for(i=2;i<ido;i+=2){
  120442. t5+=2;
  120443. t6+=2;
  120444. t9+=2;
  120445. t11-=2;
  120446. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120447. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120448. ch[t5]=cc[t9]-cc[t11];
  120449. ch[t6]=cc[t9]+cc[t11];
  120450. }
  120451. t3+=ido;
  120452. t4+=ido;
  120453. t8+=t10;
  120454. }
  120455. }
  120456. goto L116;
  120457. L112:
  120458. t1=0;
  120459. t2=ipp2*t0;
  120460. t7=0;
  120461. for(j=1;j<ipph;j++){
  120462. t1+=t0;
  120463. t2-=t0;
  120464. t3=t1;
  120465. t4=t2;
  120466. t7+=(ido<<1);
  120467. t8=t7;
  120468. t9=t7;
  120469. for(i=2;i<ido;i+=2){
  120470. t3+=2;
  120471. t4+=2;
  120472. t8+=2;
  120473. t9-=2;
  120474. t5=t3;
  120475. t6=t4;
  120476. t11=t8;
  120477. t12=t9;
  120478. for(k=0;k<l1;k++){
  120479. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120480. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120481. ch[t5]=cc[t11]-cc[t12];
  120482. ch[t6]=cc[t11]+cc[t12];
  120483. t5+=ido;
  120484. t6+=ido;
  120485. t11+=t10;
  120486. t12+=t10;
  120487. }
  120488. }
  120489. }
  120490. L116:
  120491. ar1=1.f;
  120492. ai1=0.f;
  120493. t1=0;
  120494. t9=(t2=ipp2*idl1);
  120495. t3=(ip-1)*idl1;
  120496. for(l=1;l<ipph;l++){
  120497. t1+=idl1;
  120498. t2-=idl1;
  120499. ar1h=dcp*ar1-dsp*ai1;
  120500. ai1=dcp*ai1+dsp*ar1;
  120501. ar1=ar1h;
  120502. t4=t1;
  120503. t5=t2;
  120504. t6=0;
  120505. t7=idl1;
  120506. t8=t3;
  120507. for(ik=0;ik<idl1;ik++){
  120508. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120509. c2[t5++]=ai1*ch2[t8++];
  120510. }
  120511. dc2=ar1;
  120512. ds2=ai1;
  120513. ar2=ar1;
  120514. ai2=ai1;
  120515. t6=idl1;
  120516. t7=t9-idl1;
  120517. for(j=2;j<ipph;j++){
  120518. t6+=idl1;
  120519. t7-=idl1;
  120520. ar2h=dc2*ar2-ds2*ai2;
  120521. ai2=dc2*ai2+ds2*ar2;
  120522. ar2=ar2h;
  120523. t4=t1;
  120524. t5=t2;
  120525. t11=t6;
  120526. t12=t7;
  120527. for(ik=0;ik<idl1;ik++){
  120528. c2[t4++]+=ar2*ch2[t11++];
  120529. c2[t5++]+=ai2*ch2[t12++];
  120530. }
  120531. }
  120532. }
  120533. t1=0;
  120534. for(j=1;j<ipph;j++){
  120535. t1+=idl1;
  120536. t2=t1;
  120537. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120538. }
  120539. t1=0;
  120540. t2=ipp2*t0;
  120541. for(j=1;j<ipph;j++){
  120542. t1+=t0;
  120543. t2-=t0;
  120544. t3=t1;
  120545. t4=t2;
  120546. for(k=0;k<l1;k++){
  120547. ch[t3]=c1[t3]-c1[t4];
  120548. ch[t4]=c1[t3]+c1[t4];
  120549. t3+=ido;
  120550. t4+=ido;
  120551. }
  120552. }
  120553. if(ido==1)goto L132;
  120554. if(nbd<l1)goto L128;
  120555. t1=0;
  120556. t2=ipp2*t0;
  120557. for(j=1;j<ipph;j++){
  120558. t1+=t0;
  120559. t2-=t0;
  120560. t3=t1;
  120561. t4=t2;
  120562. for(k=0;k<l1;k++){
  120563. t5=t3;
  120564. t6=t4;
  120565. for(i=2;i<ido;i+=2){
  120566. t5+=2;
  120567. t6+=2;
  120568. ch[t5-1]=c1[t5-1]-c1[t6];
  120569. ch[t6-1]=c1[t5-1]+c1[t6];
  120570. ch[t5]=c1[t5]+c1[t6-1];
  120571. ch[t6]=c1[t5]-c1[t6-1];
  120572. }
  120573. t3+=ido;
  120574. t4+=ido;
  120575. }
  120576. }
  120577. goto L132;
  120578. L128:
  120579. t1=0;
  120580. t2=ipp2*t0;
  120581. for(j=1;j<ipph;j++){
  120582. t1+=t0;
  120583. t2-=t0;
  120584. t3=t1;
  120585. t4=t2;
  120586. for(i=2;i<ido;i+=2){
  120587. t3+=2;
  120588. t4+=2;
  120589. t5=t3;
  120590. t6=t4;
  120591. for(k=0;k<l1;k++){
  120592. ch[t5-1]=c1[t5-1]-c1[t6];
  120593. ch[t6-1]=c1[t5-1]+c1[t6];
  120594. ch[t5]=c1[t5]+c1[t6-1];
  120595. ch[t6]=c1[t5]-c1[t6-1];
  120596. t5+=ido;
  120597. t6+=ido;
  120598. }
  120599. }
  120600. }
  120601. L132:
  120602. if(ido==1)return;
  120603. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120604. t1=0;
  120605. for(j=1;j<ip;j++){
  120606. t2=(t1+=t0);
  120607. for(k=0;k<l1;k++){
  120608. c1[t2]=ch[t2];
  120609. t2+=ido;
  120610. }
  120611. }
  120612. if(nbd>l1)goto L139;
  120613. is= -ido-1;
  120614. t1=0;
  120615. for(j=1;j<ip;j++){
  120616. is+=ido;
  120617. t1+=t0;
  120618. idij=is;
  120619. t2=t1;
  120620. for(i=2;i<ido;i+=2){
  120621. t2+=2;
  120622. idij+=2;
  120623. t3=t2;
  120624. for(k=0;k<l1;k++){
  120625. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120626. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120627. t3+=ido;
  120628. }
  120629. }
  120630. }
  120631. return;
  120632. L139:
  120633. is= -ido-1;
  120634. t1=0;
  120635. for(j=1;j<ip;j++){
  120636. is+=ido;
  120637. t1+=t0;
  120638. t2=t1;
  120639. for(k=0;k<l1;k++){
  120640. idij=is;
  120641. t3=t2;
  120642. for(i=2;i<ido;i+=2){
  120643. idij+=2;
  120644. t3+=2;
  120645. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120646. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120647. }
  120648. t2+=ido;
  120649. }
  120650. }
  120651. }
  120652. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120653. int i,k1,l1,l2;
  120654. int na;
  120655. int nf,ip,iw,ix2,ix3,ido,idl1;
  120656. nf=ifac[1];
  120657. na=0;
  120658. l1=1;
  120659. iw=1;
  120660. for(k1=0;k1<nf;k1++){
  120661. ip=ifac[k1 + 2];
  120662. l2=ip*l1;
  120663. ido=n/l2;
  120664. idl1=ido*l1;
  120665. if(ip!=4)goto L103;
  120666. ix2=iw+ido;
  120667. ix3=ix2+ido;
  120668. if(na!=0)
  120669. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120670. else
  120671. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120672. na=1-na;
  120673. goto L115;
  120674. L103:
  120675. if(ip!=2)goto L106;
  120676. if(na!=0)
  120677. dradb2(ido,l1,ch,c,wa+iw-1);
  120678. else
  120679. dradb2(ido,l1,c,ch,wa+iw-1);
  120680. na=1-na;
  120681. goto L115;
  120682. L106:
  120683. if(ip!=3)goto L109;
  120684. ix2=iw+ido;
  120685. if(na!=0)
  120686. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120687. else
  120688. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120689. na=1-na;
  120690. goto L115;
  120691. L109:
  120692. /* The radix five case can be translated later..... */
  120693. /* if(ip!=5)goto L112;
  120694. ix2=iw+ido;
  120695. ix3=ix2+ido;
  120696. ix4=ix3+ido;
  120697. if(na!=0)
  120698. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120699. else
  120700. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120701. na=1-na;
  120702. goto L115;
  120703. L112:*/
  120704. if(na!=0)
  120705. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120706. else
  120707. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120708. if(ido==1)na=1-na;
  120709. L115:
  120710. l1=l2;
  120711. iw+=(ip-1)*ido;
  120712. }
  120713. if(na==0)return;
  120714. for(i=0;i<n;i++)c[i]=ch[i];
  120715. }
  120716. void drft_forward(drft_lookup *l,float *data){
  120717. if(l->n==1)return;
  120718. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120719. }
  120720. void drft_backward(drft_lookup *l,float *data){
  120721. if (l->n==1)return;
  120722. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120723. }
  120724. void drft_init(drft_lookup *l,int n){
  120725. l->n=n;
  120726. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120727. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120728. fdrffti(n, l->trigcache, l->splitcache);
  120729. }
  120730. void drft_clear(drft_lookup *l){
  120731. if(l){
  120732. if(l->trigcache)_ogg_free(l->trigcache);
  120733. if(l->splitcache)_ogg_free(l->splitcache);
  120734. memset(l,0,sizeof(*l));
  120735. }
  120736. }
  120737. #endif
  120738. /*** End of inlined file: smallft.c ***/
  120739. /*** Start of inlined file: synthesis.c ***/
  120740. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120741. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120742. // tasks..
  120743. #if JUCE_MSVC
  120744. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120745. #endif
  120746. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120747. #if JUCE_USE_OGGVORBIS
  120748. #include <stdio.h>
  120749. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120750. vorbis_dsp_state *vd=vb->vd;
  120751. private_state *b=(private_state*)vd->backend_state;
  120752. vorbis_info *vi=vd->vi;
  120753. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120754. oggpack_buffer *opb=&vb->opb;
  120755. int type,mode,i;
  120756. /* first things first. Make sure decode is ready */
  120757. _vorbis_block_ripcord(vb);
  120758. oggpack_readinit(opb,op->packet,op->bytes);
  120759. /* Check the packet type */
  120760. if(oggpack_read(opb,1)!=0){
  120761. /* Oops. This is not an audio data packet */
  120762. return(OV_ENOTAUDIO);
  120763. }
  120764. /* read our mode and pre/post windowsize */
  120765. mode=oggpack_read(opb,b->modebits);
  120766. if(mode==-1)return(OV_EBADPACKET);
  120767. vb->mode=mode;
  120768. vb->W=ci->mode_param[mode]->blockflag;
  120769. if(vb->W){
  120770. /* this doesn;t get mapped through mode selection as it's used
  120771. only for window selection */
  120772. vb->lW=oggpack_read(opb,1);
  120773. vb->nW=oggpack_read(opb,1);
  120774. if(vb->nW==-1) return(OV_EBADPACKET);
  120775. }else{
  120776. vb->lW=0;
  120777. vb->nW=0;
  120778. }
  120779. /* more setup */
  120780. vb->granulepos=op->granulepos;
  120781. vb->sequence=op->packetno;
  120782. vb->eofflag=op->e_o_s;
  120783. /* alloc pcm passback storage */
  120784. vb->pcmend=ci->blocksizes[vb->W];
  120785. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120786. for(i=0;i<vi->channels;i++)
  120787. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120788. /* unpack_header enforces range checking */
  120789. type=ci->map_type[ci->mode_param[mode]->mapping];
  120790. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120791. mapping]));
  120792. }
  120793. /* used to track pcm position without actually performing decode.
  120794. Useful for sequential 'fast forward' */
  120795. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120796. vorbis_dsp_state *vd=vb->vd;
  120797. private_state *b=(private_state*)vd->backend_state;
  120798. vorbis_info *vi=vd->vi;
  120799. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120800. oggpack_buffer *opb=&vb->opb;
  120801. int mode;
  120802. /* first things first. Make sure decode is ready */
  120803. _vorbis_block_ripcord(vb);
  120804. oggpack_readinit(opb,op->packet,op->bytes);
  120805. /* Check the packet type */
  120806. if(oggpack_read(opb,1)!=0){
  120807. /* Oops. This is not an audio data packet */
  120808. return(OV_ENOTAUDIO);
  120809. }
  120810. /* read our mode and pre/post windowsize */
  120811. mode=oggpack_read(opb,b->modebits);
  120812. if(mode==-1)return(OV_EBADPACKET);
  120813. vb->mode=mode;
  120814. vb->W=ci->mode_param[mode]->blockflag;
  120815. if(vb->W){
  120816. vb->lW=oggpack_read(opb,1);
  120817. vb->nW=oggpack_read(opb,1);
  120818. if(vb->nW==-1) return(OV_EBADPACKET);
  120819. }else{
  120820. vb->lW=0;
  120821. vb->nW=0;
  120822. }
  120823. /* more setup */
  120824. vb->granulepos=op->granulepos;
  120825. vb->sequence=op->packetno;
  120826. vb->eofflag=op->e_o_s;
  120827. /* no pcm */
  120828. vb->pcmend=0;
  120829. vb->pcm=NULL;
  120830. return(0);
  120831. }
  120832. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120833. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120834. oggpack_buffer opb;
  120835. int mode;
  120836. oggpack_readinit(&opb,op->packet,op->bytes);
  120837. /* Check the packet type */
  120838. if(oggpack_read(&opb,1)!=0){
  120839. /* Oops. This is not an audio data packet */
  120840. return(OV_ENOTAUDIO);
  120841. }
  120842. {
  120843. int modebits=0;
  120844. int v=ci->modes;
  120845. while(v>1){
  120846. modebits++;
  120847. v>>=1;
  120848. }
  120849. /* read our mode and pre/post windowsize */
  120850. mode=oggpack_read(&opb,modebits);
  120851. }
  120852. if(mode==-1)return(OV_EBADPACKET);
  120853. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120854. }
  120855. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120856. /* set / clear half-sample-rate mode */
  120857. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120858. /* right now, our MDCT can't handle < 64 sample windows. */
  120859. if(ci->blocksizes[0]<=64 && flag)return -1;
  120860. ci->halfrate_flag=(flag?1:0);
  120861. return 0;
  120862. }
  120863. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120864. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120865. return ci->halfrate_flag;
  120866. }
  120867. #endif
  120868. /*** End of inlined file: synthesis.c ***/
  120869. /*** Start of inlined file: vorbisenc.c ***/
  120870. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120871. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120872. // tasks..
  120873. #if JUCE_MSVC
  120874. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120875. #endif
  120876. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120877. #if JUCE_USE_OGGVORBIS
  120878. #include <stdlib.h>
  120879. #include <string.h>
  120880. #include <math.h>
  120881. /* careful with this; it's using static array sizing to make managing
  120882. all the modes a little less annoying. If we use a residue backend
  120883. with > 12 partition types, or a different division of iteration,
  120884. this needs to be updated. */
  120885. typedef struct {
  120886. static_codebook *books[12][3];
  120887. } static_bookblock;
  120888. typedef struct {
  120889. int res_type;
  120890. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120891. vorbis_info_residue0 *res;
  120892. static_codebook *book_aux;
  120893. static_codebook *book_aux_managed;
  120894. static_bookblock *books_base;
  120895. static_bookblock *books_base_managed;
  120896. } vorbis_residue_template;
  120897. typedef struct {
  120898. vorbis_info_mapping0 *map;
  120899. vorbis_residue_template *res;
  120900. } vorbis_mapping_template;
  120901. typedef struct vp_adjblock{
  120902. int block[P_BANDS];
  120903. } vp_adjblock;
  120904. typedef struct {
  120905. int data[NOISE_COMPAND_LEVELS];
  120906. } compandblock;
  120907. /* high level configuration information for setting things up
  120908. step-by-step with the detailed vorbis_encode_ctl interface.
  120909. There's a fair amount of redundancy such that interactive setup
  120910. does not directly deal with any vorbis_info or codec_setup_info
  120911. initialization; it's all stored (until full init) in this highlevel
  120912. setup, then flushed out to the real codec setup structs later. */
  120913. typedef struct {
  120914. int att[P_NOISECURVES];
  120915. float boost;
  120916. float decay;
  120917. } att3;
  120918. typedef struct { int data[P_NOISECURVES]; } adj3;
  120919. typedef struct {
  120920. int pre[PACKETBLOBS];
  120921. int post[PACKETBLOBS];
  120922. float kHz[PACKETBLOBS];
  120923. float lowpasskHz[PACKETBLOBS];
  120924. } adj_stereo;
  120925. typedef struct {
  120926. int lo;
  120927. int hi;
  120928. int fixed;
  120929. } noiseguard;
  120930. typedef struct {
  120931. int data[P_NOISECURVES][17];
  120932. } noise3;
  120933. typedef struct {
  120934. int mappings;
  120935. double *rate_mapping;
  120936. double *quality_mapping;
  120937. int coupling_restriction;
  120938. long samplerate_min_restriction;
  120939. long samplerate_max_restriction;
  120940. int *blocksize_short;
  120941. int *blocksize_long;
  120942. att3 *psy_tone_masteratt;
  120943. int *psy_tone_0dB;
  120944. int *psy_tone_dBsuppress;
  120945. vp_adjblock *psy_tone_adj_impulse;
  120946. vp_adjblock *psy_tone_adj_long;
  120947. vp_adjblock *psy_tone_adj_other;
  120948. noiseguard *psy_noiseguards;
  120949. noise3 *psy_noise_bias_impulse;
  120950. noise3 *psy_noise_bias_padding;
  120951. noise3 *psy_noise_bias_trans;
  120952. noise3 *psy_noise_bias_long;
  120953. int *psy_noise_dBsuppress;
  120954. compandblock *psy_noise_compand;
  120955. double *psy_noise_compand_short_mapping;
  120956. double *psy_noise_compand_long_mapping;
  120957. int *psy_noise_normal_start[2];
  120958. int *psy_noise_normal_partition[2];
  120959. double *psy_noise_normal_thresh;
  120960. int *psy_ath_float;
  120961. int *psy_ath_abs;
  120962. double *psy_lowpass;
  120963. vorbis_info_psy_global *global_params;
  120964. double *global_mapping;
  120965. adj_stereo *stereo_modes;
  120966. static_codebook ***floor_books;
  120967. vorbis_info_floor1 *floor_params;
  120968. int *floor_short_mapping;
  120969. int *floor_long_mapping;
  120970. vorbis_mapping_template *maps;
  120971. } ve_setup_data_template;
  120972. /* a few static coder conventions */
  120973. static vorbis_info_mode _mode_template[2]={
  120974. {0,0,0,0},
  120975. {1,0,0,1}
  120976. };
  120977. static vorbis_info_mapping0 _map_nominal[2]={
  120978. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120979. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120980. };
  120981. /*** Start of inlined file: setup_44.h ***/
  120982. /*** Start of inlined file: floor_all.h ***/
  120983. /*** Start of inlined file: floor_books.h ***/
  120984. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120985. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120986. };
  120987. static static_codebook _huff_book_line_256x7_0sub1 = {
  120988. 1, 9,
  120989. _huff_lengthlist_line_256x7_0sub1,
  120990. 0, 0, 0, 0, 0,
  120991. NULL,
  120992. NULL,
  120993. NULL,
  120994. NULL,
  120995. 0
  120996. };
  120997. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120999. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  121000. };
  121001. static static_codebook _huff_book_line_256x7_0sub2 = {
  121002. 1, 25,
  121003. _huff_lengthlist_line_256x7_0sub2,
  121004. 0, 0, 0, 0, 0,
  121005. NULL,
  121006. NULL,
  121007. NULL,
  121008. NULL,
  121009. 0
  121010. };
  121011. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121014. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121015. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121016. };
  121017. static static_codebook _huff_book_line_256x7_0sub3 = {
  121018. 1, 64,
  121019. _huff_lengthlist_line_256x7_0sub3,
  121020. 0, 0, 0, 0, 0,
  121021. NULL,
  121022. NULL,
  121023. NULL,
  121024. NULL,
  121025. 0
  121026. };
  121027. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121028. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121029. };
  121030. static static_codebook _huff_book_line_256x7_1sub1 = {
  121031. 1, 9,
  121032. _huff_lengthlist_line_256x7_1sub1,
  121033. 0, 0, 0, 0, 0,
  121034. NULL,
  121035. NULL,
  121036. NULL,
  121037. NULL,
  121038. 0
  121039. };
  121040. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121042. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121043. };
  121044. static static_codebook _huff_book_line_256x7_1sub2 = {
  121045. 1, 25,
  121046. _huff_lengthlist_line_256x7_1sub2,
  121047. 0, 0, 0, 0, 0,
  121048. NULL,
  121049. NULL,
  121050. NULL,
  121051. NULL,
  121052. 0
  121053. };
  121054. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121057. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121058. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121059. };
  121060. static static_codebook _huff_book_line_256x7_1sub3 = {
  121061. 1, 64,
  121062. _huff_lengthlist_line_256x7_1sub3,
  121063. 0, 0, 0, 0, 0,
  121064. NULL,
  121065. NULL,
  121066. NULL,
  121067. NULL,
  121068. 0
  121069. };
  121070. static long _huff_lengthlist_line_256x7_class0[] = {
  121071. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121072. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121073. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121074. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121075. };
  121076. static static_codebook _huff_book_line_256x7_class0 = {
  121077. 1, 64,
  121078. _huff_lengthlist_line_256x7_class0,
  121079. 0, 0, 0, 0, 0,
  121080. NULL,
  121081. NULL,
  121082. NULL,
  121083. NULL,
  121084. 0
  121085. };
  121086. static long _huff_lengthlist_line_256x7_class1[] = {
  121087. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121088. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121089. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121090. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121091. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121092. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121093. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121094. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121095. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121096. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121097. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121098. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121099. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121100. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121101. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121102. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121103. };
  121104. static static_codebook _huff_book_line_256x7_class1 = {
  121105. 1, 256,
  121106. _huff_lengthlist_line_256x7_class1,
  121107. 0, 0, 0, 0, 0,
  121108. NULL,
  121109. NULL,
  121110. NULL,
  121111. NULL,
  121112. 0
  121113. };
  121114. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121115. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121116. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121117. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121118. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121119. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121120. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121121. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121122. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121123. };
  121124. static static_codebook _huff_book_line_512x17_0sub0 = {
  121125. 1, 128,
  121126. _huff_lengthlist_line_512x17_0sub0,
  121127. 0, 0, 0, 0, 0,
  121128. NULL,
  121129. NULL,
  121130. NULL,
  121131. NULL,
  121132. 0
  121133. };
  121134. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121135. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121136. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121137. };
  121138. static static_codebook _huff_book_line_512x17_1sub0 = {
  121139. 1, 32,
  121140. _huff_lengthlist_line_512x17_1sub0,
  121141. 0, 0, 0, 0, 0,
  121142. NULL,
  121143. NULL,
  121144. NULL,
  121145. NULL,
  121146. 0
  121147. };
  121148. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121151. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121152. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121153. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121154. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121155. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121156. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121157. };
  121158. static static_codebook _huff_book_line_512x17_1sub1 = {
  121159. 1, 128,
  121160. _huff_lengthlist_line_512x17_1sub1,
  121161. 0, 0, 0, 0, 0,
  121162. NULL,
  121163. NULL,
  121164. NULL,
  121165. NULL,
  121166. 0
  121167. };
  121168. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121169. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121170. 5, 3,
  121171. };
  121172. static static_codebook _huff_book_line_512x17_2sub1 = {
  121173. 1, 18,
  121174. _huff_lengthlist_line_512x17_2sub1,
  121175. 0, 0, 0, 0, 0,
  121176. NULL,
  121177. NULL,
  121178. NULL,
  121179. NULL,
  121180. 0
  121181. };
  121182. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121184. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121185. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121186. 9, 8,
  121187. };
  121188. static static_codebook _huff_book_line_512x17_2sub2 = {
  121189. 1, 50,
  121190. _huff_lengthlist_line_512x17_2sub2,
  121191. 0, 0, 0, 0, 0,
  121192. NULL,
  121193. NULL,
  121194. NULL,
  121195. NULL,
  121196. 0
  121197. };
  121198. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121202. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121203. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121204. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121205. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121206. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121207. };
  121208. static static_codebook _huff_book_line_512x17_2sub3 = {
  121209. 1, 128,
  121210. _huff_lengthlist_line_512x17_2sub3,
  121211. 0, 0, 0, 0, 0,
  121212. NULL,
  121213. NULL,
  121214. NULL,
  121215. NULL,
  121216. 0
  121217. };
  121218. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121219. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121220. 5, 5,
  121221. };
  121222. static static_codebook _huff_book_line_512x17_3sub1 = {
  121223. 1, 18,
  121224. _huff_lengthlist_line_512x17_3sub1,
  121225. 0, 0, 0, 0, 0,
  121226. NULL,
  121227. NULL,
  121228. NULL,
  121229. NULL,
  121230. 0
  121231. };
  121232. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121235. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121236. 11,14,
  121237. };
  121238. static static_codebook _huff_book_line_512x17_3sub2 = {
  121239. 1, 50,
  121240. _huff_lengthlist_line_512x17_3sub2,
  121241. 0, 0, 0, 0, 0,
  121242. NULL,
  121243. NULL,
  121244. NULL,
  121245. NULL,
  121246. 0
  121247. };
  121248. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121252. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121253. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121254. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121255. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121256. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121257. };
  121258. static static_codebook _huff_book_line_512x17_3sub3 = {
  121259. 1, 128,
  121260. _huff_lengthlist_line_512x17_3sub3,
  121261. 0, 0, 0, 0, 0,
  121262. NULL,
  121263. NULL,
  121264. NULL,
  121265. NULL,
  121266. 0
  121267. };
  121268. static long _huff_lengthlist_line_512x17_class1[] = {
  121269. 1, 2, 3, 6, 5, 4, 7, 7,
  121270. };
  121271. static static_codebook _huff_book_line_512x17_class1 = {
  121272. 1, 8,
  121273. _huff_lengthlist_line_512x17_class1,
  121274. 0, 0, 0, 0, 0,
  121275. NULL,
  121276. NULL,
  121277. NULL,
  121278. NULL,
  121279. 0
  121280. };
  121281. static long _huff_lengthlist_line_512x17_class2[] = {
  121282. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121283. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121284. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121285. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121286. };
  121287. static static_codebook _huff_book_line_512x17_class2 = {
  121288. 1, 64,
  121289. _huff_lengthlist_line_512x17_class2,
  121290. 0, 0, 0, 0, 0,
  121291. NULL,
  121292. NULL,
  121293. NULL,
  121294. NULL,
  121295. 0
  121296. };
  121297. static long _huff_lengthlist_line_512x17_class3[] = {
  121298. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121299. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121300. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121301. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121302. };
  121303. static static_codebook _huff_book_line_512x17_class3 = {
  121304. 1, 64,
  121305. _huff_lengthlist_line_512x17_class3,
  121306. 0, 0, 0, 0, 0,
  121307. NULL,
  121308. NULL,
  121309. NULL,
  121310. NULL,
  121311. 0
  121312. };
  121313. static long _huff_lengthlist_line_128x4_class0[] = {
  121314. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121315. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121316. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121317. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121318. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121319. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121320. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121321. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121322. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121323. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121324. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121325. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121326. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121327. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121328. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121329. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121330. };
  121331. static static_codebook _huff_book_line_128x4_class0 = {
  121332. 1, 256,
  121333. _huff_lengthlist_line_128x4_class0,
  121334. 0, 0, 0, 0, 0,
  121335. NULL,
  121336. NULL,
  121337. NULL,
  121338. NULL,
  121339. 0
  121340. };
  121341. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121342. 2, 2, 2, 2,
  121343. };
  121344. static static_codebook _huff_book_line_128x4_0sub0 = {
  121345. 1, 4,
  121346. _huff_lengthlist_line_128x4_0sub0,
  121347. 0, 0, 0, 0, 0,
  121348. NULL,
  121349. NULL,
  121350. NULL,
  121351. NULL,
  121352. 0
  121353. };
  121354. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121355. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121356. };
  121357. static static_codebook _huff_book_line_128x4_0sub1 = {
  121358. 1, 10,
  121359. _huff_lengthlist_line_128x4_0sub1,
  121360. 0, 0, 0, 0, 0,
  121361. NULL,
  121362. NULL,
  121363. NULL,
  121364. NULL,
  121365. 0
  121366. };
  121367. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121369. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121370. };
  121371. static static_codebook _huff_book_line_128x4_0sub2 = {
  121372. 1, 25,
  121373. _huff_lengthlist_line_128x4_0sub2,
  121374. 0, 0, 0, 0, 0,
  121375. NULL,
  121376. NULL,
  121377. NULL,
  121378. NULL,
  121379. 0
  121380. };
  121381. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121384. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121385. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121386. };
  121387. static static_codebook _huff_book_line_128x4_0sub3 = {
  121388. 1, 64,
  121389. _huff_lengthlist_line_128x4_0sub3,
  121390. 0, 0, 0, 0, 0,
  121391. NULL,
  121392. NULL,
  121393. NULL,
  121394. NULL,
  121395. 0
  121396. };
  121397. static long _huff_lengthlist_line_256x4_class0[] = {
  121398. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121399. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121400. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121401. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121402. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121403. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121404. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121405. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121406. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121407. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121408. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121409. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121410. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121411. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121412. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121413. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121414. };
  121415. static static_codebook _huff_book_line_256x4_class0 = {
  121416. 1, 256,
  121417. _huff_lengthlist_line_256x4_class0,
  121418. 0, 0, 0, 0, 0,
  121419. NULL,
  121420. NULL,
  121421. NULL,
  121422. NULL,
  121423. 0
  121424. };
  121425. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121426. 2, 2, 2, 2,
  121427. };
  121428. static static_codebook _huff_book_line_256x4_0sub0 = {
  121429. 1, 4,
  121430. _huff_lengthlist_line_256x4_0sub0,
  121431. 0, 0, 0, 0, 0,
  121432. NULL,
  121433. NULL,
  121434. NULL,
  121435. NULL,
  121436. 0
  121437. };
  121438. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121439. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121440. };
  121441. static static_codebook _huff_book_line_256x4_0sub1 = {
  121442. 1, 10,
  121443. _huff_lengthlist_line_256x4_0sub1,
  121444. 0, 0, 0, 0, 0,
  121445. NULL,
  121446. NULL,
  121447. NULL,
  121448. NULL,
  121449. 0
  121450. };
  121451. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121453. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121454. };
  121455. static static_codebook _huff_book_line_256x4_0sub2 = {
  121456. 1, 25,
  121457. _huff_lengthlist_line_256x4_0sub2,
  121458. 0, 0, 0, 0, 0,
  121459. NULL,
  121460. NULL,
  121461. NULL,
  121462. NULL,
  121463. 0
  121464. };
  121465. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121468. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121469. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121470. };
  121471. static static_codebook _huff_book_line_256x4_0sub3 = {
  121472. 1, 64,
  121473. _huff_lengthlist_line_256x4_0sub3,
  121474. 0, 0, 0, 0, 0,
  121475. NULL,
  121476. NULL,
  121477. NULL,
  121478. NULL,
  121479. 0
  121480. };
  121481. static long _huff_lengthlist_line_128x7_class0[] = {
  121482. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121483. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121484. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121485. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121486. };
  121487. static static_codebook _huff_book_line_128x7_class0 = {
  121488. 1, 64,
  121489. _huff_lengthlist_line_128x7_class0,
  121490. 0, 0, 0, 0, 0,
  121491. NULL,
  121492. NULL,
  121493. NULL,
  121494. NULL,
  121495. 0
  121496. };
  121497. static long _huff_lengthlist_line_128x7_class1[] = {
  121498. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121499. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121500. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121501. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121502. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121503. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121504. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121505. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121506. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121507. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121508. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121509. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121510. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121511. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121512. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121513. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121514. };
  121515. static static_codebook _huff_book_line_128x7_class1 = {
  121516. 1, 256,
  121517. _huff_lengthlist_line_128x7_class1,
  121518. 0, 0, 0, 0, 0,
  121519. NULL,
  121520. NULL,
  121521. NULL,
  121522. NULL,
  121523. 0
  121524. };
  121525. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121526. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121527. };
  121528. static static_codebook _huff_book_line_128x7_0sub1 = {
  121529. 1, 9,
  121530. _huff_lengthlist_line_128x7_0sub1,
  121531. 0, 0, 0, 0, 0,
  121532. NULL,
  121533. NULL,
  121534. NULL,
  121535. NULL,
  121536. 0
  121537. };
  121538. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121540. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121541. };
  121542. static static_codebook _huff_book_line_128x7_0sub2 = {
  121543. 1, 25,
  121544. _huff_lengthlist_line_128x7_0sub2,
  121545. 0, 0, 0, 0, 0,
  121546. NULL,
  121547. NULL,
  121548. NULL,
  121549. NULL,
  121550. 0
  121551. };
  121552. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121555. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121556. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121557. };
  121558. static static_codebook _huff_book_line_128x7_0sub3 = {
  121559. 1, 64,
  121560. _huff_lengthlist_line_128x7_0sub3,
  121561. 0, 0, 0, 0, 0,
  121562. NULL,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. 0
  121567. };
  121568. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121569. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121570. };
  121571. static static_codebook _huff_book_line_128x7_1sub1 = {
  121572. 1, 9,
  121573. _huff_lengthlist_line_128x7_1sub1,
  121574. 0, 0, 0, 0, 0,
  121575. NULL,
  121576. NULL,
  121577. NULL,
  121578. NULL,
  121579. 0
  121580. };
  121581. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121583. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121584. };
  121585. static static_codebook _huff_book_line_128x7_1sub2 = {
  121586. 1, 25,
  121587. _huff_lengthlist_line_128x7_1sub2,
  121588. 0, 0, 0, 0, 0,
  121589. NULL,
  121590. NULL,
  121591. NULL,
  121592. NULL,
  121593. 0
  121594. };
  121595. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121598. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121599. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121600. };
  121601. static static_codebook _huff_book_line_128x7_1sub3 = {
  121602. 1, 64,
  121603. _huff_lengthlist_line_128x7_1sub3,
  121604. 0, 0, 0, 0, 0,
  121605. NULL,
  121606. NULL,
  121607. NULL,
  121608. NULL,
  121609. 0
  121610. };
  121611. static long _huff_lengthlist_line_128x11_class1[] = {
  121612. 1, 6, 3, 7, 2, 4, 5, 7,
  121613. };
  121614. static static_codebook _huff_book_line_128x11_class1 = {
  121615. 1, 8,
  121616. _huff_lengthlist_line_128x11_class1,
  121617. 0, 0, 0, 0, 0,
  121618. NULL,
  121619. NULL,
  121620. NULL,
  121621. NULL,
  121622. 0
  121623. };
  121624. static long _huff_lengthlist_line_128x11_class2[] = {
  121625. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121626. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121627. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121628. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121629. };
  121630. static static_codebook _huff_book_line_128x11_class2 = {
  121631. 1, 64,
  121632. _huff_lengthlist_line_128x11_class2,
  121633. 0, 0, 0, 0, 0,
  121634. NULL,
  121635. NULL,
  121636. NULL,
  121637. NULL,
  121638. 0
  121639. };
  121640. static long _huff_lengthlist_line_128x11_class3[] = {
  121641. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121642. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121643. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121644. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121645. };
  121646. static static_codebook _huff_book_line_128x11_class3 = {
  121647. 1, 64,
  121648. _huff_lengthlist_line_128x11_class3,
  121649. 0, 0, 0, 0, 0,
  121650. NULL,
  121651. NULL,
  121652. NULL,
  121653. NULL,
  121654. 0
  121655. };
  121656. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121657. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121658. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121659. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121660. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121661. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121662. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121663. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121664. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121665. };
  121666. static static_codebook _huff_book_line_128x11_0sub0 = {
  121667. 1, 128,
  121668. _huff_lengthlist_line_128x11_0sub0,
  121669. 0, 0, 0, 0, 0,
  121670. NULL,
  121671. NULL,
  121672. NULL,
  121673. NULL,
  121674. 0
  121675. };
  121676. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121677. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121678. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121679. };
  121680. static static_codebook _huff_book_line_128x11_1sub0 = {
  121681. 1, 32,
  121682. _huff_lengthlist_line_128x11_1sub0,
  121683. 0, 0, 0, 0, 0,
  121684. NULL,
  121685. NULL,
  121686. NULL,
  121687. NULL,
  121688. 0
  121689. };
  121690. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121693. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121694. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121695. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121696. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121697. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121698. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121699. };
  121700. static static_codebook _huff_book_line_128x11_1sub1 = {
  121701. 1, 128,
  121702. _huff_lengthlist_line_128x11_1sub1,
  121703. 0, 0, 0, 0, 0,
  121704. NULL,
  121705. NULL,
  121706. NULL,
  121707. NULL,
  121708. 0
  121709. };
  121710. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121711. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121712. 5, 5,
  121713. };
  121714. static static_codebook _huff_book_line_128x11_2sub1 = {
  121715. 1, 18,
  121716. _huff_lengthlist_line_128x11_2sub1,
  121717. 0, 0, 0, 0, 0,
  121718. NULL,
  121719. NULL,
  121720. NULL,
  121721. NULL,
  121722. 0
  121723. };
  121724. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121726. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121727. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121728. 8,11,
  121729. };
  121730. static static_codebook _huff_book_line_128x11_2sub2 = {
  121731. 1, 50,
  121732. _huff_lengthlist_line_128x11_2sub2,
  121733. 0, 0, 0, 0, 0,
  121734. NULL,
  121735. NULL,
  121736. NULL,
  121737. NULL,
  121738. 0
  121739. };
  121740. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121741. 0, 0, 0, 0, 0, 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, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121745. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121746. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121747. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121748. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121749. };
  121750. static static_codebook _huff_book_line_128x11_2sub3 = {
  121751. 1, 128,
  121752. _huff_lengthlist_line_128x11_2sub3,
  121753. 0, 0, 0, 0, 0,
  121754. NULL,
  121755. NULL,
  121756. NULL,
  121757. NULL,
  121758. 0
  121759. };
  121760. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121761. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121762. 5, 4,
  121763. };
  121764. static static_codebook _huff_book_line_128x11_3sub1 = {
  121765. 1, 18,
  121766. _huff_lengthlist_line_128x11_3sub1,
  121767. 0, 0, 0, 0, 0,
  121768. NULL,
  121769. NULL,
  121770. NULL,
  121771. NULL,
  121772. 0
  121773. };
  121774. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121777. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121778. 12, 6,
  121779. };
  121780. static static_codebook _huff_book_line_128x11_3sub2 = {
  121781. 1, 50,
  121782. _huff_lengthlist_line_128x11_3sub2,
  121783. 0, 0, 0, 0, 0,
  121784. NULL,
  121785. NULL,
  121786. NULL,
  121787. NULL,
  121788. 0
  121789. };
  121790. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121795. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121796. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121797. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121798. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121799. };
  121800. static static_codebook _huff_book_line_128x11_3sub3 = {
  121801. 1, 128,
  121802. _huff_lengthlist_line_128x11_3sub3,
  121803. 0, 0, 0, 0, 0,
  121804. NULL,
  121805. NULL,
  121806. NULL,
  121807. NULL,
  121808. 0
  121809. };
  121810. static long _huff_lengthlist_line_128x17_class1[] = {
  121811. 1, 3, 4, 7, 2, 5, 6, 7,
  121812. };
  121813. static static_codebook _huff_book_line_128x17_class1 = {
  121814. 1, 8,
  121815. _huff_lengthlist_line_128x17_class1,
  121816. 0, 0, 0, 0, 0,
  121817. NULL,
  121818. NULL,
  121819. NULL,
  121820. NULL,
  121821. 0
  121822. };
  121823. static long _huff_lengthlist_line_128x17_class2[] = {
  121824. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121825. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121826. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121827. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121828. };
  121829. static static_codebook _huff_book_line_128x17_class2 = {
  121830. 1, 64,
  121831. _huff_lengthlist_line_128x17_class2,
  121832. 0, 0, 0, 0, 0,
  121833. NULL,
  121834. NULL,
  121835. NULL,
  121836. NULL,
  121837. 0
  121838. };
  121839. static long _huff_lengthlist_line_128x17_class3[] = {
  121840. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121841. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121842. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121843. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121844. };
  121845. static static_codebook _huff_book_line_128x17_class3 = {
  121846. 1, 64,
  121847. _huff_lengthlist_line_128x17_class3,
  121848. 0, 0, 0, 0, 0,
  121849. NULL,
  121850. NULL,
  121851. NULL,
  121852. NULL,
  121853. 0
  121854. };
  121855. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121856. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121857. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121858. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121859. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121860. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121861. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121862. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121863. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121864. };
  121865. static static_codebook _huff_book_line_128x17_0sub0 = {
  121866. 1, 128,
  121867. _huff_lengthlist_line_128x17_0sub0,
  121868. 0, 0, 0, 0, 0,
  121869. NULL,
  121870. NULL,
  121871. NULL,
  121872. NULL,
  121873. 0
  121874. };
  121875. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121876. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121877. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121878. };
  121879. static static_codebook _huff_book_line_128x17_1sub0 = {
  121880. 1, 32,
  121881. _huff_lengthlist_line_128x17_1sub0,
  121882. 0, 0, 0, 0, 0,
  121883. NULL,
  121884. NULL,
  121885. NULL,
  121886. NULL,
  121887. 0
  121888. };
  121889. static long _huff_lengthlist_line_128x17_1sub1[] = {
  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. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121893. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121894. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121895. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121896. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121897. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121898. };
  121899. static static_codebook _huff_book_line_128x17_1sub1 = {
  121900. 1, 128,
  121901. _huff_lengthlist_line_128x17_1sub1,
  121902. 0, 0, 0, 0, 0,
  121903. NULL,
  121904. NULL,
  121905. NULL,
  121906. NULL,
  121907. 0
  121908. };
  121909. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121910. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121911. 9, 4,
  121912. };
  121913. static static_codebook _huff_book_line_128x17_2sub1 = {
  121914. 1, 18,
  121915. _huff_lengthlist_line_128x17_2sub1,
  121916. 0, 0, 0, 0, 0,
  121917. NULL,
  121918. NULL,
  121919. NULL,
  121920. NULL,
  121921. 0
  121922. };
  121923. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121926. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121927. 13,13,
  121928. };
  121929. static static_codebook _huff_book_line_128x17_2sub2 = {
  121930. 1, 50,
  121931. _huff_lengthlist_line_128x17_2sub2,
  121932. 0, 0, 0, 0, 0,
  121933. NULL,
  121934. NULL,
  121935. NULL,
  121936. NULL,
  121937. 0
  121938. };
  121939. static long _huff_lengthlist_line_128x17_2sub3[] = {
  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, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121944. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121945. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121946. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121947. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121948. };
  121949. static static_codebook _huff_book_line_128x17_2sub3 = {
  121950. 1, 128,
  121951. _huff_lengthlist_line_128x17_2sub3,
  121952. 0, 0, 0, 0, 0,
  121953. NULL,
  121954. NULL,
  121955. NULL,
  121956. NULL,
  121957. 0
  121958. };
  121959. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121960. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121961. 6, 4,
  121962. };
  121963. static static_codebook _huff_book_line_128x17_3sub1 = {
  121964. 1, 18,
  121965. _huff_lengthlist_line_128x17_3sub1,
  121966. 0, 0, 0, 0, 0,
  121967. NULL,
  121968. NULL,
  121969. NULL,
  121970. NULL,
  121971. 0
  121972. };
  121973. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121975. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121976. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121977. 10, 8,
  121978. };
  121979. static static_codebook _huff_book_line_128x17_3sub2 = {
  121980. 1, 50,
  121981. _huff_lengthlist_line_128x17_3sub2,
  121982. 0, 0, 0, 0, 0,
  121983. NULL,
  121984. NULL,
  121985. NULL,
  121986. NULL,
  121987. 0
  121988. };
  121989. static long _huff_lengthlist_line_128x17_3sub3[] = {
  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, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121994. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121995. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121998. };
  121999. static static_codebook _huff_book_line_128x17_3sub3 = {
  122000. 1, 128,
  122001. _huff_lengthlist_line_128x17_3sub3,
  122002. 0, 0, 0, 0, 0,
  122003. NULL,
  122004. NULL,
  122005. NULL,
  122006. NULL,
  122007. 0
  122008. };
  122009. static long _huff_lengthlist_line_1024x27_class1[] = {
  122010. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122011. };
  122012. static static_codebook _huff_book_line_1024x27_class1 = {
  122013. 1, 16,
  122014. _huff_lengthlist_line_1024x27_class1,
  122015. 0, 0, 0, 0, 0,
  122016. NULL,
  122017. NULL,
  122018. NULL,
  122019. NULL,
  122020. 0
  122021. };
  122022. static long _huff_lengthlist_line_1024x27_class2[] = {
  122023. 1, 4, 2, 6, 3, 7, 5, 7,
  122024. };
  122025. static static_codebook _huff_book_line_1024x27_class2 = {
  122026. 1, 8,
  122027. _huff_lengthlist_line_1024x27_class2,
  122028. 0, 0, 0, 0, 0,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. NULL,
  122033. 0
  122034. };
  122035. static long _huff_lengthlist_line_1024x27_class3[] = {
  122036. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122037. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122038. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122039. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122040. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122041. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122042. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122043. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122044. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122045. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122046. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122047. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122048. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122049. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122050. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122051. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122052. };
  122053. static static_codebook _huff_book_line_1024x27_class3 = {
  122054. 1, 256,
  122055. _huff_lengthlist_line_1024x27_class3,
  122056. 0, 0, 0, 0, 0,
  122057. NULL,
  122058. NULL,
  122059. NULL,
  122060. NULL,
  122061. 0
  122062. };
  122063. static long _huff_lengthlist_line_1024x27_class4[] = {
  122064. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122065. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122066. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122067. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122068. };
  122069. static static_codebook _huff_book_line_1024x27_class4 = {
  122070. 1, 64,
  122071. _huff_lengthlist_line_1024x27_class4,
  122072. 0, 0, 0, 0, 0,
  122073. NULL,
  122074. NULL,
  122075. NULL,
  122076. NULL,
  122077. 0
  122078. };
  122079. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122080. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122081. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122082. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122083. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122084. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122085. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122086. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122087. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122088. };
  122089. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122090. 1, 128,
  122091. _huff_lengthlist_line_1024x27_0sub0,
  122092. 0, 0, 0, 0, 0,
  122093. NULL,
  122094. NULL,
  122095. NULL,
  122096. NULL,
  122097. 0
  122098. };
  122099. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122100. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122101. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122102. };
  122103. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122104. 1, 32,
  122105. _huff_lengthlist_line_1024x27_1sub0,
  122106. 0, 0, 0, 0, 0,
  122107. NULL,
  122108. NULL,
  122109. NULL,
  122110. NULL,
  122111. 0
  122112. };
  122113. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  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. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122117. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122118. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122119. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122120. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122121. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122122. };
  122123. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122124. 1, 128,
  122125. _huff_lengthlist_line_1024x27_1sub1,
  122126. 0, 0, 0, 0, 0,
  122127. NULL,
  122128. NULL,
  122129. NULL,
  122130. NULL,
  122131. 0
  122132. };
  122133. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122134. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122135. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122136. };
  122137. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122138. 1, 32,
  122139. _huff_lengthlist_line_1024x27_2sub0,
  122140. 0, 0, 0, 0, 0,
  122141. NULL,
  122142. NULL,
  122143. NULL,
  122144. NULL,
  122145. 0
  122146. };
  122147. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  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. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122151. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122152. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122153. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122154. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122155. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122156. };
  122157. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122158. 1, 128,
  122159. _huff_lengthlist_line_1024x27_2sub1,
  122160. 0, 0, 0, 0, 0,
  122161. NULL,
  122162. NULL,
  122163. NULL,
  122164. NULL,
  122165. 0
  122166. };
  122167. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122168. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122169. 5, 5,
  122170. };
  122171. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122172. 1, 18,
  122173. _huff_lengthlist_line_1024x27_3sub1,
  122174. 0, 0, 0, 0, 0,
  122175. NULL,
  122176. NULL,
  122177. NULL,
  122178. NULL,
  122179. 0
  122180. };
  122181. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122184. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122185. 9,11,
  122186. };
  122187. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122188. 1, 50,
  122189. _huff_lengthlist_line_1024x27_3sub2,
  122190. 0, 0, 0, 0, 0,
  122191. NULL,
  122192. NULL,
  122193. NULL,
  122194. NULL,
  122195. 0
  122196. };
  122197. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  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, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122202. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122203. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122204. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122205. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122206. };
  122207. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122208. 1, 128,
  122209. _huff_lengthlist_line_1024x27_3sub3,
  122210. 0, 0, 0, 0, 0,
  122211. NULL,
  122212. NULL,
  122213. NULL,
  122214. NULL,
  122215. 0
  122216. };
  122217. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122218. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122219. 5, 4,
  122220. };
  122221. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122222. 1, 18,
  122223. _huff_lengthlist_line_1024x27_4sub1,
  122224. 0, 0, 0, 0, 0,
  122225. NULL,
  122226. NULL,
  122227. NULL,
  122228. NULL,
  122229. 0
  122230. };
  122231. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122233. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122234. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122235. 9,12,
  122236. };
  122237. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122238. 1, 50,
  122239. _huff_lengthlist_line_1024x27_4sub2,
  122240. 0, 0, 0, 0, 0,
  122241. NULL,
  122242. NULL,
  122243. NULL,
  122244. NULL,
  122245. 0
  122246. };
  122247. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122251. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122252. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122255. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122256. };
  122257. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122258. 1, 128,
  122259. _huff_lengthlist_line_1024x27_4sub3,
  122260. 0, 0, 0, 0, 0,
  122261. NULL,
  122262. NULL,
  122263. NULL,
  122264. NULL,
  122265. 0
  122266. };
  122267. static long _huff_lengthlist_line_2048x27_class1[] = {
  122268. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122269. };
  122270. static static_codebook _huff_book_line_2048x27_class1 = {
  122271. 1, 16,
  122272. _huff_lengthlist_line_2048x27_class1,
  122273. 0, 0, 0, 0, 0,
  122274. NULL,
  122275. NULL,
  122276. NULL,
  122277. NULL,
  122278. 0
  122279. };
  122280. static long _huff_lengthlist_line_2048x27_class2[] = {
  122281. 1, 2, 3, 6, 4, 7, 5, 7,
  122282. };
  122283. static static_codebook _huff_book_line_2048x27_class2 = {
  122284. 1, 8,
  122285. _huff_lengthlist_line_2048x27_class2,
  122286. 0, 0, 0, 0, 0,
  122287. NULL,
  122288. NULL,
  122289. NULL,
  122290. NULL,
  122291. 0
  122292. };
  122293. static long _huff_lengthlist_line_2048x27_class3[] = {
  122294. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122295. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122296. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122297. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122298. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122299. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122300. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122301. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122302. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122303. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122304. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122305. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122306. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122307. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122308. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122309. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122310. };
  122311. static static_codebook _huff_book_line_2048x27_class3 = {
  122312. 1, 256,
  122313. _huff_lengthlist_line_2048x27_class3,
  122314. 0, 0, 0, 0, 0,
  122315. NULL,
  122316. NULL,
  122317. NULL,
  122318. NULL,
  122319. 0
  122320. };
  122321. static long _huff_lengthlist_line_2048x27_class4[] = {
  122322. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122323. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122324. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122325. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122326. };
  122327. static static_codebook _huff_book_line_2048x27_class4 = {
  122328. 1, 64,
  122329. _huff_lengthlist_line_2048x27_class4,
  122330. 0, 0, 0, 0, 0,
  122331. NULL,
  122332. NULL,
  122333. NULL,
  122334. NULL,
  122335. 0
  122336. };
  122337. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122338. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122339. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122340. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122341. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122342. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122343. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122344. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122345. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122346. };
  122347. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122348. 1, 128,
  122349. _huff_lengthlist_line_2048x27_0sub0,
  122350. 0, 0, 0, 0, 0,
  122351. NULL,
  122352. NULL,
  122353. NULL,
  122354. NULL,
  122355. 0
  122356. };
  122357. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122358. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122359. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122360. };
  122361. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122362. 1, 32,
  122363. _huff_lengthlist_line_2048x27_1sub0,
  122364. 0, 0, 0, 0, 0,
  122365. NULL,
  122366. NULL,
  122367. NULL,
  122368. NULL,
  122369. 0
  122370. };
  122371. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122375. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122376. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122377. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122378. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122379. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122380. };
  122381. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122382. 1, 128,
  122383. _huff_lengthlist_line_2048x27_1sub1,
  122384. 0, 0, 0, 0, 0,
  122385. NULL,
  122386. NULL,
  122387. NULL,
  122388. NULL,
  122389. 0
  122390. };
  122391. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122392. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122393. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122394. };
  122395. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122396. 1, 32,
  122397. _huff_lengthlist_line_2048x27_2sub0,
  122398. 0, 0, 0, 0, 0,
  122399. NULL,
  122400. NULL,
  122401. NULL,
  122402. NULL,
  122403. 0
  122404. };
  122405. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122409. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122410. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122411. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122412. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122413. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122414. };
  122415. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122416. 1, 128,
  122417. _huff_lengthlist_line_2048x27_2sub1,
  122418. 0, 0, 0, 0, 0,
  122419. NULL,
  122420. NULL,
  122421. NULL,
  122422. NULL,
  122423. 0
  122424. };
  122425. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122426. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122427. 5, 5,
  122428. };
  122429. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122430. 1, 18,
  122431. _huff_lengthlist_line_2048x27_3sub1,
  122432. 0, 0, 0, 0, 0,
  122433. NULL,
  122434. NULL,
  122435. NULL,
  122436. NULL,
  122437. 0
  122438. };
  122439. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122442. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122443. 10,12,
  122444. };
  122445. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122446. 1, 50,
  122447. _huff_lengthlist_line_2048x27_3sub2,
  122448. 0, 0, 0, 0, 0,
  122449. NULL,
  122450. NULL,
  122451. NULL,
  122452. NULL,
  122453. 0
  122454. };
  122455. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122460. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122461. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122462. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122463. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122464. };
  122465. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122466. 1, 128,
  122467. _huff_lengthlist_line_2048x27_3sub3,
  122468. 0, 0, 0, 0, 0,
  122469. NULL,
  122470. NULL,
  122471. NULL,
  122472. NULL,
  122473. 0
  122474. };
  122475. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122476. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122477. 4, 5,
  122478. };
  122479. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122480. 1, 18,
  122481. _huff_lengthlist_line_2048x27_4sub1,
  122482. 0, 0, 0, 0, 0,
  122483. NULL,
  122484. NULL,
  122485. NULL,
  122486. NULL,
  122487. 0
  122488. };
  122489. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122492. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122493. 10,10,
  122494. };
  122495. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122496. 1, 50,
  122497. _huff_lengthlist_line_2048x27_4sub2,
  122498. 0, 0, 0, 0, 0,
  122499. NULL,
  122500. NULL,
  122501. NULL,
  122502. NULL,
  122503. 0
  122504. };
  122505. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122510. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122511. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122512. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122513. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122514. };
  122515. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122516. 1, 128,
  122517. _huff_lengthlist_line_2048x27_4sub3,
  122518. 0, 0, 0, 0, 0,
  122519. NULL,
  122520. NULL,
  122521. NULL,
  122522. NULL,
  122523. 0
  122524. };
  122525. static long _huff_lengthlist_line_256x4low_class0[] = {
  122526. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122527. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122528. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122529. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122530. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122531. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122532. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122533. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122534. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122535. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122536. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122537. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122538. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122539. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122540. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122541. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122542. };
  122543. static static_codebook _huff_book_line_256x4low_class0 = {
  122544. 1, 256,
  122545. _huff_lengthlist_line_256x4low_class0,
  122546. 0, 0, 0, 0, 0,
  122547. NULL,
  122548. NULL,
  122549. NULL,
  122550. NULL,
  122551. 0
  122552. };
  122553. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122554. 1, 3, 2, 3,
  122555. };
  122556. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122557. 1, 4,
  122558. _huff_lengthlist_line_256x4low_0sub0,
  122559. 0, 0, 0, 0, 0,
  122560. NULL,
  122561. NULL,
  122562. NULL,
  122563. NULL,
  122564. 0
  122565. };
  122566. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122567. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122568. };
  122569. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122570. 1, 10,
  122571. _huff_lengthlist_line_256x4low_0sub1,
  122572. 0, 0, 0, 0, 0,
  122573. NULL,
  122574. NULL,
  122575. NULL,
  122576. NULL,
  122577. 0
  122578. };
  122579. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122581. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122582. };
  122583. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122584. 1, 25,
  122585. _huff_lengthlist_line_256x4low_0sub2,
  122586. 0, 0, 0, 0, 0,
  122587. NULL,
  122588. NULL,
  122589. NULL,
  122590. NULL,
  122591. 0
  122592. };
  122593. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122596. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122597. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122598. };
  122599. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122600. 1, 64,
  122601. _huff_lengthlist_line_256x4low_0sub3,
  122602. 0, 0, 0, 0, 0,
  122603. NULL,
  122604. NULL,
  122605. NULL,
  122606. NULL,
  122607. 0
  122608. };
  122609. /*** End of inlined file: floor_books.h ***/
  122610. static static_codebook *_floor_128x4_books[]={
  122611. &_huff_book_line_128x4_class0,
  122612. &_huff_book_line_128x4_0sub0,
  122613. &_huff_book_line_128x4_0sub1,
  122614. &_huff_book_line_128x4_0sub2,
  122615. &_huff_book_line_128x4_0sub3,
  122616. };
  122617. static static_codebook *_floor_256x4_books[]={
  122618. &_huff_book_line_256x4_class0,
  122619. &_huff_book_line_256x4_0sub0,
  122620. &_huff_book_line_256x4_0sub1,
  122621. &_huff_book_line_256x4_0sub2,
  122622. &_huff_book_line_256x4_0sub3,
  122623. };
  122624. static static_codebook *_floor_128x7_books[]={
  122625. &_huff_book_line_128x7_class0,
  122626. &_huff_book_line_128x7_class1,
  122627. &_huff_book_line_128x7_0sub1,
  122628. &_huff_book_line_128x7_0sub2,
  122629. &_huff_book_line_128x7_0sub3,
  122630. &_huff_book_line_128x7_1sub1,
  122631. &_huff_book_line_128x7_1sub2,
  122632. &_huff_book_line_128x7_1sub3,
  122633. };
  122634. static static_codebook *_floor_256x7_books[]={
  122635. &_huff_book_line_256x7_class0,
  122636. &_huff_book_line_256x7_class1,
  122637. &_huff_book_line_256x7_0sub1,
  122638. &_huff_book_line_256x7_0sub2,
  122639. &_huff_book_line_256x7_0sub3,
  122640. &_huff_book_line_256x7_1sub1,
  122641. &_huff_book_line_256x7_1sub2,
  122642. &_huff_book_line_256x7_1sub3,
  122643. };
  122644. static static_codebook *_floor_128x11_books[]={
  122645. &_huff_book_line_128x11_class1,
  122646. &_huff_book_line_128x11_class2,
  122647. &_huff_book_line_128x11_class3,
  122648. &_huff_book_line_128x11_0sub0,
  122649. &_huff_book_line_128x11_1sub0,
  122650. &_huff_book_line_128x11_1sub1,
  122651. &_huff_book_line_128x11_2sub1,
  122652. &_huff_book_line_128x11_2sub2,
  122653. &_huff_book_line_128x11_2sub3,
  122654. &_huff_book_line_128x11_3sub1,
  122655. &_huff_book_line_128x11_3sub2,
  122656. &_huff_book_line_128x11_3sub3,
  122657. };
  122658. static static_codebook *_floor_128x17_books[]={
  122659. &_huff_book_line_128x17_class1,
  122660. &_huff_book_line_128x17_class2,
  122661. &_huff_book_line_128x17_class3,
  122662. &_huff_book_line_128x17_0sub0,
  122663. &_huff_book_line_128x17_1sub0,
  122664. &_huff_book_line_128x17_1sub1,
  122665. &_huff_book_line_128x17_2sub1,
  122666. &_huff_book_line_128x17_2sub2,
  122667. &_huff_book_line_128x17_2sub3,
  122668. &_huff_book_line_128x17_3sub1,
  122669. &_huff_book_line_128x17_3sub2,
  122670. &_huff_book_line_128x17_3sub3,
  122671. };
  122672. static static_codebook *_floor_256x4low_books[]={
  122673. &_huff_book_line_256x4low_class0,
  122674. &_huff_book_line_256x4low_0sub0,
  122675. &_huff_book_line_256x4low_0sub1,
  122676. &_huff_book_line_256x4low_0sub2,
  122677. &_huff_book_line_256x4low_0sub3,
  122678. };
  122679. static static_codebook *_floor_1024x27_books[]={
  122680. &_huff_book_line_1024x27_class1,
  122681. &_huff_book_line_1024x27_class2,
  122682. &_huff_book_line_1024x27_class3,
  122683. &_huff_book_line_1024x27_class4,
  122684. &_huff_book_line_1024x27_0sub0,
  122685. &_huff_book_line_1024x27_1sub0,
  122686. &_huff_book_line_1024x27_1sub1,
  122687. &_huff_book_line_1024x27_2sub0,
  122688. &_huff_book_line_1024x27_2sub1,
  122689. &_huff_book_line_1024x27_3sub1,
  122690. &_huff_book_line_1024x27_3sub2,
  122691. &_huff_book_line_1024x27_3sub3,
  122692. &_huff_book_line_1024x27_4sub1,
  122693. &_huff_book_line_1024x27_4sub2,
  122694. &_huff_book_line_1024x27_4sub3,
  122695. };
  122696. static static_codebook *_floor_2048x27_books[]={
  122697. &_huff_book_line_2048x27_class1,
  122698. &_huff_book_line_2048x27_class2,
  122699. &_huff_book_line_2048x27_class3,
  122700. &_huff_book_line_2048x27_class4,
  122701. &_huff_book_line_2048x27_0sub0,
  122702. &_huff_book_line_2048x27_1sub0,
  122703. &_huff_book_line_2048x27_1sub1,
  122704. &_huff_book_line_2048x27_2sub0,
  122705. &_huff_book_line_2048x27_2sub1,
  122706. &_huff_book_line_2048x27_3sub1,
  122707. &_huff_book_line_2048x27_3sub2,
  122708. &_huff_book_line_2048x27_3sub3,
  122709. &_huff_book_line_2048x27_4sub1,
  122710. &_huff_book_line_2048x27_4sub2,
  122711. &_huff_book_line_2048x27_4sub3,
  122712. };
  122713. static static_codebook *_floor_512x17_books[]={
  122714. &_huff_book_line_512x17_class1,
  122715. &_huff_book_line_512x17_class2,
  122716. &_huff_book_line_512x17_class3,
  122717. &_huff_book_line_512x17_0sub0,
  122718. &_huff_book_line_512x17_1sub0,
  122719. &_huff_book_line_512x17_1sub1,
  122720. &_huff_book_line_512x17_2sub1,
  122721. &_huff_book_line_512x17_2sub2,
  122722. &_huff_book_line_512x17_2sub3,
  122723. &_huff_book_line_512x17_3sub1,
  122724. &_huff_book_line_512x17_3sub2,
  122725. &_huff_book_line_512x17_3sub3,
  122726. };
  122727. static static_codebook **_floor_books[10]={
  122728. _floor_128x4_books,
  122729. _floor_256x4_books,
  122730. _floor_128x7_books,
  122731. _floor_256x7_books,
  122732. _floor_128x11_books,
  122733. _floor_128x17_books,
  122734. _floor_256x4low_books,
  122735. _floor_1024x27_books,
  122736. _floor_2048x27_books,
  122737. _floor_512x17_books,
  122738. };
  122739. static vorbis_info_floor1 _floor[10]={
  122740. /* 128 x 4 */
  122741. {
  122742. 1,{0},{4},{2},{0},
  122743. {{1,2,3,4}},
  122744. 4,{0,128, 33,8,16,70},
  122745. 60,30,500, 1.,18., -1
  122746. },
  122747. /* 256 x 4 */
  122748. {
  122749. 1,{0},{4},{2},{0},
  122750. {{1,2,3,4}},
  122751. 4,{0,256, 66,16,32,140},
  122752. 60,30,500, 1.,18., -1
  122753. },
  122754. /* 128 x 7 */
  122755. {
  122756. 2,{0,1},{3,4},{2,2},{0,1},
  122757. {{-1,2,3,4},{-1,5,6,7}},
  122758. 4,{0,128, 14,4,58, 2,8,28,90},
  122759. 60,30,500, 1.,18., -1
  122760. },
  122761. /* 256 x 7 */
  122762. {
  122763. 2,{0,1},{3,4},{2,2},{0,1},
  122764. {{-1,2,3,4},{-1,5,6,7}},
  122765. 4,{0,256, 28,8,116, 4,16,56,180},
  122766. 60,30,500, 1.,18., -1
  122767. },
  122768. /* 128 x 11 */
  122769. {
  122770. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122771. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122772. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122773. 60,30,500, 1,18., -1
  122774. },
  122775. /* 128 x 17 */
  122776. {
  122777. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122778. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122779. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122780. 60,30,500, 1,18., -1
  122781. },
  122782. /* 256 x 4 (low bitrate version) */
  122783. {
  122784. 1,{0},{4},{2},{0},
  122785. {{1,2,3,4}},
  122786. 4,{0,256, 66,16,32,140},
  122787. 60,30,500, 1.,18., -1
  122788. },
  122789. /* 1024 x 27 */
  122790. {
  122791. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122792. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122793. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122794. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122795. 60,30,500, 3,18., -1 /* lowpass */
  122796. },
  122797. /* 2048 x 27 */
  122798. {
  122799. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122800. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122801. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122802. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122803. 60,30,500, 3,18., -1 /* lowpass */
  122804. },
  122805. /* 512 x 17 */
  122806. {
  122807. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122808. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122809. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122810. 7,23,39, 55,79,110, 156,232,360},
  122811. 60,30,500, 1,18., -1 /* lowpass! */
  122812. },
  122813. };
  122814. /*** End of inlined file: floor_all.h ***/
  122815. /*** Start of inlined file: residue_44.h ***/
  122816. /*** Start of inlined file: res_books_stereo.h ***/
  122817. static long _vq_quantlist__16c0_s_p1_0[] = {
  122818. 1,
  122819. 0,
  122820. 2,
  122821. };
  122822. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122823. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122824. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122829. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122834. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122869. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122874. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122879. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122915. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122920. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122925. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123053. 0, 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,
  123234. };
  123235. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123236. -0.5, 0.5,
  123237. };
  123238. static long _vq_quantmap__16c0_s_p1_0[] = {
  123239. 1, 0, 2,
  123240. };
  123241. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123242. _vq_quantthresh__16c0_s_p1_0,
  123243. _vq_quantmap__16c0_s_p1_0,
  123244. 3,
  123245. 3
  123246. };
  123247. static static_codebook _16c0_s_p1_0 = {
  123248. 8, 6561,
  123249. _vq_lengthlist__16c0_s_p1_0,
  123250. 1, -535822336, 1611661312, 2, 0,
  123251. _vq_quantlist__16c0_s_p1_0,
  123252. NULL,
  123253. &_vq_auxt__16c0_s_p1_0,
  123254. NULL,
  123255. 0
  123256. };
  123257. static long _vq_quantlist__16c0_s_p2_0[] = {
  123258. 2,
  123259. 1,
  123260. 3,
  123261. 0,
  123262. 4,
  123263. };
  123264. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123304. 0,
  123305. };
  123306. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123307. -1.5, -0.5, 0.5, 1.5,
  123308. };
  123309. static long _vq_quantmap__16c0_s_p2_0[] = {
  123310. 3, 1, 0, 2, 4,
  123311. };
  123312. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123313. _vq_quantthresh__16c0_s_p2_0,
  123314. _vq_quantmap__16c0_s_p2_0,
  123315. 5,
  123316. 5
  123317. };
  123318. static static_codebook _16c0_s_p2_0 = {
  123319. 4, 625,
  123320. _vq_lengthlist__16c0_s_p2_0,
  123321. 1, -533725184, 1611661312, 3, 0,
  123322. _vq_quantlist__16c0_s_p2_0,
  123323. NULL,
  123324. &_vq_auxt__16c0_s_p2_0,
  123325. NULL,
  123326. 0
  123327. };
  123328. static long _vq_quantlist__16c0_s_p3_0[] = {
  123329. 2,
  123330. 1,
  123331. 3,
  123332. 0,
  123333. 4,
  123334. };
  123335. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123336. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123342. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0,
  123376. };
  123377. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123378. -1.5, -0.5, 0.5, 1.5,
  123379. };
  123380. static long _vq_quantmap__16c0_s_p3_0[] = {
  123381. 3, 1, 0, 2, 4,
  123382. };
  123383. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123384. _vq_quantthresh__16c0_s_p3_0,
  123385. _vq_quantmap__16c0_s_p3_0,
  123386. 5,
  123387. 5
  123388. };
  123389. static static_codebook _16c0_s_p3_0 = {
  123390. 4, 625,
  123391. _vq_lengthlist__16c0_s_p3_0,
  123392. 1, -533725184, 1611661312, 3, 0,
  123393. _vq_quantlist__16c0_s_p3_0,
  123394. NULL,
  123395. &_vq_auxt__16c0_s_p3_0,
  123396. NULL,
  123397. 0
  123398. };
  123399. static long _vq_quantlist__16c0_s_p4_0[] = {
  123400. 4,
  123401. 3,
  123402. 5,
  123403. 2,
  123404. 6,
  123405. 1,
  123406. 7,
  123407. 0,
  123408. 8,
  123409. };
  123410. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123411. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123412. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123413. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123414. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123415. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0,
  123417. };
  123418. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123419. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123420. };
  123421. static long _vq_quantmap__16c0_s_p4_0[] = {
  123422. 7, 5, 3, 1, 0, 2, 4, 6,
  123423. 8,
  123424. };
  123425. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123426. _vq_quantthresh__16c0_s_p4_0,
  123427. _vq_quantmap__16c0_s_p4_0,
  123428. 9,
  123429. 9
  123430. };
  123431. static static_codebook _16c0_s_p4_0 = {
  123432. 2, 81,
  123433. _vq_lengthlist__16c0_s_p4_0,
  123434. 1, -531628032, 1611661312, 4, 0,
  123435. _vq_quantlist__16c0_s_p4_0,
  123436. NULL,
  123437. &_vq_auxt__16c0_s_p4_0,
  123438. NULL,
  123439. 0
  123440. };
  123441. static long _vq_quantlist__16c0_s_p5_0[] = {
  123442. 4,
  123443. 3,
  123444. 5,
  123445. 2,
  123446. 6,
  123447. 1,
  123448. 7,
  123449. 0,
  123450. 8,
  123451. };
  123452. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123453. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123454. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123455. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123456. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123457. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123458. 10,
  123459. };
  123460. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123461. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123462. };
  123463. static long _vq_quantmap__16c0_s_p5_0[] = {
  123464. 7, 5, 3, 1, 0, 2, 4, 6,
  123465. 8,
  123466. };
  123467. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123468. _vq_quantthresh__16c0_s_p5_0,
  123469. _vq_quantmap__16c0_s_p5_0,
  123470. 9,
  123471. 9
  123472. };
  123473. static static_codebook _16c0_s_p5_0 = {
  123474. 2, 81,
  123475. _vq_lengthlist__16c0_s_p5_0,
  123476. 1, -531628032, 1611661312, 4, 0,
  123477. _vq_quantlist__16c0_s_p5_0,
  123478. NULL,
  123479. &_vq_auxt__16c0_s_p5_0,
  123480. NULL,
  123481. 0
  123482. };
  123483. static long _vq_quantlist__16c0_s_p6_0[] = {
  123484. 8,
  123485. 7,
  123486. 9,
  123487. 6,
  123488. 10,
  123489. 5,
  123490. 11,
  123491. 4,
  123492. 12,
  123493. 3,
  123494. 13,
  123495. 2,
  123496. 14,
  123497. 1,
  123498. 15,
  123499. 0,
  123500. 16,
  123501. };
  123502. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123503. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123504. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123505. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123506. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123507. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123508. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123509. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123510. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123511. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123512. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123513. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123514. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123515. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123516. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123517. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123518. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123519. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123521. 14,
  123522. };
  123523. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123524. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123525. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123526. };
  123527. static long _vq_quantmap__16c0_s_p6_0[] = {
  123528. 15, 13, 11, 9, 7, 5, 3, 1,
  123529. 0, 2, 4, 6, 8, 10, 12, 14,
  123530. 16,
  123531. };
  123532. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123533. _vq_quantthresh__16c0_s_p6_0,
  123534. _vq_quantmap__16c0_s_p6_0,
  123535. 17,
  123536. 17
  123537. };
  123538. static static_codebook _16c0_s_p6_0 = {
  123539. 2, 289,
  123540. _vq_lengthlist__16c0_s_p6_0,
  123541. 1, -529530880, 1611661312, 5, 0,
  123542. _vq_quantlist__16c0_s_p6_0,
  123543. NULL,
  123544. &_vq_auxt__16c0_s_p6_0,
  123545. NULL,
  123546. 0
  123547. };
  123548. static long _vq_quantlist__16c0_s_p7_0[] = {
  123549. 1,
  123550. 0,
  123551. 2,
  123552. };
  123553. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123554. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123555. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123556. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123557. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123558. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123559. 13,
  123560. };
  123561. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123562. -5.5, 5.5,
  123563. };
  123564. static long _vq_quantmap__16c0_s_p7_0[] = {
  123565. 1, 0, 2,
  123566. };
  123567. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123568. _vq_quantthresh__16c0_s_p7_0,
  123569. _vq_quantmap__16c0_s_p7_0,
  123570. 3,
  123571. 3
  123572. };
  123573. static static_codebook _16c0_s_p7_0 = {
  123574. 4, 81,
  123575. _vq_lengthlist__16c0_s_p7_0,
  123576. 1, -529137664, 1618345984, 2, 0,
  123577. _vq_quantlist__16c0_s_p7_0,
  123578. NULL,
  123579. &_vq_auxt__16c0_s_p7_0,
  123580. NULL,
  123581. 0
  123582. };
  123583. static long _vq_quantlist__16c0_s_p7_1[] = {
  123584. 5,
  123585. 4,
  123586. 6,
  123587. 3,
  123588. 7,
  123589. 2,
  123590. 8,
  123591. 1,
  123592. 9,
  123593. 0,
  123594. 10,
  123595. };
  123596. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123597. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123598. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123599. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123600. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123601. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123602. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123603. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123604. 11,11,11, 9, 9, 9, 9,10,10,
  123605. };
  123606. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123607. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123608. 3.5, 4.5,
  123609. };
  123610. static long _vq_quantmap__16c0_s_p7_1[] = {
  123611. 9, 7, 5, 3, 1, 0, 2, 4,
  123612. 6, 8, 10,
  123613. };
  123614. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123615. _vq_quantthresh__16c0_s_p7_1,
  123616. _vq_quantmap__16c0_s_p7_1,
  123617. 11,
  123618. 11
  123619. };
  123620. static static_codebook _16c0_s_p7_1 = {
  123621. 2, 121,
  123622. _vq_lengthlist__16c0_s_p7_1,
  123623. 1, -531365888, 1611661312, 4, 0,
  123624. _vq_quantlist__16c0_s_p7_1,
  123625. NULL,
  123626. &_vq_auxt__16c0_s_p7_1,
  123627. NULL,
  123628. 0
  123629. };
  123630. static long _vq_quantlist__16c0_s_p8_0[] = {
  123631. 6,
  123632. 5,
  123633. 7,
  123634. 4,
  123635. 8,
  123636. 3,
  123637. 9,
  123638. 2,
  123639. 10,
  123640. 1,
  123641. 11,
  123642. 0,
  123643. 12,
  123644. };
  123645. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123646. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123647. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123648. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123649. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123650. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123651. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123652. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123653. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123654. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123655. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123656. 0,12,13,13,12,13,14,14,14,
  123657. };
  123658. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123659. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123660. 12.5, 17.5, 22.5, 27.5,
  123661. };
  123662. static long _vq_quantmap__16c0_s_p8_0[] = {
  123663. 11, 9, 7, 5, 3, 1, 0, 2,
  123664. 4, 6, 8, 10, 12,
  123665. };
  123666. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123667. _vq_quantthresh__16c0_s_p8_0,
  123668. _vq_quantmap__16c0_s_p8_0,
  123669. 13,
  123670. 13
  123671. };
  123672. static static_codebook _16c0_s_p8_0 = {
  123673. 2, 169,
  123674. _vq_lengthlist__16c0_s_p8_0,
  123675. 1, -526516224, 1616117760, 4, 0,
  123676. _vq_quantlist__16c0_s_p8_0,
  123677. NULL,
  123678. &_vq_auxt__16c0_s_p8_0,
  123679. NULL,
  123680. 0
  123681. };
  123682. static long _vq_quantlist__16c0_s_p8_1[] = {
  123683. 2,
  123684. 1,
  123685. 3,
  123686. 0,
  123687. 4,
  123688. };
  123689. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123690. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123691. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123692. };
  123693. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123694. -1.5, -0.5, 0.5, 1.5,
  123695. };
  123696. static long _vq_quantmap__16c0_s_p8_1[] = {
  123697. 3, 1, 0, 2, 4,
  123698. };
  123699. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123700. _vq_quantthresh__16c0_s_p8_1,
  123701. _vq_quantmap__16c0_s_p8_1,
  123702. 5,
  123703. 5
  123704. };
  123705. static static_codebook _16c0_s_p8_1 = {
  123706. 2, 25,
  123707. _vq_lengthlist__16c0_s_p8_1,
  123708. 1, -533725184, 1611661312, 3, 0,
  123709. _vq_quantlist__16c0_s_p8_1,
  123710. NULL,
  123711. &_vq_auxt__16c0_s_p8_1,
  123712. NULL,
  123713. 0
  123714. };
  123715. static long _vq_quantlist__16c0_s_p9_0[] = {
  123716. 1,
  123717. 0,
  123718. 2,
  123719. };
  123720. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123721. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123722. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123723. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123724. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123725. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123726. 7,
  123727. };
  123728. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123729. -157.5, 157.5,
  123730. };
  123731. static long _vq_quantmap__16c0_s_p9_0[] = {
  123732. 1, 0, 2,
  123733. };
  123734. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123735. _vq_quantthresh__16c0_s_p9_0,
  123736. _vq_quantmap__16c0_s_p9_0,
  123737. 3,
  123738. 3
  123739. };
  123740. static static_codebook _16c0_s_p9_0 = {
  123741. 4, 81,
  123742. _vq_lengthlist__16c0_s_p9_0,
  123743. 1, -518803456, 1628680192, 2, 0,
  123744. _vq_quantlist__16c0_s_p9_0,
  123745. NULL,
  123746. &_vq_auxt__16c0_s_p9_0,
  123747. NULL,
  123748. 0
  123749. };
  123750. static long _vq_quantlist__16c0_s_p9_1[] = {
  123751. 7,
  123752. 6,
  123753. 8,
  123754. 5,
  123755. 9,
  123756. 4,
  123757. 10,
  123758. 3,
  123759. 11,
  123760. 2,
  123761. 12,
  123762. 1,
  123763. 13,
  123764. 0,
  123765. 14,
  123766. };
  123767. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123768. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123769. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123770. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123771. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123772. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123773. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123775. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123776. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123777. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123779. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123780. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123781. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123782. 10,
  123783. };
  123784. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123785. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123786. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123787. };
  123788. static long _vq_quantmap__16c0_s_p9_1[] = {
  123789. 13, 11, 9, 7, 5, 3, 1, 0,
  123790. 2, 4, 6, 8, 10, 12, 14,
  123791. };
  123792. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123793. _vq_quantthresh__16c0_s_p9_1,
  123794. _vq_quantmap__16c0_s_p9_1,
  123795. 15,
  123796. 15
  123797. };
  123798. static static_codebook _16c0_s_p9_1 = {
  123799. 2, 225,
  123800. _vq_lengthlist__16c0_s_p9_1,
  123801. 1, -520986624, 1620377600, 4, 0,
  123802. _vq_quantlist__16c0_s_p9_1,
  123803. NULL,
  123804. &_vq_auxt__16c0_s_p9_1,
  123805. NULL,
  123806. 0
  123807. };
  123808. static long _vq_quantlist__16c0_s_p9_2[] = {
  123809. 10,
  123810. 9,
  123811. 11,
  123812. 8,
  123813. 12,
  123814. 7,
  123815. 13,
  123816. 6,
  123817. 14,
  123818. 5,
  123819. 15,
  123820. 4,
  123821. 16,
  123822. 3,
  123823. 17,
  123824. 2,
  123825. 18,
  123826. 1,
  123827. 19,
  123828. 0,
  123829. 20,
  123830. };
  123831. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123832. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123833. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123834. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123835. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123836. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123837. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123838. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123839. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123840. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123841. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123842. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123843. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123844. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123845. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123846. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123847. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123848. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123849. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123850. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123851. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123852. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123853. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123854. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123855. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123856. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123857. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123858. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123859. 10,11,10,10,11, 9,10,10,10,
  123860. };
  123861. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123862. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123863. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123864. 6.5, 7.5, 8.5, 9.5,
  123865. };
  123866. static long _vq_quantmap__16c0_s_p9_2[] = {
  123867. 19, 17, 15, 13, 11, 9, 7, 5,
  123868. 3, 1, 0, 2, 4, 6, 8, 10,
  123869. 12, 14, 16, 18, 20,
  123870. };
  123871. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123872. _vq_quantthresh__16c0_s_p9_2,
  123873. _vq_quantmap__16c0_s_p9_2,
  123874. 21,
  123875. 21
  123876. };
  123877. static static_codebook _16c0_s_p9_2 = {
  123878. 2, 441,
  123879. _vq_lengthlist__16c0_s_p9_2,
  123880. 1, -529268736, 1611661312, 5, 0,
  123881. _vq_quantlist__16c0_s_p9_2,
  123882. NULL,
  123883. &_vq_auxt__16c0_s_p9_2,
  123884. NULL,
  123885. 0
  123886. };
  123887. static long _huff_lengthlist__16c0_s_single[] = {
  123888. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123889. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123890. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123891. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123892. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123893. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123894. 16,16,18,18,
  123895. };
  123896. static static_codebook _huff_book__16c0_s_single = {
  123897. 2, 100,
  123898. _huff_lengthlist__16c0_s_single,
  123899. 0, 0, 0, 0, 0,
  123900. NULL,
  123901. NULL,
  123902. NULL,
  123903. NULL,
  123904. 0
  123905. };
  123906. static long _huff_lengthlist__16c1_s_long[] = {
  123907. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123908. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123909. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123910. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123911. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123912. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123913. 12,11,11,13,
  123914. };
  123915. static static_codebook _huff_book__16c1_s_long = {
  123916. 2, 100,
  123917. _huff_lengthlist__16c1_s_long,
  123918. 0, 0, 0, 0, 0,
  123919. NULL,
  123920. NULL,
  123921. NULL,
  123922. NULL,
  123923. 0
  123924. };
  123925. static long _vq_quantlist__16c1_s_p1_0[] = {
  123926. 1,
  123927. 0,
  123928. 2,
  123929. };
  123930. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123931. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123932. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123937. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123942. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123977. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123982. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123987. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124023. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124028. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124033. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124150. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124341. 0,
  124342. };
  124343. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124344. -0.5, 0.5,
  124345. };
  124346. static long _vq_quantmap__16c1_s_p1_0[] = {
  124347. 1, 0, 2,
  124348. };
  124349. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124350. _vq_quantthresh__16c1_s_p1_0,
  124351. _vq_quantmap__16c1_s_p1_0,
  124352. 3,
  124353. 3
  124354. };
  124355. static static_codebook _16c1_s_p1_0 = {
  124356. 8, 6561,
  124357. _vq_lengthlist__16c1_s_p1_0,
  124358. 1, -535822336, 1611661312, 2, 0,
  124359. _vq_quantlist__16c1_s_p1_0,
  124360. NULL,
  124361. &_vq_auxt__16c1_s_p1_0,
  124362. NULL,
  124363. 0
  124364. };
  124365. static long _vq_quantlist__16c1_s_p2_0[] = {
  124366. 2,
  124367. 1,
  124368. 3,
  124369. 0,
  124370. 4,
  124371. };
  124372. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124412. 0,
  124413. };
  124414. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124415. -1.5, -0.5, 0.5, 1.5,
  124416. };
  124417. static long _vq_quantmap__16c1_s_p2_0[] = {
  124418. 3, 1, 0, 2, 4,
  124419. };
  124420. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124421. _vq_quantthresh__16c1_s_p2_0,
  124422. _vq_quantmap__16c1_s_p2_0,
  124423. 5,
  124424. 5
  124425. };
  124426. static static_codebook _16c1_s_p2_0 = {
  124427. 4, 625,
  124428. _vq_lengthlist__16c1_s_p2_0,
  124429. 1, -533725184, 1611661312, 3, 0,
  124430. _vq_quantlist__16c1_s_p2_0,
  124431. NULL,
  124432. &_vq_auxt__16c1_s_p2_0,
  124433. NULL,
  124434. 0
  124435. };
  124436. static long _vq_quantlist__16c1_s_p3_0[] = {
  124437. 2,
  124438. 1,
  124439. 3,
  124440. 0,
  124441. 4,
  124442. };
  124443. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124444. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124450. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0,
  124484. };
  124485. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124486. -1.5, -0.5, 0.5, 1.5,
  124487. };
  124488. static long _vq_quantmap__16c1_s_p3_0[] = {
  124489. 3, 1, 0, 2, 4,
  124490. };
  124491. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124492. _vq_quantthresh__16c1_s_p3_0,
  124493. _vq_quantmap__16c1_s_p3_0,
  124494. 5,
  124495. 5
  124496. };
  124497. static static_codebook _16c1_s_p3_0 = {
  124498. 4, 625,
  124499. _vq_lengthlist__16c1_s_p3_0,
  124500. 1, -533725184, 1611661312, 3, 0,
  124501. _vq_quantlist__16c1_s_p3_0,
  124502. NULL,
  124503. &_vq_auxt__16c1_s_p3_0,
  124504. NULL,
  124505. 0
  124506. };
  124507. static long _vq_quantlist__16c1_s_p4_0[] = {
  124508. 4,
  124509. 3,
  124510. 5,
  124511. 2,
  124512. 6,
  124513. 1,
  124514. 7,
  124515. 0,
  124516. 8,
  124517. };
  124518. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124519. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124520. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124521. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124522. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124523. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124524. 0,
  124525. };
  124526. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124527. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124528. };
  124529. static long _vq_quantmap__16c1_s_p4_0[] = {
  124530. 7, 5, 3, 1, 0, 2, 4, 6,
  124531. 8,
  124532. };
  124533. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124534. _vq_quantthresh__16c1_s_p4_0,
  124535. _vq_quantmap__16c1_s_p4_0,
  124536. 9,
  124537. 9
  124538. };
  124539. static static_codebook _16c1_s_p4_0 = {
  124540. 2, 81,
  124541. _vq_lengthlist__16c1_s_p4_0,
  124542. 1, -531628032, 1611661312, 4, 0,
  124543. _vq_quantlist__16c1_s_p4_0,
  124544. NULL,
  124545. &_vq_auxt__16c1_s_p4_0,
  124546. NULL,
  124547. 0
  124548. };
  124549. static long _vq_quantlist__16c1_s_p5_0[] = {
  124550. 4,
  124551. 3,
  124552. 5,
  124553. 2,
  124554. 6,
  124555. 1,
  124556. 7,
  124557. 0,
  124558. 8,
  124559. };
  124560. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124561. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124562. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124563. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124564. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124565. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124566. 10,
  124567. };
  124568. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124569. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124570. };
  124571. static long _vq_quantmap__16c1_s_p5_0[] = {
  124572. 7, 5, 3, 1, 0, 2, 4, 6,
  124573. 8,
  124574. };
  124575. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124576. _vq_quantthresh__16c1_s_p5_0,
  124577. _vq_quantmap__16c1_s_p5_0,
  124578. 9,
  124579. 9
  124580. };
  124581. static static_codebook _16c1_s_p5_0 = {
  124582. 2, 81,
  124583. _vq_lengthlist__16c1_s_p5_0,
  124584. 1, -531628032, 1611661312, 4, 0,
  124585. _vq_quantlist__16c1_s_p5_0,
  124586. NULL,
  124587. &_vq_auxt__16c1_s_p5_0,
  124588. NULL,
  124589. 0
  124590. };
  124591. static long _vq_quantlist__16c1_s_p6_0[] = {
  124592. 8,
  124593. 7,
  124594. 9,
  124595. 6,
  124596. 10,
  124597. 5,
  124598. 11,
  124599. 4,
  124600. 12,
  124601. 3,
  124602. 13,
  124603. 2,
  124604. 14,
  124605. 1,
  124606. 15,
  124607. 0,
  124608. 16,
  124609. };
  124610. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124611. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124612. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124613. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124614. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124615. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124616. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124617. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124618. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124619. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124620. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124621. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124622. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124623. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124624. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124625. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124626. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124627. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124629. 14,
  124630. };
  124631. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124632. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124633. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124634. };
  124635. static long _vq_quantmap__16c1_s_p6_0[] = {
  124636. 15, 13, 11, 9, 7, 5, 3, 1,
  124637. 0, 2, 4, 6, 8, 10, 12, 14,
  124638. 16,
  124639. };
  124640. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124641. _vq_quantthresh__16c1_s_p6_0,
  124642. _vq_quantmap__16c1_s_p6_0,
  124643. 17,
  124644. 17
  124645. };
  124646. static static_codebook _16c1_s_p6_0 = {
  124647. 2, 289,
  124648. _vq_lengthlist__16c1_s_p6_0,
  124649. 1, -529530880, 1611661312, 5, 0,
  124650. _vq_quantlist__16c1_s_p6_0,
  124651. NULL,
  124652. &_vq_auxt__16c1_s_p6_0,
  124653. NULL,
  124654. 0
  124655. };
  124656. static long _vq_quantlist__16c1_s_p7_0[] = {
  124657. 1,
  124658. 0,
  124659. 2,
  124660. };
  124661. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124662. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124663. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124664. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124665. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124666. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124667. 11,
  124668. };
  124669. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124670. -5.5, 5.5,
  124671. };
  124672. static long _vq_quantmap__16c1_s_p7_0[] = {
  124673. 1, 0, 2,
  124674. };
  124675. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124676. _vq_quantthresh__16c1_s_p7_0,
  124677. _vq_quantmap__16c1_s_p7_0,
  124678. 3,
  124679. 3
  124680. };
  124681. static static_codebook _16c1_s_p7_0 = {
  124682. 4, 81,
  124683. _vq_lengthlist__16c1_s_p7_0,
  124684. 1, -529137664, 1618345984, 2, 0,
  124685. _vq_quantlist__16c1_s_p7_0,
  124686. NULL,
  124687. &_vq_auxt__16c1_s_p7_0,
  124688. NULL,
  124689. 0
  124690. };
  124691. static long _vq_quantlist__16c1_s_p7_1[] = {
  124692. 5,
  124693. 4,
  124694. 6,
  124695. 3,
  124696. 7,
  124697. 2,
  124698. 8,
  124699. 1,
  124700. 9,
  124701. 0,
  124702. 10,
  124703. };
  124704. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124705. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124706. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124707. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124708. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124709. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124710. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124711. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124712. 10,10,10, 8, 8, 8, 8, 9, 9,
  124713. };
  124714. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124715. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124716. 3.5, 4.5,
  124717. };
  124718. static long _vq_quantmap__16c1_s_p7_1[] = {
  124719. 9, 7, 5, 3, 1, 0, 2, 4,
  124720. 6, 8, 10,
  124721. };
  124722. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124723. _vq_quantthresh__16c1_s_p7_1,
  124724. _vq_quantmap__16c1_s_p7_1,
  124725. 11,
  124726. 11
  124727. };
  124728. static static_codebook _16c1_s_p7_1 = {
  124729. 2, 121,
  124730. _vq_lengthlist__16c1_s_p7_1,
  124731. 1, -531365888, 1611661312, 4, 0,
  124732. _vq_quantlist__16c1_s_p7_1,
  124733. NULL,
  124734. &_vq_auxt__16c1_s_p7_1,
  124735. NULL,
  124736. 0
  124737. };
  124738. static long _vq_quantlist__16c1_s_p8_0[] = {
  124739. 6,
  124740. 5,
  124741. 7,
  124742. 4,
  124743. 8,
  124744. 3,
  124745. 9,
  124746. 2,
  124747. 10,
  124748. 1,
  124749. 11,
  124750. 0,
  124751. 12,
  124752. };
  124753. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124754. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124755. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124756. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124757. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124758. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124759. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124760. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124761. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124762. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124763. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124764. 0,12,12,12,12,13,13,14,15,
  124765. };
  124766. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124767. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124768. 12.5, 17.5, 22.5, 27.5,
  124769. };
  124770. static long _vq_quantmap__16c1_s_p8_0[] = {
  124771. 11, 9, 7, 5, 3, 1, 0, 2,
  124772. 4, 6, 8, 10, 12,
  124773. };
  124774. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124775. _vq_quantthresh__16c1_s_p8_0,
  124776. _vq_quantmap__16c1_s_p8_0,
  124777. 13,
  124778. 13
  124779. };
  124780. static static_codebook _16c1_s_p8_0 = {
  124781. 2, 169,
  124782. _vq_lengthlist__16c1_s_p8_0,
  124783. 1, -526516224, 1616117760, 4, 0,
  124784. _vq_quantlist__16c1_s_p8_0,
  124785. NULL,
  124786. &_vq_auxt__16c1_s_p8_0,
  124787. NULL,
  124788. 0
  124789. };
  124790. static long _vq_quantlist__16c1_s_p8_1[] = {
  124791. 2,
  124792. 1,
  124793. 3,
  124794. 0,
  124795. 4,
  124796. };
  124797. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124798. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124799. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124800. };
  124801. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124802. -1.5, -0.5, 0.5, 1.5,
  124803. };
  124804. static long _vq_quantmap__16c1_s_p8_1[] = {
  124805. 3, 1, 0, 2, 4,
  124806. };
  124807. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124808. _vq_quantthresh__16c1_s_p8_1,
  124809. _vq_quantmap__16c1_s_p8_1,
  124810. 5,
  124811. 5
  124812. };
  124813. static static_codebook _16c1_s_p8_1 = {
  124814. 2, 25,
  124815. _vq_lengthlist__16c1_s_p8_1,
  124816. 1, -533725184, 1611661312, 3, 0,
  124817. _vq_quantlist__16c1_s_p8_1,
  124818. NULL,
  124819. &_vq_auxt__16c1_s_p8_1,
  124820. NULL,
  124821. 0
  124822. };
  124823. static long _vq_quantlist__16c1_s_p9_0[] = {
  124824. 6,
  124825. 5,
  124826. 7,
  124827. 4,
  124828. 8,
  124829. 3,
  124830. 9,
  124831. 2,
  124832. 10,
  124833. 1,
  124834. 11,
  124835. 0,
  124836. 12,
  124837. };
  124838. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124839. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124840. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124841. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124842. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124843. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124844. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124845. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124846. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124847. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124848. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124849. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124850. };
  124851. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124852. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124853. 787.5, 1102.5, 1417.5, 1732.5,
  124854. };
  124855. static long _vq_quantmap__16c1_s_p9_0[] = {
  124856. 11, 9, 7, 5, 3, 1, 0, 2,
  124857. 4, 6, 8, 10, 12,
  124858. };
  124859. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124860. _vq_quantthresh__16c1_s_p9_0,
  124861. _vq_quantmap__16c1_s_p9_0,
  124862. 13,
  124863. 13
  124864. };
  124865. static static_codebook _16c1_s_p9_0 = {
  124866. 2, 169,
  124867. _vq_lengthlist__16c1_s_p9_0,
  124868. 1, -513964032, 1628680192, 4, 0,
  124869. _vq_quantlist__16c1_s_p9_0,
  124870. NULL,
  124871. &_vq_auxt__16c1_s_p9_0,
  124872. NULL,
  124873. 0
  124874. };
  124875. static long _vq_quantlist__16c1_s_p9_1[] = {
  124876. 7,
  124877. 6,
  124878. 8,
  124879. 5,
  124880. 9,
  124881. 4,
  124882. 10,
  124883. 3,
  124884. 11,
  124885. 2,
  124886. 12,
  124887. 1,
  124888. 13,
  124889. 0,
  124890. 14,
  124891. };
  124892. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124893. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124894. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124895. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124896. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124897. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124898. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124899. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124900. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124901. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124902. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124903. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124904. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124905. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124906. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124907. 13,
  124908. };
  124909. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124910. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124911. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124912. };
  124913. static long _vq_quantmap__16c1_s_p9_1[] = {
  124914. 13, 11, 9, 7, 5, 3, 1, 0,
  124915. 2, 4, 6, 8, 10, 12, 14,
  124916. };
  124917. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124918. _vq_quantthresh__16c1_s_p9_1,
  124919. _vq_quantmap__16c1_s_p9_1,
  124920. 15,
  124921. 15
  124922. };
  124923. static static_codebook _16c1_s_p9_1 = {
  124924. 2, 225,
  124925. _vq_lengthlist__16c1_s_p9_1,
  124926. 1, -520986624, 1620377600, 4, 0,
  124927. _vq_quantlist__16c1_s_p9_1,
  124928. NULL,
  124929. &_vq_auxt__16c1_s_p9_1,
  124930. NULL,
  124931. 0
  124932. };
  124933. static long _vq_quantlist__16c1_s_p9_2[] = {
  124934. 10,
  124935. 9,
  124936. 11,
  124937. 8,
  124938. 12,
  124939. 7,
  124940. 13,
  124941. 6,
  124942. 14,
  124943. 5,
  124944. 15,
  124945. 4,
  124946. 16,
  124947. 3,
  124948. 17,
  124949. 2,
  124950. 18,
  124951. 1,
  124952. 19,
  124953. 0,
  124954. 20,
  124955. };
  124956. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124957. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124958. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124959. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124960. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124961. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124962. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124963. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124964. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124965. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124966. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124967. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124968. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124969. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124970. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124971. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124972. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124973. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124974. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124975. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124976. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124977. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124978. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124979. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124980. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124981. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124982. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124983. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124984. 11,11,11,11,12,11,11,12,11,
  124985. };
  124986. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124987. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124988. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124989. 6.5, 7.5, 8.5, 9.5,
  124990. };
  124991. static long _vq_quantmap__16c1_s_p9_2[] = {
  124992. 19, 17, 15, 13, 11, 9, 7, 5,
  124993. 3, 1, 0, 2, 4, 6, 8, 10,
  124994. 12, 14, 16, 18, 20,
  124995. };
  124996. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124997. _vq_quantthresh__16c1_s_p9_2,
  124998. _vq_quantmap__16c1_s_p9_2,
  124999. 21,
  125000. 21
  125001. };
  125002. static static_codebook _16c1_s_p9_2 = {
  125003. 2, 441,
  125004. _vq_lengthlist__16c1_s_p9_2,
  125005. 1, -529268736, 1611661312, 5, 0,
  125006. _vq_quantlist__16c1_s_p9_2,
  125007. NULL,
  125008. &_vq_auxt__16c1_s_p9_2,
  125009. NULL,
  125010. 0
  125011. };
  125012. static long _huff_lengthlist__16c1_s_short[] = {
  125013. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125014. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125015. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125016. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125017. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125018. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125019. 9, 9,10,13,
  125020. };
  125021. static static_codebook _huff_book__16c1_s_short = {
  125022. 2, 100,
  125023. _huff_lengthlist__16c1_s_short,
  125024. 0, 0, 0, 0, 0,
  125025. NULL,
  125026. NULL,
  125027. NULL,
  125028. NULL,
  125029. 0
  125030. };
  125031. static long _huff_lengthlist__16c2_s_long[] = {
  125032. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125033. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125034. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125035. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125036. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125037. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125038. 14,14,16,18,
  125039. };
  125040. static static_codebook _huff_book__16c2_s_long = {
  125041. 2, 100,
  125042. _huff_lengthlist__16c2_s_long,
  125043. 0, 0, 0, 0, 0,
  125044. NULL,
  125045. NULL,
  125046. NULL,
  125047. NULL,
  125048. 0
  125049. };
  125050. static long _vq_quantlist__16c2_s_p1_0[] = {
  125051. 1,
  125052. 0,
  125053. 2,
  125054. };
  125055. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125056. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125057. 0, 0, 4, 5, 5, 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,
  125062. };
  125063. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125064. -0.5, 0.5,
  125065. };
  125066. static long _vq_quantmap__16c2_s_p1_0[] = {
  125067. 1, 0, 2,
  125068. };
  125069. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125070. _vq_quantthresh__16c2_s_p1_0,
  125071. _vq_quantmap__16c2_s_p1_0,
  125072. 3,
  125073. 3
  125074. };
  125075. static static_codebook _16c2_s_p1_0 = {
  125076. 4, 81,
  125077. _vq_lengthlist__16c2_s_p1_0,
  125078. 1, -535822336, 1611661312, 2, 0,
  125079. _vq_quantlist__16c2_s_p1_0,
  125080. NULL,
  125081. &_vq_auxt__16c2_s_p1_0,
  125082. NULL,
  125083. 0
  125084. };
  125085. static long _vq_quantlist__16c2_s_p2_0[] = {
  125086. 2,
  125087. 1,
  125088. 3,
  125089. 0,
  125090. 4,
  125091. };
  125092. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125093. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125094. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125095. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125096. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125097. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125098. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125099. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125100. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 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, 8, 8, 8,11,11, 0, 0, 0,
  125106. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125107. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125108. 0, 0, 0,12,13, 0, 0, 0,13,13, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125114. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125115. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125116. 13,13, 0, 0, 0,12,13, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125122. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125123. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125124. 0, 0,13,13, 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, 8,
  125129. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125130. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125131. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125132. 13,
  125133. };
  125134. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125135. -1.5, -0.5, 0.5, 1.5,
  125136. };
  125137. static long _vq_quantmap__16c2_s_p2_0[] = {
  125138. 3, 1, 0, 2, 4,
  125139. };
  125140. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125141. _vq_quantthresh__16c2_s_p2_0,
  125142. _vq_quantmap__16c2_s_p2_0,
  125143. 5,
  125144. 5
  125145. };
  125146. static static_codebook _16c2_s_p2_0 = {
  125147. 4, 625,
  125148. _vq_lengthlist__16c2_s_p2_0,
  125149. 1, -533725184, 1611661312, 3, 0,
  125150. _vq_quantlist__16c2_s_p2_0,
  125151. NULL,
  125152. &_vq_auxt__16c2_s_p2_0,
  125153. NULL,
  125154. 0
  125155. };
  125156. static long _vq_quantlist__16c2_s_p3_0[] = {
  125157. 4,
  125158. 3,
  125159. 5,
  125160. 2,
  125161. 6,
  125162. 1,
  125163. 7,
  125164. 0,
  125165. 8,
  125166. };
  125167. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125168. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125169. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125170. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125171. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125173. 0,
  125174. };
  125175. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125176. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125177. };
  125178. static long _vq_quantmap__16c2_s_p3_0[] = {
  125179. 7, 5, 3, 1, 0, 2, 4, 6,
  125180. 8,
  125181. };
  125182. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125183. _vq_quantthresh__16c2_s_p3_0,
  125184. _vq_quantmap__16c2_s_p3_0,
  125185. 9,
  125186. 9
  125187. };
  125188. static static_codebook _16c2_s_p3_0 = {
  125189. 2, 81,
  125190. _vq_lengthlist__16c2_s_p3_0,
  125191. 1, -531628032, 1611661312, 4, 0,
  125192. _vq_quantlist__16c2_s_p3_0,
  125193. NULL,
  125194. &_vq_auxt__16c2_s_p3_0,
  125195. NULL,
  125196. 0
  125197. };
  125198. static long _vq_quantlist__16c2_s_p4_0[] = {
  125199. 8,
  125200. 7,
  125201. 9,
  125202. 6,
  125203. 10,
  125204. 5,
  125205. 11,
  125206. 4,
  125207. 12,
  125208. 3,
  125209. 13,
  125210. 2,
  125211. 14,
  125212. 1,
  125213. 15,
  125214. 0,
  125215. 16,
  125216. };
  125217. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125218. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125219. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125220. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125221. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125222. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125223. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125224. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125225. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125226. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125227. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125236. 0,
  125237. };
  125238. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125239. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125240. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125241. };
  125242. static long _vq_quantmap__16c2_s_p4_0[] = {
  125243. 15, 13, 11, 9, 7, 5, 3, 1,
  125244. 0, 2, 4, 6, 8, 10, 12, 14,
  125245. 16,
  125246. };
  125247. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125248. _vq_quantthresh__16c2_s_p4_0,
  125249. _vq_quantmap__16c2_s_p4_0,
  125250. 17,
  125251. 17
  125252. };
  125253. static static_codebook _16c2_s_p4_0 = {
  125254. 2, 289,
  125255. _vq_lengthlist__16c2_s_p4_0,
  125256. 1, -529530880, 1611661312, 5, 0,
  125257. _vq_quantlist__16c2_s_p4_0,
  125258. NULL,
  125259. &_vq_auxt__16c2_s_p4_0,
  125260. NULL,
  125261. 0
  125262. };
  125263. static long _vq_quantlist__16c2_s_p5_0[] = {
  125264. 1,
  125265. 0,
  125266. 2,
  125267. };
  125268. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125269. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125270. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125271. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125272. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125273. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125274. 12,
  125275. };
  125276. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125277. -5.5, 5.5,
  125278. };
  125279. static long _vq_quantmap__16c2_s_p5_0[] = {
  125280. 1, 0, 2,
  125281. };
  125282. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125283. _vq_quantthresh__16c2_s_p5_0,
  125284. _vq_quantmap__16c2_s_p5_0,
  125285. 3,
  125286. 3
  125287. };
  125288. static static_codebook _16c2_s_p5_0 = {
  125289. 4, 81,
  125290. _vq_lengthlist__16c2_s_p5_0,
  125291. 1, -529137664, 1618345984, 2, 0,
  125292. _vq_quantlist__16c2_s_p5_0,
  125293. NULL,
  125294. &_vq_auxt__16c2_s_p5_0,
  125295. NULL,
  125296. 0
  125297. };
  125298. static long _vq_quantlist__16c2_s_p5_1[] = {
  125299. 5,
  125300. 4,
  125301. 6,
  125302. 3,
  125303. 7,
  125304. 2,
  125305. 8,
  125306. 1,
  125307. 9,
  125308. 0,
  125309. 10,
  125310. };
  125311. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125312. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125313. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125314. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125315. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125316. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125317. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125318. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125319. 11,11,11, 7, 7, 8, 8, 8, 8,
  125320. };
  125321. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125322. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125323. 3.5, 4.5,
  125324. };
  125325. static long _vq_quantmap__16c2_s_p5_1[] = {
  125326. 9, 7, 5, 3, 1, 0, 2, 4,
  125327. 6, 8, 10,
  125328. };
  125329. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125330. _vq_quantthresh__16c2_s_p5_1,
  125331. _vq_quantmap__16c2_s_p5_1,
  125332. 11,
  125333. 11
  125334. };
  125335. static static_codebook _16c2_s_p5_1 = {
  125336. 2, 121,
  125337. _vq_lengthlist__16c2_s_p5_1,
  125338. 1, -531365888, 1611661312, 4, 0,
  125339. _vq_quantlist__16c2_s_p5_1,
  125340. NULL,
  125341. &_vq_auxt__16c2_s_p5_1,
  125342. NULL,
  125343. 0
  125344. };
  125345. static long _vq_quantlist__16c2_s_p6_0[] = {
  125346. 6,
  125347. 5,
  125348. 7,
  125349. 4,
  125350. 8,
  125351. 3,
  125352. 9,
  125353. 2,
  125354. 10,
  125355. 1,
  125356. 11,
  125357. 0,
  125358. 12,
  125359. };
  125360. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125361. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125362. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125363. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125364. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125365. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125366. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. };
  125373. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125374. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125375. 12.5, 17.5, 22.5, 27.5,
  125376. };
  125377. static long _vq_quantmap__16c2_s_p6_0[] = {
  125378. 11, 9, 7, 5, 3, 1, 0, 2,
  125379. 4, 6, 8, 10, 12,
  125380. };
  125381. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125382. _vq_quantthresh__16c2_s_p6_0,
  125383. _vq_quantmap__16c2_s_p6_0,
  125384. 13,
  125385. 13
  125386. };
  125387. static static_codebook _16c2_s_p6_0 = {
  125388. 2, 169,
  125389. _vq_lengthlist__16c2_s_p6_0,
  125390. 1, -526516224, 1616117760, 4, 0,
  125391. _vq_quantlist__16c2_s_p6_0,
  125392. NULL,
  125393. &_vq_auxt__16c2_s_p6_0,
  125394. NULL,
  125395. 0
  125396. };
  125397. static long _vq_quantlist__16c2_s_p6_1[] = {
  125398. 2,
  125399. 1,
  125400. 3,
  125401. 0,
  125402. 4,
  125403. };
  125404. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125405. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125406. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125407. };
  125408. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125409. -1.5, -0.5, 0.5, 1.5,
  125410. };
  125411. static long _vq_quantmap__16c2_s_p6_1[] = {
  125412. 3, 1, 0, 2, 4,
  125413. };
  125414. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125415. _vq_quantthresh__16c2_s_p6_1,
  125416. _vq_quantmap__16c2_s_p6_1,
  125417. 5,
  125418. 5
  125419. };
  125420. static static_codebook _16c2_s_p6_1 = {
  125421. 2, 25,
  125422. _vq_lengthlist__16c2_s_p6_1,
  125423. 1, -533725184, 1611661312, 3, 0,
  125424. _vq_quantlist__16c2_s_p6_1,
  125425. NULL,
  125426. &_vq_auxt__16c2_s_p6_1,
  125427. NULL,
  125428. 0
  125429. };
  125430. static long _vq_quantlist__16c2_s_p7_0[] = {
  125431. 6,
  125432. 5,
  125433. 7,
  125434. 4,
  125435. 8,
  125436. 3,
  125437. 9,
  125438. 2,
  125439. 10,
  125440. 1,
  125441. 11,
  125442. 0,
  125443. 12,
  125444. };
  125445. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125446. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125447. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125448. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125449. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125450. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125451. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125452. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125453. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125454. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125455. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125456. 18,13,14,13,13,14,13,15,14,
  125457. };
  125458. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125459. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125460. 27.5, 38.5, 49.5, 60.5,
  125461. };
  125462. static long _vq_quantmap__16c2_s_p7_0[] = {
  125463. 11, 9, 7, 5, 3, 1, 0, 2,
  125464. 4, 6, 8, 10, 12,
  125465. };
  125466. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125467. _vq_quantthresh__16c2_s_p7_0,
  125468. _vq_quantmap__16c2_s_p7_0,
  125469. 13,
  125470. 13
  125471. };
  125472. static static_codebook _16c2_s_p7_0 = {
  125473. 2, 169,
  125474. _vq_lengthlist__16c2_s_p7_0,
  125475. 1, -523206656, 1618345984, 4, 0,
  125476. _vq_quantlist__16c2_s_p7_0,
  125477. NULL,
  125478. &_vq_auxt__16c2_s_p7_0,
  125479. NULL,
  125480. 0
  125481. };
  125482. static long _vq_quantlist__16c2_s_p7_1[] = {
  125483. 5,
  125484. 4,
  125485. 6,
  125486. 3,
  125487. 7,
  125488. 2,
  125489. 8,
  125490. 1,
  125491. 9,
  125492. 0,
  125493. 10,
  125494. };
  125495. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125496. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125497. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125498. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125499. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125500. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125501. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125502. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125503. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125504. };
  125505. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125506. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125507. 3.5, 4.5,
  125508. };
  125509. static long _vq_quantmap__16c2_s_p7_1[] = {
  125510. 9, 7, 5, 3, 1, 0, 2, 4,
  125511. 6, 8, 10,
  125512. };
  125513. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125514. _vq_quantthresh__16c2_s_p7_1,
  125515. _vq_quantmap__16c2_s_p7_1,
  125516. 11,
  125517. 11
  125518. };
  125519. static static_codebook _16c2_s_p7_1 = {
  125520. 2, 121,
  125521. _vq_lengthlist__16c2_s_p7_1,
  125522. 1, -531365888, 1611661312, 4, 0,
  125523. _vq_quantlist__16c2_s_p7_1,
  125524. NULL,
  125525. &_vq_auxt__16c2_s_p7_1,
  125526. NULL,
  125527. 0
  125528. };
  125529. static long _vq_quantlist__16c2_s_p8_0[] = {
  125530. 7,
  125531. 6,
  125532. 8,
  125533. 5,
  125534. 9,
  125535. 4,
  125536. 10,
  125537. 3,
  125538. 11,
  125539. 2,
  125540. 12,
  125541. 1,
  125542. 13,
  125543. 0,
  125544. 14,
  125545. };
  125546. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125547. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125548. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125549. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125550. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125551. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125552. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125553. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125554. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125555. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125556. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125557. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125558. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125559. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125560. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125561. 13,
  125562. };
  125563. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125564. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125565. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125566. };
  125567. static long _vq_quantmap__16c2_s_p8_0[] = {
  125568. 13, 11, 9, 7, 5, 3, 1, 0,
  125569. 2, 4, 6, 8, 10, 12, 14,
  125570. };
  125571. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125572. _vq_quantthresh__16c2_s_p8_0,
  125573. _vq_quantmap__16c2_s_p8_0,
  125574. 15,
  125575. 15
  125576. };
  125577. static static_codebook _16c2_s_p8_0 = {
  125578. 2, 225,
  125579. _vq_lengthlist__16c2_s_p8_0,
  125580. 1, -520986624, 1620377600, 4, 0,
  125581. _vq_quantlist__16c2_s_p8_0,
  125582. NULL,
  125583. &_vq_auxt__16c2_s_p8_0,
  125584. NULL,
  125585. 0
  125586. };
  125587. static long _vq_quantlist__16c2_s_p8_1[] = {
  125588. 10,
  125589. 9,
  125590. 11,
  125591. 8,
  125592. 12,
  125593. 7,
  125594. 13,
  125595. 6,
  125596. 14,
  125597. 5,
  125598. 15,
  125599. 4,
  125600. 16,
  125601. 3,
  125602. 17,
  125603. 2,
  125604. 18,
  125605. 1,
  125606. 19,
  125607. 0,
  125608. 20,
  125609. };
  125610. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125611. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125612. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125613. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125614. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125615. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125616. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125617. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125618. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125619. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125620. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125621. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125622. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125623. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125624. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125625. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125626. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125627. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125628. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125629. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125630. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125631. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125632. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125633. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125634. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125635. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125636. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125637. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125638. 10,11,10,10,10,10,10,10,10,
  125639. };
  125640. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125641. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125642. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125643. 6.5, 7.5, 8.5, 9.5,
  125644. };
  125645. static long _vq_quantmap__16c2_s_p8_1[] = {
  125646. 19, 17, 15, 13, 11, 9, 7, 5,
  125647. 3, 1, 0, 2, 4, 6, 8, 10,
  125648. 12, 14, 16, 18, 20,
  125649. };
  125650. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125651. _vq_quantthresh__16c2_s_p8_1,
  125652. _vq_quantmap__16c2_s_p8_1,
  125653. 21,
  125654. 21
  125655. };
  125656. static static_codebook _16c2_s_p8_1 = {
  125657. 2, 441,
  125658. _vq_lengthlist__16c2_s_p8_1,
  125659. 1, -529268736, 1611661312, 5, 0,
  125660. _vq_quantlist__16c2_s_p8_1,
  125661. NULL,
  125662. &_vq_auxt__16c2_s_p8_1,
  125663. NULL,
  125664. 0
  125665. };
  125666. static long _vq_quantlist__16c2_s_p9_0[] = {
  125667. 6,
  125668. 5,
  125669. 7,
  125670. 4,
  125671. 8,
  125672. 3,
  125673. 9,
  125674. 2,
  125675. 10,
  125676. 1,
  125677. 11,
  125678. 0,
  125679. 12,
  125680. };
  125681. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125682. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125683. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125684. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125685. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125686. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125687. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125688. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125689. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125690. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125691. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125692. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125693. };
  125694. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125695. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125696. 2327.5, 3258.5, 4189.5, 5120.5,
  125697. };
  125698. static long _vq_quantmap__16c2_s_p9_0[] = {
  125699. 11, 9, 7, 5, 3, 1, 0, 2,
  125700. 4, 6, 8, 10, 12,
  125701. };
  125702. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125703. _vq_quantthresh__16c2_s_p9_0,
  125704. _vq_quantmap__16c2_s_p9_0,
  125705. 13,
  125706. 13
  125707. };
  125708. static static_codebook _16c2_s_p9_0 = {
  125709. 2, 169,
  125710. _vq_lengthlist__16c2_s_p9_0,
  125711. 1, -510275072, 1631393792, 4, 0,
  125712. _vq_quantlist__16c2_s_p9_0,
  125713. NULL,
  125714. &_vq_auxt__16c2_s_p9_0,
  125715. NULL,
  125716. 0
  125717. };
  125718. static long _vq_quantlist__16c2_s_p9_1[] = {
  125719. 8,
  125720. 7,
  125721. 9,
  125722. 6,
  125723. 10,
  125724. 5,
  125725. 11,
  125726. 4,
  125727. 12,
  125728. 3,
  125729. 13,
  125730. 2,
  125731. 14,
  125732. 1,
  125733. 15,
  125734. 0,
  125735. 16,
  125736. };
  125737. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125738. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125739. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125740. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125741. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125742. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125743. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125744. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125745. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125746. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125749. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125753. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125754. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125755. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125756. 10,
  125757. };
  125758. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125759. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125760. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125761. };
  125762. static long _vq_quantmap__16c2_s_p9_1[] = {
  125763. 15, 13, 11, 9, 7, 5, 3, 1,
  125764. 0, 2, 4, 6, 8, 10, 12, 14,
  125765. 16,
  125766. };
  125767. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125768. _vq_quantthresh__16c2_s_p9_1,
  125769. _vq_quantmap__16c2_s_p9_1,
  125770. 17,
  125771. 17
  125772. };
  125773. static static_codebook _16c2_s_p9_1 = {
  125774. 2, 289,
  125775. _vq_lengthlist__16c2_s_p9_1,
  125776. 1, -518488064, 1622704128, 5, 0,
  125777. _vq_quantlist__16c2_s_p9_1,
  125778. NULL,
  125779. &_vq_auxt__16c2_s_p9_1,
  125780. NULL,
  125781. 0
  125782. };
  125783. static long _vq_quantlist__16c2_s_p9_2[] = {
  125784. 13,
  125785. 12,
  125786. 14,
  125787. 11,
  125788. 15,
  125789. 10,
  125790. 16,
  125791. 9,
  125792. 17,
  125793. 8,
  125794. 18,
  125795. 7,
  125796. 19,
  125797. 6,
  125798. 20,
  125799. 5,
  125800. 21,
  125801. 4,
  125802. 22,
  125803. 3,
  125804. 23,
  125805. 2,
  125806. 24,
  125807. 1,
  125808. 25,
  125809. 0,
  125810. 26,
  125811. };
  125812. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125813. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125814. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125815. };
  125816. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125817. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125818. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125819. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125820. 11.5, 12.5,
  125821. };
  125822. static long _vq_quantmap__16c2_s_p9_2[] = {
  125823. 25, 23, 21, 19, 17, 15, 13, 11,
  125824. 9, 7, 5, 3, 1, 0, 2, 4,
  125825. 6, 8, 10, 12, 14, 16, 18, 20,
  125826. 22, 24, 26,
  125827. };
  125828. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125829. _vq_quantthresh__16c2_s_p9_2,
  125830. _vq_quantmap__16c2_s_p9_2,
  125831. 27,
  125832. 27
  125833. };
  125834. static static_codebook _16c2_s_p9_2 = {
  125835. 1, 27,
  125836. _vq_lengthlist__16c2_s_p9_2,
  125837. 1, -528875520, 1611661312, 5, 0,
  125838. _vq_quantlist__16c2_s_p9_2,
  125839. NULL,
  125840. &_vq_auxt__16c2_s_p9_2,
  125841. NULL,
  125842. 0
  125843. };
  125844. static long _huff_lengthlist__16c2_s_short[] = {
  125845. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125846. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125847. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125848. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125849. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125850. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125851. 15,12,14,14,
  125852. };
  125853. static static_codebook _huff_book__16c2_s_short = {
  125854. 2, 100,
  125855. _huff_lengthlist__16c2_s_short,
  125856. 0, 0, 0, 0, 0,
  125857. NULL,
  125858. NULL,
  125859. NULL,
  125860. NULL,
  125861. 0
  125862. };
  125863. static long _vq_quantlist__8c0_s_p1_0[] = {
  125864. 1,
  125865. 0,
  125866. 2,
  125867. };
  125868. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125869. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125870. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125875. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125880. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125915. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125920. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9,10, 0, 0,
  125925. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125960. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125961. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125966. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125971. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126279. 0,
  126280. };
  126281. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126282. -0.5, 0.5,
  126283. };
  126284. static long _vq_quantmap__8c0_s_p1_0[] = {
  126285. 1, 0, 2,
  126286. };
  126287. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126288. _vq_quantthresh__8c0_s_p1_0,
  126289. _vq_quantmap__8c0_s_p1_0,
  126290. 3,
  126291. 3
  126292. };
  126293. static static_codebook _8c0_s_p1_0 = {
  126294. 8, 6561,
  126295. _vq_lengthlist__8c0_s_p1_0,
  126296. 1, -535822336, 1611661312, 2, 0,
  126297. _vq_quantlist__8c0_s_p1_0,
  126298. NULL,
  126299. &_vq_auxt__8c0_s_p1_0,
  126300. NULL,
  126301. 0
  126302. };
  126303. static long _vq_quantlist__8c0_s_p2_0[] = {
  126304. 2,
  126305. 1,
  126306. 3,
  126307. 0,
  126308. 4,
  126309. };
  126310. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0,
  126351. };
  126352. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126353. -1.5, -0.5, 0.5, 1.5,
  126354. };
  126355. static long _vq_quantmap__8c0_s_p2_0[] = {
  126356. 3, 1, 0, 2, 4,
  126357. };
  126358. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126359. _vq_quantthresh__8c0_s_p2_0,
  126360. _vq_quantmap__8c0_s_p2_0,
  126361. 5,
  126362. 5
  126363. };
  126364. static static_codebook _8c0_s_p2_0 = {
  126365. 4, 625,
  126366. _vq_lengthlist__8c0_s_p2_0,
  126367. 1, -533725184, 1611661312, 3, 0,
  126368. _vq_quantlist__8c0_s_p2_0,
  126369. NULL,
  126370. &_vq_auxt__8c0_s_p2_0,
  126371. NULL,
  126372. 0
  126373. };
  126374. static long _vq_quantlist__8c0_s_p3_0[] = {
  126375. 2,
  126376. 1,
  126377. 3,
  126378. 0,
  126379. 4,
  126380. };
  126381. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126382. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126388. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0,
  126422. };
  126423. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126424. -1.5, -0.5, 0.5, 1.5,
  126425. };
  126426. static long _vq_quantmap__8c0_s_p3_0[] = {
  126427. 3, 1, 0, 2, 4,
  126428. };
  126429. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126430. _vq_quantthresh__8c0_s_p3_0,
  126431. _vq_quantmap__8c0_s_p3_0,
  126432. 5,
  126433. 5
  126434. };
  126435. static static_codebook _8c0_s_p3_0 = {
  126436. 4, 625,
  126437. _vq_lengthlist__8c0_s_p3_0,
  126438. 1, -533725184, 1611661312, 3, 0,
  126439. _vq_quantlist__8c0_s_p3_0,
  126440. NULL,
  126441. &_vq_auxt__8c0_s_p3_0,
  126442. NULL,
  126443. 0
  126444. };
  126445. static long _vq_quantlist__8c0_s_p4_0[] = {
  126446. 4,
  126447. 3,
  126448. 5,
  126449. 2,
  126450. 6,
  126451. 1,
  126452. 7,
  126453. 0,
  126454. 8,
  126455. };
  126456. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126457. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126458. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126459. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126460. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126461. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0,
  126463. };
  126464. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126465. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126466. };
  126467. static long _vq_quantmap__8c0_s_p4_0[] = {
  126468. 7, 5, 3, 1, 0, 2, 4, 6,
  126469. 8,
  126470. };
  126471. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126472. _vq_quantthresh__8c0_s_p4_0,
  126473. _vq_quantmap__8c0_s_p4_0,
  126474. 9,
  126475. 9
  126476. };
  126477. static static_codebook _8c0_s_p4_0 = {
  126478. 2, 81,
  126479. _vq_lengthlist__8c0_s_p4_0,
  126480. 1, -531628032, 1611661312, 4, 0,
  126481. _vq_quantlist__8c0_s_p4_0,
  126482. NULL,
  126483. &_vq_auxt__8c0_s_p4_0,
  126484. NULL,
  126485. 0
  126486. };
  126487. static long _vq_quantlist__8c0_s_p5_0[] = {
  126488. 4,
  126489. 3,
  126490. 5,
  126491. 2,
  126492. 6,
  126493. 1,
  126494. 7,
  126495. 0,
  126496. 8,
  126497. };
  126498. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126499. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126500. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126501. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126502. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126503. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126504. 10,
  126505. };
  126506. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126507. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126508. };
  126509. static long _vq_quantmap__8c0_s_p5_0[] = {
  126510. 7, 5, 3, 1, 0, 2, 4, 6,
  126511. 8,
  126512. };
  126513. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126514. _vq_quantthresh__8c0_s_p5_0,
  126515. _vq_quantmap__8c0_s_p5_0,
  126516. 9,
  126517. 9
  126518. };
  126519. static static_codebook _8c0_s_p5_0 = {
  126520. 2, 81,
  126521. _vq_lengthlist__8c0_s_p5_0,
  126522. 1, -531628032, 1611661312, 4, 0,
  126523. _vq_quantlist__8c0_s_p5_0,
  126524. NULL,
  126525. &_vq_auxt__8c0_s_p5_0,
  126526. NULL,
  126527. 0
  126528. };
  126529. static long _vq_quantlist__8c0_s_p6_0[] = {
  126530. 8,
  126531. 7,
  126532. 9,
  126533. 6,
  126534. 10,
  126535. 5,
  126536. 11,
  126537. 4,
  126538. 12,
  126539. 3,
  126540. 13,
  126541. 2,
  126542. 14,
  126543. 1,
  126544. 15,
  126545. 0,
  126546. 16,
  126547. };
  126548. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126549. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126550. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126551. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126552. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126553. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126554. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126555. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126556. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126557. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126558. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126559. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126560. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126561. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126562. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126563. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126564. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126565. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126567. 14,
  126568. };
  126569. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126572. };
  126573. static long _vq_quantmap__8c0_s_p6_0[] = {
  126574. 15, 13, 11, 9, 7, 5, 3, 1,
  126575. 0, 2, 4, 6, 8, 10, 12, 14,
  126576. 16,
  126577. };
  126578. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126579. _vq_quantthresh__8c0_s_p6_0,
  126580. _vq_quantmap__8c0_s_p6_0,
  126581. 17,
  126582. 17
  126583. };
  126584. static static_codebook _8c0_s_p6_0 = {
  126585. 2, 289,
  126586. _vq_lengthlist__8c0_s_p6_0,
  126587. 1, -529530880, 1611661312, 5, 0,
  126588. _vq_quantlist__8c0_s_p6_0,
  126589. NULL,
  126590. &_vq_auxt__8c0_s_p6_0,
  126591. NULL,
  126592. 0
  126593. };
  126594. static long _vq_quantlist__8c0_s_p7_0[] = {
  126595. 1,
  126596. 0,
  126597. 2,
  126598. };
  126599. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126600. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126601. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126602. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126603. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126604. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126605. 10,
  126606. };
  126607. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126608. -5.5, 5.5,
  126609. };
  126610. static long _vq_quantmap__8c0_s_p7_0[] = {
  126611. 1, 0, 2,
  126612. };
  126613. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126614. _vq_quantthresh__8c0_s_p7_0,
  126615. _vq_quantmap__8c0_s_p7_0,
  126616. 3,
  126617. 3
  126618. };
  126619. static static_codebook _8c0_s_p7_0 = {
  126620. 4, 81,
  126621. _vq_lengthlist__8c0_s_p7_0,
  126622. 1, -529137664, 1618345984, 2, 0,
  126623. _vq_quantlist__8c0_s_p7_0,
  126624. NULL,
  126625. &_vq_auxt__8c0_s_p7_0,
  126626. NULL,
  126627. 0
  126628. };
  126629. static long _vq_quantlist__8c0_s_p7_1[] = {
  126630. 5,
  126631. 4,
  126632. 6,
  126633. 3,
  126634. 7,
  126635. 2,
  126636. 8,
  126637. 1,
  126638. 9,
  126639. 0,
  126640. 10,
  126641. };
  126642. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126643. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126644. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126645. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126646. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126647. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126648. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126649. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126650. 10,10,10, 9, 9, 9,10,10,10,
  126651. };
  126652. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126654. 3.5, 4.5,
  126655. };
  126656. static long _vq_quantmap__8c0_s_p7_1[] = {
  126657. 9, 7, 5, 3, 1, 0, 2, 4,
  126658. 6, 8, 10,
  126659. };
  126660. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126661. _vq_quantthresh__8c0_s_p7_1,
  126662. _vq_quantmap__8c0_s_p7_1,
  126663. 11,
  126664. 11
  126665. };
  126666. static static_codebook _8c0_s_p7_1 = {
  126667. 2, 121,
  126668. _vq_lengthlist__8c0_s_p7_1,
  126669. 1, -531365888, 1611661312, 4, 0,
  126670. _vq_quantlist__8c0_s_p7_1,
  126671. NULL,
  126672. &_vq_auxt__8c0_s_p7_1,
  126673. NULL,
  126674. 0
  126675. };
  126676. static long _vq_quantlist__8c0_s_p8_0[] = {
  126677. 6,
  126678. 5,
  126679. 7,
  126680. 4,
  126681. 8,
  126682. 3,
  126683. 9,
  126684. 2,
  126685. 10,
  126686. 1,
  126687. 11,
  126688. 0,
  126689. 12,
  126690. };
  126691. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126692. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126693. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126694. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126695. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126696. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126697. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126698. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126699. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126700. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126701. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126702. 0, 0,13,13,11,13,13,11,12,
  126703. };
  126704. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126705. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126706. 12.5, 17.5, 22.5, 27.5,
  126707. };
  126708. static long _vq_quantmap__8c0_s_p8_0[] = {
  126709. 11, 9, 7, 5, 3, 1, 0, 2,
  126710. 4, 6, 8, 10, 12,
  126711. };
  126712. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126713. _vq_quantthresh__8c0_s_p8_0,
  126714. _vq_quantmap__8c0_s_p8_0,
  126715. 13,
  126716. 13
  126717. };
  126718. static static_codebook _8c0_s_p8_0 = {
  126719. 2, 169,
  126720. _vq_lengthlist__8c0_s_p8_0,
  126721. 1, -526516224, 1616117760, 4, 0,
  126722. _vq_quantlist__8c0_s_p8_0,
  126723. NULL,
  126724. &_vq_auxt__8c0_s_p8_0,
  126725. NULL,
  126726. 0
  126727. };
  126728. static long _vq_quantlist__8c0_s_p8_1[] = {
  126729. 2,
  126730. 1,
  126731. 3,
  126732. 0,
  126733. 4,
  126734. };
  126735. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126736. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126737. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126738. };
  126739. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126740. -1.5, -0.5, 0.5, 1.5,
  126741. };
  126742. static long _vq_quantmap__8c0_s_p8_1[] = {
  126743. 3, 1, 0, 2, 4,
  126744. };
  126745. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126746. _vq_quantthresh__8c0_s_p8_1,
  126747. _vq_quantmap__8c0_s_p8_1,
  126748. 5,
  126749. 5
  126750. };
  126751. static static_codebook _8c0_s_p8_1 = {
  126752. 2, 25,
  126753. _vq_lengthlist__8c0_s_p8_1,
  126754. 1, -533725184, 1611661312, 3, 0,
  126755. _vq_quantlist__8c0_s_p8_1,
  126756. NULL,
  126757. &_vq_auxt__8c0_s_p8_1,
  126758. NULL,
  126759. 0
  126760. };
  126761. static long _vq_quantlist__8c0_s_p9_0[] = {
  126762. 1,
  126763. 0,
  126764. 2,
  126765. };
  126766. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126767. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126768. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126769. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126770. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126771. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126772. 7,
  126773. };
  126774. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126775. -157.5, 157.5,
  126776. };
  126777. static long _vq_quantmap__8c0_s_p9_0[] = {
  126778. 1, 0, 2,
  126779. };
  126780. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126781. _vq_quantthresh__8c0_s_p9_0,
  126782. _vq_quantmap__8c0_s_p9_0,
  126783. 3,
  126784. 3
  126785. };
  126786. static static_codebook _8c0_s_p9_0 = {
  126787. 4, 81,
  126788. _vq_lengthlist__8c0_s_p9_0,
  126789. 1, -518803456, 1628680192, 2, 0,
  126790. _vq_quantlist__8c0_s_p9_0,
  126791. NULL,
  126792. &_vq_auxt__8c0_s_p9_0,
  126793. NULL,
  126794. 0
  126795. };
  126796. static long _vq_quantlist__8c0_s_p9_1[] = {
  126797. 7,
  126798. 6,
  126799. 8,
  126800. 5,
  126801. 9,
  126802. 4,
  126803. 10,
  126804. 3,
  126805. 11,
  126806. 2,
  126807. 12,
  126808. 1,
  126809. 13,
  126810. 0,
  126811. 14,
  126812. };
  126813. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126814. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126815. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126816. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126817. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126818. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126819. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126828. 11,
  126829. };
  126830. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126831. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126832. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126833. };
  126834. static long _vq_quantmap__8c0_s_p9_1[] = {
  126835. 13, 11, 9, 7, 5, 3, 1, 0,
  126836. 2, 4, 6, 8, 10, 12, 14,
  126837. };
  126838. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126839. _vq_quantthresh__8c0_s_p9_1,
  126840. _vq_quantmap__8c0_s_p9_1,
  126841. 15,
  126842. 15
  126843. };
  126844. static static_codebook _8c0_s_p9_1 = {
  126845. 2, 225,
  126846. _vq_lengthlist__8c0_s_p9_1,
  126847. 1, -520986624, 1620377600, 4, 0,
  126848. _vq_quantlist__8c0_s_p9_1,
  126849. NULL,
  126850. &_vq_auxt__8c0_s_p9_1,
  126851. NULL,
  126852. 0
  126853. };
  126854. static long _vq_quantlist__8c0_s_p9_2[] = {
  126855. 10,
  126856. 9,
  126857. 11,
  126858. 8,
  126859. 12,
  126860. 7,
  126861. 13,
  126862. 6,
  126863. 14,
  126864. 5,
  126865. 15,
  126866. 4,
  126867. 16,
  126868. 3,
  126869. 17,
  126870. 2,
  126871. 18,
  126872. 1,
  126873. 19,
  126874. 0,
  126875. 20,
  126876. };
  126877. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126878. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126879. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126880. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126881. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126882. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126883. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126884. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126885. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126886. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126887. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126888. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126889. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126890. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126891. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126892. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126893. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126894. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126895. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126896. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126897. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126898. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126899. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126900. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126901. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126902. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126903. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126904. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126905. 10,11, 9,11,10, 9,10, 9,10,
  126906. };
  126907. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126908. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126909. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126910. 6.5, 7.5, 8.5, 9.5,
  126911. };
  126912. static long _vq_quantmap__8c0_s_p9_2[] = {
  126913. 19, 17, 15, 13, 11, 9, 7, 5,
  126914. 3, 1, 0, 2, 4, 6, 8, 10,
  126915. 12, 14, 16, 18, 20,
  126916. };
  126917. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126918. _vq_quantthresh__8c0_s_p9_2,
  126919. _vq_quantmap__8c0_s_p9_2,
  126920. 21,
  126921. 21
  126922. };
  126923. static static_codebook _8c0_s_p9_2 = {
  126924. 2, 441,
  126925. _vq_lengthlist__8c0_s_p9_2,
  126926. 1, -529268736, 1611661312, 5, 0,
  126927. _vq_quantlist__8c0_s_p9_2,
  126928. NULL,
  126929. &_vq_auxt__8c0_s_p9_2,
  126930. NULL,
  126931. 0
  126932. };
  126933. static long _huff_lengthlist__8c0_s_single[] = {
  126934. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126935. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126936. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126937. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126938. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126939. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126940. 17,16,17,17,
  126941. };
  126942. static static_codebook _huff_book__8c0_s_single = {
  126943. 2, 100,
  126944. _huff_lengthlist__8c0_s_single,
  126945. 0, 0, 0, 0, 0,
  126946. NULL,
  126947. NULL,
  126948. NULL,
  126949. NULL,
  126950. 0
  126951. };
  126952. static long _vq_quantlist__8c1_s_p1_0[] = {
  126953. 1,
  126954. 0,
  126955. 2,
  126956. };
  126957. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126958. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126959. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126964. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126969. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127002. 0, 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, 5, 8, 8, 0, 0, 0, 0,
  127004. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 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, 7, 9, 9, 0, 0, 0,
  127009. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127014. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  127046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127050. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127055. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127060. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127369. };
  127370. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127371. -0.5, 0.5,
  127372. };
  127373. static long _vq_quantmap__8c1_s_p1_0[] = {
  127374. 1, 0, 2,
  127375. };
  127376. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127377. _vq_quantthresh__8c1_s_p1_0,
  127378. _vq_quantmap__8c1_s_p1_0,
  127379. 3,
  127380. 3
  127381. };
  127382. static static_codebook _8c1_s_p1_0 = {
  127383. 8, 6561,
  127384. _vq_lengthlist__8c1_s_p1_0,
  127385. 1, -535822336, 1611661312, 2, 0,
  127386. _vq_quantlist__8c1_s_p1_0,
  127387. NULL,
  127388. &_vq_auxt__8c1_s_p1_0,
  127389. NULL,
  127390. 0
  127391. };
  127392. static long _vq_quantlist__8c1_s_p2_0[] = {
  127393. 2,
  127394. 1,
  127395. 3,
  127396. 0,
  127397. 4,
  127398. };
  127399. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0,
  127440. };
  127441. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127442. -1.5, -0.5, 0.5, 1.5,
  127443. };
  127444. static long _vq_quantmap__8c1_s_p2_0[] = {
  127445. 3, 1, 0, 2, 4,
  127446. };
  127447. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127448. _vq_quantthresh__8c1_s_p2_0,
  127449. _vq_quantmap__8c1_s_p2_0,
  127450. 5,
  127451. 5
  127452. };
  127453. static static_codebook _8c1_s_p2_0 = {
  127454. 4, 625,
  127455. _vq_lengthlist__8c1_s_p2_0,
  127456. 1, -533725184, 1611661312, 3, 0,
  127457. _vq_quantlist__8c1_s_p2_0,
  127458. NULL,
  127459. &_vq_auxt__8c1_s_p2_0,
  127460. NULL,
  127461. 0
  127462. };
  127463. static long _vq_quantlist__8c1_s_p3_0[] = {
  127464. 2,
  127465. 1,
  127466. 3,
  127467. 0,
  127468. 4,
  127469. };
  127470. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127471. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0,
  127511. };
  127512. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127513. -1.5, -0.5, 0.5, 1.5,
  127514. };
  127515. static long _vq_quantmap__8c1_s_p3_0[] = {
  127516. 3, 1, 0, 2, 4,
  127517. };
  127518. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127519. _vq_quantthresh__8c1_s_p3_0,
  127520. _vq_quantmap__8c1_s_p3_0,
  127521. 5,
  127522. 5
  127523. };
  127524. static static_codebook _8c1_s_p3_0 = {
  127525. 4, 625,
  127526. _vq_lengthlist__8c1_s_p3_0,
  127527. 1, -533725184, 1611661312, 3, 0,
  127528. _vq_quantlist__8c1_s_p3_0,
  127529. NULL,
  127530. &_vq_auxt__8c1_s_p3_0,
  127531. NULL,
  127532. 0
  127533. };
  127534. static long _vq_quantlist__8c1_s_p4_0[] = {
  127535. 4,
  127536. 3,
  127537. 5,
  127538. 2,
  127539. 6,
  127540. 1,
  127541. 7,
  127542. 0,
  127543. 8,
  127544. };
  127545. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127546. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127547. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127548. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127549. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127550. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0,
  127552. };
  127553. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127554. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127555. };
  127556. static long _vq_quantmap__8c1_s_p4_0[] = {
  127557. 7, 5, 3, 1, 0, 2, 4, 6,
  127558. 8,
  127559. };
  127560. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127561. _vq_quantthresh__8c1_s_p4_0,
  127562. _vq_quantmap__8c1_s_p4_0,
  127563. 9,
  127564. 9
  127565. };
  127566. static static_codebook _8c1_s_p4_0 = {
  127567. 2, 81,
  127568. _vq_lengthlist__8c1_s_p4_0,
  127569. 1, -531628032, 1611661312, 4, 0,
  127570. _vq_quantlist__8c1_s_p4_0,
  127571. NULL,
  127572. &_vq_auxt__8c1_s_p4_0,
  127573. NULL,
  127574. 0
  127575. };
  127576. static long _vq_quantlist__8c1_s_p5_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__8c1_s_p5_0[] = {
  127588. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127589. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127590. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127591. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127592. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127593. 10,
  127594. };
  127595. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127596. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127597. };
  127598. static long _vq_quantmap__8c1_s_p5_0[] = {
  127599. 7, 5, 3, 1, 0, 2, 4, 6,
  127600. 8,
  127601. };
  127602. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127603. _vq_quantthresh__8c1_s_p5_0,
  127604. _vq_quantmap__8c1_s_p5_0,
  127605. 9,
  127606. 9
  127607. };
  127608. static static_codebook _8c1_s_p5_0 = {
  127609. 2, 81,
  127610. _vq_lengthlist__8c1_s_p5_0,
  127611. 1, -531628032, 1611661312, 4, 0,
  127612. _vq_quantlist__8c1_s_p5_0,
  127613. NULL,
  127614. &_vq_auxt__8c1_s_p5_0,
  127615. NULL,
  127616. 0
  127617. };
  127618. static long _vq_quantlist__8c1_s_p6_0[] = {
  127619. 8,
  127620. 7,
  127621. 9,
  127622. 6,
  127623. 10,
  127624. 5,
  127625. 11,
  127626. 4,
  127627. 12,
  127628. 3,
  127629. 13,
  127630. 2,
  127631. 14,
  127632. 1,
  127633. 15,
  127634. 0,
  127635. 16,
  127636. };
  127637. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127638. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127639. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127640. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127641. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127642. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127643. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127644. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127645. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127646. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127647. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127648. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127649. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127650. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127651. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127652. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127653. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127654. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127656. 14,
  127657. };
  127658. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127659. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127660. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127661. };
  127662. static long _vq_quantmap__8c1_s_p6_0[] = {
  127663. 15, 13, 11, 9, 7, 5, 3, 1,
  127664. 0, 2, 4, 6, 8, 10, 12, 14,
  127665. 16,
  127666. };
  127667. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127668. _vq_quantthresh__8c1_s_p6_0,
  127669. _vq_quantmap__8c1_s_p6_0,
  127670. 17,
  127671. 17
  127672. };
  127673. static static_codebook _8c1_s_p6_0 = {
  127674. 2, 289,
  127675. _vq_lengthlist__8c1_s_p6_0,
  127676. 1, -529530880, 1611661312, 5, 0,
  127677. _vq_quantlist__8c1_s_p6_0,
  127678. NULL,
  127679. &_vq_auxt__8c1_s_p6_0,
  127680. NULL,
  127681. 0
  127682. };
  127683. static long _vq_quantlist__8c1_s_p7_0[] = {
  127684. 1,
  127685. 0,
  127686. 2,
  127687. };
  127688. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127689. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127690. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127691. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127692. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127693. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127694. 9,
  127695. };
  127696. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127697. -5.5, 5.5,
  127698. };
  127699. static long _vq_quantmap__8c1_s_p7_0[] = {
  127700. 1, 0, 2,
  127701. };
  127702. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127703. _vq_quantthresh__8c1_s_p7_0,
  127704. _vq_quantmap__8c1_s_p7_0,
  127705. 3,
  127706. 3
  127707. };
  127708. static static_codebook _8c1_s_p7_0 = {
  127709. 4, 81,
  127710. _vq_lengthlist__8c1_s_p7_0,
  127711. 1, -529137664, 1618345984, 2, 0,
  127712. _vq_quantlist__8c1_s_p7_0,
  127713. NULL,
  127714. &_vq_auxt__8c1_s_p7_0,
  127715. NULL,
  127716. 0
  127717. };
  127718. static long _vq_quantlist__8c1_s_p7_1[] = {
  127719. 5,
  127720. 4,
  127721. 6,
  127722. 3,
  127723. 7,
  127724. 2,
  127725. 8,
  127726. 1,
  127727. 9,
  127728. 0,
  127729. 10,
  127730. };
  127731. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127732. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127733. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127734. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127735. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127736. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127737. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127738. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127739. 10,10,10, 8, 8, 8, 8, 8, 8,
  127740. };
  127741. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127742. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127743. 3.5, 4.5,
  127744. };
  127745. static long _vq_quantmap__8c1_s_p7_1[] = {
  127746. 9, 7, 5, 3, 1, 0, 2, 4,
  127747. 6, 8, 10,
  127748. };
  127749. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127750. _vq_quantthresh__8c1_s_p7_1,
  127751. _vq_quantmap__8c1_s_p7_1,
  127752. 11,
  127753. 11
  127754. };
  127755. static static_codebook _8c1_s_p7_1 = {
  127756. 2, 121,
  127757. _vq_lengthlist__8c1_s_p7_1,
  127758. 1, -531365888, 1611661312, 4, 0,
  127759. _vq_quantlist__8c1_s_p7_1,
  127760. NULL,
  127761. &_vq_auxt__8c1_s_p7_1,
  127762. NULL,
  127763. 0
  127764. };
  127765. static long _vq_quantlist__8c1_s_p8_0[] = {
  127766. 6,
  127767. 5,
  127768. 7,
  127769. 4,
  127770. 8,
  127771. 3,
  127772. 9,
  127773. 2,
  127774. 10,
  127775. 1,
  127776. 11,
  127777. 0,
  127778. 12,
  127779. };
  127780. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127781. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127782. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127783. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127784. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127785. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127786. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127787. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127788. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127789. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127790. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127791. 0,12,12,11,10,12,11,13,12,
  127792. };
  127793. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127794. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127795. 12.5, 17.5, 22.5, 27.5,
  127796. };
  127797. static long _vq_quantmap__8c1_s_p8_0[] = {
  127798. 11, 9, 7, 5, 3, 1, 0, 2,
  127799. 4, 6, 8, 10, 12,
  127800. };
  127801. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127802. _vq_quantthresh__8c1_s_p8_0,
  127803. _vq_quantmap__8c1_s_p8_0,
  127804. 13,
  127805. 13
  127806. };
  127807. static static_codebook _8c1_s_p8_0 = {
  127808. 2, 169,
  127809. _vq_lengthlist__8c1_s_p8_0,
  127810. 1, -526516224, 1616117760, 4, 0,
  127811. _vq_quantlist__8c1_s_p8_0,
  127812. NULL,
  127813. &_vq_auxt__8c1_s_p8_0,
  127814. NULL,
  127815. 0
  127816. };
  127817. static long _vq_quantlist__8c1_s_p8_1[] = {
  127818. 2,
  127819. 1,
  127820. 3,
  127821. 0,
  127822. 4,
  127823. };
  127824. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127825. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127826. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127827. };
  127828. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127829. -1.5, -0.5, 0.5, 1.5,
  127830. };
  127831. static long _vq_quantmap__8c1_s_p8_1[] = {
  127832. 3, 1, 0, 2, 4,
  127833. };
  127834. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127835. _vq_quantthresh__8c1_s_p8_1,
  127836. _vq_quantmap__8c1_s_p8_1,
  127837. 5,
  127838. 5
  127839. };
  127840. static static_codebook _8c1_s_p8_1 = {
  127841. 2, 25,
  127842. _vq_lengthlist__8c1_s_p8_1,
  127843. 1, -533725184, 1611661312, 3, 0,
  127844. _vq_quantlist__8c1_s_p8_1,
  127845. NULL,
  127846. &_vq_auxt__8c1_s_p8_1,
  127847. NULL,
  127848. 0
  127849. };
  127850. static long _vq_quantlist__8c1_s_p9_0[] = {
  127851. 6,
  127852. 5,
  127853. 7,
  127854. 4,
  127855. 8,
  127856. 3,
  127857. 9,
  127858. 2,
  127859. 10,
  127860. 1,
  127861. 11,
  127862. 0,
  127863. 12,
  127864. };
  127865. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127866. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127867. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127868. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127876. 10,10,10,10,10, 9, 9, 9, 9,
  127877. };
  127878. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127879. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127880. 787.5, 1102.5, 1417.5, 1732.5,
  127881. };
  127882. static long _vq_quantmap__8c1_s_p9_0[] = {
  127883. 11, 9, 7, 5, 3, 1, 0, 2,
  127884. 4, 6, 8, 10, 12,
  127885. };
  127886. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127887. _vq_quantthresh__8c1_s_p9_0,
  127888. _vq_quantmap__8c1_s_p9_0,
  127889. 13,
  127890. 13
  127891. };
  127892. static static_codebook _8c1_s_p9_0 = {
  127893. 2, 169,
  127894. _vq_lengthlist__8c1_s_p9_0,
  127895. 1, -513964032, 1628680192, 4, 0,
  127896. _vq_quantlist__8c1_s_p9_0,
  127897. NULL,
  127898. &_vq_auxt__8c1_s_p9_0,
  127899. NULL,
  127900. 0
  127901. };
  127902. static long _vq_quantlist__8c1_s_p9_1[] = {
  127903. 7,
  127904. 6,
  127905. 8,
  127906. 5,
  127907. 9,
  127908. 4,
  127909. 10,
  127910. 3,
  127911. 11,
  127912. 2,
  127913. 12,
  127914. 1,
  127915. 13,
  127916. 0,
  127917. 14,
  127918. };
  127919. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127920. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127921. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127922. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127923. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127924. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127925. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127926. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127927. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127928. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127929. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127930. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127931. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127932. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127933. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127934. 15,
  127935. };
  127936. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127937. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127938. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127939. };
  127940. static long _vq_quantmap__8c1_s_p9_1[] = {
  127941. 13, 11, 9, 7, 5, 3, 1, 0,
  127942. 2, 4, 6, 8, 10, 12, 14,
  127943. };
  127944. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127945. _vq_quantthresh__8c1_s_p9_1,
  127946. _vq_quantmap__8c1_s_p9_1,
  127947. 15,
  127948. 15
  127949. };
  127950. static static_codebook _8c1_s_p9_1 = {
  127951. 2, 225,
  127952. _vq_lengthlist__8c1_s_p9_1,
  127953. 1, -520986624, 1620377600, 4, 0,
  127954. _vq_quantlist__8c1_s_p9_1,
  127955. NULL,
  127956. &_vq_auxt__8c1_s_p9_1,
  127957. NULL,
  127958. 0
  127959. };
  127960. static long _vq_quantlist__8c1_s_p9_2[] = {
  127961. 10,
  127962. 9,
  127963. 11,
  127964. 8,
  127965. 12,
  127966. 7,
  127967. 13,
  127968. 6,
  127969. 14,
  127970. 5,
  127971. 15,
  127972. 4,
  127973. 16,
  127974. 3,
  127975. 17,
  127976. 2,
  127977. 18,
  127978. 1,
  127979. 19,
  127980. 0,
  127981. 20,
  127982. };
  127983. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127984. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127985. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127986. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127987. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127988. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127989. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127990. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127991. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127992. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127993. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127994. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127995. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127996. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127997. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127998. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127999. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  128000. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128001. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  128002. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  128003. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  128004. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128005. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128006. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128007. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128008. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128009. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128010. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128011. 10,10,10,10,10,10,10,10,10,
  128012. };
  128013. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128014. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128015. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128016. 6.5, 7.5, 8.5, 9.5,
  128017. };
  128018. static long _vq_quantmap__8c1_s_p9_2[] = {
  128019. 19, 17, 15, 13, 11, 9, 7, 5,
  128020. 3, 1, 0, 2, 4, 6, 8, 10,
  128021. 12, 14, 16, 18, 20,
  128022. };
  128023. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128024. _vq_quantthresh__8c1_s_p9_2,
  128025. _vq_quantmap__8c1_s_p9_2,
  128026. 21,
  128027. 21
  128028. };
  128029. static static_codebook _8c1_s_p9_2 = {
  128030. 2, 441,
  128031. _vq_lengthlist__8c1_s_p9_2,
  128032. 1, -529268736, 1611661312, 5, 0,
  128033. _vq_quantlist__8c1_s_p9_2,
  128034. NULL,
  128035. &_vq_auxt__8c1_s_p9_2,
  128036. NULL,
  128037. 0
  128038. };
  128039. static long _huff_lengthlist__8c1_s_single[] = {
  128040. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128041. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128042. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128043. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128044. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128045. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128046. 9, 7, 7, 8,
  128047. };
  128048. static static_codebook _huff_book__8c1_s_single = {
  128049. 2, 100,
  128050. _huff_lengthlist__8c1_s_single,
  128051. 0, 0, 0, 0, 0,
  128052. NULL,
  128053. NULL,
  128054. NULL,
  128055. NULL,
  128056. 0
  128057. };
  128058. static long _huff_lengthlist__44c2_s_long[] = {
  128059. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128060. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128061. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128062. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128063. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128064. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128065. 10, 8, 8, 9,
  128066. };
  128067. static static_codebook _huff_book__44c2_s_long = {
  128068. 2, 100,
  128069. _huff_lengthlist__44c2_s_long,
  128070. 0, 0, 0, 0, 0,
  128071. NULL,
  128072. NULL,
  128073. NULL,
  128074. NULL,
  128075. 0
  128076. };
  128077. static long _vq_quantlist__44c2_s_p1_0[] = {
  128078. 1,
  128079. 0,
  128080. 2,
  128081. };
  128082. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128083. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128084. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128089. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128094. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128107. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128112. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128129. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128134. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128139. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128174. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128175. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128180. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128185. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128493. 0,
  128494. };
  128495. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128496. -0.5, 0.5,
  128497. };
  128498. static long _vq_quantmap__44c2_s_p1_0[] = {
  128499. 1, 0, 2,
  128500. };
  128501. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128502. _vq_quantthresh__44c2_s_p1_0,
  128503. _vq_quantmap__44c2_s_p1_0,
  128504. 3,
  128505. 3
  128506. };
  128507. static static_codebook _44c2_s_p1_0 = {
  128508. 8, 6561,
  128509. _vq_lengthlist__44c2_s_p1_0,
  128510. 1, -535822336, 1611661312, 2, 0,
  128511. _vq_quantlist__44c2_s_p1_0,
  128512. NULL,
  128513. &_vq_auxt__44c2_s_p1_0,
  128514. NULL,
  128515. 0
  128516. };
  128517. static long _vq_quantlist__44c2_s_p2_0[] = {
  128518. 2,
  128519. 1,
  128520. 3,
  128521. 0,
  128522. 4,
  128523. };
  128524. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128525. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128526. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128527. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128528. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128529. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128534. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128535. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128536. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128537. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128542. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128543. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128544. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128550. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128551. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128552. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0,
  128565. };
  128566. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128567. -1.5, -0.5, 0.5, 1.5,
  128568. };
  128569. static long _vq_quantmap__44c2_s_p2_0[] = {
  128570. 3, 1, 0, 2, 4,
  128571. };
  128572. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128573. _vq_quantthresh__44c2_s_p2_0,
  128574. _vq_quantmap__44c2_s_p2_0,
  128575. 5,
  128576. 5
  128577. };
  128578. static static_codebook _44c2_s_p2_0 = {
  128579. 4, 625,
  128580. _vq_lengthlist__44c2_s_p2_0,
  128581. 1, -533725184, 1611661312, 3, 0,
  128582. _vq_quantlist__44c2_s_p2_0,
  128583. NULL,
  128584. &_vq_auxt__44c2_s_p2_0,
  128585. NULL,
  128586. 0
  128587. };
  128588. static long _vq_quantlist__44c2_s_p3_0[] = {
  128589. 2,
  128590. 1,
  128591. 3,
  128592. 0,
  128593. 4,
  128594. };
  128595. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128596. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0,
  128636. };
  128637. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128638. -1.5, -0.5, 0.5, 1.5,
  128639. };
  128640. static long _vq_quantmap__44c2_s_p3_0[] = {
  128641. 3, 1, 0, 2, 4,
  128642. };
  128643. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128644. _vq_quantthresh__44c2_s_p3_0,
  128645. _vq_quantmap__44c2_s_p3_0,
  128646. 5,
  128647. 5
  128648. };
  128649. static static_codebook _44c2_s_p3_0 = {
  128650. 4, 625,
  128651. _vq_lengthlist__44c2_s_p3_0,
  128652. 1, -533725184, 1611661312, 3, 0,
  128653. _vq_quantlist__44c2_s_p3_0,
  128654. NULL,
  128655. &_vq_auxt__44c2_s_p3_0,
  128656. NULL,
  128657. 0
  128658. };
  128659. static long _vq_quantlist__44c2_s_p4_0[] = {
  128660. 4,
  128661. 3,
  128662. 5,
  128663. 2,
  128664. 6,
  128665. 1,
  128666. 7,
  128667. 0,
  128668. 8,
  128669. };
  128670. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128671. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128672. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128673. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128674. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128675. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0,
  128677. };
  128678. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128679. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128680. };
  128681. static long _vq_quantmap__44c2_s_p4_0[] = {
  128682. 7, 5, 3, 1, 0, 2, 4, 6,
  128683. 8,
  128684. };
  128685. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128686. _vq_quantthresh__44c2_s_p4_0,
  128687. _vq_quantmap__44c2_s_p4_0,
  128688. 9,
  128689. 9
  128690. };
  128691. static static_codebook _44c2_s_p4_0 = {
  128692. 2, 81,
  128693. _vq_lengthlist__44c2_s_p4_0,
  128694. 1, -531628032, 1611661312, 4, 0,
  128695. _vq_quantlist__44c2_s_p4_0,
  128696. NULL,
  128697. &_vq_auxt__44c2_s_p4_0,
  128698. NULL,
  128699. 0
  128700. };
  128701. static long _vq_quantlist__44c2_s_p5_0[] = {
  128702. 4,
  128703. 3,
  128704. 5,
  128705. 2,
  128706. 6,
  128707. 1,
  128708. 7,
  128709. 0,
  128710. 8,
  128711. };
  128712. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128713. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128714. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128715. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128716. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128717. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128718. 11,
  128719. };
  128720. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128721. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128722. };
  128723. static long _vq_quantmap__44c2_s_p5_0[] = {
  128724. 7, 5, 3, 1, 0, 2, 4, 6,
  128725. 8,
  128726. };
  128727. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128728. _vq_quantthresh__44c2_s_p5_0,
  128729. _vq_quantmap__44c2_s_p5_0,
  128730. 9,
  128731. 9
  128732. };
  128733. static static_codebook _44c2_s_p5_0 = {
  128734. 2, 81,
  128735. _vq_lengthlist__44c2_s_p5_0,
  128736. 1, -531628032, 1611661312, 4, 0,
  128737. _vq_quantlist__44c2_s_p5_0,
  128738. NULL,
  128739. &_vq_auxt__44c2_s_p5_0,
  128740. NULL,
  128741. 0
  128742. };
  128743. static long _vq_quantlist__44c2_s_p6_0[] = {
  128744. 8,
  128745. 7,
  128746. 9,
  128747. 6,
  128748. 10,
  128749. 5,
  128750. 11,
  128751. 4,
  128752. 12,
  128753. 3,
  128754. 13,
  128755. 2,
  128756. 14,
  128757. 1,
  128758. 15,
  128759. 0,
  128760. 16,
  128761. };
  128762. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128763. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128764. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128765. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128766. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128767. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128768. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128769. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128770. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128771. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128772. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128773. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128774. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128775. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128776. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128777. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128778. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128779. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128781. 14,
  128782. };
  128783. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128786. };
  128787. static long _vq_quantmap__44c2_s_p6_0[] = {
  128788. 15, 13, 11, 9, 7, 5, 3, 1,
  128789. 0, 2, 4, 6, 8, 10, 12, 14,
  128790. 16,
  128791. };
  128792. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128793. _vq_quantthresh__44c2_s_p6_0,
  128794. _vq_quantmap__44c2_s_p6_0,
  128795. 17,
  128796. 17
  128797. };
  128798. static static_codebook _44c2_s_p6_0 = {
  128799. 2, 289,
  128800. _vq_lengthlist__44c2_s_p6_0,
  128801. 1, -529530880, 1611661312, 5, 0,
  128802. _vq_quantlist__44c2_s_p6_0,
  128803. NULL,
  128804. &_vq_auxt__44c2_s_p6_0,
  128805. NULL,
  128806. 0
  128807. };
  128808. static long _vq_quantlist__44c2_s_p7_0[] = {
  128809. 1,
  128810. 0,
  128811. 2,
  128812. };
  128813. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128814. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128815. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128816. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128817. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128818. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128819. 11,
  128820. };
  128821. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128822. -5.5, 5.5,
  128823. };
  128824. static long _vq_quantmap__44c2_s_p7_0[] = {
  128825. 1, 0, 2,
  128826. };
  128827. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128828. _vq_quantthresh__44c2_s_p7_0,
  128829. _vq_quantmap__44c2_s_p7_0,
  128830. 3,
  128831. 3
  128832. };
  128833. static static_codebook _44c2_s_p7_0 = {
  128834. 4, 81,
  128835. _vq_lengthlist__44c2_s_p7_0,
  128836. 1, -529137664, 1618345984, 2, 0,
  128837. _vq_quantlist__44c2_s_p7_0,
  128838. NULL,
  128839. &_vq_auxt__44c2_s_p7_0,
  128840. NULL,
  128841. 0
  128842. };
  128843. static long _vq_quantlist__44c2_s_p7_1[] = {
  128844. 5,
  128845. 4,
  128846. 6,
  128847. 3,
  128848. 7,
  128849. 2,
  128850. 8,
  128851. 1,
  128852. 9,
  128853. 0,
  128854. 10,
  128855. };
  128856. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128857. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128858. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128859. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128860. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128861. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128862. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128863. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128864. 10,10,10, 8, 8, 8, 8, 8, 8,
  128865. };
  128866. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128867. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128868. 3.5, 4.5,
  128869. };
  128870. static long _vq_quantmap__44c2_s_p7_1[] = {
  128871. 9, 7, 5, 3, 1, 0, 2, 4,
  128872. 6, 8, 10,
  128873. };
  128874. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128875. _vq_quantthresh__44c2_s_p7_1,
  128876. _vq_quantmap__44c2_s_p7_1,
  128877. 11,
  128878. 11
  128879. };
  128880. static static_codebook _44c2_s_p7_1 = {
  128881. 2, 121,
  128882. _vq_lengthlist__44c2_s_p7_1,
  128883. 1, -531365888, 1611661312, 4, 0,
  128884. _vq_quantlist__44c2_s_p7_1,
  128885. NULL,
  128886. &_vq_auxt__44c2_s_p7_1,
  128887. NULL,
  128888. 0
  128889. };
  128890. static long _vq_quantlist__44c2_s_p8_0[] = {
  128891. 6,
  128892. 5,
  128893. 7,
  128894. 4,
  128895. 8,
  128896. 3,
  128897. 9,
  128898. 2,
  128899. 10,
  128900. 1,
  128901. 11,
  128902. 0,
  128903. 12,
  128904. };
  128905. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128906. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128907. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128908. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128909. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128910. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128911. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128912. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128913. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128914. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128915. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128916. 0,12,12,12,12,13,12,14,14,
  128917. };
  128918. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128919. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128920. 12.5, 17.5, 22.5, 27.5,
  128921. };
  128922. static long _vq_quantmap__44c2_s_p8_0[] = {
  128923. 11, 9, 7, 5, 3, 1, 0, 2,
  128924. 4, 6, 8, 10, 12,
  128925. };
  128926. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128927. _vq_quantthresh__44c2_s_p8_0,
  128928. _vq_quantmap__44c2_s_p8_0,
  128929. 13,
  128930. 13
  128931. };
  128932. static static_codebook _44c2_s_p8_0 = {
  128933. 2, 169,
  128934. _vq_lengthlist__44c2_s_p8_0,
  128935. 1, -526516224, 1616117760, 4, 0,
  128936. _vq_quantlist__44c2_s_p8_0,
  128937. NULL,
  128938. &_vq_auxt__44c2_s_p8_0,
  128939. NULL,
  128940. 0
  128941. };
  128942. static long _vq_quantlist__44c2_s_p8_1[] = {
  128943. 2,
  128944. 1,
  128945. 3,
  128946. 0,
  128947. 4,
  128948. };
  128949. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128950. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128951. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128952. };
  128953. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128954. -1.5, -0.5, 0.5, 1.5,
  128955. };
  128956. static long _vq_quantmap__44c2_s_p8_1[] = {
  128957. 3, 1, 0, 2, 4,
  128958. };
  128959. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128960. _vq_quantthresh__44c2_s_p8_1,
  128961. _vq_quantmap__44c2_s_p8_1,
  128962. 5,
  128963. 5
  128964. };
  128965. static static_codebook _44c2_s_p8_1 = {
  128966. 2, 25,
  128967. _vq_lengthlist__44c2_s_p8_1,
  128968. 1, -533725184, 1611661312, 3, 0,
  128969. _vq_quantlist__44c2_s_p8_1,
  128970. NULL,
  128971. &_vq_auxt__44c2_s_p8_1,
  128972. NULL,
  128973. 0
  128974. };
  128975. static long _vq_quantlist__44c2_s_p9_0[] = {
  128976. 6,
  128977. 5,
  128978. 7,
  128979. 4,
  128980. 8,
  128981. 3,
  128982. 9,
  128983. 2,
  128984. 10,
  128985. 1,
  128986. 11,
  128987. 0,
  128988. 12,
  128989. };
  128990. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128991. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128992. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128994. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128995. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129001. 11,11,11,11,11,11,11,11,11,
  129002. };
  129003. static float _vq_quantthresh__44c2_s_p9_0[] = {
  129004. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129005. 552.5, 773.5, 994.5, 1215.5,
  129006. };
  129007. static long _vq_quantmap__44c2_s_p9_0[] = {
  129008. 11, 9, 7, 5, 3, 1, 0, 2,
  129009. 4, 6, 8, 10, 12,
  129010. };
  129011. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129012. _vq_quantthresh__44c2_s_p9_0,
  129013. _vq_quantmap__44c2_s_p9_0,
  129014. 13,
  129015. 13
  129016. };
  129017. static static_codebook _44c2_s_p9_0 = {
  129018. 2, 169,
  129019. _vq_lengthlist__44c2_s_p9_0,
  129020. 1, -514541568, 1627103232, 4, 0,
  129021. _vq_quantlist__44c2_s_p9_0,
  129022. NULL,
  129023. &_vq_auxt__44c2_s_p9_0,
  129024. NULL,
  129025. 0
  129026. };
  129027. static long _vq_quantlist__44c2_s_p9_1[] = {
  129028. 6,
  129029. 5,
  129030. 7,
  129031. 4,
  129032. 8,
  129033. 3,
  129034. 9,
  129035. 2,
  129036. 10,
  129037. 1,
  129038. 11,
  129039. 0,
  129040. 12,
  129041. };
  129042. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129043. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129044. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129045. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129046. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129047. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129048. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129049. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129050. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129051. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129052. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129053. 17,13,12,12,10,13,11,14,14,
  129054. };
  129055. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129056. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129057. 42.5, 59.5, 76.5, 93.5,
  129058. };
  129059. static long _vq_quantmap__44c2_s_p9_1[] = {
  129060. 11, 9, 7, 5, 3, 1, 0, 2,
  129061. 4, 6, 8, 10, 12,
  129062. };
  129063. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129064. _vq_quantthresh__44c2_s_p9_1,
  129065. _vq_quantmap__44c2_s_p9_1,
  129066. 13,
  129067. 13
  129068. };
  129069. static static_codebook _44c2_s_p9_1 = {
  129070. 2, 169,
  129071. _vq_lengthlist__44c2_s_p9_1,
  129072. 1, -522616832, 1620115456, 4, 0,
  129073. _vq_quantlist__44c2_s_p9_1,
  129074. NULL,
  129075. &_vq_auxt__44c2_s_p9_1,
  129076. NULL,
  129077. 0
  129078. };
  129079. static long _vq_quantlist__44c2_s_p9_2[] = {
  129080. 8,
  129081. 7,
  129082. 9,
  129083. 6,
  129084. 10,
  129085. 5,
  129086. 11,
  129087. 4,
  129088. 12,
  129089. 3,
  129090. 13,
  129091. 2,
  129092. 14,
  129093. 1,
  129094. 15,
  129095. 0,
  129096. 16,
  129097. };
  129098. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129099. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129100. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129101. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129102. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129103. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129104. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129105. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129106. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129107. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129108. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129109. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129110. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129111. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129112. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129113. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129114. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129115. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129116. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129117. 10,
  129118. };
  129119. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129120. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129121. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129122. };
  129123. static long _vq_quantmap__44c2_s_p9_2[] = {
  129124. 15, 13, 11, 9, 7, 5, 3, 1,
  129125. 0, 2, 4, 6, 8, 10, 12, 14,
  129126. 16,
  129127. };
  129128. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129129. _vq_quantthresh__44c2_s_p9_2,
  129130. _vq_quantmap__44c2_s_p9_2,
  129131. 17,
  129132. 17
  129133. };
  129134. static static_codebook _44c2_s_p9_2 = {
  129135. 2, 289,
  129136. _vq_lengthlist__44c2_s_p9_2,
  129137. 1, -529530880, 1611661312, 5, 0,
  129138. _vq_quantlist__44c2_s_p9_2,
  129139. NULL,
  129140. &_vq_auxt__44c2_s_p9_2,
  129141. NULL,
  129142. 0
  129143. };
  129144. static long _huff_lengthlist__44c2_s_short[] = {
  129145. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129146. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129147. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129148. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129149. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129150. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129151. 6, 8, 9,12,
  129152. };
  129153. static static_codebook _huff_book__44c2_s_short = {
  129154. 2, 100,
  129155. _huff_lengthlist__44c2_s_short,
  129156. 0, 0, 0, 0, 0,
  129157. NULL,
  129158. NULL,
  129159. NULL,
  129160. NULL,
  129161. 0
  129162. };
  129163. static long _huff_lengthlist__44c3_s_long[] = {
  129164. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129165. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129166. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129167. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129168. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129169. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129170. 9, 8, 8, 8,
  129171. };
  129172. static static_codebook _huff_book__44c3_s_long = {
  129173. 2, 100,
  129174. _huff_lengthlist__44c3_s_long,
  129175. 0, 0, 0, 0, 0,
  129176. NULL,
  129177. NULL,
  129178. NULL,
  129179. NULL,
  129180. 0
  129181. };
  129182. static long _vq_quantlist__44c3_s_p1_0[] = {
  129183. 1,
  129184. 0,
  129185. 2,
  129186. };
  129187. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129188. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129189. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129194. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129199. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129218. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129223. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129234. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129239. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129244. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  129272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129279. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129280. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129285. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129290. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129598. 0,
  129599. };
  129600. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129601. -0.5, 0.5,
  129602. };
  129603. static long _vq_quantmap__44c3_s_p1_0[] = {
  129604. 1, 0, 2,
  129605. };
  129606. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129607. _vq_quantthresh__44c3_s_p1_0,
  129608. _vq_quantmap__44c3_s_p1_0,
  129609. 3,
  129610. 3
  129611. };
  129612. static static_codebook _44c3_s_p1_0 = {
  129613. 8, 6561,
  129614. _vq_lengthlist__44c3_s_p1_0,
  129615. 1, -535822336, 1611661312, 2, 0,
  129616. _vq_quantlist__44c3_s_p1_0,
  129617. NULL,
  129618. &_vq_auxt__44c3_s_p1_0,
  129619. NULL,
  129620. 0
  129621. };
  129622. static long _vq_quantlist__44c3_s_p2_0[] = {
  129623. 2,
  129624. 1,
  129625. 3,
  129626. 0,
  129627. 4,
  129628. };
  129629. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129630. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129631. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129632. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129633. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129634. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129639. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129640. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129641. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129642. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129648. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129649. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129656. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129657. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0,
  129670. };
  129671. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129672. -1.5, -0.5, 0.5, 1.5,
  129673. };
  129674. static long _vq_quantmap__44c3_s_p2_0[] = {
  129675. 3, 1, 0, 2, 4,
  129676. };
  129677. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129678. _vq_quantthresh__44c3_s_p2_0,
  129679. _vq_quantmap__44c3_s_p2_0,
  129680. 5,
  129681. 5
  129682. };
  129683. static static_codebook _44c3_s_p2_0 = {
  129684. 4, 625,
  129685. _vq_lengthlist__44c3_s_p2_0,
  129686. 1, -533725184, 1611661312, 3, 0,
  129687. _vq_quantlist__44c3_s_p2_0,
  129688. NULL,
  129689. &_vq_auxt__44c3_s_p2_0,
  129690. NULL,
  129691. 0
  129692. };
  129693. static long _vq_quantlist__44c3_s_p3_0[] = {
  129694. 2,
  129695. 1,
  129696. 3,
  129697. 0,
  129698. 4,
  129699. };
  129700. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129701. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129707. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0,
  129741. };
  129742. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129743. -1.5, -0.5, 0.5, 1.5,
  129744. };
  129745. static long _vq_quantmap__44c3_s_p3_0[] = {
  129746. 3, 1, 0, 2, 4,
  129747. };
  129748. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129749. _vq_quantthresh__44c3_s_p3_0,
  129750. _vq_quantmap__44c3_s_p3_0,
  129751. 5,
  129752. 5
  129753. };
  129754. static static_codebook _44c3_s_p3_0 = {
  129755. 4, 625,
  129756. _vq_lengthlist__44c3_s_p3_0,
  129757. 1, -533725184, 1611661312, 3, 0,
  129758. _vq_quantlist__44c3_s_p3_0,
  129759. NULL,
  129760. &_vq_auxt__44c3_s_p3_0,
  129761. NULL,
  129762. 0
  129763. };
  129764. static long _vq_quantlist__44c3_s_p4_0[] = {
  129765. 4,
  129766. 3,
  129767. 5,
  129768. 2,
  129769. 6,
  129770. 1,
  129771. 7,
  129772. 0,
  129773. 8,
  129774. };
  129775. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129776. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129777. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129778. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129779. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129780. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0,
  129782. };
  129783. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129784. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129785. };
  129786. static long _vq_quantmap__44c3_s_p4_0[] = {
  129787. 7, 5, 3, 1, 0, 2, 4, 6,
  129788. 8,
  129789. };
  129790. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129791. _vq_quantthresh__44c3_s_p4_0,
  129792. _vq_quantmap__44c3_s_p4_0,
  129793. 9,
  129794. 9
  129795. };
  129796. static static_codebook _44c3_s_p4_0 = {
  129797. 2, 81,
  129798. _vq_lengthlist__44c3_s_p4_0,
  129799. 1, -531628032, 1611661312, 4, 0,
  129800. _vq_quantlist__44c3_s_p4_0,
  129801. NULL,
  129802. &_vq_auxt__44c3_s_p4_0,
  129803. NULL,
  129804. 0
  129805. };
  129806. static long _vq_quantlist__44c3_s_p5_0[] = {
  129807. 4,
  129808. 3,
  129809. 5,
  129810. 2,
  129811. 6,
  129812. 1,
  129813. 7,
  129814. 0,
  129815. 8,
  129816. };
  129817. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129818. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129819. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129820. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129821. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129822. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129823. 11,
  129824. };
  129825. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129826. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129827. };
  129828. static long _vq_quantmap__44c3_s_p5_0[] = {
  129829. 7, 5, 3, 1, 0, 2, 4, 6,
  129830. 8,
  129831. };
  129832. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129833. _vq_quantthresh__44c3_s_p5_0,
  129834. _vq_quantmap__44c3_s_p5_0,
  129835. 9,
  129836. 9
  129837. };
  129838. static static_codebook _44c3_s_p5_0 = {
  129839. 2, 81,
  129840. _vq_lengthlist__44c3_s_p5_0,
  129841. 1, -531628032, 1611661312, 4, 0,
  129842. _vq_quantlist__44c3_s_p5_0,
  129843. NULL,
  129844. &_vq_auxt__44c3_s_p5_0,
  129845. NULL,
  129846. 0
  129847. };
  129848. static long _vq_quantlist__44c3_s_p6_0[] = {
  129849. 8,
  129850. 7,
  129851. 9,
  129852. 6,
  129853. 10,
  129854. 5,
  129855. 11,
  129856. 4,
  129857. 12,
  129858. 3,
  129859. 13,
  129860. 2,
  129861. 14,
  129862. 1,
  129863. 15,
  129864. 0,
  129865. 16,
  129866. };
  129867. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129868. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129869. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129870. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129871. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129872. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129873. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129874. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129875. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129876. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129877. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129878. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129879. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129880. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129881. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129882. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129883. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129884. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129886. 13,
  129887. };
  129888. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129889. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129890. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129891. };
  129892. static long _vq_quantmap__44c3_s_p6_0[] = {
  129893. 15, 13, 11, 9, 7, 5, 3, 1,
  129894. 0, 2, 4, 6, 8, 10, 12, 14,
  129895. 16,
  129896. };
  129897. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129898. _vq_quantthresh__44c3_s_p6_0,
  129899. _vq_quantmap__44c3_s_p6_0,
  129900. 17,
  129901. 17
  129902. };
  129903. static static_codebook _44c3_s_p6_0 = {
  129904. 2, 289,
  129905. _vq_lengthlist__44c3_s_p6_0,
  129906. 1, -529530880, 1611661312, 5, 0,
  129907. _vq_quantlist__44c3_s_p6_0,
  129908. NULL,
  129909. &_vq_auxt__44c3_s_p6_0,
  129910. NULL,
  129911. 0
  129912. };
  129913. static long _vq_quantlist__44c3_s_p7_0[] = {
  129914. 1,
  129915. 0,
  129916. 2,
  129917. };
  129918. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129919. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129920. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129921. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129922. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129923. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129924. 10,
  129925. };
  129926. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129927. -5.5, 5.5,
  129928. };
  129929. static long _vq_quantmap__44c3_s_p7_0[] = {
  129930. 1, 0, 2,
  129931. };
  129932. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129933. _vq_quantthresh__44c3_s_p7_0,
  129934. _vq_quantmap__44c3_s_p7_0,
  129935. 3,
  129936. 3
  129937. };
  129938. static static_codebook _44c3_s_p7_0 = {
  129939. 4, 81,
  129940. _vq_lengthlist__44c3_s_p7_0,
  129941. 1, -529137664, 1618345984, 2, 0,
  129942. _vq_quantlist__44c3_s_p7_0,
  129943. NULL,
  129944. &_vq_auxt__44c3_s_p7_0,
  129945. NULL,
  129946. 0
  129947. };
  129948. static long _vq_quantlist__44c3_s_p7_1[] = {
  129949. 5,
  129950. 4,
  129951. 6,
  129952. 3,
  129953. 7,
  129954. 2,
  129955. 8,
  129956. 1,
  129957. 9,
  129958. 0,
  129959. 10,
  129960. };
  129961. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129962. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129963. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129964. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129965. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129966. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129967. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129968. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129969. 10,10,10, 8, 8, 8, 8, 8, 8,
  129970. };
  129971. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129972. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129973. 3.5, 4.5,
  129974. };
  129975. static long _vq_quantmap__44c3_s_p7_1[] = {
  129976. 9, 7, 5, 3, 1, 0, 2, 4,
  129977. 6, 8, 10,
  129978. };
  129979. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129980. _vq_quantthresh__44c3_s_p7_1,
  129981. _vq_quantmap__44c3_s_p7_1,
  129982. 11,
  129983. 11
  129984. };
  129985. static static_codebook _44c3_s_p7_1 = {
  129986. 2, 121,
  129987. _vq_lengthlist__44c3_s_p7_1,
  129988. 1, -531365888, 1611661312, 4, 0,
  129989. _vq_quantlist__44c3_s_p7_1,
  129990. NULL,
  129991. &_vq_auxt__44c3_s_p7_1,
  129992. NULL,
  129993. 0
  129994. };
  129995. static long _vq_quantlist__44c3_s_p8_0[] = {
  129996. 6,
  129997. 5,
  129998. 7,
  129999. 4,
  130000. 8,
  130001. 3,
  130002. 9,
  130003. 2,
  130004. 10,
  130005. 1,
  130006. 11,
  130007. 0,
  130008. 12,
  130009. };
  130010. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130011. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130012. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130013. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130014. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130015. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130016. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130017. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130018. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130019. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130020. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130021. 0,13,13,12,12,13,12,14,13,
  130022. };
  130023. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130024. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130025. 12.5, 17.5, 22.5, 27.5,
  130026. };
  130027. static long _vq_quantmap__44c3_s_p8_0[] = {
  130028. 11, 9, 7, 5, 3, 1, 0, 2,
  130029. 4, 6, 8, 10, 12,
  130030. };
  130031. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130032. _vq_quantthresh__44c3_s_p8_0,
  130033. _vq_quantmap__44c3_s_p8_0,
  130034. 13,
  130035. 13
  130036. };
  130037. static static_codebook _44c3_s_p8_0 = {
  130038. 2, 169,
  130039. _vq_lengthlist__44c3_s_p8_0,
  130040. 1, -526516224, 1616117760, 4, 0,
  130041. _vq_quantlist__44c3_s_p8_0,
  130042. NULL,
  130043. &_vq_auxt__44c3_s_p8_0,
  130044. NULL,
  130045. 0
  130046. };
  130047. static long _vq_quantlist__44c3_s_p8_1[] = {
  130048. 2,
  130049. 1,
  130050. 3,
  130051. 0,
  130052. 4,
  130053. };
  130054. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130055. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130056. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130057. };
  130058. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130059. -1.5, -0.5, 0.5, 1.5,
  130060. };
  130061. static long _vq_quantmap__44c3_s_p8_1[] = {
  130062. 3, 1, 0, 2, 4,
  130063. };
  130064. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130065. _vq_quantthresh__44c3_s_p8_1,
  130066. _vq_quantmap__44c3_s_p8_1,
  130067. 5,
  130068. 5
  130069. };
  130070. static static_codebook _44c3_s_p8_1 = {
  130071. 2, 25,
  130072. _vq_lengthlist__44c3_s_p8_1,
  130073. 1, -533725184, 1611661312, 3, 0,
  130074. _vq_quantlist__44c3_s_p8_1,
  130075. NULL,
  130076. &_vq_auxt__44c3_s_p8_1,
  130077. NULL,
  130078. 0
  130079. };
  130080. static long _vq_quantlist__44c3_s_p9_0[] = {
  130081. 6,
  130082. 5,
  130083. 7,
  130084. 4,
  130085. 8,
  130086. 3,
  130087. 9,
  130088. 2,
  130089. 10,
  130090. 1,
  130091. 11,
  130092. 0,
  130093. 12,
  130094. };
  130095. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130096. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130097. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130098. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130099. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130100. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130101. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130102. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130103. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130104. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130105. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130106. 11,11,11,11,11,11,11,11,11,
  130107. };
  130108. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130109. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130110. 637.5, 892.5, 1147.5, 1402.5,
  130111. };
  130112. static long _vq_quantmap__44c3_s_p9_0[] = {
  130113. 11, 9, 7, 5, 3, 1, 0, 2,
  130114. 4, 6, 8, 10, 12,
  130115. };
  130116. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130117. _vq_quantthresh__44c3_s_p9_0,
  130118. _vq_quantmap__44c3_s_p9_0,
  130119. 13,
  130120. 13
  130121. };
  130122. static static_codebook _44c3_s_p9_0 = {
  130123. 2, 169,
  130124. _vq_lengthlist__44c3_s_p9_0,
  130125. 1, -514332672, 1627381760, 4, 0,
  130126. _vq_quantlist__44c3_s_p9_0,
  130127. NULL,
  130128. &_vq_auxt__44c3_s_p9_0,
  130129. NULL,
  130130. 0
  130131. };
  130132. static long _vq_quantlist__44c3_s_p9_1[] = {
  130133. 7,
  130134. 6,
  130135. 8,
  130136. 5,
  130137. 9,
  130138. 4,
  130139. 10,
  130140. 3,
  130141. 11,
  130142. 2,
  130143. 12,
  130144. 1,
  130145. 13,
  130146. 0,
  130147. 14,
  130148. };
  130149. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130150. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130151. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130152. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130153. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130154. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130155. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130156. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130157. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130158. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130159. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130160. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130161. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130162. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130163. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130164. 15,
  130165. };
  130166. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130167. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130168. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130169. };
  130170. static long _vq_quantmap__44c3_s_p9_1[] = {
  130171. 13, 11, 9, 7, 5, 3, 1, 0,
  130172. 2, 4, 6, 8, 10, 12, 14,
  130173. };
  130174. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130175. _vq_quantthresh__44c3_s_p9_1,
  130176. _vq_quantmap__44c3_s_p9_1,
  130177. 15,
  130178. 15
  130179. };
  130180. static static_codebook _44c3_s_p9_1 = {
  130181. 2, 225,
  130182. _vq_lengthlist__44c3_s_p9_1,
  130183. 1, -522338304, 1620115456, 4, 0,
  130184. _vq_quantlist__44c3_s_p9_1,
  130185. NULL,
  130186. &_vq_auxt__44c3_s_p9_1,
  130187. NULL,
  130188. 0
  130189. };
  130190. static long _vq_quantlist__44c3_s_p9_2[] = {
  130191. 8,
  130192. 7,
  130193. 9,
  130194. 6,
  130195. 10,
  130196. 5,
  130197. 11,
  130198. 4,
  130199. 12,
  130200. 3,
  130201. 13,
  130202. 2,
  130203. 14,
  130204. 1,
  130205. 15,
  130206. 0,
  130207. 16,
  130208. };
  130209. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130210. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130211. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130212. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130213. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130214. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130215. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130216. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130217. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130218. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130219. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130220. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130221. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130222. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130223. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130224. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130225. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130226. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130227. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130228. 10,
  130229. };
  130230. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130231. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130232. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130233. };
  130234. static long _vq_quantmap__44c3_s_p9_2[] = {
  130235. 15, 13, 11, 9, 7, 5, 3, 1,
  130236. 0, 2, 4, 6, 8, 10, 12, 14,
  130237. 16,
  130238. };
  130239. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130240. _vq_quantthresh__44c3_s_p9_2,
  130241. _vq_quantmap__44c3_s_p9_2,
  130242. 17,
  130243. 17
  130244. };
  130245. static static_codebook _44c3_s_p9_2 = {
  130246. 2, 289,
  130247. _vq_lengthlist__44c3_s_p9_2,
  130248. 1, -529530880, 1611661312, 5, 0,
  130249. _vq_quantlist__44c3_s_p9_2,
  130250. NULL,
  130251. &_vq_auxt__44c3_s_p9_2,
  130252. NULL,
  130253. 0
  130254. };
  130255. static long _huff_lengthlist__44c3_s_short[] = {
  130256. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130257. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130258. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130259. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130260. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130261. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130262. 6, 8, 9,11,
  130263. };
  130264. static static_codebook _huff_book__44c3_s_short = {
  130265. 2, 100,
  130266. _huff_lengthlist__44c3_s_short,
  130267. 0, 0, 0, 0, 0,
  130268. NULL,
  130269. NULL,
  130270. NULL,
  130271. NULL,
  130272. 0
  130273. };
  130274. static long _huff_lengthlist__44c4_s_long[] = {
  130275. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130276. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130277. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130278. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130279. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130280. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130281. 9, 8, 7, 7,
  130282. };
  130283. static static_codebook _huff_book__44c4_s_long = {
  130284. 2, 100,
  130285. _huff_lengthlist__44c4_s_long,
  130286. 0, 0, 0, 0, 0,
  130287. NULL,
  130288. NULL,
  130289. NULL,
  130290. NULL,
  130291. 0
  130292. };
  130293. static long _vq_quantlist__44c4_s_p1_0[] = {
  130294. 1,
  130295. 0,
  130296. 2,
  130297. };
  130298. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130299. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130300. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130305. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130310. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130345. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130350. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130355. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  130387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130391. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130396. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130401. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130434. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130439. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130709. 0,
  130710. };
  130711. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130712. -0.5, 0.5,
  130713. };
  130714. static long _vq_quantmap__44c4_s_p1_0[] = {
  130715. 1, 0, 2,
  130716. };
  130717. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130718. _vq_quantthresh__44c4_s_p1_0,
  130719. _vq_quantmap__44c4_s_p1_0,
  130720. 3,
  130721. 3
  130722. };
  130723. static static_codebook _44c4_s_p1_0 = {
  130724. 8, 6561,
  130725. _vq_lengthlist__44c4_s_p1_0,
  130726. 1, -535822336, 1611661312, 2, 0,
  130727. _vq_quantlist__44c4_s_p1_0,
  130728. NULL,
  130729. &_vq_auxt__44c4_s_p1_0,
  130730. NULL,
  130731. 0
  130732. };
  130733. static long _vq_quantlist__44c4_s_p2_0[] = {
  130734. 2,
  130735. 1,
  130736. 3,
  130737. 0,
  130738. 4,
  130739. };
  130740. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130741. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130742. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130743. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130744. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130745. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130751. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130752. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130753. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130758. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130759. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130760. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130766. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130767. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130768. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0,
  130781. };
  130782. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130783. -1.5, -0.5, 0.5, 1.5,
  130784. };
  130785. static long _vq_quantmap__44c4_s_p2_0[] = {
  130786. 3, 1, 0, 2, 4,
  130787. };
  130788. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130789. _vq_quantthresh__44c4_s_p2_0,
  130790. _vq_quantmap__44c4_s_p2_0,
  130791. 5,
  130792. 5
  130793. };
  130794. static static_codebook _44c4_s_p2_0 = {
  130795. 4, 625,
  130796. _vq_lengthlist__44c4_s_p2_0,
  130797. 1, -533725184, 1611661312, 3, 0,
  130798. _vq_quantlist__44c4_s_p2_0,
  130799. NULL,
  130800. &_vq_auxt__44c4_s_p2_0,
  130801. NULL,
  130802. 0
  130803. };
  130804. static long _vq_quantlist__44c4_s_p3_0[] = {
  130805. 2,
  130806. 1,
  130807. 3,
  130808. 0,
  130809. 4,
  130810. };
  130811. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130812. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130818. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0,
  130852. };
  130853. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130854. -1.5, -0.5, 0.5, 1.5,
  130855. };
  130856. static long _vq_quantmap__44c4_s_p3_0[] = {
  130857. 3, 1, 0, 2, 4,
  130858. };
  130859. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130860. _vq_quantthresh__44c4_s_p3_0,
  130861. _vq_quantmap__44c4_s_p3_0,
  130862. 5,
  130863. 5
  130864. };
  130865. static static_codebook _44c4_s_p3_0 = {
  130866. 4, 625,
  130867. _vq_lengthlist__44c4_s_p3_0,
  130868. 1, -533725184, 1611661312, 3, 0,
  130869. _vq_quantlist__44c4_s_p3_0,
  130870. NULL,
  130871. &_vq_auxt__44c4_s_p3_0,
  130872. NULL,
  130873. 0
  130874. };
  130875. static long _vq_quantlist__44c4_s_p4_0[] = {
  130876. 4,
  130877. 3,
  130878. 5,
  130879. 2,
  130880. 6,
  130881. 1,
  130882. 7,
  130883. 0,
  130884. 8,
  130885. };
  130886. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130887. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130888. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130889. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130890. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130891. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0,
  130893. };
  130894. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130895. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130896. };
  130897. static long _vq_quantmap__44c4_s_p4_0[] = {
  130898. 7, 5, 3, 1, 0, 2, 4, 6,
  130899. 8,
  130900. };
  130901. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130902. _vq_quantthresh__44c4_s_p4_0,
  130903. _vq_quantmap__44c4_s_p4_0,
  130904. 9,
  130905. 9
  130906. };
  130907. static static_codebook _44c4_s_p4_0 = {
  130908. 2, 81,
  130909. _vq_lengthlist__44c4_s_p4_0,
  130910. 1, -531628032, 1611661312, 4, 0,
  130911. _vq_quantlist__44c4_s_p4_0,
  130912. NULL,
  130913. &_vq_auxt__44c4_s_p4_0,
  130914. NULL,
  130915. 0
  130916. };
  130917. static long _vq_quantlist__44c4_s_p5_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__44c4_s_p5_0[] = {
  130929. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130930. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130931. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130932. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130933. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130934. 10,
  130935. };
  130936. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130937. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130938. };
  130939. static long _vq_quantmap__44c4_s_p5_0[] = {
  130940. 7, 5, 3, 1, 0, 2, 4, 6,
  130941. 8,
  130942. };
  130943. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130944. _vq_quantthresh__44c4_s_p5_0,
  130945. _vq_quantmap__44c4_s_p5_0,
  130946. 9,
  130947. 9
  130948. };
  130949. static static_codebook _44c4_s_p5_0 = {
  130950. 2, 81,
  130951. _vq_lengthlist__44c4_s_p5_0,
  130952. 1, -531628032, 1611661312, 4, 0,
  130953. _vq_quantlist__44c4_s_p5_0,
  130954. NULL,
  130955. &_vq_auxt__44c4_s_p5_0,
  130956. NULL,
  130957. 0
  130958. };
  130959. static long _vq_quantlist__44c4_s_p6_0[] = {
  130960. 8,
  130961. 7,
  130962. 9,
  130963. 6,
  130964. 10,
  130965. 5,
  130966. 11,
  130967. 4,
  130968. 12,
  130969. 3,
  130970. 13,
  130971. 2,
  130972. 14,
  130973. 1,
  130974. 15,
  130975. 0,
  130976. 16,
  130977. };
  130978. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130979. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130980. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130981. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130982. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130983. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130984. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130985. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130986. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130987. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130988. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130989. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130990. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130991. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130992. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130993. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130994. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130995. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130997. 13,
  130998. };
  130999. static float _vq_quantthresh__44c4_s_p6_0[] = {
  131000. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131001. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131002. };
  131003. static long _vq_quantmap__44c4_s_p6_0[] = {
  131004. 15, 13, 11, 9, 7, 5, 3, 1,
  131005. 0, 2, 4, 6, 8, 10, 12, 14,
  131006. 16,
  131007. };
  131008. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131009. _vq_quantthresh__44c4_s_p6_0,
  131010. _vq_quantmap__44c4_s_p6_0,
  131011. 17,
  131012. 17
  131013. };
  131014. static static_codebook _44c4_s_p6_0 = {
  131015. 2, 289,
  131016. _vq_lengthlist__44c4_s_p6_0,
  131017. 1, -529530880, 1611661312, 5, 0,
  131018. _vq_quantlist__44c4_s_p6_0,
  131019. NULL,
  131020. &_vq_auxt__44c4_s_p6_0,
  131021. NULL,
  131022. 0
  131023. };
  131024. static long _vq_quantlist__44c4_s_p7_0[] = {
  131025. 1,
  131026. 0,
  131027. 2,
  131028. };
  131029. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131030. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131031. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131032. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131033. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131034. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131035. 10,
  131036. };
  131037. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131038. -5.5, 5.5,
  131039. };
  131040. static long _vq_quantmap__44c4_s_p7_0[] = {
  131041. 1, 0, 2,
  131042. };
  131043. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131044. _vq_quantthresh__44c4_s_p7_0,
  131045. _vq_quantmap__44c4_s_p7_0,
  131046. 3,
  131047. 3
  131048. };
  131049. static static_codebook _44c4_s_p7_0 = {
  131050. 4, 81,
  131051. _vq_lengthlist__44c4_s_p7_0,
  131052. 1, -529137664, 1618345984, 2, 0,
  131053. _vq_quantlist__44c4_s_p7_0,
  131054. NULL,
  131055. &_vq_auxt__44c4_s_p7_0,
  131056. NULL,
  131057. 0
  131058. };
  131059. static long _vq_quantlist__44c4_s_p7_1[] = {
  131060. 5,
  131061. 4,
  131062. 6,
  131063. 3,
  131064. 7,
  131065. 2,
  131066. 8,
  131067. 1,
  131068. 9,
  131069. 0,
  131070. 10,
  131071. };
  131072. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131073. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131074. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131075. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131076. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131077. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131078. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131079. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131080. 10,10,10, 8, 8, 8, 8, 9, 9,
  131081. };
  131082. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131083. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131084. 3.5, 4.5,
  131085. };
  131086. static long _vq_quantmap__44c4_s_p7_1[] = {
  131087. 9, 7, 5, 3, 1, 0, 2, 4,
  131088. 6, 8, 10,
  131089. };
  131090. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131091. _vq_quantthresh__44c4_s_p7_1,
  131092. _vq_quantmap__44c4_s_p7_1,
  131093. 11,
  131094. 11
  131095. };
  131096. static static_codebook _44c4_s_p7_1 = {
  131097. 2, 121,
  131098. _vq_lengthlist__44c4_s_p7_1,
  131099. 1, -531365888, 1611661312, 4, 0,
  131100. _vq_quantlist__44c4_s_p7_1,
  131101. NULL,
  131102. &_vq_auxt__44c4_s_p7_1,
  131103. NULL,
  131104. 0
  131105. };
  131106. static long _vq_quantlist__44c4_s_p8_0[] = {
  131107. 6,
  131108. 5,
  131109. 7,
  131110. 4,
  131111. 8,
  131112. 3,
  131113. 9,
  131114. 2,
  131115. 10,
  131116. 1,
  131117. 11,
  131118. 0,
  131119. 12,
  131120. };
  131121. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131122. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131123. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131124. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131125. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131126. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131127. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131128. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131129. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131130. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131131. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131132. 0,13,12,12,12,12,12,13,13,
  131133. };
  131134. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131135. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131136. 12.5, 17.5, 22.5, 27.5,
  131137. };
  131138. static long _vq_quantmap__44c4_s_p8_0[] = {
  131139. 11, 9, 7, 5, 3, 1, 0, 2,
  131140. 4, 6, 8, 10, 12,
  131141. };
  131142. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131143. _vq_quantthresh__44c4_s_p8_0,
  131144. _vq_quantmap__44c4_s_p8_0,
  131145. 13,
  131146. 13
  131147. };
  131148. static static_codebook _44c4_s_p8_0 = {
  131149. 2, 169,
  131150. _vq_lengthlist__44c4_s_p8_0,
  131151. 1, -526516224, 1616117760, 4, 0,
  131152. _vq_quantlist__44c4_s_p8_0,
  131153. NULL,
  131154. &_vq_auxt__44c4_s_p8_0,
  131155. NULL,
  131156. 0
  131157. };
  131158. static long _vq_quantlist__44c4_s_p8_1[] = {
  131159. 2,
  131160. 1,
  131161. 3,
  131162. 0,
  131163. 4,
  131164. };
  131165. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131166. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131167. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131168. };
  131169. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131170. -1.5, -0.5, 0.5, 1.5,
  131171. };
  131172. static long _vq_quantmap__44c4_s_p8_1[] = {
  131173. 3, 1, 0, 2, 4,
  131174. };
  131175. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131176. _vq_quantthresh__44c4_s_p8_1,
  131177. _vq_quantmap__44c4_s_p8_1,
  131178. 5,
  131179. 5
  131180. };
  131181. static static_codebook _44c4_s_p8_1 = {
  131182. 2, 25,
  131183. _vq_lengthlist__44c4_s_p8_1,
  131184. 1, -533725184, 1611661312, 3, 0,
  131185. _vq_quantlist__44c4_s_p8_1,
  131186. NULL,
  131187. &_vq_auxt__44c4_s_p8_1,
  131188. NULL,
  131189. 0
  131190. };
  131191. static long _vq_quantlist__44c4_s_p9_0[] = {
  131192. 6,
  131193. 5,
  131194. 7,
  131195. 4,
  131196. 8,
  131197. 3,
  131198. 9,
  131199. 2,
  131200. 10,
  131201. 1,
  131202. 11,
  131203. 0,
  131204. 12,
  131205. };
  131206. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131207. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131208. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131209. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131210. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131211. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131212. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131213. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131214. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131215. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131216. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131217. 12,12,12,12,12,12,12,12,12,
  131218. };
  131219. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131220. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131221. 787.5, 1102.5, 1417.5, 1732.5,
  131222. };
  131223. static long _vq_quantmap__44c4_s_p9_0[] = {
  131224. 11, 9, 7, 5, 3, 1, 0, 2,
  131225. 4, 6, 8, 10, 12,
  131226. };
  131227. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131228. _vq_quantthresh__44c4_s_p9_0,
  131229. _vq_quantmap__44c4_s_p9_0,
  131230. 13,
  131231. 13
  131232. };
  131233. static static_codebook _44c4_s_p9_0 = {
  131234. 2, 169,
  131235. _vq_lengthlist__44c4_s_p9_0,
  131236. 1, -513964032, 1628680192, 4, 0,
  131237. _vq_quantlist__44c4_s_p9_0,
  131238. NULL,
  131239. &_vq_auxt__44c4_s_p9_0,
  131240. NULL,
  131241. 0
  131242. };
  131243. static long _vq_quantlist__44c4_s_p9_1[] = {
  131244. 7,
  131245. 6,
  131246. 8,
  131247. 5,
  131248. 9,
  131249. 4,
  131250. 10,
  131251. 3,
  131252. 11,
  131253. 2,
  131254. 12,
  131255. 1,
  131256. 13,
  131257. 0,
  131258. 14,
  131259. };
  131260. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131261. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131262. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131263. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131264. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131265. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131266. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131267. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131268. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131269. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131270. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131271. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131272. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131273. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131274. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131275. 15,
  131276. };
  131277. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131278. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131279. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131280. };
  131281. static long _vq_quantmap__44c4_s_p9_1[] = {
  131282. 13, 11, 9, 7, 5, 3, 1, 0,
  131283. 2, 4, 6, 8, 10, 12, 14,
  131284. };
  131285. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131286. _vq_quantthresh__44c4_s_p9_1,
  131287. _vq_quantmap__44c4_s_p9_1,
  131288. 15,
  131289. 15
  131290. };
  131291. static static_codebook _44c4_s_p9_1 = {
  131292. 2, 225,
  131293. _vq_lengthlist__44c4_s_p9_1,
  131294. 1, -520986624, 1620377600, 4, 0,
  131295. _vq_quantlist__44c4_s_p9_1,
  131296. NULL,
  131297. &_vq_auxt__44c4_s_p9_1,
  131298. NULL,
  131299. 0
  131300. };
  131301. static long _vq_quantlist__44c4_s_p9_2[] = {
  131302. 10,
  131303. 9,
  131304. 11,
  131305. 8,
  131306. 12,
  131307. 7,
  131308. 13,
  131309. 6,
  131310. 14,
  131311. 5,
  131312. 15,
  131313. 4,
  131314. 16,
  131315. 3,
  131316. 17,
  131317. 2,
  131318. 18,
  131319. 1,
  131320. 19,
  131321. 0,
  131322. 20,
  131323. };
  131324. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131325. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131326. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131327. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131328. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131329. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131330. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131331. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131332. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131333. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131334. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131335. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131336. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131337. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131338. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131339. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131340. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131341. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131342. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131343. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131344. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131345. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131346. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131347. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131348. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131349. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131350. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131351. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131352. 10,10,10,10,10,10,10,10,10,
  131353. };
  131354. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131355. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131356. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131357. 6.5, 7.5, 8.5, 9.5,
  131358. };
  131359. static long _vq_quantmap__44c4_s_p9_2[] = {
  131360. 19, 17, 15, 13, 11, 9, 7, 5,
  131361. 3, 1, 0, 2, 4, 6, 8, 10,
  131362. 12, 14, 16, 18, 20,
  131363. };
  131364. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131365. _vq_quantthresh__44c4_s_p9_2,
  131366. _vq_quantmap__44c4_s_p9_2,
  131367. 21,
  131368. 21
  131369. };
  131370. static static_codebook _44c4_s_p9_2 = {
  131371. 2, 441,
  131372. _vq_lengthlist__44c4_s_p9_2,
  131373. 1, -529268736, 1611661312, 5, 0,
  131374. _vq_quantlist__44c4_s_p9_2,
  131375. NULL,
  131376. &_vq_auxt__44c4_s_p9_2,
  131377. NULL,
  131378. 0
  131379. };
  131380. static long _huff_lengthlist__44c4_s_short[] = {
  131381. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131382. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131383. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131384. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131385. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131386. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131387. 7, 9,12,17,
  131388. };
  131389. static static_codebook _huff_book__44c4_s_short = {
  131390. 2, 100,
  131391. _huff_lengthlist__44c4_s_short,
  131392. 0, 0, 0, 0, 0,
  131393. NULL,
  131394. NULL,
  131395. NULL,
  131396. NULL,
  131397. 0
  131398. };
  131399. static long _huff_lengthlist__44c5_s_long[] = {
  131400. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131401. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131402. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131403. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131404. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131405. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131406. 9, 8, 7, 7,
  131407. };
  131408. static static_codebook _huff_book__44c5_s_long = {
  131409. 2, 100,
  131410. _huff_lengthlist__44c5_s_long,
  131411. 0, 0, 0, 0, 0,
  131412. NULL,
  131413. NULL,
  131414. NULL,
  131415. NULL,
  131416. 0
  131417. };
  131418. static long _vq_quantlist__44c5_s_p1_0[] = {
  131419. 1,
  131420. 0,
  131421. 2,
  131422. };
  131423. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131424. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131425. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131430. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131435. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131470. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131475. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131480. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131515. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131516. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131521. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131526. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0,
  131552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0,
  131835. };
  131836. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131837. -0.5, 0.5,
  131838. };
  131839. static long _vq_quantmap__44c5_s_p1_0[] = {
  131840. 1, 0, 2,
  131841. };
  131842. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131843. _vq_quantthresh__44c5_s_p1_0,
  131844. _vq_quantmap__44c5_s_p1_0,
  131845. 3,
  131846. 3
  131847. };
  131848. static static_codebook _44c5_s_p1_0 = {
  131849. 8, 6561,
  131850. _vq_lengthlist__44c5_s_p1_0,
  131851. 1, -535822336, 1611661312, 2, 0,
  131852. _vq_quantlist__44c5_s_p1_0,
  131853. NULL,
  131854. &_vq_auxt__44c5_s_p1_0,
  131855. NULL,
  131856. 0
  131857. };
  131858. static long _vq_quantlist__44c5_s_p2_0[] = {
  131859. 2,
  131860. 1,
  131861. 3,
  131862. 0,
  131863. 4,
  131864. };
  131865. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131866. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131867. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131868. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131869. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131870. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131875. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131876. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131877. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131878. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131883. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131884. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131885. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131891. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131892. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131893. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0,
  131906. };
  131907. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131908. -1.5, -0.5, 0.5, 1.5,
  131909. };
  131910. static long _vq_quantmap__44c5_s_p2_0[] = {
  131911. 3, 1, 0, 2, 4,
  131912. };
  131913. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131914. _vq_quantthresh__44c5_s_p2_0,
  131915. _vq_quantmap__44c5_s_p2_0,
  131916. 5,
  131917. 5
  131918. };
  131919. static static_codebook _44c5_s_p2_0 = {
  131920. 4, 625,
  131921. _vq_lengthlist__44c5_s_p2_0,
  131922. 1, -533725184, 1611661312, 3, 0,
  131923. _vq_quantlist__44c5_s_p2_0,
  131924. NULL,
  131925. &_vq_auxt__44c5_s_p2_0,
  131926. NULL,
  131927. 0
  131928. };
  131929. static long _vq_quantlist__44c5_s_p3_0[] = {
  131930. 2,
  131931. 1,
  131932. 3,
  131933. 0,
  131934. 4,
  131935. };
  131936. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131937. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131943. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0,
  131977. };
  131978. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131979. -1.5, -0.5, 0.5, 1.5,
  131980. };
  131981. static long _vq_quantmap__44c5_s_p3_0[] = {
  131982. 3, 1, 0, 2, 4,
  131983. };
  131984. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131985. _vq_quantthresh__44c5_s_p3_0,
  131986. _vq_quantmap__44c5_s_p3_0,
  131987. 5,
  131988. 5
  131989. };
  131990. static static_codebook _44c5_s_p3_0 = {
  131991. 4, 625,
  131992. _vq_lengthlist__44c5_s_p3_0,
  131993. 1, -533725184, 1611661312, 3, 0,
  131994. _vq_quantlist__44c5_s_p3_0,
  131995. NULL,
  131996. &_vq_auxt__44c5_s_p3_0,
  131997. NULL,
  131998. 0
  131999. };
  132000. static long _vq_quantlist__44c5_s_p4_0[] = {
  132001. 4,
  132002. 3,
  132003. 5,
  132004. 2,
  132005. 6,
  132006. 1,
  132007. 7,
  132008. 0,
  132009. 8,
  132010. };
  132011. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132012. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132013. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132014. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132015. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132016. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132017. 0,
  132018. };
  132019. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132020. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132021. };
  132022. static long _vq_quantmap__44c5_s_p4_0[] = {
  132023. 7, 5, 3, 1, 0, 2, 4, 6,
  132024. 8,
  132025. };
  132026. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132027. _vq_quantthresh__44c5_s_p4_0,
  132028. _vq_quantmap__44c5_s_p4_0,
  132029. 9,
  132030. 9
  132031. };
  132032. static static_codebook _44c5_s_p4_0 = {
  132033. 2, 81,
  132034. _vq_lengthlist__44c5_s_p4_0,
  132035. 1, -531628032, 1611661312, 4, 0,
  132036. _vq_quantlist__44c5_s_p4_0,
  132037. NULL,
  132038. &_vq_auxt__44c5_s_p4_0,
  132039. NULL,
  132040. 0
  132041. };
  132042. static long _vq_quantlist__44c5_s_p5_0[] = {
  132043. 4,
  132044. 3,
  132045. 5,
  132046. 2,
  132047. 6,
  132048. 1,
  132049. 7,
  132050. 0,
  132051. 8,
  132052. };
  132053. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132054. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132055. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132056. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132057. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132058. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132059. 10,
  132060. };
  132061. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132062. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132063. };
  132064. static long _vq_quantmap__44c5_s_p5_0[] = {
  132065. 7, 5, 3, 1, 0, 2, 4, 6,
  132066. 8,
  132067. };
  132068. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132069. _vq_quantthresh__44c5_s_p5_0,
  132070. _vq_quantmap__44c5_s_p5_0,
  132071. 9,
  132072. 9
  132073. };
  132074. static static_codebook _44c5_s_p5_0 = {
  132075. 2, 81,
  132076. _vq_lengthlist__44c5_s_p5_0,
  132077. 1, -531628032, 1611661312, 4, 0,
  132078. _vq_quantlist__44c5_s_p5_0,
  132079. NULL,
  132080. &_vq_auxt__44c5_s_p5_0,
  132081. NULL,
  132082. 0
  132083. };
  132084. static long _vq_quantlist__44c5_s_p6_0[] = {
  132085. 8,
  132086. 7,
  132087. 9,
  132088. 6,
  132089. 10,
  132090. 5,
  132091. 11,
  132092. 4,
  132093. 12,
  132094. 3,
  132095. 13,
  132096. 2,
  132097. 14,
  132098. 1,
  132099. 15,
  132100. 0,
  132101. 16,
  132102. };
  132103. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132104. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132105. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132106. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132107. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132108. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132109. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132110. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132111. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132112. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132113. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132114. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132115. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132116. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132117. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132118. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132119. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132120. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132122. 13,
  132123. };
  132124. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132125. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132126. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132127. };
  132128. static long _vq_quantmap__44c5_s_p6_0[] = {
  132129. 15, 13, 11, 9, 7, 5, 3, 1,
  132130. 0, 2, 4, 6, 8, 10, 12, 14,
  132131. 16,
  132132. };
  132133. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132134. _vq_quantthresh__44c5_s_p6_0,
  132135. _vq_quantmap__44c5_s_p6_0,
  132136. 17,
  132137. 17
  132138. };
  132139. static static_codebook _44c5_s_p6_0 = {
  132140. 2, 289,
  132141. _vq_lengthlist__44c5_s_p6_0,
  132142. 1, -529530880, 1611661312, 5, 0,
  132143. _vq_quantlist__44c5_s_p6_0,
  132144. NULL,
  132145. &_vq_auxt__44c5_s_p6_0,
  132146. NULL,
  132147. 0
  132148. };
  132149. static long _vq_quantlist__44c5_s_p7_0[] = {
  132150. 1,
  132151. 0,
  132152. 2,
  132153. };
  132154. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132155. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132156. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132157. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132158. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132159. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132160. 10,
  132161. };
  132162. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132163. -5.5, 5.5,
  132164. };
  132165. static long _vq_quantmap__44c5_s_p7_0[] = {
  132166. 1, 0, 2,
  132167. };
  132168. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132169. _vq_quantthresh__44c5_s_p7_0,
  132170. _vq_quantmap__44c5_s_p7_0,
  132171. 3,
  132172. 3
  132173. };
  132174. static static_codebook _44c5_s_p7_0 = {
  132175. 4, 81,
  132176. _vq_lengthlist__44c5_s_p7_0,
  132177. 1, -529137664, 1618345984, 2, 0,
  132178. _vq_quantlist__44c5_s_p7_0,
  132179. NULL,
  132180. &_vq_auxt__44c5_s_p7_0,
  132181. NULL,
  132182. 0
  132183. };
  132184. static long _vq_quantlist__44c5_s_p7_1[] = {
  132185. 5,
  132186. 4,
  132187. 6,
  132188. 3,
  132189. 7,
  132190. 2,
  132191. 8,
  132192. 1,
  132193. 9,
  132194. 0,
  132195. 10,
  132196. };
  132197. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132198. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132199. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132200. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132201. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132202. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132203. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132204. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132205. 10,10,10, 8, 8, 8, 8, 8, 8,
  132206. };
  132207. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132208. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132209. 3.5, 4.5,
  132210. };
  132211. static long _vq_quantmap__44c5_s_p7_1[] = {
  132212. 9, 7, 5, 3, 1, 0, 2, 4,
  132213. 6, 8, 10,
  132214. };
  132215. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132216. _vq_quantthresh__44c5_s_p7_1,
  132217. _vq_quantmap__44c5_s_p7_1,
  132218. 11,
  132219. 11
  132220. };
  132221. static static_codebook _44c5_s_p7_1 = {
  132222. 2, 121,
  132223. _vq_lengthlist__44c5_s_p7_1,
  132224. 1, -531365888, 1611661312, 4, 0,
  132225. _vq_quantlist__44c5_s_p7_1,
  132226. NULL,
  132227. &_vq_auxt__44c5_s_p7_1,
  132228. NULL,
  132229. 0
  132230. };
  132231. static long _vq_quantlist__44c5_s_p8_0[] = {
  132232. 6,
  132233. 5,
  132234. 7,
  132235. 4,
  132236. 8,
  132237. 3,
  132238. 9,
  132239. 2,
  132240. 10,
  132241. 1,
  132242. 11,
  132243. 0,
  132244. 12,
  132245. };
  132246. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132247. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132248. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132249. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132250. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132251. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132252. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132253. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132254. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132255. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132256. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132257. 0,12,12,12,12,12,12,13,13,
  132258. };
  132259. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132260. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132261. 12.5, 17.5, 22.5, 27.5,
  132262. };
  132263. static long _vq_quantmap__44c5_s_p8_0[] = {
  132264. 11, 9, 7, 5, 3, 1, 0, 2,
  132265. 4, 6, 8, 10, 12,
  132266. };
  132267. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132268. _vq_quantthresh__44c5_s_p8_0,
  132269. _vq_quantmap__44c5_s_p8_0,
  132270. 13,
  132271. 13
  132272. };
  132273. static static_codebook _44c5_s_p8_0 = {
  132274. 2, 169,
  132275. _vq_lengthlist__44c5_s_p8_0,
  132276. 1, -526516224, 1616117760, 4, 0,
  132277. _vq_quantlist__44c5_s_p8_0,
  132278. NULL,
  132279. &_vq_auxt__44c5_s_p8_0,
  132280. NULL,
  132281. 0
  132282. };
  132283. static long _vq_quantlist__44c5_s_p8_1[] = {
  132284. 2,
  132285. 1,
  132286. 3,
  132287. 0,
  132288. 4,
  132289. };
  132290. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132291. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132292. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132293. };
  132294. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132295. -1.5, -0.5, 0.5, 1.5,
  132296. };
  132297. static long _vq_quantmap__44c5_s_p8_1[] = {
  132298. 3, 1, 0, 2, 4,
  132299. };
  132300. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132301. _vq_quantthresh__44c5_s_p8_1,
  132302. _vq_quantmap__44c5_s_p8_1,
  132303. 5,
  132304. 5
  132305. };
  132306. static static_codebook _44c5_s_p8_1 = {
  132307. 2, 25,
  132308. _vq_lengthlist__44c5_s_p8_1,
  132309. 1, -533725184, 1611661312, 3, 0,
  132310. _vq_quantlist__44c5_s_p8_1,
  132311. NULL,
  132312. &_vq_auxt__44c5_s_p8_1,
  132313. NULL,
  132314. 0
  132315. };
  132316. static long _vq_quantlist__44c5_s_p9_0[] = {
  132317. 7,
  132318. 6,
  132319. 8,
  132320. 5,
  132321. 9,
  132322. 4,
  132323. 10,
  132324. 3,
  132325. 11,
  132326. 2,
  132327. 12,
  132328. 1,
  132329. 13,
  132330. 0,
  132331. 14,
  132332. };
  132333. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132334. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132335. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132336. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132337. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132338. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132339. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132340. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132341. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132342. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132343. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132344. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132345. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132346. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132347. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132348. 12,
  132349. };
  132350. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132351. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132352. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132353. };
  132354. static long _vq_quantmap__44c5_s_p9_0[] = {
  132355. 13, 11, 9, 7, 5, 3, 1, 0,
  132356. 2, 4, 6, 8, 10, 12, 14,
  132357. };
  132358. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132359. _vq_quantthresh__44c5_s_p9_0,
  132360. _vq_quantmap__44c5_s_p9_0,
  132361. 15,
  132362. 15
  132363. };
  132364. static static_codebook _44c5_s_p9_0 = {
  132365. 2, 225,
  132366. _vq_lengthlist__44c5_s_p9_0,
  132367. 1, -512522752, 1628852224, 4, 0,
  132368. _vq_quantlist__44c5_s_p9_0,
  132369. NULL,
  132370. &_vq_auxt__44c5_s_p9_0,
  132371. NULL,
  132372. 0
  132373. };
  132374. static long _vq_quantlist__44c5_s_p9_1[] = {
  132375. 8,
  132376. 7,
  132377. 9,
  132378. 6,
  132379. 10,
  132380. 5,
  132381. 11,
  132382. 4,
  132383. 12,
  132384. 3,
  132385. 13,
  132386. 2,
  132387. 14,
  132388. 1,
  132389. 15,
  132390. 0,
  132391. 16,
  132392. };
  132393. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132394. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132395. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132396. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132397. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132398. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132399. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132400. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132401. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132402. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132403. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132404. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132405. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132406. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132407. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132408. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132409. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132410. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132411. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132412. 15,
  132413. };
  132414. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132415. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132416. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132417. };
  132418. static long _vq_quantmap__44c5_s_p9_1[] = {
  132419. 15, 13, 11, 9, 7, 5, 3, 1,
  132420. 0, 2, 4, 6, 8, 10, 12, 14,
  132421. 16,
  132422. };
  132423. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132424. _vq_quantthresh__44c5_s_p9_1,
  132425. _vq_quantmap__44c5_s_p9_1,
  132426. 17,
  132427. 17
  132428. };
  132429. static static_codebook _44c5_s_p9_1 = {
  132430. 2, 289,
  132431. _vq_lengthlist__44c5_s_p9_1,
  132432. 1, -520814592, 1620377600, 5, 0,
  132433. _vq_quantlist__44c5_s_p9_1,
  132434. NULL,
  132435. &_vq_auxt__44c5_s_p9_1,
  132436. NULL,
  132437. 0
  132438. };
  132439. static long _vq_quantlist__44c5_s_p9_2[] = {
  132440. 10,
  132441. 9,
  132442. 11,
  132443. 8,
  132444. 12,
  132445. 7,
  132446. 13,
  132447. 6,
  132448. 14,
  132449. 5,
  132450. 15,
  132451. 4,
  132452. 16,
  132453. 3,
  132454. 17,
  132455. 2,
  132456. 18,
  132457. 1,
  132458. 19,
  132459. 0,
  132460. 20,
  132461. };
  132462. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132463. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132464. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132465. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132466. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132467. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132468. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132469. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132470. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132471. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132472. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132473. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132474. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132475. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132476. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132477. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132478. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132479. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132480. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132481. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132482. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132483. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132484. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132485. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132486. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132487. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132488. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132489. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132490. 10,10,10,10,10,10,10,10,10,
  132491. };
  132492. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132493. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132494. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132495. 6.5, 7.5, 8.5, 9.5,
  132496. };
  132497. static long _vq_quantmap__44c5_s_p9_2[] = {
  132498. 19, 17, 15, 13, 11, 9, 7, 5,
  132499. 3, 1, 0, 2, 4, 6, 8, 10,
  132500. 12, 14, 16, 18, 20,
  132501. };
  132502. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132503. _vq_quantthresh__44c5_s_p9_2,
  132504. _vq_quantmap__44c5_s_p9_2,
  132505. 21,
  132506. 21
  132507. };
  132508. static static_codebook _44c5_s_p9_2 = {
  132509. 2, 441,
  132510. _vq_lengthlist__44c5_s_p9_2,
  132511. 1, -529268736, 1611661312, 5, 0,
  132512. _vq_quantlist__44c5_s_p9_2,
  132513. NULL,
  132514. &_vq_auxt__44c5_s_p9_2,
  132515. NULL,
  132516. 0
  132517. };
  132518. static long _huff_lengthlist__44c5_s_short[] = {
  132519. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132520. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132521. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132522. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132523. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132524. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132525. 6, 8,11,16,
  132526. };
  132527. static static_codebook _huff_book__44c5_s_short = {
  132528. 2, 100,
  132529. _huff_lengthlist__44c5_s_short,
  132530. 0, 0, 0, 0, 0,
  132531. NULL,
  132532. NULL,
  132533. NULL,
  132534. NULL,
  132535. 0
  132536. };
  132537. static long _huff_lengthlist__44c6_s_long[] = {
  132538. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132539. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132540. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132541. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132542. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132543. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132544. 11,10,10,12,
  132545. };
  132546. static static_codebook _huff_book__44c6_s_long = {
  132547. 2, 100,
  132548. _huff_lengthlist__44c6_s_long,
  132549. 0, 0, 0, 0, 0,
  132550. NULL,
  132551. NULL,
  132552. NULL,
  132553. NULL,
  132554. 0
  132555. };
  132556. static long _vq_quantlist__44c6_s_p1_0[] = {
  132557. 1,
  132558. 0,
  132559. 2,
  132560. };
  132561. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132562. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132563. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132564. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132565. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132566. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132567. 8,
  132568. };
  132569. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132570. -0.5, 0.5,
  132571. };
  132572. static long _vq_quantmap__44c6_s_p1_0[] = {
  132573. 1, 0, 2,
  132574. };
  132575. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132576. _vq_quantthresh__44c6_s_p1_0,
  132577. _vq_quantmap__44c6_s_p1_0,
  132578. 3,
  132579. 3
  132580. };
  132581. static static_codebook _44c6_s_p1_0 = {
  132582. 4, 81,
  132583. _vq_lengthlist__44c6_s_p1_0,
  132584. 1, -535822336, 1611661312, 2, 0,
  132585. _vq_quantlist__44c6_s_p1_0,
  132586. NULL,
  132587. &_vq_auxt__44c6_s_p1_0,
  132588. NULL,
  132589. 0
  132590. };
  132591. static long _vq_quantlist__44c6_s_p2_0[] = {
  132592. 2,
  132593. 1,
  132594. 3,
  132595. 0,
  132596. 4,
  132597. };
  132598. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132599. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132600. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132601. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132602. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132603. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132604. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132605. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132606. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132608. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132609. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132610. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132611. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132612. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132613. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132614. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132616. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132617. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132618. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132619. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132620. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132621. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132622. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132624. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132625. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132626. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132627. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132628. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132629. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132630. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132635. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132636. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132637. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132638. 13,
  132639. };
  132640. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132641. -1.5, -0.5, 0.5, 1.5,
  132642. };
  132643. static long _vq_quantmap__44c6_s_p2_0[] = {
  132644. 3, 1, 0, 2, 4,
  132645. };
  132646. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132647. _vq_quantthresh__44c6_s_p2_0,
  132648. _vq_quantmap__44c6_s_p2_0,
  132649. 5,
  132650. 5
  132651. };
  132652. static static_codebook _44c6_s_p2_0 = {
  132653. 4, 625,
  132654. _vq_lengthlist__44c6_s_p2_0,
  132655. 1, -533725184, 1611661312, 3, 0,
  132656. _vq_quantlist__44c6_s_p2_0,
  132657. NULL,
  132658. &_vq_auxt__44c6_s_p2_0,
  132659. NULL,
  132660. 0
  132661. };
  132662. static long _vq_quantlist__44c6_s_p3_0[] = {
  132663. 4,
  132664. 3,
  132665. 5,
  132666. 2,
  132667. 6,
  132668. 1,
  132669. 7,
  132670. 0,
  132671. 8,
  132672. };
  132673. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132674. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132675. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132676. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132677. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132679. 0,
  132680. };
  132681. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132682. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132683. };
  132684. static long _vq_quantmap__44c6_s_p3_0[] = {
  132685. 7, 5, 3, 1, 0, 2, 4, 6,
  132686. 8,
  132687. };
  132688. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132689. _vq_quantthresh__44c6_s_p3_0,
  132690. _vq_quantmap__44c6_s_p3_0,
  132691. 9,
  132692. 9
  132693. };
  132694. static static_codebook _44c6_s_p3_0 = {
  132695. 2, 81,
  132696. _vq_lengthlist__44c6_s_p3_0,
  132697. 1, -531628032, 1611661312, 4, 0,
  132698. _vq_quantlist__44c6_s_p3_0,
  132699. NULL,
  132700. &_vq_auxt__44c6_s_p3_0,
  132701. NULL,
  132702. 0
  132703. };
  132704. static long _vq_quantlist__44c6_s_p4_0[] = {
  132705. 8,
  132706. 7,
  132707. 9,
  132708. 6,
  132709. 10,
  132710. 5,
  132711. 11,
  132712. 4,
  132713. 12,
  132714. 3,
  132715. 13,
  132716. 2,
  132717. 14,
  132718. 1,
  132719. 15,
  132720. 0,
  132721. 16,
  132722. };
  132723. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132724. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132725. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132726. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132727. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132728. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132729. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132730. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132731. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132732. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132733. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132742. 0,
  132743. };
  132744. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132745. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132746. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132747. };
  132748. static long _vq_quantmap__44c6_s_p4_0[] = {
  132749. 15, 13, 11, 9, 7, 5, 3, 1,
  132750. 0, 2, 4, 6, 8, 10, 12, 14,
  132751. 16,
  132752. };
  132753. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132754. _vq_quantthresh__44c6_s_p4_0,
  132755. _vq_quantmap__44c6_s_p4_0,
  132756. 17,
  132757. 17
  132758. };
  132759. static static_codebook _44c6_s_p4_0 = {
  132760. 2, 289,
  132761. _vq_lengthlist__44c6_s_p4_0,
  132762. 1, -529530880, 1611661312, 5, 0,
  132763. _vq_quantlist__44c6_s_p4_0,
  132764. NULL,
  132765. &_vq_auxt__44c6_s_p4_0,
  132766. NULL,
  132767. 0
  132768. };
  132769. static long _vq_quantlist__44c6_s_p5_0[] = {
  132770. 1,
  132771. 0,
  132772. 2,
  132773. };
  132774. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132775. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132776. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132777. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132778. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132779. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132780. 12,
  132781. };
  132782. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132783. -5.5, 5.5,
  132784. };
  132785. static long _vq_quantmap__44c6_s_p5_0[] = {
  132786. 1, 0, 2,
  132787. };
  132788. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132789. _vq_quantthresh__44c6_s_p5_0,
  132790. _vq_quantmap__44c6_s_p5_0,
  132791. 3,
  132792. 3
  132793. };
  132794. static static_codebook _44c6_s_p5_0 = {
  132795. 4, 81,
  132796. _vq_lengthlist__44c6_s_p5_0,
  132797. 1, -529137664, 1618345984, 2, 0,
  132798. _vq_quantlist__44c6_s_p5_0,
  132799. NULL,
  132800. &_vq_auxt__44c6_s_p5_0,
  132801. NULL,
  132802. 0
  132803. };
  132804. static long _vq_quantlist__44c6_s_p5_1[] = {
  132805. 5,
  132806. 4,
  132807. 6,
  132808. 3,
  132809. 7,
  132810. 2,
  132811. 8,
  132812. 1,
  132813. 9,
  132814. 0,
  132815. 10,
  132816. };
  132817. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132818. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132819. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132820. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132821. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132822. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132823. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132824. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132825. 11,10,10, 7, 7, 8, 8, 8, 8,
  132826. };
  132827. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132828. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132829. 3.5, 4.5,
  132830. };
  132831. static long _vq_quantmap__44c6_s_p5_1[] = {
  132832. 9, 7, 5, 3, 1, 0, 2, 4,
  132833. 6, 8, 10,
  132834. };
  132835. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132836. _vq_quantthresh__44c6_s_p5_1,
  132837. _vq_quantmap__44c6_s_p5_1,
  132838. 11,
  132839. 11
  132840. };
  132841. static static_codebook _44c6_s_p5_1 = {
  132842. 2, 121,
  132843. _vq_lengthlist__44c6_s_p5_1,
  132844. 1, -531365888, 1611661312, 4, 0,
  132845. _vq_quantlist__44c6_s_p5_1,
  132846. NULL,
  132847. &_vq_auxt__44c6_s_p5_1,
  132848. NULL,
  132849. 0
  132850. };
  132851. static long _vq_quantlist__44c6_s_p6_0[] = {
  132852. 6,
  132853. 5,
  132854. 7,
  132855. 4,
  132856. 8,
  132857. 3,
  132858. 9,
  132859. 2,
  132860. 10,
  132861. 1,
  132862. 11,
  132863. 0,
  132864. 12,
  132865. };
  132866. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132867. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132868. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132869. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132870. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132871. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132872. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132877. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132878. };
  132879. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132880. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132881. 12.5, 17.5, 22.5, 27.5,
  132882. };
  132883. static long _vq_quantmap__44c6_s_p6_0[] = {
  132884. 11, 9, 7, 5, 3, 1, 0, 2,
  132885. 4, 6, 8, 10, 12,
  132886. };
  132887. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132888. _vq_quantthresh__44c6_s_p6_0,
  132889. _vq_quantmap__44c6_s_p6_0,
  132890. 13,
  132891. 13
  132892. };
  132893. static static_codebook _44c6_s_p6_0 = {
  132894. 2, 169,
  132895. _vq_lengthlist__44c6_s_p6_0,
  132896. 1, -526516224, 1616117760, 4, 0,
  132897. _vq_quantlist__44c6_s_p6_0,
  132898. NULL,
  132899. &_vq_auxt__44c6_s_p6_0,
  132900. NULL,
  132901. 0
  132902. };
  132903. static long _vq_quantlist__44c6_s_p6_1[] = {
  132904. 2,
  132905. 1,
  132906. 3,
  132907. 0,
  132908. 4,
  132909. };
  132910. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132911. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132912. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132913. };
  132914. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132915. -1.5, -0.5, 0.5, 1.5,
  132916. };
  132917. static long _vq_quantmap__44c6_s_p6_1[] = {
  132918. 3, 1, 0, 2, 4,
  132919. };
  132920. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132921. _vq_quantthresh__44c6_s_p6_1,
  132922. _vq_quantmap__44c6_s_p6_1,
  132923. 5,
  132924. 5
  132925. };
  132926. static static_codebook _44c6_s_p6_1 = {
  132927. 2, 25,
  132928. _vq_lengthlist__44c6_s_p6_1,
  132929. 1, -533725184, 1611661312, 3, 0,
  132930. _vq_quantlist__44c6_s_p6_1,
  132931. NULL,
  132932. &_vq_auxt__44c6_s_p6_1,
  132933. NULL,
  132934. 0
  132935. };
  132936. static long _vq_quantlist__44c6_s_p7_0[] = {
  132937. 6,
  132938. 5,
  132939. 7,
  132940. 4,
  132941. 8,
  132942. 3,
  132943. 9,
  132944. 2,
  132945. 10,
  132946. 1,
  132947. 11,
  132948. 0,
  132949. 12,
  132950. };
  132951. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132952. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132953. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132954. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132955. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132956. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132957. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132958. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132959. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132960. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132961. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132962. 20,13,13,13,13,13,13,14,14,
  132963. };
  132964. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132965. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132966. 27.5, 38.5, 49.5, 60.5,
  132967. };
  132968. static long _vq_quantmap__44c6_s_p7_0[] = {
  132969. 11, 9, 7, 5, 3, 1, 0, 2,
  132970. 4, 6, 8, 10, 12,
  132971. };
  132972. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132973. _vq_quantthresh__44c6_s_p7_0,
  132974. _vq_quantmap__44c6_s_p7_0,
  132975. 13,
  132976. 13
  132977. };
  132978. static static_codebook _44c6_s_p7_0 = {
  132979. 2, 169,
  132980. _vq_lengthlist__44c6_s_p7_0,
  132981. 1, -523206656, 1618345984, 4, 0,
  132982. _vq_quantlist__44c6_s_p7_0,
  132983. NULL,
  132984. &_vq_auxt__44c6_s_p7_0,
  132985. NULL,
  132986. 0
  132987. };
  132988. static long _vq_quantlist__44c6_s_p7_1[] = {
  132989. 5,
  132990. 4,
  132991. 6,
  132992. 3,
  132993. 7,
  132994. 2,
  132995. 8,
  132996. 1,
  132997. 9,
  132998. 0,
  132999. 10,
  133000. };
  133001. static long _vq_lengthlist__44c6_s_p7_1[] = {
  133002. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  133003. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  133004. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133005. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133006. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133007. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133008. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133009. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133010. };
  133011. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133012. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133013. 3.5, 4.5,
  133014. };
  133015. static long _vq_quantmap__44c6_s_p7_1[] = {
  133016. 9, 7, 5, 3, 1, 0, 2, 4,
  133017. 6, 8, 10,
  133018. };
  133019. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133020. _vq_quantthresh__44c6_s_p7_1,
  133021. _vq_quantmap__44c6_s_p7_1,
  133022. 11,
  133023. 11
  133024. };
  133025. static static_codebook _44c6_s_p7_1 = {
  133026. 2, 121,
  133027. _vq_lengthlist__44c6_s_p7_1,
  133028. 1, -531365888, 1611661312, 4, 0,
  133029. _vq_quantlist__44c6_s_p7_1,
  133030. NULL,
  133031. &_vq_auxt__44c6_s_p7_1,
  133032. NULL,
  133033. 0
  133034. };
  133035. static long _vq_quantlist__44c6_s_p8_0[] = {
  133036. 7,
  133037. 6,
  133038. 8,
  133039. 5,
  133040. 9,
  133041. 4,
  133042. 10,
  133043. 3,
  133044. 11,
  133045. 2,
  133046. 12,
  133047. 1,
  133048. 13,
  133049. 0,
  133050. 14,
  133051. };
  133052. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133053. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133054. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133055. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133056. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133057. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133058. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133059. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133060. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133061. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133062. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133063. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133064. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133065. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133066. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133067. 14,
  133068. };
  133069. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133070. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133071. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133072. };
  133073. static long _vq_quantmap__44c6_s_p8_0[] = {
  133074. 13, 11, 9, 7, 5, 3, 1, 0,
  133075. 2, 4, 6, 8, 10, 12, 14,
  133076. };
  133077. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133078. _vq_quantthresh__44c6_s_p8_0,
  133079. _vq_quantmap__44c6_s_p8_0,
  133080. 15,
  133081. 15
  133082. };
  133083. static static_codebook _44c6_s_p8_0 = {
  133084. 2, 225,
  133085. _vq_lengthlist__44c6_s_p8_0,
  133086. 1, -520986624, 1620377600, 4, 0,
  133087. _vq_quantlist__44c6_s_p8_0,
  133088. NULL,
  133089. &_vq_auxt__44c6_s_p8_0,
  133090. NULL,
  133091. 0
  133092. };
  133093. static long _vq_quantlist__44c6_s_p8_1[] = {
  133094. 10,
  133095. 9,
  133096. 11,
  133097. 8,
  133098. 12,
  133099. 7,
  133100. 13,
  133101. 6,
  133102. 14,
  133103. 5,
  133104. 15,
  133105. 4,
  133106. 16,
  133107. 3,
  133108. 17,
  133109. 2,
  133110. 18,
  133111. 1,
  133112. 19,
  133113. 0,
  133114. 20,
  133115. };
  133116. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133117. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133118. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133119. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133120. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133121. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133122. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133123. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133124. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133125. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133126. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133127. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133128. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133129. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133130. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133131. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133132. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133133. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133134. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133135. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133136. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133137. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133138. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133139. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133140. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133141. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133142. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133143. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133144. 10,10,10,10,10,10,10,10,10,
  133145. };
  133146. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133147. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133148. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133149. 6.5, 7.5, 8.5, 9.5,
  133150. };
  133151. static long _vq_quantmap__44c6_s_p8_1[] = {
  133152. 19, 17, 15, 13, 11, 9, 7, 5,
  133153. 3, 1, 0, 2, 4, 6, 8, 10,
  133154. 12, 14, 16, 18, 20,
  133155. };
  133156. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133157. _vq_quantthresh__44c6_s_p8_1,
  133158. _vq_quantmap__44c6_s_p8_1,
  133159. 21,
  133160. 21
  133161. };
  133162. static static_codebook _44c6_s_p8_1 = {
  133163. 2, 441,
  133164. _vq_lengthlist__44c6_s_p8_1,
  133165. 1, -529268736, 1611661312, 5, 0,
  133166. _vq_quantlist__44c6_s_p8_1,
  133167. NULL,
  133168. &_vq_auxt__44c6_s_p8_1,
  133169. NULL,
  133170. 0
  133171. };
  133172. static long _vq_quantlist__44c6_s_p9_0[] = {
  133173. 6,
  133174. 5,
  133175. 7,
  133176. 4,
  133177. 8,
  133178. 3,
  133179. 9,
  133180. 2,
  133181. 10,
  133182. 1,
  133183. 11,
  133184. 0,
  133185. 12,
  133186. };
  133187. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133188. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133189. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133191. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133192. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133193. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133194. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133195. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133196. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133197. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133198. 10,10,10,10,10,10,10,10,10,
  133199. };
  133200. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133201. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133202. 1592.5, 2229.5, 2866.5, 3503.5,
  133203. };
  133204. static long _vq_quantmap__44c6_s_p9_0[] = {
  133205. 11, 9, 7, 5, 3, 1, 0, 2,
  133206. 4, 6, 8, 10, 12,
  133207. };
  133208. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133209. _vq_quantthresh__44c6_s_p9_0,
  133210. _vq_quantmap__44c6_s_p9_0,
  133211. 13,
  133212. 13
  133213. };
  133214. static static_codebook _44c6_s_p9_0 = {
  133215. 2, 169,
  133216. _vq_lengthlist__44c6_s_p9_0,
  133217. 1, -511845376, 1630791680, 4, 0,
  133218. _vq_quantlist__44c6_s_p9_0,
  133219. NULL,
  133220. &_vq_auxt__44c6_s_p9_0,
  133221. NULL,
  133222. 0
  133223. };
  133224. static long _vq_quantlist__44c6_s_p9_1[] = {
  133225. 6,
  133226. 5,
  133227. 7,
  133228. 4,
  133229. 8,
  133230. 3,
  133231. 9,
  133232. 2,
  133233. 10,
  133234. 1,
  133235. 11,
  133236. 0,
  133237. 12,
  133238. };
  133239. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133240. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133241. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133242. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133243. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133244. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133245. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133246. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133247. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133248. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133249. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133250. 15,12,10,11,11,13,11,12,13,
  133251. };
  133252. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133253. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133254. 122.5, 171.5, 220.5, 269.5,
  133255. };
  133256. static long _vq_quantmap__44c6_s_p9_1[] = {
  133257. 11, 9, 7, 5, 3, 1, 0, 2,
  133258. 4, 6, 8, 10, 12,
  133259. };
  133260. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133261. _vq_quantthresh__44c6_s_p9_1,
  133262. _vq_quantmap__44c6_s_p9_1,
  133263. 13,
  133264. 13
  133265. };
  133266. static static_codebook _44c6_s_p9_1 = {
  133267. 2, 169,
  133268. _vq_lengthlist__44c6_s_p9_1,
  133269. 1, -518889472, 1622704128, 4, 0,
  133270. _vq_quantlist__44c6_s_p9_1,
  133271. NULL,
  133272. &_vq_auxt__44c6_s_p9_1,
  133273. NULL,
  133274. 0
  133275. };
  133276. static long _vq_quantlist__44c6_s_p9_2[] = {
  133277. 24,
  133278. 23,
  133279. 25,
  133280. 22,
  133281. 26,
  133282. 21,
  133283. 27,
  133284. 20,
  133285. 28,
  133286. 19,
  133287. 29,
  133288. 18,
  133289. 30,
  133290. 17,
  133291. 31,
  133292. 16,
  133293. 32,
  133294. 15,
  133295. 33,
  133296. 14,
  133297. 34,
  133298. 13,
  133299. 35,
  133300. 12,
  133301. 36,
  133302. 11,
  133303. 37,
  133304. 10,
  133305. 38,
  133306. 9,
  133307. 39,
  133308. 8,
  133309. 40,
  133310. 7,
  133311. 41,
  133312. 6,
  133313. 42,
  133314. 5,
  133315. 43,
  133316. 4,
  133317. 44,
  133318. 3,
  133319. 45,
  133320. 2,
  133321. 46,
  133322. 1,
  133323. 47,
  133324. 0,
  133325. 48,
  133326. };
  133327. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133328. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133329. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133330. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133331. 7,
  133332. };
  133333. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133334. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133335. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133336. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133337. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133338. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133339. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133340. };
  133341. static long _vq_quantmap__44c6_s_p9_2[] = {
  133342. 47, 45, 43, 41, 39, 37, 35, 33,
  133343. 31, 29, 27, 25, 23, 21, 19, 17,
  133344. 15, 13, 11, 9, 7, 5, 3, 1,
  133345. 0, 2, 4, 6, 8, 10, 12, 14,
  133346. 16, 18, 20, 22, 24, 26, 28, 30,
  133347. 32, 34, 36, 38, 40, 42, 44, 46,
  133348. 48,
  133349. };
  133350. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133351. _vq_quantthresh__44c6_s_p9_2,
  133352. _vq_quantmap__44c6_s_p9_2,
  133353. 49,
  133354. 49
  133355. };
  133356. static static_codebook _44c6_s_p9_2 = {
  133357. 1, 49,
  133358. _vq_lengthlist__44c6_s_p9_2,
  133359. 1, -526909440, 1611661312, 6, 0,
  133360. _vq_quantlist__44c6_s_p9_2,
  133361. NULL,
  133362. &_vq_auxt__44c6_s_p9_2,
  133363. NULL,
  133364. 0
  133365. };
  133366. static long _huff_lengthlist__44c6_s_short[] = {
  133367. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133368. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133369. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133370. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133371. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133372. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133373. 9,10,17,18,
  133374. };
  133375. static static_codebook _huff_book__44c6_s_short = {
  133376. 2, 100,
  133377. _huff_lengthlist__44c6_s_short,
  133378. 0, 0, 0, 0, 0,
  133379. NULL,
  133380. NULL,
  133381. NULL,
  133382. NULL,
  133383. 0
  133384. };
  133385. static long _huff_lengthlist__44c7_s_long[] = {
  133386. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133387. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133388. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133389. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133390. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133391. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133392. 11,10,10,12,
  133393. };
  133394. static static_codebook _huff_book__44c7_s_long = {
  133395. 2, 100,
  133396. _huff_lengthlist__44c7_s_long,
  133397. 0, 0, 0, 0, 0,
  133398. NULL,
  133399. NULL,
  133400. NULL,
  133401. NULL,
  133402. 0
  133403. };
  133404. static long _vq_quantlist__44c7_s_p1_0[] = {
  133405. 1,
  133406. 0,
  133407. 2,
  133408. };
  133409. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133410. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133411. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133412. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133413. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133414. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133415. 8,
  133416. };
  133417. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133418. -0.5, 0.5,
  133419. };
  133420. static long _vq_quantmap__44c7_s_p1_0[] = {
  133421. 1, 0, 2,
  133422. };
  133423. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133424. _vq_quantthresh__44c7_s_p1_0,
  133425. _vq_quantmap__44c7_s_p1_0,
  133426. 3,
  133427. 3
  133428. };
  133429. static static_codebook _44c7_s_p1_0 = {
  133430. 4, 81,
  133431. _vq_lengthlist__44c7_s_p1_0,
  133432. 1, -535822336, 1611661312, 2, 0,
  133433. _vq_quantlist__44c7_s_p1_0,
  133434. NULL,
  133435. &_vq_auxt__44c7_s_p1_0,
  133436. NULL,
  133437. 0
  133438. };
  133439. static long _vq_quantlist__44c7_s_p2_0[] = {
  133440. 2,
  133441. 1,
  133442. 3,
  133443. 0,
  133444. 4,
  133445. };
  133446. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133447. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133448. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133449. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133450. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133451. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133452. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133453. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133454. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133456. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133457. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133458. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133459. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133460. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133461. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133462. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133464. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133465. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133466. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133467. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133468. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133469. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133470. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133472. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133473. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133474. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133475. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133476. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133477. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133478. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133483. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133484. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133485. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133486. 13,
  133487. };
  133488. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133489. -1.5, -0.5, 0.5, 1.5,
  133490. };
  133491. static long _vq_quantmap__44c7_s_p2_0[] = {
  133492. 3, 1, 0, 2, 4,
  133493. };
  133494. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133495. _vq_quantthresh__44c7_s_p2_0,
  133496. _vq_quantmap__44c7_s_p2_0,
  133497. 5,
  133498. 5
  133499. };
  133500. static static_codebook _44c7_s_p2_0 = {
  133501. 4, 625,
  133502. _vq_lengthlist__44c7_s_p2_0,
  133503. 1, -533725184, 1611661312, 3, 0,
  133504. _vq_quantlist__44c7_s_p2_0,
  133505. NULL,
  133506. &_vq_auxt__44c7_s_p2_0,
  133507. NULL,
  133508. 0
  133509. };
  133510. static long _vq_quantlist__44c7_s_p3_0[] = {
  133511. 4,
  133512. 3,
  133513. 5,
  133514. 2,
  133515. 6,
  133516. 1,
  133517. 7,
  133518. 0,
  133519. 8,
  133520. };
  133521. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133522. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133523. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133524. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133525. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133527. 0,
  133528. };
  133529. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133530. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133531. };
  133532. static long _vq_quantmap__44c7_s_p3_0[] = {
  133533. 7, 5, 3, 1, 0, 2, 4, 6,
  133534. 8,
  133535. };
  133536. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133537. _vq_quantthresh__44c7_s_p3_0,
  133538. _vq_quantmap__44c7_s_p3_0,
  133539. 9,
  133540. 9
  133541. };
  133542. static static_codebook _44c7_s_p3_0 = {
  133543. 2, 81,
  133544. _vq_lengthlist__44c7_s_p3_0,
  133545. 1, -531628032, 1611661312, 4, 0,
  133546. _vq_quantlist__44c7_s_p3_0,
  133547. NULL,
  133548. &_vq_auxt__44c7_s_p3_0,
  133549. NULL,
  133550. 0
  133551. };
  133552. static long _vq_quantlist__44c7_s_p4_0[] = {
  133553. 8,
  133554. 7,
  133555. 9,
  133556. 6,
  133557. 10,
  133558. 5,
  133559. 11,
  133560. 4,
  133561. 12,
  133562. 3,
  133563. 13,
  133564. 2,
  133565. 14,
  133566. 1,
  133567. 15,
  133568. 0,
  133569. 16,
  133570. };
  133571. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133572. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133573. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133574. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133575. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133576. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133577. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133578. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133579. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133580. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133581. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133590. 0,
  133591. };
  133592. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133593. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133594. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133595. };
  133596. static long _vq_quantmap__44c7_s_p4_0[] = {
  133597. 15, 13, 11, 9, 7, 5, 3, 1,
  133598. 0, 2, 4, 6, 8, 10, 12, 14,
  133599. 16,
  133600. };
  133601. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133602. _vq_quantthresh__44c7_s_p4_0,
  133603. _vq_quantmap__44c7_s_p4_0,
  133604. 17,
  133605. 17
  133606. };
  133607. static static_codebook _44c7_s_p4_0 = {
  133608. 2, 289,
  133609. _vq_lengthlist__44c7_s_p4_0,
  133610. 1, -529530880, 1611661312, 5, 0,
  133611. _vq_quantlist__44c7_s_p4_0,
  133612. NULL,
  133613. &_vq_auxt__44c7_s_p4_0,
  133614. NULL,
  133615. 0
  133616. };
  133617. static long _vq_quantlist__44c7_s_p5_0[] = {
  133618. 1,
  133619. 0,
  133620. 2,
  133621. };
  133622. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133623. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133624. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133625. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133626. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133627. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133628. 12,
  133629. };
  133630. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133631. -5.5, 5.5,
  133632. };
  133633. static long _vq_quantmap__44c7_s_p5_0[] = {
  133634. 1, 0, 2,
  133635. };
  133636. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133637. _vq_quantthresh__44c7_s_p5_0,
  133638. _vq_quantmap__44c7_s_p5_0,
  133639. 3,
  133640. 3
  133641. };
  133642. static static_codebook _44c7_s_p5_0 = {
  133643. 4, 81,
  133644. _vq_lengthlist__44c7_s_p5_0,
  133645. 1, -529137664, 1618345984, 2, 0,
  133646. _vq_quantlist__44c7_s_p5_0,
  133647. NULL,
  133648. &_vq_auxt__44c7_s_p5_0,
  133649. NULL,
  133650. 0
  133651. };
  133652. static long _vq_quantlist__44c7_s_p5_1[] = {
  133653. 5,
  133654. 4,
  133655. 6,
  133656. 3,
  133657. 7,
  133658. 2,
  133659. 8,
  133660. 1,
  133661. 9,
  133662. 0,
  133663. 10,
  133664. };
  133665. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133666. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133667. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133668. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133669. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133670. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133671. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133672. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133673. 11,11,11, 7, 7, 8, 8, 8, 8,
  133674. };
  133675. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133676. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133677. 3.5, 4.5,
  133678. };
  133679. static long _vq_quantmap__44c7_s_p5_1[] = {
  133680. 9, 7, 5, 3, 1, 0, 2, 4,
  133681. 6, 8, 10,
  133682. };
  133683. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133684. _vq_quantthresh__44c7_s_p5_1,
  133685. _vq_quantmap__44c7_s_p5_1,
  133686. 11,
  133687. 11
  133688. };
  133689. static static_codebook _44c7_s_p5_1 = {
  133690. 2, 121,
  133691. _vq_lengthlist__44c7_s_p5_1,
  133692. 1, -531365888, 1611661312, 4, 0,
  133693. _vq_quantlist__44c7_s_p5_1,
  133694. NULL,
  133695. &_vq_auxt__44c7_s_p5_1,
  133696. NULL,
  133697. 0
  133698. };
  133699. static long _vq_quantlist__44c7_s_p6_0[] = {
  133700. 6,
  133701. 5,
  133702. 7,
  133703. 4,
  133704. 8,
  133705. 3,
  133706. 9,
  133707. 2,
  133708. 10,
  133709. 1,
  133710. 11,
  133711. 0,
  133712. 12,
  133713. };
  133714. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133715. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133716. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133717. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133718. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133719. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133720. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133725. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133726. };
  133727. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133728. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133729. 12.5, 17.5, 22.5, 27.5,
  133730. };
  133731. static long _vq_quantmap__44c7_s_p6_0[] = {
  133732. 11, 9, 7, 5, 3, 1, 0, 2,
  133733. 4, 6, 8, 10, 12,
  133734. };
  133735. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133736. _vq_quantthresh__44c7_s_p6_0,
  133737. _vq_quantmap__44c7_s_p6_0,
  133738. 13,
  133739. 13
  133740. };
  133741. static static_codebook _44c7_s_p6_0 = {
  133742. 2, 169,
  133743. _vq_lengthlist__44c7_s_p6_0,
  133744. 1, -526516224, 1616117760, 4, 0,
  133745. _vq_quantlist__44c7_s_p6_0,
  133746. NULL,
  133747. &_vq_auxt__44c7_s_p6_0,
  133748. NULL,
  133749. 0
  133750. };
  133751. static long _vq_quantlist__44c7_s_p6_1[] = {
  133752. 2,
  133753. 1,
  133754. 3,
  133755. 0,
  133756. 4,
  133757. };
  133758. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133759. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133760. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133761. };
  133762. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133763. -1.5, -0.5, 0.5, 1.5,
  133764. };
  133765. static long _vq_quantmap__44c7_s_p6_1[] = {
  133766. 3, 1, 0, 2, 4,
  133767. };
  133768. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133769. _vq_quantthresh__44c7_s_p6_1,
  133770. _vq_quantmap__44c7_s_p6_1,
  133771. 5,
  133772. 5
  133773. };
  133774. static static_codebook _44c7_s_p6_1 = {
  133775. 2, 25,
  133776. _vq_lengthlist__44c7_s_p6_1,
  133777. 1, -533725184, 1611661312, 3, 0,
  133778. _vq_quantlist__44c7_s_p6_1,
  133779. NULL,
  133780. &_vq_auxt__44c7_s_p6_1,
  133781. NULL,
  133782. 0
  133783. };
  133784. static long _vq_quantlist__44c7_s_p7_0[] = {
  133785. 6,
  133786. 5,
  133787. 7,
  133788. 4,
  133789. 8,
  133790. 3,
  133791. 9,
  133792. 2,
  133793. 10,
  133794. 1,
  133795. 11,
  133796. 0,
  133797. 12,
  133798. };
  133799. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133800. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133801. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133802. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133803. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133804. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133805. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133806. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133807. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133808. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133809. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133810. 19,13,13,13,13,14,14,15,15,
  133811. };
  133812. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133813. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133814. 27.5, 38.5, 49.5, 60.5,
  133815. };
  133816. static long _vq_quantmap__44c7_s_p7_0[] = {
  133817. 11, 9, 7, 5, 3, 1, 0, 2,
  133818. 4, 6, 8, 10, 12,
  133819. };
  133820. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133821. _vq_quantthresh__44c7_s_p7_0,
  133822. _vq_quantmap__44c7_s_p7_0,
  133823. 13,
  133824. 13
  133825. };
  133826. static static_codebook _44c7_s_p7_0 = {
  133827. 2, 169,
  133828. _vq_lengthlist__44c7_s_p7_0,
  133829. 1, -523206656, 1618345984, 4, 0,
  133830. _vq_quantlist__44c7_s_p7_0,
  133831. NULL,
  133832. &_vq_auxt__44c7_s_p7_0,
  133833. NULL,
  133834. 0
  133835. };
  133836. static long _vq_quantlist__44c7_s_p7_1[] = {
  133837. 5,
  133838. 4,
  133839. 6,
  133840. 3,
  133841. 7,
  133842. 2,
  133843. 8,
  133844. 1,
  133845. 9,
  133846. 0,
  133847. 10,
  133848. };
  133849. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133850. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133851. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133852. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133853. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133854. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133855. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133856. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133857. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133858. };
  133859. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133860. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133861. 3.5, 4.5,
  133862. };
  133863. static long _vq_quantmap__44c7_s_p7_1[] = {
  133864. 9, 7, 5, 3, 1, 0, 2, 4,
  133865. 6, 8, 10,
  133866. };
  133867. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133868. _vq_quantthresh__44c7_s_p7_1,
  133869. _vq_quantmap__44c7_s_p7_1,
  133870. 11,
  133871. 11
  133872. };
  133873. static static_codebook _44c7_s_p7_1 = {
  133874. 2, 121,
  133875. _vq_lengthlist__44c7_s_p7_1,
  133876. 1, -531365888, 1611661312, 4, 0,
  133877. _vq_quantlist__44c7_s_p7_1,
  133878. NULL,
  133879. &_vq_auxt__44c7_s_p7_1,
  133880. NULL,
  133881. 0
  133882. };
  133883. static long _vq_quantlist__44c7_s_p8_0[] = {
  133884. 7,
  133885. 6,
  133886. 8,
  133887. 5,
  133888. 9,
  133889. 4,
  133890. 10,
  133891. 3,
  133892. 11,
  133893. 2,
  133894. 12,
  133895. 1,
  133896. 13,
  133897. 0,
  133898. 14,
  133899. };
  133900. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133901. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133902. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133903. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133904. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133905. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133906. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133907. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133908. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133909. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133910. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133911. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133912. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133913. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133914. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133915. 14,
  133916. };
  133917. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133918. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133919. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133920. };
  133921. static long _vq_quantmap__44c7_s_p8_0[] = {
  133922. 13, 11, 9, 7, 5, 3, 1, 0,
  133923. 2, 4, 6, 8, 10, 12, 14,
  133924. };
  133925. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133926. _vq_quantthresh__44c7_s_p8_0,
  133927. _vq_quantmap__44c7_s_p8_0,
  133928. 15,
  133929. 15
  133930. };
  133931. static static_codebook _44c7_s_p8_0 = {
  133932. 2, 225,
  133933. _vq_lengthlist__44c7_s_p8_0,
  133934. 1, -520986624, 1620377600, 4, 0,
  133935. _vq_quantlist__44c7_s_p8_0,
  133936. NULL,
  133937. &_vq_auxt__44c7_s_p8_0,
  133938. NULL,
  133939. 0
  133940. };
  133941. static long _vq_quantlist__44c7_s_p8_1[] = {
  133942. 10,
  133943. 9,
  133944. 11,
  133945. 8,
  133946. 12,
  133947. 7,
  133948. 13,
  133949. 6,
  133950. 14,
  133951. 5,
  133952. 15,
  133953. 4,
  133954. 16,
  133955. 3,
  133956. 17,
  133957. 2,
  133958. 18,
  133959. 1,
  133960. 19,
  133961. 0,
  133962. 20,
  133963. };
  133964. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133965. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133966. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133967. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133968. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133969. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133970. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133971. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133972. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133973. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133974. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133975. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133976. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133977. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133978. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133979. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133980. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133981. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133982. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133983. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133984. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133985. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133986. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133987. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133988. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133989. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133990. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133991. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133992. 10,10,10,10,10,10,10,10,10,
  133993. };
  133994. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133995. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133996. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133997. 6.5, 7.5, 8.5, 9.5,
  133998. };
  133999. static long _vq_quantmap__44c7_s_p8_1[] = {
  134000. 19, 17, 15, 13, 11, 9, 7, 5,
  134001. 3, 1, 0, 2, 4, 6, 8, 10,
  134002. 12, 14, 16, 18, 20,
  134003. };
  134004. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134005. _vq_quantthresh__44c7_s_p8_1,
  134006. _vq_quantmap__44c7_s_p8_1,
  134007. 21,
  134008. 21
  134009. };
  134010. static static_codebook _44c7_s_p8_1 = {
  134011. 2, 441,
  134012. _vq_lengthlist__44c7_s_p8_1,
  134013. 1, -529268736, 1611661312, 5, 0,
  134014. _vq_quantlist__44c7_s_p8_1,
  134015. NULL,
  134016. &_vq_auxt__44c7_s_p8_1,
  134017. NULL,
  134018. 0
  134019. };
  134020. static long _vq_quantlist__44c7_s_p9_0[] = {
  134021. 6,
  134022. 5,
  134023. 7,
  134024. 4,
  134025. 8,
  134026. 3,
  134027. 9,
  134028. 2,
  134029. 10,
  134030. 1,
  134031. 11,
  134032. 0,
  134033. 12,
  134034. };
  134035. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134036. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134037. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134046. 11,11,11,11,11,11,11,11,11,
  134047. };
  134048. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134049. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134050. 1592.5, 2229.5, 2866.5, 3503.5,
  134051. };
  134052. static long _vq_quantmap__44c7_s_p9_0[] = {
  134053. 11, 9, 7, 5, 3, 1, 0, 2,
  134054. 4, 6, 8, 10, 12,
  134055. };
  134056. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134057. _vq_quantthresh__44c7_s_p9_0,
  134058. _vq_quantmap__44c7_s_p9_0,
  134059. 13,
  134060. 13
  134061. };
  134062. static static_codebook _44c7_s_p9_0 = {
  134063. 2, 169,
  134064. _vq_lengthlist__44c7_s_p9_0,
  134065. 1, -511845376, 1630791680, 4, 0,
  134066. _vq_quantlist__44c7_s_p9_0,
  134067. NULL,
  134068. &_vq_auxt__44c7_s_p9_0,
  134069. NULL,
  134070. 0
  134071. };
  134072. static long _vq_quantlist__44c7_s_p9_1[] = {
  134073. 6,
  134074. 5,
  134075. 7,
  134076. 4,
  134077. 8,
  134078. 3,
  134079. 9,
  134080. 2,
  134081. 10,
  134082. 1,
  134083. 11,
  134084. 0,
  134085. 12,
  134086. };
  134087. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134088. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134089. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134090. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134091. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134092. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134093. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134094. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134095. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134096. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134097. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134098. 15,11,11,10,10,12,12,12,12,
  134099. };
  134100. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134101. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134102. 122.5, 171.5, 220.5, 269.5,
  134103. };
  134104. static long _vq_quantmap__44c7_s_p9_1[] = {
  134105. 11, 9, 7, 5, 3, 1, 0, 2,
  134106. 4, 6, 8, 10, 12,
  134107. };
  134108. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134109. _vq_quantthresh__44c7_s_p9_1,
  134110. _vq_quantmap__44c7_s_p9_1,
  134111. 13,
  134112. 13
  134113. };
  134114. static static_codebook _44c7_s_p9_1 = {
  134115. 2, 169,
  134116. _vq_lengthlist__44c7_s_p9_1,
  134117. 1, -518889472, 1622704128, 4, 0,
  134118. _vq_quantlist__44c7_s_p9_1,
  134119. NULL,
  134120. &_vq_auxt__44c7_s_p9_1,
  134121. NULL,
  134122. 0
  134123. };
  134124. static long _vq_quantlist__44c7_s_p9_2[] = {
  134125. 24,
  134126. 23,
  134127. 25,
  134128. 22,
  134129. 26,
  134130. 21,
  134131. 27,
  134132. 20,
  134133. 28,
  134134. 19,
  134135. 29,
  134136. 18,
  134137. 30,
  134138. 17,
  134139. 31,
  134140. 16,
  134141. 32,
  134142. 15,
  134143. 33,
  134144. 14,
  134145. 34,
  134146. 13,
  134147. 35,
  134148. 12,
  134149. 36,
  134150. 11,
  134151. 37,
  134152. 10,
  134153. 38,
  134154. 9,
  134155. 39,
  134156. 8,
  134157. 40,
  134158. 7,
  134159. 41,
  134160. 6,
  134161. 42,
  134162. 5,
  134163. 43,
  134164. 4,
  134165. 44,
  134166. 3,
  134167. 45,
  134168. 2,
  134169. 46,
  134170. 1,
  134171. 47,
  134172. 0,
  134173. 48,
  134174. };
  134175. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134176. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134177. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134178. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134179. 7,
  134180. };
  134181. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134182. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134183. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134184. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134185. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134186. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134187. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134188. };
  134189. static long _vq_quantmap__44c7_s_p9_2[] = {
  134190. 47, 45, 43, 41, 39, 37, 35, 33,
  134191. 31, 29, 27, 25, 23, 21, 19, 17,
  134192. 15, 13, 11, 9, 7, 5, 3, 1,
  134193. 0, 2, 4, 6, 8, 10, 12, 14,
  134194. 16, 18, 20, 22, 24, 26, 28, 30,
  134195. 32, 34, 36, 38, 40, 42, 44, 46,
  134196. 48,
  134197. };
  134198. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134199. _vq_quantthresh__44c7_s_p9_2,
  134200. _vq_quantmap__44c7_s_p9_2,
  134201. 49,
  134202. 49
  134203. };
  134204. static static_codebook _44c7_s_p9_2 = {
  134205. 1, 49,
  134206. _vq_lengthlist__44c7_s_p9_2,
  134207. 1, -526909440, 1611661312, 6, 0,
  134208. _vq_quantlist__44c7_s_p9_2,
  134209. NULL,
  134210. &_vq_auxt__44c7_s_p9_2,
  134211. NULL,
  134212. 0
  134213. };
  134214. static long _huff_lengthlist__44c7_s_short[] = {
  134215. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134216. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134217. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134218. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134219. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134220. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134221. 10, 9,11,14,
  134222. };
  134223. static static_codebook _huff_book__44c7_s_short = {
  134224. 2, 100,
  134225. _huff_lengthlist__44c7_s_short,
  134226. 0, 0, 0, 0, 0,
  134227. NULL,
  134228. NULL,
  134229. NULL,
  134230. NULL,
  134231. 0
  134232. };
  134233. static long _huff_lengthlist__44c8_s_long[] = {
  134234. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134235. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134236. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134237. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134238. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134239. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134240. 11, 9, 9,10,
  134241. };
  134242. static static_codebook _huff_book__44c8_s_long = {
  134243. 2, 100,
  134244. _huff_lengthlist__44c8_s_long,
  134245. 0, 0, 0, 0, 0,
  134246. NULL,
  134247. NULL,
  134248. NULL,
  134249. NULL,
  134250. 0
  134251. };
  134252. static long _vq_quantlist__44c8_s_p1_0[] = {
  134253. 1,
  134254. 0,
  134255. 2,
  134256. };
  134257. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134258. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134259. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134260. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134261. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134262. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134263. 8,
  134264. };
  134265. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134266. -0.5, 0.5,
  134267. };
  134268. static long _vq_quantmap__44c8_s_p1_0[] = {
  134269. 1, 0, 2,
  134270. };
  134271. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134272. _vq_quantthresh__44c8_s_p1_0,
  134273. _vq_quantmap__44c8_s_p1_0,
  134274. 3,
  134275. 3
  134276. };
  134277. static static_codebook _44c8_s_p1_0 = {
  134278. 4, 81,
  134279. _vq_lengthlist__44c8_s_p1_0,
  134280. 1, -535822336, 1611661312, 2, 0,
  134281. _vq_quantlist__44c8_s_p1_0,
  134282. NULL,
  134283. &_vq_auxt__44c8_s_p1_0,
  134284. NULL,
  134285. 0
  134286. };
  134287. static long _vq_quantlist__44c8_s_p2_0[] = {
  134288. 2,
  134289. 1,
  134290. 3,
  134291. 0,
  134292. 4,
  134293. };
  134294. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134295. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134296. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134297. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134298. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134299. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134300. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134301. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134302. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134304. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134305. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134306. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134307. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134308. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134309. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134310. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134312. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134313. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134314. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134315. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134316. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134317. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134318. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134320. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134321. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134322. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134323. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134324. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134325. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134326. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134331. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134332. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134333. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134334. 13,
  134335. };
  134336. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134337. -1.5, -0.5, 0.5, 1.5,
  134338. };
  134339. static long _vq_quantmap__44c8_s_p2_0[] = {
  134340. 3, 1, 0, 2, 4,
  134341. };
  134342. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134343. _vq_quantthresh__44c8_s_p2_0,
  134344. _vq_quantmap__44c8_s_p2_0,
  134345. 5,
  134346. 5
  134347. };
  134348. static static_codebook _44c8_s_p2_0 = {
  134349. 4, 625,
  134350. _vq_lengthlist__44c8_s_p2_0,
  134351. 1, -533725184, 1611661312, 3, 0,
  134352. _vq_quantlist__44c8_s_p2_0,
  134353. NULL,
  134354. &_vq_auxt__44c8_s_p2_0,
  134355. NULL,
  134356. 0
  134357. };
  134358. static long _vq_quantlist__44c8_s_p3_0[] = {
  134359. 4,
  134360. 3,
  134361. 5,
  134362. 2,
  134363. 6,
  134364. 1,
  134365. 7,
  134366. 0,
  134367. 8,
  134368. };
  134369. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134370. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134371. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134372. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134373. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134375. 0,
  134376. };
  134377. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134378. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134379. };
  134380. static long _vq_quantmap__44c8_s_p3_0[] = {
  134381. 7, 5, 3, 1, 0, 2, 4, 6,
  134382. 8,
  134383. };
  134384. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134385. _vq_quantthresh__44c8_s_p3_0,
  134386. _vq_quantmap__44c8_s_p3_0,
  134387. 9,
  134388. 9
  134389. };
  134390. static static_codebook _44c8_s_p3_0 = {
  134391. 2, 81,
  134392. _vq_lengthlist__44c8_s_p3_0,
  134393. 1, -531628032, 1611661312, 4, 0,
  134394. _vq_quantlist__44c8_s_p3_0,
  134395. NULL,
  134396. &_vq_auxt__44c8_s_p3_0,
  134397. NULL,
  134398. 0
  134399. };
  134400. static long _vq_quantlist__44c8_s_p4_0[] = {
  134401. 8,
  134402. 7,
  134403. 9,
  134404. 6,
  134405. 10,
  134406. 5,
  134407. 11,
  134408. 4,
  134409. 12,
  134410. 3,
  134411. 13,
  134412. 2,
  134413. 14,
  134414. 1,
  134415. 15,
  134416. 0,
  134417. 16,
  134418. };
  134419. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134420. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134421. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134422. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134423. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134424. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134425. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134426. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134427. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134428. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134429. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134438. 0,
  134439. };
  134440. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134441. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134442. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134443. };
  134444. static long _vq_quantmap__44c8_s_p4_0[] = {
  134445. 15, 13, 11, 9, 7, 5, 3, 1,
  134446. 0, 2, 4, 6, 8, 10, 12, 14,
  134447. 16,
  134448. };
  134449. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134450. _vq_quantthresh__44c8_s_p4_0,
  134451. _vq_quantmap__44c8_s_p4_0,
  134452. 17,
  134453. 17
  134454. };
  134455. static static_codebook _44c8_s_p4_0 = {
  134456. 2, 289,
  134457. _vq_lengthlist__44c8_s_p4_0,
  134458. 1, -529530880, 1611661312, 5, 0,
  134459. _vq_quantlist__44c8_s_p4_0,
  134460. NULL,
  134461. &_vq_auxt__44c8_s_p4_0,
  134462. NULL,
  134463. 0
  134464. };
  134465. static long _vq_quantlist__44c8_s_p5_0[] = {
  134466. 1,
  134467. 0,
  134468. 2,
  134469. };
  134470. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134471. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134472. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134473. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134474. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134475. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134476. 12,
  134477. };
  134478. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134479. -5.5, 5.5,
  134480. };
  134481. static long _vq_quantmap__44c8_s_p5_0[] = {
  134482. 1, 0, 2,
  134483. };
  134484. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134485. _vq_quantthresh__44c8_s_p5_0,
  134486. _vq_quantmap__44c8_s_p5_0,
  134487. 3,
  134488. 3
  134489. };
  134490. static static_codebook _44c8_s_p5_0 = {
  134491. 4, 81,
  134492. _vq_lengthlist__44c8_s_p5_0,
  134493. 1, -529137664, 1618345984, 2, 0,
  134494. _vq_quantlist__44c8_s_p5_0,
  134495. NULL,
  134496. &_vq_auxt__44c8_s_p5_0,
  134497. NULL,
  134498. 0
  134499. };
  134500. static long _vq_quantlist__44c8_s_p5_1[] = {
  134501. 5,
  134502. 4,
  134503. 6,
  134504. 3,
  134505. 7,
  134506. 2,
  134507. 8,
  134508. 1,
  134509. 9,
  134510. 0,
  134511. 10,
  134512. };
  134513. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134514. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134515. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134516. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134517. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134518. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134519. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134520. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134521. 11,11,11, 7, 7, 7, 7, 8, 8,
  134522. };
  134523. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134524. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134525. 3.5, 4.5,
  134526. };
  134527. static long _vq_quantmap__44c8_s_p5_1[] = {
  134528. 9, 7, 5, 3, 1, 0, 2, 4,
  134529. 6, 8, 10,
  134530. };
  134531. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134532. _vq_quantthresh__44c8_s_p5_1,
  134533. _vq_quantmap__44c8_s_p5_1,
  134534. 11,
  134535. 11
  134536. };
  134537. static static_codebook _44c8_s_p5_1 = {
  134538. 2, 121,
  134539. _vq_lengthlist__44c8_s_p5_1,
  134540. 1, -531365888, 1611661312, 4, 0,
  134541. _vq_quantlist__44c8_s_p5_1,
  134542. NULL,
  134543. &_vq_auxt__44c8_s_p5_1,
  134544. NULL,
  134545. 0
  134546. };
  134547. static long _vq_quantlist__44c8_s_p6_0[] = {
  134548. 6,
  134549. 5,
  134550. 7,
  134551. 4,
  134552. 8,
  134553. 3,
  134554. 9,
  134555. 2,
  134556. 10,
  134557. 1,
  134558. 11,
  134559. 0,
  134560. 12,
  134561. };
  134562. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134563. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134564. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134565. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134566. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134567. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134568. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134573. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134574. };
  134575. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134576. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134577. 12.5, 17.5, 22.5, 27.5,
  134578. };
  134579. static long _vq_quantmap__44c8_s_p6_0[] = {
  134580. 11, 9, 7, 5, 3, 1, 0, 2,
  134581. 4, 6, 8, 10, 12,
  134582. };
  134583. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134584. _vq_quantthresh__44c8_s_p6_0,
  134585. _vq_quantmap__44c8_s_p6_0,
  134586. 13,
  134587. 13
  134588. };
  134589. static static_codebook _44c8_s_p6_0 = {
  134590. 2, 169,
  134591. _vq_lengthlist__44c8_s_p6_0,
  134592. 1, -526516224, 1616117760, 4, 0,
  134593. _vq_quantlist__44c8_s_p6_0,
  134594. NULL,
  134595. &_vq_auxt__44c8_s_p6_0,
  134596. NULL,
  134597. 0
  134598. };
  134599. static long _vq_quantlist__44c8_s_p6_1[] = {
  134600. 2,
  134601. 1,
  134602. 3,
  134603. 0,
  134604. 4,
  134605. };
  134606. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134607. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134608. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134609. };
  134610. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134611. -1.5, -0.5, 0.5, 1.5,
  134612. };
  134613. static long _vq_quantmap__44c8_s_p6_1[] = {
  134614. 3, 1, 0, 2, 4,
  134615. };
  134616. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134617. _vq_quantthresh__44c8_s_p6_1,
  134618. _vq_quantmap__44c8_s_p6_1,
  134619. 5,
  134620. 5
  134621. };
  134622. static static_codebook _44c8_s_p6_1 = {
  134623. 2, 25,
  134624. _vq_lengthlist__44c8_s_p6_1,
  134625. 1, -533725184, 1611661312, 3, 0,
  134626. _vq_quantlist__44c8_s_p6_1,
  134627. NULL,
  134628. &_vq_auxt__44c8_s_p6_1,
  134629. NULL,
  134630. 0
  134631. };
  134632. static long _vq_quantlist__44c8_s_p7_0[] = {
  134633. 6,
  134634. 5,
  134635. 7,
  134636. 4,
  134637. 8,
  134638. 3,
  134639. 9,
  134640. 2,
  134641. 10,
  134642. 1,
  134643. 11,
  134644. 0,
  134645. 12,
  134646. };
  134647. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134648. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134649. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134650. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134651. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134652. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134653. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134654. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134655. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134656. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134657. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134658. 20,13,13,13,13,14,13,15,15,
  134659. };
  134660. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134661. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134662. 27.5, 38.5, 49.5, 60.5,
  134663. };
  134664. static long _vq_quantmap__44c8_s_p7_0[] = {
  134665. 11, 9, 7, 5, 3, 1, 0, 2,
  134666. 4, 6, 8, 10, 12,
  134667. };
  134668. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134669. _vq_quantthresh__44c8_s_p7_0,
  134670. _vq_quantmap__44c8_s_p7_0,
  134671. 13,
  134672. 13
  134673. };
  134674. static static_codebook _44c8_s_p7_0 = {
  134675. 2, 169,
  134676. _vq_lengthlist__44c8_s_p7_0,
  134677. 1, -523206656, 1618345984, 4, 0,
  134678. _vq_quantlist__44c8_s_p7_0,
  134679. NULL,
  134680. &_vq_auxt__44c8_s_p7_0,
  134681. NULL,
  134682. 0
  134683. };
  134684. static long _vq_quantlist__44c8_s_p7_1[] = {
  134685. 5,
  134686. 4,
  134687. 6,
  134688. 3,
  134689. 7,
  134690. 2,
  134691. 8,
  134692. 1,
  134693. 9,
  134694. 0,
  134695. 10,
  134696. };
  134697. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134698. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134699. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134700. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134701. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134702. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134703. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134704. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134705. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134706. };
  134707. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134708. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134709. 3.5, 4.5,
  134710. };
  134711. static long _vq_quantmap__44c8_s_p7_1[] = {
  134712. 9, 7, 5, 3, 1, 0, 2, 4,
  134713. 6, 8, 10,
  134714. };
  134715. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134716. _vq_quantthresh__44c8_s_p7_1,
  134717. _vq_quantmap__44c8_s_p7_1,
  134718. 11,
  134719. 11
  134720. };
  134721. static static_codebook _44c8_s_p7_1 = {
  134722. 2, 121,
  134723. _vq_lengthlist__44c8_s_p7_1,
  134724. 1, -531365888, 1611661312, 4, 0,
  134725. _vq_quantlist__44c8_s_p7_1,
  134726. NULL,
  134727. &_vq_auxt__44c8_s_p7_1,
  134728. NULL,
  134729. 0
  134730. };
  134731. static long _vq_quantlist__44c8_s_p8_0[] = {
  134732. 7,
  134733. 6,
  134734. 8,
  134735. 5,
  134736. 9,
  134737. 4,
  134738. 10,
  134739. 3,
  134740. 11,
  134741. 2,
  134742. 12,
  134743. 1,
  134744. 13,
  134745. 0,
  134746. 14,
  134747. };
  134748. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134749. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134750. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134751. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134752. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134753. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134754. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134755. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134756. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134757. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134758. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134759. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134760. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134761. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134762. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134763. 15,
  134764. };
  134765. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134766. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134767. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134768. };
  134769. static long _vq_quantmap__44c8_s_p8_0[] = {
  134770. 13, 11, 9, 7, 5, 3, 1, 0,
  134771. 2, 4, 6, 8, 10, 12, 14,
  134772. };
  134773. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134774. _vq_quantthresh__44c8_s_p8_0,
  134775. _vq_quantmap__44c8_s_p8_0,
  134776. 15,
  134777. 15
  134778. };
  134779. static static_codebook _44c8_s_p8_0 = {
  134780. 2, 225,
  134781. _vq_lengthlist__44c8_s_p8_0,
  134782. 1, -520986624, 1620377600, 4, 0,
  134783. _vq_quantlist__44c8_s_p8_0,
  134784. NULL,
  134785. &_vq_auxt__44c8_s_p8_0,
  134786. NULL,
  134787. 0
  134788. };
  134789. static long _vq_quantlist__44c8_s_p8_1[] = {
  134790. 10,
  134791. 9,
  134792. 11,
  134793. 8,
  134794. 12,
  134795. 7,
  134796. 13,
  134797. 6,
  134798. 14,
  134799. 5,
  134800. 15,
  134801. 4,
  134802. 16,
  134803. 3,
  134804. 17,
  134805. 2,
  134806. 18,
  134807. 1,
  134808. 19,
  134809. 0,
  134810. 20,
  134811. };
  134812. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134813. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134814. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134815. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134816. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134817. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134818. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134819. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134820. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134821. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134822. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134823. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134824. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134825. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134826. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134827. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134828. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134829. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134830. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134831. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134832. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134833. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134835. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134836. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134837. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134838. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134839. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134840. 10, 9, 9,10,10, 9,10, 9, 9,
  134841. };
  134842. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134843. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134844. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134845. 6.5, 7.5, 8.5, 9.5,
  134846. };
  134847. static long _vq_quantmap__44c8_s_p8_1[] = {
  134848. 19, 17, 15, 13, 11, 9, 7, 5,
  134849. 3, 1, 0, 2, 4, 6, 8, 10,
  134850. 12, 14, 16, 18, 20,
  134851. };
  134852. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134853. _vq_quantthresh__44c8_s_p8_1,
  134854. _vq_quantmap__44c8_s_p8_1,
  134855. 21,
  134856. 21
  134857. };
  134858. static static_codebook _44c8_s_p8_1 = {
  134859. 2, 441,
  134860. _vq_lengthlist__44c8_s_p8_1,
  134861. 1, -529268736, 1611661312, 5, 0,
  134862. _vq_quantlist__44c8_s_p8_1,
  134863. NULL,
  134864. &_vq_auxt__44c8_s_p8_1,
  134865. NULL,
  134866. 0
  134867. };
  134868. static long _vq_quantlist__44c8_s_p9_0[] = {
  134869. 8,
  134870. 7,
  134871. 9,
  134872. 6,
  134873. 10,
  134874. 5,
  134875. 11,
  134876. 4,
  134877. 12,
  134878. 3,
  134879. 13,
  134880. 2,
  134881. 14,
  134882. 1,
  134883. 15,
  134884. 0,
  134885. 16,
  134886. };
  134887. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134888. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134889. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134890. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134894. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134895. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134896. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134897. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134898. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134899. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134902. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134903. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134904. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134906. 10,
  134907. };
  134908. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134909. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134910. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134911. };
  134912. static long _vq_quantmap__44c8_s_p9_0[] = {
  134913. 15, 13, 11, 9, 7, 5, 3, 1,
  134914. 0, 2, 4, 6, 8, 10, 12, 14,
  134915. 16,
  134916. };
  134917. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134918. _vq_quantthresh__44c8_s_p9_0,
  134919. _vq_quantmap__44c8_s_p9_0,
  134920. 17,
  134921. 17
  134922. };
  134923. static static_codebook _44c8_s_p9_0 = {
  134924. 2, 289,
  134925. _vq_lengthlist__44c8_s_p9_0,
  134926. 1, -509798400, 1631393792, 5, 0,
  134927. _vq_quantlist__44c8_s_p9_0,
  134928. NULL,
  134929. &_vq_auxt__44c8_s_p9_0,
  134930. NULL,
  134931. 0
  134932. };
  134933. static long _vq_quantlist__44c8_s_p9_1[] = {
  134934. 9,
  134935. 8,
  134936. 10,
  134937. 7,
  134938. 11,
  134939. 6,
  134940. 12,
  134941. 5,
  134942. 13,
  134943. 4,
  134944. 14,
  134945. 3,
  134946. 15,
  134947. 2,
  134948. 16,
  134949. 1,
  134950. 17,
  134951. 0,
  134952. 18,
  134953. };
  134954. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134955. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134956. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134957. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134958. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134959. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134960. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134961. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134962. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134963. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134964. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134965. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134966. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134967. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134968. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134969. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134970. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134971. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134972. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134973. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134974. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134975. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134976. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134977. 14,13,13,14,14,15,14,15,14,
  134978. };
  134979. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134980. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134981. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134982. 367.5, 416.5,
  134983. };
  134984. static long _vq_quantmap__44c8_s_p9_1[] = {
  134985. 17, 15, 13, 11, 9, 7, 5, 3,
  134986. 1, 0, 2, 4, 6, 8, 10, 12,
  134987. 14, 16, 18,
  134988. };
  134989. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134990. _vq_quantthresh__44c8_s_p9_1,
  134991. _vq_quantmap__44c8_s_p9_1,
  134992. 19,
  134993. 19
  134994. };
  134995. static static_codebook _44c8_s_p9_1 = {
  134996. 2, 361,
  134997. _vq_lengthlist__44c8_s_p9_1,
  134998. 1, -518287360, 1622704128, 5, 0,
  134999. _vq_quantlist__44c8_s_p9_1,
  135000. NULL,
  135001. &_vq_auxt__44c8_s_p9_1,
  135002. NULL,
  135003. 0
  135004. };
  135005. static long _vq_quantlist__44c8_s_p9_2[] = {
  135006. 24,
  135007. 23,
  135008. 25,
  135009. 22,
  135010. 26,
  135011. 21,
  135012. 27,
  135013. 20,
  135014. 28,
  135015. 19,
  135016. 29,
  135017. 18,
  135018. 30,
  135019. 17,
  135020. 31,
  135021. 16,
  135022. 32,
  135023. 15,
  135024. 33,
  135025. 14,
  135026. 34,
  135027. 13,
  135028. 35,
  135029. 12,
  135030. 36,
  135031. 11,
  135032. 37,
  135033. 10,
  135034. 38,
  135035. 9,
  135036. 39,
  135037. 8,
  135038. 40,
  135039. 7,
  135040. 41,
  135041. 6,
  135042. 42,
  135043. 5,
  135044. 43,
  135045. 4,
  135046. 44,
  135047. 3,
  135048. 45,
  135049. 2,
  135050. 46,
  135051. 1,
  135052. 47,
  135053. 0,
  135054. 48,
  135055. };
  135056. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135057. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135058. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135059. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135060. 7,
  135061. };
  135062. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135063. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135064. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135065. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135066. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135067. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135068. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135069. };
  135070. static long _vq_quantmap__44c8_s_p9_2[] = {
  135071. 47, 45, 43, 41, 39, 37, 35, 33,
  135072. 31, 29, 27, 25, 23, 21, 19, 17,
  135073. 15, 13, 11, 9, 7, 5, 3, 1,
  135074. 0, 2, 4, 6, 8, 10, 12, 14,
  135075. 16, 18, 20, 22, 24, 26, 28, 30,
  135076. 32, 34, 36, 38, 40, 42, 44, 46,
  135077. 48,
  135078. };
  135079. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135080. _vq_quantthresh__44c8_s_p9_2,
  135081. _vq_quantmap__44c8_s_p9_2,
  135082. 49,
  135083. 49
  135084. };
  135085. static static_codebook _44c8_s_p9_2 = {
  135086. 1, 49,
  135087. _vq_lengthlist__44c8_s_p9_2,
  135088. 1, -526909440, 1611661312, 6, 0,
  135089. _vq_quantlist__44c8_s_p9_2,
  135090. NULL,
  135091. &_vq_auxt__44c8_s_p9_2,
  135092. NULL,
  135093. 0
  135094. };
  135095. static long _huff_lengthlist__44c8_s_short[] = {
  135096. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135097. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135098. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135099. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135100. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135101. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135102. 10, 9,11,14,
  135103. };
  135104. static static_codebook _huff_book__44c8_s_short = {
  135105. 2, 100,
  135106. _huff_lengthlist__44c8_s_short,
  135107. 0, 0, 0, 0, 0,
  135108. NULL,
  135109. NULL,
  135110. NULL,
  135111. NULL,
  135112. 0
  135113. };
  135114. static long _huff_lengthlist__44c9_s_long[] = {
  135115. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135116. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135117. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135118. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135119. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135120. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135121. 10, 9, 8, 9,
  135122. };
  135123. static static_codebook _huff_book__44c9_s_long = {
  135124. 2, 100,
  135125. _huff_lengthlist__44c9_s_long,
  135126. 0, 0, 0, 0, 0,
  135127. NULL,
  135128. NULL,
  135129. NULL,
  135130. NULL,
  135131. 0
  135132. };
  135133. static long _vq_quantlist__44c9_s_p1_0[] = {
  135134. 1,
  135135. 0,
  135136. 2,
  135137. };
  135138. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135139. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135140. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135141. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135142. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135143. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135144. 7,
  135145. };
  135146. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135147. -0.5, 0.5,
  135148. };
  135149. static long _vq_quantmap__44c9_s_p1_0[] = {
  135150. 1, 0, 2,
  135151. };
  135152. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135153. _vq_quantthresh__44c9_s_p1_0,
  135154. _vq_quantmap__44c9_s_p1_0,
  135155. 3,
  135156. 3
  135157. };
  135158. static static_codebook _44c9_s_p1_0 = {
  135159. 4, 81,
  135160. _vq_lengthlist__44c9_s_p1_0,
  135161. 1, -535822336, 1611661312, 2, 0,
  135162. _vq_quantlist__44c9_s_p1_0,
  135163. NULL,
  135164. &_vq_auxt__44c9_s_p1_0,
  135165. NULL,
  135166. 0
  135167. };
  135168. static long _vq_quantlist__44c9_s_p2_0[] = {
  135169. 2,
  135170. 1,
  135171. 3,
  135172. 0,
  135173. 4,
  135174. };
  135175. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135176. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135177. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135178. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135179. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135180. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135181. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135182. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135183. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 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, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135186. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135187. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135188. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135189. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135190. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135191. 0,12,12,12,12, 0, 0, 0,12,12, 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, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135194. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135195. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135196. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135197. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135198. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135199. 12,12, 0, 0, 0,12,12, 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. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135202. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135203. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135204. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135205. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135206. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135207. 0, 0,12,13, 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, 9,
  135212. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135213. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135214. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135215. 12,
  135216. };
  135217. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135218. -1.5, -0.5, 0.5, 1.5,
  135219. };
  135220. static long _vq_quantmap__44c9_s_p2_0[] = {
  135221. 3, 1, 0, 2, 4,
  135222. };
  135223. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135224. _vq_quantthresh__44c9_s_p2_0,
  135225. _vq_quantmap__44c9_s_p2_0,
  135226. 5,
  135227. 5
  135228. };
  135229. static static_codebook _44c9_s_p2_0 = {
  135230. 4, 625,
  135231. _vq_lengthlist__44c9_s_p2_0,
  135232. 1, -533725184, 1611661312, 3, 0,
  135233. _vq_quantlist__44c9_s_p2_0,
  135234. NULL,
  135235. &_vq_auxt__44c9_s_p2_0,
  135236. NULL,
  135237. 0
  135238. };
  135239. static long _vq_quantlist__44c9_s_p3_0[] = {
  135240. 4,
  135241. 3,
  135242. 5,
  135243. 2,
  135244. 6,
  135245. 1,
  135246. 7,
  135247. 0,
  135248. 8,
  135249. };
  135250. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135251. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135252. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135253. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135254. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135256. 0,
  135257. };
  135258. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135259. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135260. };
  135261. static long _vq_quantmap__44c9_s_p3_0[] = {
  135262. 7, 5, 3, 1, 0, 2, 4, 6,
  135263. 8,
  135264. };
  135265. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135266. _vq_quantthresh__44c9_s_p3_0,
  135267. _vq_quantmap__44c9_s_p3_0,
  135268. 9,
  135269. 9
  135270. };
  135271. static static_codebook _44c9_s_p3_0 = {
  135272. 2, 81,
  135273. _vq_lengthlist__44c9_s_p3_0,
  135274. 1, -531628032, 1611661312, 4, 0,
  135275. _vq_quantlist__44c9_s_p3_0,
  135276. NULL,
  135277. &_vq_auxt__44c9_s_p3_0,
  135278. NULL,
  135279. 0
  135280. };
  135281. static long _vq_quantlist__44c9_s_p4_0[] = {
  135282. 8,
  135283. 7,
  135284. 9,
  135285. 6,
  135286. 10,
  135287. 5,
  135288. 11,
  135289. 4,
  135290. 12,
  135291. 3,
  135292. 13,
  135293. 2,
  135294. 14,
  135295. 1,
  135296. 15,
  135297. 0,
  135298. 16,
  135299. };
  135300. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135301. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135302. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135303. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135304. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135305. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135306. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135307. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135308. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135309. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135310. 9,10,10,11,11,12,12,12,12, 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,
  135320. };
  135321. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135324. };
  135325. static long _vq_quantmap__44c9_s_p4_0[] = {
  135326. 15, 13, 11, 9, 7, 5, 3, 1,
  135327. 0, 2, 4, 6, 8, 10, 12, 14,
  135328. 16,
  135329. };
  135330. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135331. _vq_quantthresh__44c9_s_p4_0,
  135332. _vq_quantmap__44c9_s_p4_0,
  135333. 17,
  135334. 17
  135335. };
  135336. static static_codebook _44c9_s_p4_0 = {
  135337. 2, 289,
  135338. _vq_lengthlist__44c9_s_p4_0,
  135339. 1, -529530880, 1611661312, 5, 0,
  135340. _vq_quantlist__44c9_s_p4_0,
  135341. NULL,
  135342. &_vq_auxt__44c9_s_p4_0,
  135343. NULL,
  135344. 0
  135345. };
  135346. static long _vq_quantlist__44c9_s_p5_0[] = {
  135347. 1,
  135348. 0,
  135349. 2,
  135350. };
  135351. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135352. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135353. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135354. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135355. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135356. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135357. 12,
  135358. };
  135359. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135360. -5.5, 5.5,
  135361. };
  135362. static long _vq_quantmap__44c9_s_p5_0[] = {
  135363. 1, 0, 2,
  135364. };
  135365. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135366. _vq_quantthresh__44c9_s_p5_0,
  135367. _vq_quantmap__44c9_s_p5_0,
  135368. 3,
  135369. 3
  135370. };
  135371. static static_codebook _44c9_s_p5_0 = {
  135372. 4, 81,
  135373. _vq_lengthlist__44c9_s_p5_0,
  135374. 1, -529137664, 1618345984, 2, 0,
  135375. _vq_quantlist__44c9_s_p5_0,
  135376. NULL,
  135377. &_vq_auxt__44c9_s_p5_0,
  135378. NULL,
  135379. 0
  135380. };
  135381. static long _vq_quantlist__44c9_s_p5_1[] = {
  135382. 5,
  135383. 4,
  135384. 6,
  135385. 3,
  135386. 7,
  135387. 2,
  135388. 8,
  135389. 1,
  135390. 9,
  135391. 0,
  135392. 10,
  135393. };
  135394. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135395. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135396. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135397. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135398. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135399. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135400. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135401. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135402. 11,11,11, 7, 7, 7, 7, 7, 7,
  135403. };
  135404. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135405. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135406. 3.5, 4.5,
  135407. };
  135408. static long _vq_quantmap__44c9_s_p5_1[] = {
  135409. 9, 7, 5, 3, 1, 0, 2, 4,
  135410. 6, 8, 10,
  135411. };
  135412. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135413. _vq_quantthresh__44c9_s_p5_1,
  135414. _vq_quantmap__44c9_s_p5_1,
  135415. 11,
  135416. 11
  135417. };
  135418. static static_codebook _44c9_s_p5_1 = {
  135419. 2, 121,
  135420. _vq_lengthlist__44c9_s_p5_1,
  135421. 1, -531365888, 1611661312, 4, 0,
  135422. _vq_quantlist__44c9_s_p5_1,
  135423. NULL,
  135424. &_vq_auxt__44c9_s_p5_1,
  135425. NULL,
  135426. 0
  135427. };
  135428. static long _vq_quantlist__44c9_s_p6_0[] = {
  135429. 6,
  135430. 5,
  135431. 7,
  135432. 4,
  135433. 8,
  135434. 3,
  135435. 9,
  135436. 2,
  135437. 10,
  135438. 1,
  135439. 11,
  135440. 0,
  135441. 12,
  135442. };
  135443. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135444. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135445. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135446. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135447. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135448. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135449. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135454. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135455. };
  135456. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135457. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135458. 12.5, 17.5, 22.5, 27.5,
  135459. };
  135460. static long _vq_quantmap__44c9_s_p6_0[] = {
  135461. 11, 9, 7, 5, 3, 1, 0, 2,
  135462. 4, 6, 8, 10, 12,
  135463. };
  135464. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135465. _vq_quantthresh__44c9_s_p6_0,
  135466. _vq_quantmap__44c9_s_p6_0,
  135467. 13,
  135468. 13
  135469. };
  135470. static static_codebook _44c9_s_p6_0 = {
  135471. 2, 169,
  135472. _vq_lengthlist__44c9_s_p6_0,
  135473. 1, -526516224, 1616117760, 4, 0,
  135474. _vq_quantlist__44c9_s_p6_0,
  135475. NULL,
  135476. &_vq_auxt__44c9_s_p6_0,
  135477. NULL,
  135478. 0
  135479. };
  135480. static long _vq_quantlist__44c9_s_p6_1[] = {
  135481. 2,
  135482. 1,
  135483. 3,
  135484. 0,
  135485. 4,
  135486. };
  135487. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135488. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135489. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135490. };
  135491. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135492. -1.5, -0.5, 0.5, 1.5,
  135493. };
  135494. static long _vq_quantmap__44c9_s_p6_1[] = {
  135495. 3, 1, 0, 2, 4,
  135496. };
  135497. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135498. _vq_quantthresh__44c9_s_p6_1,
  135499. _vq_quantmap__44c9_s_p6_1,
  135500. 5,
  135501. 5
  135502. };
  135503. static static_codebook _44c9_s_p6_1 = {
  135504. 2, 25,
  135505. _vq_lengthlist__44c9_s_p6_1,
  135506. 1, -533725184, 1611661312, 3, 0,
  135507. _vq_quantlist__44c9_s_p6_1,
  135508. NULL,
  135509. &_vq_auxt__44c9_s_p6_1,
  135510. NULL,
  135511. 0
  135512. };
  135513. static long _vq_quantlist__44c9_s_p7_0[] = {
  135514. 6,
  135515. 5,
  135516. 7,
  135517. 4,
  135518. 8,
  135519. 3,
  135520. 9,
  135521. 2,
  135522. 10,
  135523. 1,
  135524. 11,
  135525. 0,
  135526. 12,
  135527. };
  135528. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135529. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135530. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135531. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135532. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135533. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135534. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135535. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135536. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135537. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135538. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135539. 19,12,12,12,12,13,13,14,14,
  135540. };
  135541. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135542. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135543. 27.5, 38.5, 49.5, 60.5,
  135544. };
  135545. static long _vq_quantmap__44c9_s_p7_0[] = {
  135546. 11, 9, 7, 5, 3, 1, 0, 2,
  135547. 4, 6, 8, 10, 12,
  135548. };
  135549. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135550. _vq_quantthresh__44c9_s_p7_0,
  135551. _vq_quantmap__44c9_s_p7_0,
  135552. 13,
  135553. 13
  135554. };
  135555. static static_codebook _44c9_s_p7_0 = {
  135556. 2, 169,
  135557. _vq_lengthlist__44c9_s_p7_0,
  135558. 1, -523206656, 1618345984, 4, 0,
  135559. _vq_quantlist__44c9_s_p7_0,
  135560. NULL,
  135561. &_vq_auxt__44c9_s_p7_0,
  135562. NULL,
  135563. 0
  135564. };
  135565. static long _vq_quantlist__44c9_s_p7_1[] = {
  135566. 5,
  135567. 4,
  135568. 6,
  135569. 3,
  135570. 7,
  135571. 2,
  135572. 8,
  135573. 1,
  135574. 9,
  135575. 0,
  135576. 10,
  135577. };
  135578. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135579. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135580. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135581. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135582. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135583. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135584. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135585. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135586. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135587. };
  135588. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135589. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135590. 3.5, 4.5,
  135591. };
  135592. static long _vq_quantmap__44c9_s_p7_1[] = {
  135593. 9, 7, 5, 3, 1, 0, 2, 4,
  135594. 6, 8, 10,
  135595. };
  135596. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135597. _vq_quantthresh__44c9_s_p7_1,
  135598. _vq_quantmap__44c9_s_p7_1,
  135599. 11,
  135600. 11
  135601. };
  135602. static static_codebook _44c9_s_p7_1 = {
  135603. 2, 121,
  135604. _vq_lengthlist__44c9_s_p7_1,
  135605. 1, -531365888, 1611661312, 4, 0,
  135606. _vq_quantlist__44c9_s_p7_1,
  135607. NULL,
  135608. &_vq_auxt__44c9_s_p7_1,
  135609. NULL,
  135610. 0
  135611. };
  135612. static long _vq_quantlist__44c9_s_p8_0[] = {
  135613. 7,
  135614. 6,
  135615. 8,
  135616. 5,
  135617. 9,
  135618. 4,
  135619. 10,
  135620. 3,
  135621. 11,
  135622. 2,
  135623. 12,
  135624. 1,
  135625. 13,
  135626. 0,
  135627. 14,
  135628. };
  135629. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135630. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135631. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135632. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135633. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135634. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135635. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135636. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135637. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135638. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135639. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135640. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135641. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135642. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135643. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135644. 14,
  135645. };
  135646. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135647. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135648. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135649. };
  135650. static long _vq_quantmap__44c9_s_p8_0[] = {
  135651. 13, 11, 9, 7, 5, 3, 1, 0,
  135652. 2, 4, 6, 8, 10, 12, 14,
  135653. };
  135654. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135655. _vq_quantthresh__44c9_s_p8_0,
  135656. _vq_quantmap__44c9_s_p8_0,
  135657. 15,
  135658. 15
  135659. };
  135660. static static_codebook _44c9_s_p8_0 = {
  135661. 2, 225,
  135662. _vq_lengthlist__44c9_s_p8_0,
  135663. 1, -520986624, 1620377600, 4, 0,
  135664. _vq_quantlist__44c9_s_p8_0,
  135665. NULL,
  135666. &_vq_auxt__44c9_s_p8_0,
  135667. NULL,
  135668. 0
  135669. };
  135670. static long _vq_quantlist__44c9_s_p8_1[] = {
  135671. 10,
  135672. 9,
  135673. 11,
  135674. 8,
  135675. 12,
  135676. 7,
  135677. 13,
  135678. 6,
  135679. 14,
  135680. 5,
  135681. 15,
  135682. 4,
  135683. 16,
  135684. 3,
  135685. 17,
  135686. 2,
  135687. 18,
  135688. 1,
  135689. 19,
  135690. 0,
  135691. 20,
  135692. };
  135693. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135694. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135695. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135696. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135697. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135698. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135699. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135700. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135701. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135702. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135703. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135704. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135705. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135706. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135707. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135708. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135709. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135710. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135711. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135712. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135713. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135714. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135715. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135716. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135717. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135718. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135719. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135720. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135721. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135722. };
  135723. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135724. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135725. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135726. 6.5, 7.5, 8.5, 9.5,
  135727. };
  135728. static long _vq_quantmap__44c9_s_p8_1[] = {
  135729. 19, 17, 15, 13, 11, 9, 7, 5,
  135730. 3, 1, 0, 2, 4, 6, 8, 10,
  135731. 12, 14, 16, 18, 20,
  135732. };
  135733. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135734. _vq_quantthresh__44c9_s_p8_1,
  135735. _vq_quantmap__44c9_s_p8_1,
  135736. 21,
  135737. 21
  135738. };
  135739. static static_codebook _44c9_s_p8_1 = {
  135740. 2, 441,
  135741. _vq_lengthlist__44c9_s_p8_1,
  135742. 1, -529268736, 1611661312, 5, 0,
  135743. _vq_quantlist__44c9_s_p8_1,
  135744. NULL,
  135745. &_vq_auxt__44c9_s_p8_1,
  135746. NULL,
  135747. 0
  135748. };
  135749. static long _vq_quantlist__44c9_s_p9_0[] = {
  135750. 9,
  135751. 8,
  135752. 10,
  135753. 7,
  135754. 11,
  135755. 6,
  135756. 12,
  135757. 5,
  135758. 13,
  135759. 4,
  135760. 14,
  135761. 3,
  135762. 15,
  135763. 2,
  135764. 16,
  135765. 1,
  135766. 17,
  135767. 0,
  135768. 18,
  135769. };
  135770. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135771. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135772. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135773. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135774. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135775. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135776. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135777. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135778. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135779. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135780. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135781. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135782. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135783. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135784. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135785. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135786. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135787. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135793. 11,11,11,11,11,11,11,11,11,
  135794. };
  135795. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135796. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135797. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135798. 6982.5, 7913.5,
  135799. };
  135800. static long _vq_quantmap__44c9_s_p9_0[] = {
  135801. 17, 15, 13, 11, 9, 7, 5, 3,
  135802. 1, 0, 2, 4, 6, 8, 10, 12,
  135803. 14, 16, 18,
  135804. };
  135805. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135806. _vq_quantthresh__44c9_s_p9_0,
  135807. _vq_quantmap__44c9_s_p9_0,
  135808. 19,
  135809. 19
  135810. };
  135811. static static_codebook _44c9_s_p9_0 = {
  135812. 2, 361,
  135813. _vq_lengthlist__44c9_s_p9_0,
  135814. 1, -508535424, 1631393792, 5, 0,
  135815. _vq_quantlist__44c9_s_p9_0,
  135816. NULL,
  135817. &_vq_auxt__44c9_s_p9_0,
  135818. NULL,
  135819. 0
  135820. };
  135821. static long _vq_quantlist__44c9_s_p9_1[] = {
  135822. 9,
  135823. 8,
  135824. 10,
  135825. 7,
  135826. 11,
  135827. 6,
  135828. 12,
  135829. 5,
  135830. 13,
  135831. 4,
  135832. 14,
  135833. 3,
  135834. 15,
  135835. 2,
  135836. 16,
  135837. 1,
  135838. 17,
  135839. 0,
  135840. 18,
  135841. };
  135842. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135843. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135844. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135845. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135846. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135847. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135848. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135849. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135850. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135851. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135852. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135853. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135854. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135855. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135856. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135857. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135858. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135859. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135860. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135861. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135862. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135863. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135864. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135865. 13,13,13,14,13,14,15,15,15,
  135866. };
  135867. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135868. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135869. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135870. 367.5, 416.5,
  135871. };
  135872. static long _vq_quantmap__44c9_s_p9_1[] = {
  135873. 17, 15, 13, 11, 9, 7, 5, 3,
  135874. 1, 0, 2, 4, 6, 8, 10, 12,
  135875. 14, 16, 18,
  135876. };
  135877. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135878. _vq_quantthresh__44c9_s_p9_1,
  135879. _vq_quantmap__44c9_s_p9_1,
  135880. 19,
  135881. 19
  135882. };
  135883. static static_codebook _44c9_s_p9_1 = {
  135884. 2, 361,
  135885. _vq_lengthlist__44c9_s_p9_1,
  135886. 1, -518287360, 1622704128, 5, 0,
  135887. _vq_quantlist__44c9_s_p9_1,
  135888. NULL,
  135889. &_vq_auxt__44c9_s_p9_1,
  135890. NULL,
  135891. 0
  135892. };
  135893. static long _vq_quantlist__44c9_s_p9_2[] = {
  135894. 24,
  135895. 23,
  135896. 25,
  135897. 22,
  135898. 26,
  135899. 21,
  135900. 27,
  135901. 20,
  135902. 28,
  135903. 19,
  135904. 29,
  135905. 18,
  135906. 30,
  135907. 17,
  135908. 31,
  135909. 16,
  135910. 32,
  135911. 15,
  135912. 33,
  135913. 14,
  135914. 34,
  135915. 13,
  135916. 35,
  135917. 12,
  135918. 36,
  135919. 11,
  135920. 37,
  135921. 10,
  135922. 38,
  135923. 9,
  135924. 39,
  135925. 8,
  135926. 40,
  135927. 7,
  135928. 41,
  135929. 6,
  135930. 42,
  135931. 5,
  135932. 43,
  135933. 4,
  135934. 44,
  135935. 3,
  135936. 45,
  135937. 2,
  135938. 46,
  135939. 1,
  135940. 47,
  135941. 0,
  135942. 48,
  135943. };
  135944. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135945. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135946. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135947. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135948. 7,
  135949. };
  135950. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135951. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135952. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135953. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135954. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135955. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135956. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135957. };
  135958. static long _vq_quantmap__44c9_s_p9_2[] = {
  135959. 47, 45, 43, 41, 39, 37, 35, 33,
  135960. 31, 29, 27, 25, 23, 21, 19, 17,
  135961. 15, 13, 11, 9, 7, 5, 3, 1,
  135962. 0, 2, 4, 6, 8, 10, 12, 14,
  135963. 16, 18, 20, 22, 24, 26, 28, 30,
  135964. 32, 34, 36, 38, 40, 42, 44, 46,
  135965. 48,
  135966. };
  135967. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135968. _vq_quantthresh__44c9_s_p9_2,
  135969. _vq_quantmap__44c9_s_p9_2,
  135970. 49,
  135971. 49
  135972. };
  135973. static static_codebook _44c9_s_p9_2 = {
  135974. 1, 49,
  135975. _vq_lengthlist__44c9_s_p9_2,
  135976. 1, -526909440, 1611661312, 6, 0,
  135977. _vq_quantlist__44c9_s_p9_2,
  135978. NULL,
  135979. &_vq_auxt__44c9_s_p9_2,
  135980. NULL,
  135981. 0
  135982. };
  135983. static long _huff_lengthlist__44c9_s_short[] = {
  135984. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135985. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135986. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135987. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135988. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135989. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135990. 9, 8,10,13,
  135991. };
  135992. static static_codebook _huff_book__44c9_s_short = {
  135993. 2, 100,
  135994. _huff_lengthlist__44c9_s_short,
  135995. 0, 0, 0, 0, 0,
  135996. NULL,
  135997. NULL,
  135998. NULL,
  135999. NULL,
  136000. 0
  136001. };
  136002. static long _huff_lengthlist__44c0_s_long[] = {
  136003. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  136004. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136005. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136006. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136007. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136008. 12,
  136009. };
  136010. static static_codebook _huff_book__44c0_s_long = {
  136011. 2, 81,
  136012. _huff_lengthlist__44c0_s_long,
  136013. 0, 0, 0, 0, 0,
  136014. NULL,
  136015. NULL,
  136016. NULL,
  136017. NULL,
  136018. 0
  136019. };
  136020. static long _vq_quantlist__44c0_s_p1_0[] = {
  136021. 1,
  136022. 0,
  136023. 2,
  136024. };
  136025. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136026. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136027. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136032. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136037. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136072. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136077. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  136082. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136117. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136118. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136123. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136128. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136436. 0,
  136437. };
  136438. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136439. -0.5, 0.5,
  136440. };
  136441. static long _vq_quantmap__44c0_s_p1_0[] = {
  136442. 1, 0, 2,
  136443. };
  136444. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136445. _vq_quantthresh__44c0_s_p1_0,
  136446. _vq_quantmap__44c0_s_p1_0,
  136447. 3,
  136448. 3
  136449. };
  136450. static static_codebook _44c0_s_p1_0 = {
  136451. 8, 6561,
  136452. _vq_lengthlist__44c0_s_p1_0,
  136453. 1, -535822336, 1611661312, 2, 0,
  136454. _vq_quantlist__44c0_s_p1_0,
  136455. NULL,
  136456. &_vq_auxt__44c0_s_p1_0,
  136457. NULL,
  136458. 0
  136459. };
  136460. static long _vq_quantlist__44c0_s_p2_0[] = {
  136461. 2,
  136462. 1,
  136463. 3,
  136464. 0,
  136465. 4,
  136466. };
  136467. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136468. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136474. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0,
  136508. };
  136509. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136510. -1.5, -0.5, 0.5, 1.5,
  136511. };
  136512. static long _vq_quantmap__44c0_s_p2_0[] = {
  136513. 3, 1, 0, 2, 4,
  136514. };
  136515. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136516. _vq_quantthresh__44c0_s_p2_0,
  136517. _vq_quantmap__44c0_s_p2_0,
  136518. 5,
  136519. 5
  136520. };
  136521. static static_codebook _44c0_s_p2_0 = {
  136522. 4, 625,
  136523. _vq_lengthlist__44c0_s_p2_0,
  136524. 1, -533725184, 1611661312, 3, 0,
  136525. _vq_quantlist__44c0_s_p2_0,
  136526. NULL,
  136527. &_vq_auxt__44c0_s_p2_0,
  136528. NULL,
  136529. 0
  136530. };
  136531. static long _vq_quantlist__44c0_s_p3_0[] = {
  136532. 4,
  136533. 3,
  136534. 5,
  136535. 2,
  136536. 6,
  136537. 1,
  136538. 7,
  136539. 0,
  136540. 8,
  136541. };
  136542. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136543. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136544. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136545. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136546. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136547. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0,
  136549. };
  136550. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136551. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136552. };
  136553. static long _vq_quantmap__44c0_s_p3_0[] = {
  136554. 7, 5, 3, 1, 0, 2, 4, 6,
  136555. 8,
  136556. };
  136557. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136558. _vq_quantthresh__44c0_s_p3_0,
  136559. _vq_quantmap__44c0_s_p3_0,
  136560. 9,
  136561. 9
  136562. };
  136563. static static_codebook _44c0_s_p3_0 = {
  136564. 2, 81,
  136565. _vq_lengthlist__44c0_s_p3_0,
  136566. 1, -531628032, 1611661312, 4, 0,
  136567. _vq_quantlist__44c0_s_p3_0,
  136568. NULL,
  136569. &_vq_auxt__44c0_s_p3_0,
  136570. NULL,
  136571. 0
  136572. };
  136573. static long _vq_quantlist__44c0_s_p4_0[] = {
  136574. 4,
  136575. 3,
  136576. 5,
  136577. 2,
  136578. 6,
  136579. 1,
  136580. 7,
  136581. 0,
  136582. 8,
  136583. };
  136584. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136585. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136586. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136587. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136588. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136589. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136590. 10,
  136591. };
  136592. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136593. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136594. };
  136595. static long _vq_quantmap__44c0_s_p4_0[] = {
  136596. 7, 5, 3, 1, 0, 2, 4, 6,
  136597. 8,
  136598. };
  136599. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136600. _vq_quantthresh__44c0_s_p4_0,
  136601. _vq_quantmap__44c0_s_p4_0,
  136602. 9,
  136603. 9
  136604. };
  136605. static static_codebook _44c0_s_p4_0 = {
  136606. 2, 81,
  136607. _vq_lengthlist__44c0_s_p4_0,
  136608. 1, -531628032, 1611661312, 4, 0,
  136609. _vq_quantlist__44c0_s_p4_0,
  136610. NULL,
  136611. &_vq_auxt__44c0_s_p4_0,
  136612. NULL,
  136613. 0
  136614. };
  136615. static long _vq_quantlist__44c0_s_p5_0[] = {
  136616. 8,
  136617. 7,
  136618. 9,
  136619. 6,
  136620. 10,
  136621. 5,
  136622. 11,
  136623. 4,
  136624. 12,
  136625. 3,
  136626. 13,
  136627. 2,
  136628. 14,
  136629. 1,
  136630. 15,
  136631. 0,
  136632. 16,
  136633. };
  136634. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136635. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136636. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136637. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136638. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136639. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136640. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136641. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136642. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136643. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136644. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136645. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136646. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136647. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136648. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136649. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136650. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136651. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136653. 14,
  136654. };
  136655. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136656. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136657. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136658. };
  136659. static long _vq_quantmap__44c0_s_p5_0[] = {
  136660. 15, 13, 11, 9, 7, 5, 3, 1,
  136661. 0, 2, 4, 6, 8, 10, 12, 14,
  136662. 16,
  136663. };
  136664. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136665. _vq_quantthresh__44c0_s_p5_0,
  136666. _vq_quantmap__44c0_s_p5_0,
  136667. 17,
  136668. 17
  136669. };
  136670. static static_codebook _44c0_s_p5_0 = {
  136671. 2, 289,
  136672. _vq_lengthlist__44c0_s_p5_0,
  136673. 1, -529530880, 1611661312, 5, 0,
  136674. _vq_quantlist__44c0_s_p5_0,
  136675. NULL,
  136676. &_vq_auxt__44c0_s_p5_0,
  136677. NULL,
  136678. 0
  136679. };
  136680. static long _vq_quantlist__44c0_s_p6_0[] = {
  136681. 1,
  136682. 0,
  136683. 2,
  136684. };
  136685. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136686. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136687. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136688. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136689. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136690. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136691. 10,
  136692. };
  136693. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136694. -5.5, 5.5,
  136695. };
  136696. static long _vq_quantmap__44c0_s_p6_0[] = {
  136697. 1, 0, 2,
  136698. };
  136699. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136700. _vq_quantthresh__44c0_s_p6_0,
  136701. _vq_quantmap__44c0_s_p6_0,
  136702. 3,
  136703. 3
  136704. };
  136705. static static_codebook _44c0_s_p6_0 = {
  136706. 4, 81,
  136707. _vq_lengthlist__44c0_s_p6_0,
  136708. 1, -529137664, 1618345984, 2, 0,
  136709. _vq_quantlist__44c0_s_p6_0,
  136710. NULL,
  136711. &_vq_auxt__44c0_s_p6_0,
  136712. NULL,
  136713. 0
  136714. };
  136715. static long _vq_quantlist__44c0_s_p6_1[] = {
  136716. 5,
  136717. 4,
  136718. 6,
  136719. 3,
  136720. 7,
  136721. 2,
  136722. 8,
  136723. 1,
  136724. 9,
  136725. 0,
  136726. 10,
  136727. };
  136728. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136729. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136730. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136731. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136732. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136733. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136734. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136735. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136736. 10,10,10, 8, 8, 8, 8, 8, 8,
  136737. };
  136738. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136739. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136740. 3.5, 4.5,
  136741. };
  136742. static long _vq_quantmap__44c0_s_p6_1[] = {
  136743. 9, 7, 5, 3, 1, 0, 2, 4,
  136744. 6, 8, 10,
  136745. };
  136746. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136747. _vq_quantthresh__44c0_s_p6_1,
  136748. _vq_quantmap__44c0_s_p6_1,
  136749. 11,
  136750. 11
  136751. };
  136752. static static_codebook _44c0_s_p6_1 = {
  136753. 2, 121,
  136754. _vq_lengthlist__44c0_s_p6_1,
  136755. 1, -531365888, 1611661312, 4, 0,
  136756. _vq_quantlist__44c0_s_p6_1,
  136757. NULL,
  136758. &_vq_auxt__44c0_s_p6_1,
  136759. NULL,
  136760. 0
  136761. };
  136762. static long _vq_quantlist__44c0_s_p7_0[] = {
  136763. 6,
  136764. 5,
  136765. 7,
  136766. 4,
  136767. 8,
  136768. 3,
  136769. 9,
  136770. 2,
  136771. 10,
  136772. 1,
  136773. 11,
  136774. 0,
  136775. 12,
  136776. };
  136777. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136778. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136779. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136780. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136781. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136782. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136783. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136784. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136785. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136786. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136787. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136788. 0,12,12,11,11,12,12,13,13,
  136789. };
  136790. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136791. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136792. 12.5, 17.5, 22.5, 27.5,
  136793. };
  136794. static long _vq_quantmap__44c0_s_p7_0[] = {
  136795. 11, 9, 7, 5, 3, 1, 0, 2,
  136796. 4, 6, 8, 10, 12,
  136797. };
  136798. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136799. _vq_quantthresh__44c0_s_p7_0,
  136800. _vq_quantmap__44c0_s_p7_0,
  136801. 13,
  136802. 13
  136803. };
  136804. static static_codebook _44c0_s_p7_0 = {
  136805. 2, 169,
  136806. _vq_lengthlist__44c0_s_p7_0,
  136807. 1, -526516224, 1616117760, 4, 0,
  136808. _vq_quantlist__44c0_s_p7_0,
  136809. NULL,
  136810. &_vq_auxt__44c0_s_p7_0,
  136811. NULL,
  136812. 0
  136813. };
  136814. static long _vq_quantlist__44c0_s_p7_1[] = {
  136815. 2,
  136816. 1,
  136817. 3,
  136818. 0,
  136819. 4,
  136820. };
  136821. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136822. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136823. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136824. };
  136825. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136826. -1.5, -0.5, 0.5, 1.5,
  136827. };
  136828. static long _vq_quantmap__44c0_s_p7_1[] = {
  136829. 3, 1, 0, 2, 4,
  136830. };
  136831. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136832. _vq_quantthresh__44c0_s_p7_1,
  136833. _vq_quantmap__44c0_s_p7_1,
  136834. 5,
  136835. 5
  136836. };
  136837. static static_codebook _44c0_s_p7_1 = {
  136838. 2, 25,
  136839. _vq_lengthlist__44c0_s_p7_1,
  136840. 1, -533725184, 1611661312, 3, 0,
  136841. _vq_quantlist__44c0_s_p7_1,
  136842. NULL,
  136843. &_vq_auxt__44c0_s_p7_1,
  136844. NULL,
  136845. 0
  136846. };
  136847. static long _vq_quantlist__44c0_s_p8_0[] = {
  136848. 2,
  136849. 1,
  136850. 3,
  136851. 0,
  136852. 4,
  136853. };
  136854. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136855. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136856. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136857. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136858. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136859. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136860. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136861. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136862. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136863. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136864. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136865. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136866. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136867. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136868. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136869. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136870. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136871. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136872. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136873. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136874. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136875. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136876. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136877. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136881. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136882. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136883. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136884. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136885. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136886. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136887. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136888. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136889. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136890. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136891. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136892. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136893. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136894. 11,
  136895. };
  136896. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136897. -331.5, -110.5, 110.5, 331.5,
  136898. };
  136899. static long _vq_quantmap__44c0_s_p8_0[] = {
  136900. 3, 1, 0, 2, 4,
  136901. };
  136902. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136903. _vq_quantthresh__44c0_s_p8_0,
  136904. _vq_quantmap__44c0_s_p8_0,
  136905. 5,
  136906. 5
  136907. };
  136908. static static_codebook _44c0_s_p8_0 = {
  136909. 4, 625,
  136910. _vq_lengthlist__44c0_s_p8_0,
  136911. 1, -518283264, 1627103232, 3, 0,
  136912. _vq_quantlist__44c0_s_p8_0,
  136913. NULL,
  136914. &_vq_auxt__44c0_s_p8_0,
  136915. NULL,
  136916. 0
  136917. };
  136918. static long _vq_quantlist__44c0_s_p8_1[] = {
  136919. 6,
  136920. 5,
  136921. 7,
  136922. 4,
  136923. 8,
  136924. 3,
  136925. 9,
  136926. 2,
  136927. 10,
  136928. 1,
  136929. 11,
  136930. 0,
  136931. 12,
  136932. };
  136933. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136934. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136935. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136936. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136937. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136938. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136939. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136940. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136941. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136942. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136943. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136944. 16,13,13,12,12,14,14,15,13,
  136945. };
  136946. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136947. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136948. 42.5, 59.5, 76.5, 93.5,
  136949. };
  136950. static long _vq_quantmap__44c0_s_p8_1[] = {
  136951. 11, 9, 7, 5, 3, 1, 0, 2,
  136952. 4, 6, 8, 10, 12,
  136953. };
  136954. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136955. _vq_quantthresh__44c0_s_p8_1,
  136956. _vq_quantmap__44c0_s_p8_1,
  136957. 13,
  136958. 13
  136959. };
  136960. static static_codebook _44c0_s_p8_1 = {
  136961. 2, 169,
  136962. _vq_lengthlist__44c0_s_p8_1,
  136963. 1, -522616832, 1620115456, 4, 0,
  136964. _vq_quantlist__44c0_s_p8_1,
  136965. NULL,
  136966. &_vq_auxt__44c0_s_p8_1,
  136967. NULL,
  136968. 0
  136969. };
  136970. static long _vq_quantlist__44c0_s_p8_2[] = {
  136971. 8,
  136972. 7,
  136973. 9,
  136974. 6,
  136975. 10,
  136976. 5,
  136977. 11,
  136978. 4,
  136979. 12,
  136980. 3,
  136981. 13,
  136982. 2,
  136983. 14,
  136984. 1,
  136985. 15,
  136986. 0,
  136987. 16,
  136988. };
  136989. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136990. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136991. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136992. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136993. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136994. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136995. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136996. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136997. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136998. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136999. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  137000. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  137001. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137002. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  137003. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  137004. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137005. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137006. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137007. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137008. 10,
  137009. };
  137010. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137011. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137012. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137013. };
  137014. static long _vq_quantmap__44c0_s_p8_2[] = {
  137015. 15, 13, 11, 9, 7, 5, 3, 1,
  137016. 0, 2, 4, 6, 8, 10, 12, 14,
  137017. 16,
  137018. };
  137019. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137020. _vq_quantthresh__44c0_s_p8_2,
  137021. _vq_quantmap__44c0_s_p8_2,
  137022. 17,
  137023. 17
  137024. };
  137025. static static_codebook _44c0_s_p8_2 = {
  137026. 2, 289,
  137027. _vq_lengthlist__44c0_s_p8_2,
  137028. 1, -529530880, 1611661312, 5, 0,
  137029. _vq_quantlist__44c0_s_p8_2,
  137030. NULL,
  137031. &_vq_auxt__44c0_s_p8_2,
  137032. NULL,
  137033. 0
  137034. };
  137035. static long _huff_lengthlist__44c0_s_short[] = {
  137036. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137037. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137038. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137039. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137040. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137041. 12,
  137042. };
  137043. static static_codebook _huff_book__44c0_s_short = {
  137044. 2, 81,
  137045. _huff_lengthlist__44c0_s_short,
  137046. 0, 0, 0, 0, 0,
  137047. NULL,
  137048. NULL,
  137049. NULL,
  137050. NULL,
  137051. 0
  137052. };
  137053. static long _huff_lengthlist__44c0_sm_long[] = {
  137054. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137055. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137056. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137057. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137058. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137059. 13,
  137060. };
  137061. static static_codebook _huff_book__44c0_sm_long = {
  137062. 2, 81,
  137063. _huff_lengthlist__44c0_sm_long,
  137064. 0, 0, 0, 0, 0,
  137065. NULL,
  137066. NULL,
  137067. NULL,
  137068. NULL,
  137069. 0
  137070. };
  137071. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137072. 1,
  137073. 0,
  137074. 2,
  137075. };
  137076. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137077. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137078. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137083. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137088. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137123. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137128. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137133. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137169. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137174. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137179. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137487. 0,
  137488. };
  137489. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137490. -0.5, 0.5,
  137491. };
  137492. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137493. 1, 0, 2,
  137494. };
  137495. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137496. _vq_quantthresh__44c0_sm_p1_0,
  137497. _vq_quantmap__44c0_sm_p1_0,
  137498. 3,
  137499. 3
  137500. };
  137501. static static_codebook _44c0_sm_p1_0 = {
  137502. 8, 6561,
  137503. _vq_lengthlist__44c0_sm_p1_0,
  137504. 1, -535822336, 1611661312, 2, 0,
  137505. _vq_quantlist__44c0_sm_p1_0,
  137506. NULL,
  137507. &_vq_auxt__44c0_sm_p1_0,
  137508. NULL,
  137509. 0
  137510. };
  137511. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137512. 2,
  137513. 1,
  137514. 3,
  137515. 0,
  137516. 4,
  137517. };
  137518. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137519. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137525. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0,
  137559. };
  137560. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137561. -1.5, -0.5, 0.5, 1.5,
  137562. };
  137563. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137564. 3, 1, 0, 2, 4,
  137565. };
  137566. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137567. _vq_quantthresh__44c0_sm_p2_0,
  137568. _vq_quantmap__44c0_sm_p2_0,
  137569. 5,
  137570. 5
  137571. };
  137572. static static_codebook _44c0_sm_p2_0 = {
  137573. 4, 625,
  137574. _vq_lengthlist__44c0_sm_p2_0,
  137575. 1, -533725184, 1611661312, 3, 0,
  137576. _vq_quantlist__44c0_sm_p2_0,
  137577. NULL,
  137578. &_vq_auxt__44c0_sm_p2_0,
  137579. NULL,
  137580. 0
  137581. };
  137582. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137583. 4,
  137584. 3,
  137585. 5,
  137586. 2,
  137587. 6,
  137588. 1,
  137589. 7,
  137590. 0,
  137591. 8,
  137592. };
  137593. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137594. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137595. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137596. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137597. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137598. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0,
  137600. };
  137601. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137602. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137603. };
  137604. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137605. 7, 5, 3, 1, 0, 2, 4, 6,
  137606. 8,
  137607. };
  137608. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137609. _vq_quantthresh__44c0_sm_p3_0,
  137610. _vq_quantmap__44c0_sm_p3_0,
  137611. 9,
  137612. 9
  137613. };
  137614. static static_codebook _44c0_sm_p3_0 = {
  137615. 2, 81,
  137616. _vq_lengthlist__44c0_sm_p3_0,
  137617. 1, -531628032, 1611661312, 4, 0,
  137618. _vq_quantlist__44c0_sm_p3_0,
  137619. NULL,
  137620. &_vq_auxt__44c0_sm_p3_0,
  137621. NULL,
  137622. 0
  137623. };
  137624. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137625. 4,
  137626. 3,
  137627. 5,
  137628. 2,
  137629. 6,
  137630. 1,
  137631. 7,
  137632. 0,
  137633. 8,
  137634. };
  137635. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137636. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137637. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137638. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137639. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137640. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137641. 11,
  137642. };
  137643. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137644. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137645. };
  137646. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137647. 7, 5, 3, 1, 0, 2, 4, 6,
  137648. 8,
  137649. };
  137650. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137651. _vq_quantthresh__44c0_sm_p4_0,
  137652. _vq_quantmap__44c0_sm_p4_0,
  137653. 9,
  137654. 9
  137655. };
  137656. static static_codebook _44c0_sm_p4_0 = {
  137657. 2, 81,
  137658. _vq_lengthlist__44c0_sm_p4_0,
  137659. 1, -531628032, 1611661312, 4, 0,
  137660. _vq_quantlist__44c0_sm_p4_0,
  137661. NULL,
  137662. &_vq_auxt__44c0_sm_p4_0,
  137663. NULL,
  137664. 0
  137665. };
  137666. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137667. 8,
  137668. 7,
  137669. 9,
  137670. 6,
  137671. 10,
  137672. 5,
  137673. 11,
  137674. 4,
  137675. 12,
  137676. 3,
  137677. 13,
  137678. 2,
  137679. 14,
  137680. 1,
  137681. 15,
  137682. 0,
  137683. 16,
  137684. };
  137685. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137686. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137687. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137688. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137689. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137690. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137691. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137692. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137693. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137694. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137695. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137696. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137697. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137698. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137699. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137700. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137701. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137702. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137704. 14,
  137705. };
  137706. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137707. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137708. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137709. };
  137710. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137711. 15, 13, 11, 9, 7, 5, 3, 1,
  137712. 0, 2, 4, 6, 8, 10, 12, 14,
  137713. 16,
  137714. };
  137715. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137716. _vq_quantthresh__44c0_sm_p5_0,
  137717. _vq_quantmap__44c0_sm_p5_0,
  137718. 17,
  137719. 17
  137720. };
  137721. static static_codebook _44c0_sm_p5_0 = {
  137722. 2, 289,
  137723. _vq_lengthlist__44c0_sm_p5_0,
  137724. 1, -529530880, 1611661312, 5, 0,
  137725. _vq_quantlist__44c0_sm_p5_0,
  137726. NULL,
  137727. &_vq_auxt__44c0_sm_p5_0,
  137728. NULL,
  137729. 0
  137730. };
  137731. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137732. 1,
  137733. 0,
  137734. 2,
  137735. };
  137736. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137737. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137738. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137739. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137740. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137741. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137742. 11,
  137743. };
  137744. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137745. -5.5, 5.5,
  137746. };
  137747. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137748. 1, 0, 2,
  137749. };
  137750. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137751. _vq_quantthresh__44c0_sm_p6_0,
  137752. _vq_quantmap__44c0_sm_p6_0,
  137753. 3,
  137754. 3
  137755. };
  137756. static static_codebook _44c0_sm_p6_0 = {
  137757. 4, 81,
  137758. _vq_lengthlist__44c0_sm_p6_0,
  137759. 1, -529137664, 1618345984, 2, 0,
  137760. _vq_quantlist__44c0_sm_p6_0,
  137761. NULL,
  137762. &_vq_auxt__44c0_sm_p6_0,
  137763. NULL,
  137764. 0
  137765. };
  137766. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137767. 5,
  137768. 4,
  137769. 6,
  137770. 3,
  137771. 7,
  137772. 2,
  137773. 8,
  137774. 1,
  137775. 9,
  137776. 0,
  137777. 10,
  137778. };
  137779. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137780. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137781. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137782. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137783. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137784. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137785. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137786. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137787. 10,10,10, 8, 8, 8, 8, 8, 8,
  137788. };
  137789. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137790. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137791. 3.5, 4.5,
  137792. };
  137793. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137794. 9, 7, 5, 3, 1, 0, 2, 4,
  137795. 6, 8, 10,
  137796. };
  137797. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137798. _vq_quantthresh__44c0_sm_p6_1,
  137799. _vq_quantmap__44c0_sm_p6_1,
  137800. 11,
  137801. 11
  137802. };
  137803. static static_codebook _44c0_sm_p6_1 = {
  137804. 2, 121,
  137805. _vq_lengthlist__44c0_sm_p6_1,
  137806. 1, -531365888, 1611661312, 4, 0,
  137807. _vq_quantlist__44c0_sm_p6_1,
  137808. NULL,
  137809. &_vq_auxt__44c0_sm_p6_1,
  137810. NULL,
  137811. 0
  137812. };
  137813. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137814. 6,
  137815. 5,
  137816. 7,
  137817. 4,
  137818. 8,
  137819. 3,
  137820. 9,
  137821. 2,
  137822. 10,
  137823. 1,
  137824. 11,
  137825. 0,
  137826. 12,
  137827. };
  137828. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137829. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137830. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137831. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137832. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137833. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137834. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137835. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137836. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137837. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137838. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137839. 0,12,12,11,11,13,12,14,14,
  137840. };
  137841. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137842. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137843. 12.5, 17.5, 22.5, 27.5,
  137844. };
  137845. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137846. 11, 9, 7, 5, 3, 1, 0, 2,
  137847. 4, 6, 8, 10, 12,
  137848. };
  137849. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137850. _vq_quantthresh__44c0_sm_p7_0,
  137851. _vq_quantmap__44c0_sm_p7_0,
  137852. 13,
  137853. 13
  137854. };
  137855. static static_codebook _44c0_sm_p7_0 = {
  137856. 2, 169,
  137857. _vq_lengthlist__44c0_sm_p7_0,
  137858. 1, -526516224, 1616117760, 4, 0,
  137859. _vq_quantlist__44c0_sm_p7_0,
  137860. NULL,
  137861. &_vq_auxt__44c0_sm_p7_0,
  137862. NULL,
  137863. 0
  137864. };
  137865. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137866. 2,
  137867. 1,
  137868. 3,
  137869. 0,
  137870. 4,
  137871. };
  137872. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137873. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137874. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137875. };
  137876. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137877. -1.5, -0.5, 0.5, 1.5,
  137878. };
  137879. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137880. 3, 1, 0, 2, 4,
  137881. };
  137882. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137883. _vq_quantthresh__44c0_sm_p7_1,
  137884. _vq_quantmap__44c0_sm_p7_1,
  137885. 5,
  137886. 5
  137887. };
  137888. static static_codebook _44c0_sm_p7_1 = {
  137889. 2, 25,
  137890. _vq_lengthlist__44c0_sm_p7_1,
  137891. 1, -533725184, 1611661312, 3, 0,
  137892. _vq_quantlist__44c0_sm_p7_1,
  137893. NULL,
  137894. &_vq_auxt__44c0_sm_p7_1,
  137895. NULL,
  137896. 0
  137897. };
  137898. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137899. 4,
  137900. 3,
  137901. 5,
  137902. 2,
  137903. 6,
  137904. 1,
  137905. 7,
  137906. 0,
  137907. 8,
  137908. };
  137909. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137910. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137911. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137912. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137913. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137914. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137915. 12,
  137916. };
  137917. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137918. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137919. };
  137920. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137921. 7, 5, 3, 1, 0, 2, 4, 6,
  137922. 8,
  137923. };
  137924. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137925. _vq_quantthresh__44c0_sm_p8_0,
  137926. _vq_quantmap__44c0_sm_p8_0,
  137927. 9,
  137928. 9
  137929. };
  137930. static static_codebook _44c0_sm_p8_0 = {
  137931. 2, 81,
  137932. _vq_lengthlist__44c0_sm_p8_0,
  137933. 1, -516186112, 1627103232, 4, 0,
  137934. _vq_quantlist__44c0_sm_p8_0,
  137935. NULL,
  137936. &_vq_auxt__44c0_sm_p8_0,
  137937. NULL,
  137938. 0
  137939. };
  137940. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137941. 6,
  137942. 5,
  137943. 7,
  137944. 4,
  137945. 8,
  137946. 3,
  137947. 9,
  137948. 2,
  137949. 10,
  137950. 1,
  137951. 11,
  137952. 0,
  137953. 12,
  137954. };
  137955. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137956. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137957. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137958. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137959. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137960. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137961. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137962. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137963. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137964. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137965. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137966. 20,13,13,12,12,16,13,15,13,
  137967. };
  137968. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137969. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137970. 42.5, 59.5, 76.5, 93.5,
  137971. };
  137972. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137973. 11, 9, 7, 5, 3, 1, 0, 2,
  137974. 4, 6, 8, 10, 12,
  137975. };
  137976. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137977. _vq_quantthresh__44c0_sm_p8_1,
  137978. _vq_quantmap__44c0_sm_p8_1,
  137979. 13,
  137980. 13
  137981. };
  137982. static static_codebook _44c0_sm_p8_1 = {
  137983. 2, 169,
  137984. _vq_lengthlist__44c0_sm_p8_1,
  137985. 1, -522616832, 1620115456, 4, 0,
  137986. _vq_quantlist__44c0_sm_p8_1,
  137987. NULL,
  137988. &_vq_auxt__44c0_sm_p8_1,
  137989. NULL,
  137990. 0
  137991. };
  137992. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137993. 8,
  137994. 7,
  137995. 9,
  137996. 6,
  137997. 10,
  137998. 5,
  137999. 11,
  138000. 4,
  138001. 12,
  138002. 3,
  138003. 13,
  138004. 2,
  138005. 14,
  138006. 1,
  138007. 15,
  138008. 0,
  138009. 16,
  138010. };
  138011. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138012. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138013. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138014. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138015. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138016. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138017. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138018. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138019. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138020. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138021. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138022. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138023. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138024. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138025. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138026. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138027. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138028. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138029. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138030. 9,
  138031. };
  138032. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138033. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138034. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138035. };
  138036. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138037. 15, 13, 11, 9, 7, 5, 3, 1,
  138038. 0, 2, 4, 6, 8, 10, 12, 14,
  138039. 16,
  138040. };
  138041. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138042. _vq_quantthresh__44c0_sm_p8_2,
  138043. _vq_quantmap__44c0_sm_p8_2,
  138044. 17,
  138045. 17
  138046. };
  138047. static static_codebook _44c0_sm_p8_2 = {
  138048. 2, 289,
  138049. _vq_lengthlist__44c0_sm_p8_2,
  138050. 1, -529530880, 1611661312, 5, 0,
  138051. _vq_quantlist__44c0_sm_p8_2,
  138052. NULL,
  138053. &_vq_auxt__44c0_sm_p8_2,
  138054. NULL,
  138055. 0
  138056. };
  138057. static long _huff_lengthlist__44c0_sm_short[] = {
  138058. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138059. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138060. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138061. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138062. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138063. 12,
  138064. };
  138065. static static_codebook _huff_book__44c0_sm_short = {
  138066. 2, 81,
  138067. _huff_lengthlist__44c0_sm_short,
  138068. 0, 0, 0, 0, 0,
  138069. NULL,
  138070. NULL,
  138071. NULL,
  138072. NULL,
  138073. 0
  138074. };
  138075. static long _huff_lengthlist__44c1_s_long[] = {
  138076. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138077. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138078. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138079. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138080. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138081. 11,
  138082. };
  138083. static static_codebook _huff_book__44c1_s_long = {
  138084. 2, 81,
  138085. _huff_lengthlist__44c1_s_long,
  138086. 0, 0, 0, 0, 0,
  138087. NULL,
  138088. NULL,
  138089. NULL,
  138090. NULL,
  138091. 0
  138092. };
  138093. static long _vq_quantlist__44c1_s_p1_0[] = {
  138094. 1,
  138095. 0,
  138096. 2,
  138097. };
  138098. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138099. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138100. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138104. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138105. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138110. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  138145. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138150. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  138155. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138191. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138196. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138201. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138509. 0,
  138510. };
  138511. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138512. -0.5, 0.5,
  138513. };
  138514. static long _vq_quantmap__44c1_s_p1_0[] = {
  138515. 1, 0, 2,
  138516. };
  138517. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138518. _vq_quantthresh__44c1_s_p1_0,
  138519. _vq_quantmap__44c1_s_p1_0,
  138520. 3,
  138521. 3
  138522. };
  138523. static static_codebook _44c1_s_p1_0 = {
  138524. 8, 6561,
  138525. _vq_lengthlist__44c1_s_p1_0,
  138526. 1, -535822336, 1611661312, 2, 0,
  138527. _vq_quantlist__44c1_s_p1_0,
  138528. NULL,
  138529. &_vq_auxt__44c1_s_p1_0,
  138530. NULL,
  138531. 0
  138532. };
  138533. static long _vq_quantlist__44c1_s_p2_0[] = {
  138534. 2,
  138535. 1,
  138536. 3,
  138537. 0,
  138538. 4,
  138539. };
  138540. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138541. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138547. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0,
  138581. };
  138582. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138583. -1.5, -0.5, 0.5, 1.5,
  138584. };
  138585. static long _vq_quantmap__44c1_s_p2_0[] = {
  138586. 3, 1, 0, 2, 4,
  138587. };
  138588. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138589. _vq_quantthresh__44c1_s_p2_0,
  138590. _vq_quantmap__44c1_s_p2_0,
  138591. 5,
  138592. 5
  138593. };
  138594. static static_codebook _44c1_s_p2_0 = {
  138595. 4, 625,
  138596. _vq_lengthlist__44c1_s_p2_0,
  138597. 1, -533725184, 1611661312, 3, 0,
  138598. _vq_quantlist__44c1_s_p2_0,
  138599. NULL,
  138600. &_vq_auxt__44c1_s_p2_0,
  138601. NULL,
  138602. 0
  138603. };
  138604. static long _vq_quantlist__44c1_s_p3_0[] = {
  138605. 4,
  138606. 3,
  138607. 5,
  138608. 2,
  138609. 6,
  138610. 1,
  138611. 7,
  138612. 0,
  138613. 8,
  138614. };
  138615. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138616. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138617. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138618. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138619. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138620. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0,
  138622. };
  138623. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138624. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138625. };
  138626. static long _vq_quantmap__44c1_s_p3_0[] = {
  138627. 7, 5, 3, 1, 0, 2, 4, 6,
  138628. 8,
  138629. };
  138630. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138631. _vq_quantthresh__44c1_s_p3_0,
  138632. _vq_quantmap__44c1_s_p3_0,
  138633. 9,
  138634. 9
  138635. };
  138636. static static_codebook _44c1_s_p3_0 = {
  138637. 2, 81,
  138638. _vq_lengthlist__44c1_s_p3_0,
  138639. 1, -531628032, 1611661312, 4, 0,
  138640. _vq_quantlist__44c1_s_p3_0,
  138641. NULL,
  138642. &_vq_auxt__44c1_s_p3_0,
  138643. NULL,
  138644. 0
  138645. };
  138646. static long _vq_quantlist__44c1_s_p4_0[] = {
  138647. 4,
  138648. 3,
  138649. 5,
  138650. 2,
  138651. 6,
  138652. 1,
  138653. 7,
  138654. 0,
  138655. 8,
  138656. };
  138657. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138658. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138659. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138660. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138661. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138662. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138663. 11,
  138664. };
  138665. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138666. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138667. };
  138668. static long _vq_quantmap__44c1_s_p4_0[] = {
  138669. 7, 5, 3, 1, 0, 2, 4, 6,
  138670. 8,
  138671. };
  138672. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138673. _vq_quantthresh__44c1_s_p4_0,
  138674. _vq_quantmap__44c1_s_p4_0,
  138675. 9,
  138676. 9
  138677. };
  138678. static static_codebook _44c1_s_p4_0 = {
  138679. 2, 81,
  138680. _vq_lengthlist__44c1_s_p4_0,
  138681. 1, -531628032, 1611661312, 4, 0,
  138682. _vq_quantlist__44c1_s_p4_0,
  138683. NULL,
  138684. &_vq_auxt__44c1_s_p4_0,
  138685. NULL,
  138686. 0
  138687. };
  138688. static long _vq_quantlist__44c1_s_p5_0[] = {
  138689. 8,
  138690. 7,
  138691. 9,
  138692. 6,
  138693. 10,
  138694. 5,
  138695. 11,
  138696. 4,
  138697. 12,
  138698. 3,
  138699. 13,
  138700. 2,
  138701. 14,
  138702. 1,
  138703. 15,
  138704. 0,
  138705. 16,
  138706. };
  138707. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138708. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138709. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138710. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138711. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138712. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138713. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138714. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138715. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138716. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138717. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138718. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138719. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138720. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138721. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138722. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138723. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138724. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138726. 14,
  138727. };
  138728. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138729. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138730. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138731. };
  138732. static long _vq_quantmap__44c1_s_p5_0[] = {
  138733. 15, 13, 11, 9, 7, 5, 3, 1,
  138734. 0, 2, 4, 6, 8, 10, 12, 14,
  138735. 16,
  138736. };
  138737. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138738. _vq_quantthresh__44c1_s_p5_0,
  138739. _vq_quantmap__44c1_s_p5_0,
  138740. 17,
  138741. 17
  138742. };
  138743. static static_codebook _44c1_s_p5_0 = {
  138744. 2, 289,
  138745. _vq_lengthlist__44c1_s_p5_0,
  138746. 1, -529530880, 1611661312, 5, 0,
  138747. _vq_quantlist__44c1_s_p5_0,
  138748. NULL,
  138749. &_vq_auxt__44c1_s_p5_0,
  138750. NULL,
  138751. 0
  138752. };
  138753. static long _vq_quantlist__44c1_s_p6_0[] = {
  138754. 1,
  138755. 0,
  138756. 2,
  138757. };
  138758. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138759. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138760. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138761. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138762. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138763. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138764. 11,
  138765. };
  138766. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138767. -5.5, 5.5,
  138768. };
  138769. static long _vq_quantmap__44c1_s_p6_0[] = {
  138770. 1, 0, 2,
  138771. };
  138772. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138773. _vq_quantthresh__44c1_s_p6_0,
  138774. _vq_quantmap__44c1_s_p6_0,
  138775. 3,
  138776. 3
  138777. };
  138778. static static_codebook _44c1_s_p6_0 = {
  138779. 4, 81,
  138780. _vq_lengthlist__44c1_s_p6_0,
  138781. 1, -529137664, 1618345984, 2, 0,
  138782. _vq_quantlist__44c1_s_p6_0,
  138783. NULL,
  138784. &_vq_auxt__44c1_s_p6_0,
  138785. NULL,
  138786. 0
  138787. };
  138788. static long _vq_quantlist__44c1_s_p6_1[] = {
  138789. 5,
  138790. 4,
  138791. 6,
  138792. 3,
  138793. 7,
  138794. 2,
  138795. 8,
  138796. 1,
  138797. 9,
  138798. 0,
  138799. 10,
  138800. };
  138801. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138802. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138803. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138804. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138805. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138806. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138807. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138808. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138809. 10,10,10, 8, 8, 8, 8, 8, 8,
  138810. };
  138811. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138812. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138813. 3.5, 4.5,
  138814. };
  138815. static long _vq_quantmap__44c1_s_p6_1[] = {
  138816. 9, 7, 5, 3, 1, 0, 2, 4,
  138817. 6, 8, 10,
  138818. };
  138819. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138820. _vq_quantthresh__44c1_s_p6_1,
  138821. _vq_quantmap__44c1_s_p6_1,
  138822. 11,
  138823. 11
  138824. };
  138825. static static_codebook _44c1_s_p6_1 = {
  138826. 2, 121,
  138827. _vq_lengthlist__44c1_s_p6_1,
  138828. 1, -531365888, 1611661312, 4, 0,
  138829. _vq_quantlist__44c1_s_p6_1,
  138830. NULL,
  138831. &_vq_auxt__44c1_s_p6_1,
  138832. NULL,
  138833. 0
  138834. };
  138835. static long _vq_quantlist__44c1_s_p7_0[] = {
  138836. 6,
  138837. 5,
  138838. 7,
  138839. 4,
  138840. 8,
  138841. 3,
  138842. 9,
  138843. 2,
  138844. 10,
  138845. 1,
  138846. 11,
  138847. 0,
  138848. 12,
  138849. };
  138850. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138851. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138852. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138853. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138854. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138855. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138856. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138857. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138858. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138859. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138860. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138861. 0,12,11,11,11,13,10,14,13,
  138862. };
  138863. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138864. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138865. 12.5, 17.5, 22.5, 27.5,
  138866. };
  138867. static long _vq_quantmap__44c1_s_p7_0[] = {
  138868. 11, 9, 7, 5, 3, 1, 0, 2,
  138869. 4, 6, 8, 10, 12,
  138870. };
  138871. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138872. _vq_quantthresh__44c1_s_p7_0,
  138873. _vq_quantmap__44c1_s_p7_0,
  138874. 13,
  138875. 13
  138876. };
  138877. static static_codebook _44c1_s_p7_0 = {
  138878. 2, 169,
  138879. _vq_lengthlist__44c1_s_p7_0,
  138880. 1, -526516224, 1616117760, 4, 0,
  138881. _vq_quantlist__44c1_s_p7_0,
  138882. NULL,
  138883. &_vq_auxt__44c1_s_p7_0,
  138884. NULL,
  138885. 0
  138886. };
  138887. static long _vq_quantlist__44c1_s_p7_1[] = {
  138888. 2,
  138889. 1,
  138890. 3,
  138891. 0,
  138892. 4,
  138893. };
  138894. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138895. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138896. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138897. };
  138898. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138899. -1.5, -0.5, 0.5, 1.5,
  138900. };
  138901. static long _vq_quantmap__44c1_s_p7_1[] = {
  138902. 3, 1, 0, 2, 4,
  138903. };
  138904. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138905. _vq_quantthresh__44c1_s_p7_1,
  138906. _vq_quantmap__44c1_s_p7_1,
  138907. 5,
  138908. 5
  138909. };
  138910. static static_codebook _44c1_s_p7_1 = {
  138911. 2, 25,
  138912. _vq_lengthlist__44c1_s_p7_1,
  138913. 1, -533725184, 1611661312, 3, 0,
  138914. _vq_quantlist__44c1_s_p7_1,
  138915. NULL,
  138916. &_vq_auxt__44c1_s_p7_1,
  138917. NULL,
  138918. 0
  138919. };
  138920. static long _vq_quantlist__44c1_s_p8_0[] = {
  138921. 6,
  138922. 5,
  138923. 7,
  138924. 4,
  138925. 8,
  138926. 3,
  138927. 9,
  138928. 2,
  138929. 10,
  138930. 1,
  138931. 11,
  138932. 0,
  138933. 12,
  138934. };
  138935. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138936. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138937. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138938. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138941. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138942. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138943. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138944. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138945. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138946. 10,10,10,10,10,10,10,10,10,
  138947. };
  138948. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138949. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138950. 552.5, 773.5, 994.5, 1215.5,
  138951. };
  138952. static long _vq_quantmap__44c1_s_p8_0[] = {
  138953. 11, 9, 7, 5, 3, 1, 0, 2,
  138954. 4, 6, 8, 10, 12,
  138955. };
  138956. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138957. _vq_quantthresh__44c1_s_p8_0,
  138958. _vq_quantmap__44c1_s_p8_0,
  138959. 13,
  138960. 13
  138961. };
  138962. static static_codebook _44c1_s_p8_0 = {
  138963. 2, 169,
  138964. _vq_lengthlist__44c1_s_p8_0,
  138965. 1, -514541568, 1627103232, 4, 0,
  138966. _vq_quantlist__44c1_s_p8_0,
  138967. NULL,
  138968. &_vq_auxt__44c1_s_p8_0,
  138969. NULL,
  138970. 0
  138971. };
  138972. static long _vq_quantlist__44c1_s_p8_1[] = {
  138973. 6,
  138974. 5,
  138975. 7,
  138976. 4,
  138977. 8,
  138978. 3,
  138979. 9,
  138980. 2,
  138981. 10,
  138982. 1,
  138983. 11,
  138984. 0,
  138985. 12,
  138986. };
  138987. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138988. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138989. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138990. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138991. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138992. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138993. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138994. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138995. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138996. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138997. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138998. 16,13,12,12,11,14,12,15,13,
  138999. };
  139000. static float _vq_quantthresh__44c1_s_p8_1[] = {
  139001. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139002. 42.5, 59.5, 76.5, 93.5,
  139003. };
  139004. static long _vq_quantmap__44c1_s_p8_1[] = {
  139005. 11, 9, 7, 5, 3, 1, 0, 2,
  139006. 4, 6, 8, 10, 12,
  139007. };
  139008. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139009. _vq_quantthresh__44c1_s_p8_1,
  139010. _vq_quantmap__44c1_s_p8_1,
  139011. 13,
  139012. 13
  139013. };
  139014. static static_codebook _44c1_s_p8_1 = {
  139015. 2, 169,
  139016. _vq_lengthlist__44c1_s_p8_1,
  139017. 1, -522616832, 1620115456, 4, 0,
  139018. _vq_quantlist__44c1_s_p8_1,
  139019. NULL,
  139020. &_vq_auxt__44c1_s_p8_1,
  139021. NULL,
  139022. 0
  139023. };
  139024. static long _vq_quantlist__44c1_s_p8_2[] = {
  139025. 8,
  139026. 7,
  139027. 9,
  139028. 6,
  139029. 10,
  139030. 5,
  139031. 11,
  139032. 4,
  139033. 12,
  139034. 3,
  139035. 13,
  139036. 2,
  139037. 14,
  139038. 1,
  139039. 15,
  139040. 0,
  139041. 16,
  139042. };
  139043. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139044. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139045. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139046. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139047. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139048. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139049. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139050. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139051. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139052. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139053. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139054. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139055. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139056. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139057. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139058. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139059. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139060. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139061. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139062. 9,
  139063. };
  139064. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139065. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139066. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139067. };
  139068. static long _vq_quantmap__44c1_s_p8_2[] = {
  139069. 15, 13, 11, 9, 7, 5, 3, 1,
  139070. 0, 2, 4, 6, 8, 10, 12, 14,
  139071. 16,
  139072. };
  139073. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139074. _vq_quantthresh__44c1_s_p8_2,
  139075. _vq_quantmap__44c1_s_p8_2,
  139076. 17,
  139077. 17
  139078. };
  139079. static static_codebook _44c1_s_p8_2 = {
  139080. 2, 289,
  139081. _vq_lengthlist__44c1_s_p8_2,
  139082. 1, -529530880, 1611661312, 5, 0,
  139083. _vq_quantlist__44c1_s_p8_2,
  139084. NULL,
  139085. &_vq_auxt__44c1_s_p8_2,
  139086. NULL,
  139087. 0
  139088. };
  139089. static long _huff_lengthlist__44c1_s_short[] = {
  139090. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139091. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139092. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139093. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139094. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139095. 11,
  139096. };
  139097. static static_codebook _huff_book__44c1_s_short = {
  139098. 2, 81,
  139099. _huff_lengthlist__44c1_s_short,
  139100. 0, 0, 0, 0, 0,
  139101. NULL,
  139102. NULL,
  139103. NULL,
  139104. NULL,
  139105. 0
  139106. };
  139107. static long _huff_lengthlist__44c1_sm_long[] = {
  139108. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139109. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139110. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139111. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139112. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139113. 11,
  139114. };
  139115. static static_codebook _huff_book__44c1_sm_long = {
  139116. 2, 81,
  139117. _huff_lengthlist__44c1_sm_long,
  139118. 0, 0, 0, 0, 0,
  139119. NULL,
  139120. NULL,
  139121. NULL,
  139122. NULL,
  139123. 0
  139124. };
  139125. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139126. 1,
  139127. 0,
  139128. 2,
  139129. };
  139130. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139131. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139132. 0, 0, 5, 7, 7, 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, 0, 0, 0, 0, 0,
  139136. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139137. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139142. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139173. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139177. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139182. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  139187. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139223. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139228. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139233. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139541. 0,
  139542. };
  139543. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139544. -0.5, 0.5,
  139545. };
  139546. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139547. 1, 0, 2,
  139548. };
  139549. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139550. _vq_quantthresh__44c1_sm_p1_0,
  139551. _vq_quantmap__44c1_sm_p1_0,
  139552. 3,
  139553. 3
  139554. };
  139555. static static_codebook _44c1_sm_p1_0 = {
  139556. 8, 6561,
  139557. _vq_lengthlist__44c1_sm_p1_0,
  139558. 1, -535822336, 1611661312, 2, 0,
  139559. _vq_quantlist__44c1_sm_p1_0,
  139560. NULL,
  139561. &_vq_auxt__44c1_sm_p1_0,
  139562. NULL,
  139563. 0
  139564. };
  139565. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139566. 2,
  139567. 1,
  139568. 3,
  139569. 0,
  139570. 4,
  139571. };
  139572. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139573. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139579. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0,
  139613. };
  139614. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139615. -1.5, -0.5, 0.5, 1.5,
  139616. };
  139617. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139618. 3, 1, 0, 2, 4,
  139619. };
  139620. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139621. _vq_quantthresh__44c1_sm_p2_0,
  139622. _vq_quantmap__44c1_sm_p2_0,
  139623. 5,
  139624. 5
  139625. };
  139626. static static_codebook _44c1_sm_p2_0 = {
  139627. 4, 625,
  139628. _vq_lengthlist__44c1_sm_p2_0,
  139629. 1, -533725184, 1611661312, 3, 0,
  139630. _vq_quantlist__44c1_sm_p2_0,
  139631. NULL,
  139632. &_vq_auxt__44c1_sm_p2_0,
  139633. NULL,
  139634. 0
  139635. };
  139636. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139637. 4,
  139638. 3,
  139639. 5,
  139640. 2,
  139641. 6,
  139642. 1,
  139643. 7,
  139644. 0,
  139645. 8,
  139646. };
  139647. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139648. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139649. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139650. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139651. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139652. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0,
  139654. };
  139655. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139656. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139657. };
  139658. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139659. 7, 5, 3, 1, 0, 2, 4, 6,
  139660. 8,
  139661. };
  139662. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139663. _vq_quantthresh__44c1_sm_p3_0,
  139664. _vq_quantmap__44c1_sm_p3_0,
  139665. 9,
  139666. 9
  139667. };
  139668. static static_codebook _44c1_sm_p3_0 = {
  139669. 2, 81,
  139670. _vq_lengthlist__44c1_sm_p3_0,
  139671. 1, -531628032, 1611661312, 4, 0,
  139672. _vq_quantlist__44c1_sm_p3_0,
  139673. NULL,
  139674. &_vq_auxt__44c1_sm_p3_0,
  139675. NULL,
  139676. 0
  139677. };
  139678. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139679. 4,
  139680. 3,
  139681. 5,
  139682. 2,
  139683. 6,
  139684. 1,
  139685. 7,
  139686. 0,
  139687. 8,
  139688. };
  139689. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139690. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139691. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139692. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139693. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139694. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139695. 11,
  139696. };
  139697. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139698. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139699. };
  139700. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139701. 7, 5, 3, 1, 0, 2, 4, 6,
  139702. 8,
  139703. };
  139704. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139705. _vq_quantthresh__44c1_sm_p4_0,
  139706. _vq_quantmap__44c1_sm_p4_0,
  139707. 9,
  139708. 9
  139709. };
  139710. static static_codebook _44c1_sm_p4_0 = {
  139711. 2, 81,
  139712. _vq_lengthlist__44c1_sm_p4_0,
  139713. 1, -531628032, 1611661312, 4, 0,
  139714. _vq_quantlist__44c1_sm_p4_0,
  139715. NULL,
  139716. &_vq_auxt__44c1_sm_p4_0,
  139717. NULL,
  139718. 0
  139719. };
  139720. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139721. 8,
  139722. 7,
  139723. 9,
  139724. 6,
  139725. 10,
  139726. 5,
  139727. 11,
  139728. 4,
  139729. 12,
  139730. 3,
  139731. 13,
  139732. 2,
  139733. 14,
  139734. 1,
  139735. 15,
  139736. 0,
  139737. 16,
  139738. };
  139739. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139740. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139741. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139742. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139743. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139744. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139745. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139746. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139747. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139748. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139749. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139750. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139751. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139752. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139753. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139754. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139755. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139756. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139758. 14,
  139759. };
  139760. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139761. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139762. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139763. };
  139764. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139765. 15, 13, 11, 9, 7, 5, 3, 1,
  139766. 0, 2, 4, 6, 8, 10, 12, 14,
  139767. 16,
  139768. };
  139769. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139770. _vq_quantthresh__44c1_sm_p5_0,
  139771. _vq_quantmap__44c1_sm_p5_0,
  139772. 17,
  139773. 17
  139774. };
  139775. static static_codebook _44c1_sm_p5_0 = {
  139776. 2, 289,
  139777. _vq_lengthlist__44c1_sm_p5_0,
  139778. 1, -529530880, 1611661312, 5, 0,
  139779. _vq_quantlist__44c1_sm_p5_0,
  139780. NULL,
  139781. &_vq_auxt__44c1_sm_p5_0,
  139782. NULL,
  139783. 0
  139784. };
  139785. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139786. 1,
  139787. 0,
  139788. 2,
  139789. };
  139790. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139791. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139792. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139793. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139794. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139795. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139796. 11,
  139797. };
  139798. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139799. -5.5, 5.5,
  139800. };
  139801. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139802. 1, 0, 2,
  139803. };
  139804. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139805. _vq_quantthresh__44c1_sm_p6_0,
  139806. _vq_quantmap__44c1_sm_p6_0,
  139807. 3,
  139808. 3
  139809. };
  139810. static static_codebook _44c1_sm_p6_0 = {
  139811. 4, 81,
  139812. _vq_lengthlist__44c1_sm_p6_0,
  139813. 1, -529137664, 1618345984, 2, 0,
  139814. _vq_quantlist__44c1_sm_p6_0,
  139815. NULL,
  139816. &_vq_auxt__44c1_sm_p6_0,
  139817. NULL,
  139818. 0
  139819. };
  139820. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139821. 5,
  139822. 4,
  139823. 6,
  139824. 3,
  139825. 7,
  139826. 2,
  139827. 8,
  139828. 1,
  139829. 9,
  139830. 0,
  139831. 10,
  139832. };
  139833. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139834. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139835. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139836. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139837. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139838. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139839. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139840. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139841. 10,10,10, 8, 8, 8, 8, 8, 8,
  139842. };
  139843. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139844. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139845. 3.5, 4.5,
  139846. };
  139847. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139848. 9, 7, 5, 3, 1, 0, 2, 4,
  139849. 6, 8, 10,
  139850. };
  139851. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139852. _vq_quantthresh__44c1_sm_p6_1,
  139853. _vq_quantmap__44c1_sm_p6_1,
  139854. 11,
  139855. 11
  139856. };
  139857. static static_codebook _44c1_sm_p6_1 = {
  139858. 2, 121,
  139859. _vq_lengthlist__44c1_sm_p6_1,
  139860. 1, -531365888, 1611661312, 4, 0,
  139861. _vq_quantlist__44c1_sm_p6_1,
  139862. NULL,
  139863. &_vq_auxt__44c1_sm_p6_1,
  139864. NULL,
  139865. 0
  139866. };
  139867. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139868. 6,
  139869. 5,
  139870. 7,
  139871. 4,
  139872. 8,
  139873. 3,
  139874. 9,
  139875. 2,
  139876. 10,
  139877. 1,
  139878. 11,
  139879. 0,
  139880. 12,
  139881. };
  139882. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139883. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139884. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139885. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139886. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139887. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139888. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139889. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139890. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139891. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139892. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139893. 0,12,12,11,11,13,12,14,13,
  139894. };
  139895. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139896. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139897. 12.5, 17.5, 22.5, 27.5,
  139898. };
  139899. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139900. 11, 9, 7, 5, 3, 1, 0, 2,
  139901. 4, 6, 8, 10, 12,
  139902. };
  139903. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139904. _vq_quantthresh__44c1_sm_p7_0,
  139905. _vq_quantmap__44c1_sm_p7_0,
  139906. 13,
  139907. 13
  139908. };
  139909. static static_codebook _44c1_sm_p7_0 = {
  139910. 2, 169,
  139911. _vq_lengthlist__44c1_sm_p7_0,
  139912. 1, -526516224, 1616117760, 4, 0,
  139913. _vq_quantlist__44c1_sm_p7_0,
  139914. NULL,
  139915. &_vq_auxt__44c1_sm_p7_0,
  139916. NULL,
  139917. 0
  139918. };
  139919. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139920. 2,
  139921. 1,
  139922. 3,
  139923. 0,
  139924. 4,
  139925. };
  139926. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139927. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139928. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139929. };
  139930. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139931. -1.5, -0.5, 0.5, 1.5,
  139932. };
  139933. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139934. 3, 1, 0, 2, 4,
  139935. };
  139936. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139937. _vq_quantthresh__44c1_sm_p7_1,
  139938. _vq_quantmap__44c1_sm_p7_1,
  139939. 5,
  139940. 5
  139941. };
  139942. static static_codebook _44c1_sm_p7_1 = {
  139943. 2, 25,
  139944. _vq_lengthlist__44c1_sm_p7_1,
  139945. 1, -533725184, 1611661312, 3, 0,
  139946. _vq_quantlist__44c1_sm_p7_1,
  139947. NULL,
  139948. &_vq_auxt__44c1_sm_p7_1,
  139949. NULL,
  139950. 0
  139951. };
  139952. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139953. 6,
  139954. 5,
  139955. 7,
  139956. 4,
  139957. 8,
  139958. 3,
  139959. 9,
  139960. 2,
  139961. 10,
  139962. 1,
  139963. 11,
  139964. 0,
  139965. 12,
  139966. };
  139967. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139968. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139969. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139970. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139971. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139972. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139973. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139974. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139975. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139976. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139977. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139978. 13,13,13,13,13,13,13,13,13,
  139979. };
  139980. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139981. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139982. 552.5, 773.5, 994.5, 1215.5,
  139983. };
  139984. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139985. 11, 9, 7, 5, 3, 1, 0, 2,
  139986. 4, 6, 8, 10, 12,
  139987. };
  139988. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139989. _vq_quantthresh__44c1_sm_p8_0,
  139990. _vq_quantmap__44c1_sm_p8_0,
  139991. 13,
  139992. 13
  139993. };
  139994. static static_codebook _44c1_sm_p8_0 = {
  139995. 2, 169,
  139996. _vq_lengthlist__44c1_sm_p8_0,
  139997. 1, -514541568, 1627103232, 4, 0,
  139998. _vq_quantlist__44c1_sm_p8_0,
  139999. NULL,
  140000. &_vq_auxt__44c1_sm_p8_0,
  140001. NULL,
  140002. 0
  140003. };
  140004. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140005. 6,
  140006. 5,
  140007. 7,
  140008. 4,
  140009. 8,
  140010. 3,
  140011. 9,
  140012. 2,
  140013. 10,
  140014. 1,
  140015. 11,
  140016. 0,
  140017. 12,
  140018. };
  140019. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140020. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140021. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140022. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140023. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140024. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140025. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140026. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140027. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140028. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140029. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140030. 20,13,12,12,12,14,12,14,13,
  140031. };
  140032. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140033. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140034. 42.5, 59.5, 76.5, 93.5,
  140035. };
  140036. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140037. 11, 9, 7, 5, 3, 1, 0, 2,
  140038. 4, 6, 8, 10, 12,
  140039. };
  140040. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140041. _vq_quantthresh__44c1_sm_p8_1,
  140042. _vq_quantmap__44c1_sm_p8_1,
  140043. 13,
  140044. 13
  140045. };
  140046. static static_codebook _44c1_sm_p8_1 = {
  140047. 2, 169,
  140048. _vq_lengthlist__44c1_sm_p8_1,
  140049. 1, -522616832, 1620115456, 4, 0,
  140050. _vq_quantlist__44c1_sm_p8_1,
  140051. NULL,
  140052. &_vq_auxt__44c1_sm_p8_1,
  140053. NULL,
  140054. 0
  140055. };
  140056. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140057. 8,
  140058. 7,
  140059. 9,
  140060. 6,
  140061. 10,
  140062. 5,
  140063. 11,
  140064. 4,
  140065. 12,
  140066. 3,
  140067. 13,
  140068. 2,
  140069. 14,
  140070. 1,
  140071. 15,
  140072. 0,
  140073. 16,
  140074. };
  140075. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140076. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140077. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140078. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140079. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140080. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140081. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140082. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140083. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140084. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140085. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140086. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140087. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140088. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140089. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140090. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140091. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140092. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140093. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140094. 9,
  140095. };
  140096. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140097. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140098. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140099. };
  140100. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140101. 15, 13, 11, 9, 7, 5, 3, 1,
  140102. 0, 2, 4, 6, 8, 10, 12, 14,
  140103. 16,
  140104. };
  140105. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140106. _vq_quantthresh__44c1_sm_p8_2,
  140107. _vq_quantmap__44c1_sm_p8_2,
  140108. 17,
  140109. 17
  140110. };
  140111. static static_codebook _44c1_sm_p8_2 = {
  140112. 2, 289,
  140113. _vq_lengthlist__44c1_sm_p8_2,
  140114. 1, -529530880, 1611661312, 5, 0,
  140115. _vq_quantlist__44c1_sm_p8_2,
  140116. NULL,
  140117. &_vq_auxt__44c1_sm_p8_2,
  140118. NULL,
  140119. 0
  140120. };
  140121. static long _huff_lengthlist__44c1_sm_short[] = {
  140122. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140123. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140124. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140125. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140126. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140127. 11,
  140128. };
  140129. static static_codebook _huff_book__44c1_sm_short = {
  140130. 2, 81,
  140131. _huff_lengthlist__44c1_sm_short,
  140132. 0, 0, 0, 0, 0,
  140133. NULL,
  140134. NULL,
  140135. NULL,
  140136. NULL,
  140137. 0
  140138. };
  140139. static long _huff_lengthlist__44cn1_s_long[] = {
  140140. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140141. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140142. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140143. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140144. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140145. 20,
  140146. };
  140147. static static_codebook _huff_book__44cn1_s_long = {
  140148. 2, 81,
  140149. _huff_lengthlist__44cn1_s_long,
  140150. 0, 0, 0, 0, 0,
  140151. NULL,
  140152. NULL,
  140153. NULL,
  140154. NULL,
  140155. 0
  140156. };
  140157. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140158. 1,
  140159. 0,
  140160. 2,
  140161. };
  140162. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140163. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140164. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140169. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140174. 0, 0, 0, 0, 8,10, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  140177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  140182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  140187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140209. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140214. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140219. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140254. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140255. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140260. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140265. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140573. 0,
  140574. };
  140575. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140576. -0.5, 0.5,
  140577. };
  140578. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140579. 1, 0, 2,
  140580. };
  140581. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140582. _vq_quantthresh__44cn1_s_p1_0,
  140583. _vq_quantmap__44cn1_s_p1_0,
  140584. 3,
  140585. 3
  140586. };
  140587. static static_codebook _44cn1_s_p1_0 = {
  140588. 8, 6561,
  140589. _vq_lengthlist__44cn1_s_p1_0,
  140590. 1, -535822336, 1611661312, 2, 0,
  140591. _vq_quantlist__44cn1_s_p1_0,
  140592. NULL,
  140593. &_vq_auxt__44cn1_s_p1_0,
  140594. NULL,
  140595. 0
  140596. };
  140597. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140598. 2,
  140599. 1,
  140600. 3,
  140601. 0,
  140602. 4,
  140603. };
  140604. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140605. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140611. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0,
  140645. };
  140646. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140647. -1.5, -0.5, 0.5, 1.5,
  140648. };
  140649. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140650. 3, 1, 0, 2, 4,
  140651. };
  140652. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140653. _vq_quantthresh__44cn1_s_p2_0,
  140654. _vq_quantmap__44cn1_s_p2_0,
  140655. 5,
  140656. 5
  140657. };
  140658. static static_codebook _44cn1_s_p2_0 = {
  140659. 4, 625,
  140660. _vq_lengthlist__44cn1_s_p2_0,
  140661. 1, -533725184, 1611661312, 3, 0,
  140662. _vq_quantlist__44cn1_s_p2_0,
  140663. NULL,
  140664. &_vq_auxt__44cn1_s_p2_0,
  140665. NULL,
  140666. 0
  140667. };
  140668. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140669. 4,
  140670. 3,
  140671. 5,
  140672. 2,
  140673. 6,
  140674. 1,
  140675. 7,
  140676. 0,
  140677. 8,
  140678. };
  140679. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140680. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140681. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140682. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140683. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140684. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0,
  140686. };
  140687. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140688. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140689. };
  140690. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140691. 7, 5, 3, 1, 0, 2, 4, 6,
  140692. 8,
  140693. };
  140694. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140695. _vq_quantthresh__44cn1_s_p3_0,
  140696. _vq_quantmap__44cn1_s_p3_0,
  140697. 9,
  140698. 9
  140699. };
  140700. static static_codebook _44cn1_s_p3_0 = {
  140701. 2, 81,
  140702. _vq_lengthlist__44cn1_s_p3_0,
  140703. 1, -531628032, 1611661312, 4, 0,
  140704. _vq_quantlist__44cn1_s_p3_0,
  140705. NULL,
  140706. &_vq_auxt__44cn1_s_p3_0,
  140707. NULL,
  140708. 0
  140709. };
  140710. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140711. 4,
  140712. 3,
  140713. 5,
  140714. 2,
  140715. 6,
  140716. 1,
  140717. 7,
  140718. 0,
  140719. 8,
  140720. };
  140721. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140722. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140723. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140724. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140725. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140726. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140727. 11,
  140728. };
  140729. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140730. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140731. };
  140732. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140733. 7, 5, 3, 1, 0, 2, 4, 6,
  140734. 8,
  140735. };
  140736. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140737. _vq_quantthresh__44cn1_s_p4_0,
  140738. _vq_quantmap__44cn1_s_p4_0,
  140739. 9,
  140740. 9
  140741. };
  140742. static static_codebook _44cn1_s_p4_0 = {
  140743. 2, 81,
  140744. _vq_lengthlist__44cn1_s_p4_0,
  140745. 1, -531628032, 1611661312, 4, 0,
  140746. _vq_quantlist__44cn1_s_p4_0,
  140747. NULL,
  140748. &_vq_auxt__44cn1_s_p4_0,
  140749. NULL,
  140750. 0
  140751. };
  140752. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140753. 8,
  140754. 7,
  140755. 9,
  140756. 6,
  140757. 10,
  140758. 5,
  140759. 11,
  140760. 4,
  140761. 12,
  140762. 3,
  140763. 13,
  140764. 2,
  140765. 14,
  140766. 1,
  140767. 15,
  140768. 0,
  140769. 16,
  140770. };
  140771. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140772. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140773. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140774. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140775. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140776. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140777. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140778. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140779. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140780. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140781. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140782. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140783. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140784. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140785. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140786. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140787. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140788. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140790. 14,
  140791. };
  140792. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140793. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140794. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140795. };
  140796. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140797. 15, 13, 11, 9, 7, 5, 3, 1,
  140798. 0, 2, 4, 6, 8, 10, 12, 14,
  140799. 16,
  140800. };
  140801. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140802. _vq_quantthresh__44cn1_s_p5_0,
  140803. _vq_quantmap__44cn1_s_p5_0,
  140804. 17,
  140805. 17
  140806. };
  140807. static static_codebook _44cn1_s_p5_0 = {
  140808. 2, 289,
  140809. _vq_lengthlist__44cn1_s_p5_0,
  140810. 1, -529530880, 1611661312, 5, 0,
  140811. _vq_quantlist__44cn1_s_p5_0,
  140812. NULL,
  140813. &_vq_auxt__44cn1_s_p5_0,
  140814. NULL,
  140815. 0
  140816. };
  140817. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140818. 1,
  140819. 0,
  140820. 2,
  140821. };
  140822. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140823. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140824. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140825. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140826. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140827. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140828. 10,
  140829. };
  140830. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140831. -5.5, 5.5,
  140832. };
  140833. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140834. 1, 0, 2,
  140835. };
  140836. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140837. _vq_quantthresh__44cn1_s_p6_0,
  140838. _vq_quantmap__44cn1_s_p6_0,
  140839. 3,
  140840. 3
  140841. };
  140842. static static_codebook _44cn1_s_p6_0 = {
  140843. 4, 81,
  140844. _vq_lengthlist__44cn1_s_p6_0,
  140845. 1, -529137664, 1618345984, 2, 0,
  140846. _vq_quantlist__44cn1_s_p6_0,
  140847. NULL,
  140848. &_vq_auxt__44cn1_s_p6_0,
  140849. NULL,
  140850. 0
  140851. };
  140852. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140853. 5,
  140854. 4,
  140855. 6,
  140856. 3,
  140857. 7,
  140858. 2,
  140859. 8,
  140860. 1,
  140861. 9,
  140862. 0,
  140863. 10,
  140864. };
  140865. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140866. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140867. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140868. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140869. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140870. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140871. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140872. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140873. 10,10,10, 9, 9, 9, 9, 9, 9,
  140874. };
  140875. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140876. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140877. 3.5, 4.5,
  140878. };
  140879. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140880. 9, 7, 5, 3, 1, 0, 2, 4,
  140881. 6, 8, 10,
  140882. };
  140883. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140884. _vq_quantthresh__44cn1_s_p6_1,
  140885. _vq_quantmap__44cn1_s_p6_1,
  140886. 11,
  140887. 11
  140888. };
  140889. static static_codebook _44cn1_s_p6_1 = {
  140890. 2, 121,
  140891. _vq_lengthlist__44cn1_s_p6_1,
  140892. 1, -531365888, 1611661312, 4, 0,
  140893. _vq_quantlist__44cn1_s_p6_1,
  140894. NULL,
  140895. &_vq_auxt__44cn1_s_p6_1,
  140896. NULL,
  140897. 0
  140898. };
  140899. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140900. 6,
  140901. 5,
  140902. 7,
  140903. 4,
  140904. 8,
  140905. 3,
  140906. 9,
  140907. 2,
  140908. 10,
  140909. 1,
  140910. 11,
  140911. 0,
  140912. 12,
  140913. };
  140914. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140915. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140916. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140917. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140918. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140919. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140920. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140921. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140922. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140923. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140924. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140925. 0,13,13,12,12,13,13,13,14,
  140926. };
  140927. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140928. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140929. 12.5, 17.5, 22.5, 27.5,
  140930. };
  140931. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140932. 11, 9, 7, 5, 3, 1, 0, 2,
  140933. 4, 6, 8, 10, 12,
  140934. };
  140935. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140936. _vq_quantthresh__44cn1_s_p7_0,
  140937. _vq_quantmap__44cn1_s_p7_0,
  140938. 13,
  140939. 13
  140940. };
  140941. static static_codebook _44cn1_s_p7_0 = {
  140942. 2, 169,
  140943. _vq_lengthlist__44cn1_s_p7_0,
  140944. 1, -526516224, 1616117760, 4, 0,
  140945. _vq_quantlist__44cn1_s_p7_0,
  140946. NULL,
  140947. &_vq_auxt__44cn1_s_p7_0,
  140948. NULL,
  140949. 0
  140950. };
  140951. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140952. 2,
  140953. 1,
  140954. 3,
  140955. 0,
  140956. 4,
  140957. };
  140958. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140959. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140960. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140961. };
  140962. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140963. -1.5, -0.5, 0.5, 1.5,
  140964. };
  140965. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140966. 3, 1, 0, 2, 4,
  140967. };
  140968. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140969. _vq_quantthresh__44cn1_s_p7_1,
  140970. _vq_quantmap__44cn1_s_p7_1,
  140971. 5,
  140972. 5
  140973. };
  140974. static static_codebook _44cn1_s_p7_1 = {
  140975. 2, 25,
  140976. _vq_lengthlist__44cn1_s_p7_1,
  140977. 1, -533725184, 1611661312, 3, 0,
  140978. _vq_quantlist__44cn1_s_p7_1,
  140979. NULL,
  140980. &_vq_auxt__44cn1_s_p7_1,
  140981. NULL,
  140982. 0
  140983. };
  140984. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140985. 2,
  140986. 1,
  140987. 3,
  140988. 0,
  140989. 4,
  140990. };
  140991. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140992. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140993. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140995. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140996. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140997. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140998. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140999. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  141000. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141001. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  141002. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141003. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141004. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141005. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141006. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141007. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  141008. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141009. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141010. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141011. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141012. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141013. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141014. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141015. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141016. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141017. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141018. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141019. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141020. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141021. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141022. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141023. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141024. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141025. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141026. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141027. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141028. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141029. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141030. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141031. 12,
  141032. };
  141033. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141034. -331.5, -110.5, 110.5, 331.5,
  141035. };
  141036. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141037. 3, 1, 0, 2, 4,
  141038. };
  141039. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141040. _vq_quantthresh__44cn1_s_p8_0,
  141041. _vq_quantmap__44cn1_s_p8_0,
  141042. 5,
  141043. 5
  141044. };
  141045. static static_codebook _44cn1_s_p8_0 = {
  141046. 4, 625,
  141047. _vq_lengthlist__44cn1_s_p8_0,
  141048. 1, -518283264, 1627103232, 3, 0,
  141049. _vq_quantlist__44cn1_s_p8_0,
  141050. NULL,
  141051. &_vq_auxt__44cn1_s_p8_0,
  141052. NULL,
  141053. 0
  141054. };
  141055. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141056. 6,
  141057. 5,
  141058. 7,
  141059. 4,
  141060. 8,
  141061. 3,
  141062. 9,
  141063. 2,
  141064. 10,
  141065. 1,
  141066. 11,
  141067. 0,
  141068. 12,
  141069. };
  141070. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141071. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141072. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141073. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141074. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141075. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141076. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141077. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141078. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141079. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141080. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141081. 15,12,12,11,11,14,12,13,14,
  141082. };
  141083. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141084. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141085. 42.5, 59.5, 76.5, 93.5,
  141086. };
  141087. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141088. 11, 9, 7, 5, 3, 1, 0, 2,
  141089. 4, 6, 8, 10, 12,
  141090. };
  141091. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141092. _vq_quantthresh__44cn1_s_p8_1,
  141093. _vq_quantmap__44cn1_s_p8_1,
  141094. 13,
  141095. 13
  141096. };
  141097. static static_codebook _44cn1_s_p8_1 = {
  141098. 2, 169,
  141099. _vq_lengthlist__44cn1_s_p8_1,
  141100. 1, -522616832, 1620115456, 4, 0,
  141101. _vq_quantlist__44cn1_s_p8_1,
  141102. NULL,
  141103. &_vq_auxt__44cn1_s_p8_1,
  141104. NULL,
  141105. 0
  141106. };
  141107. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141108. 8,
  141109. 7,
  141110. 9,
  141111. 6,
  141112. 10,
  141113. 5,
  141114. 11,
  141115. 4,
  141116. 12,
  141117. 3,
  141118. 13,
  141119. 2,
  141120. 14,
  141121. 1,
  141122. 15,
  141123. 0,
  141124. 16,
  141125. };
  141126. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141127. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141128. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141129. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141130. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141131. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141132. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141133. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141134. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141135. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141136. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141137. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141138. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141139. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141140. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141141. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141142. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141143. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141144. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141145. 9,
  141146. };
  141147. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141148. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141149. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141150. };
  141151. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141152. 15, 13, 11, 9, 7, 5, 3, 1,
  141153. 0, 2, 4, 6, 8, 10, 12, 14,
  141154. 16,
  141155. };
  141156. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141157. _vq_quantthresh__44cn1_s_p8_2,
  141158. _vq_quantmap__44cn1_s_p8_2,
  141159. 17,
  141160. 17
  141161. };
  141162. static static_codebook _44cn1_s_p8_2 = {
  141163. 2, 289,
  141164. _vq_lengthlist__44cn1_s_p8_2,
  141165. 1, -529530880, 1611661312, 5, 0,
  141166. _vq_quantlist__44cn1_s_p8_2,
  141167. NULL,
  141168. &_vq_auxt__44cn1_s_p8_2,
  141169. NULL,
  141170. 0
  141171. };
  141172. static long _huff_lengthlist__44cn1_s_short[] = {
  141173. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141174. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141175. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141176. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141177. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141178. 10,
  141179. };
  141180. static static_codebook _huff_book__44cn1_s_short = {
  141181. 2, 81,
  141182. _huff_lengthlist__44cn1_s_short,
  141183. 0, 0, 0, 0, 0,
  141184. NULL,
  141185. NULL,
  141186. NULL,
  141187. NULL,
  141188. 0
  141189. };
  141190. static long _huff_lengthlist__44cn1_sm_long[] = {
  141191. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141192. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141193. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141194. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141195. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141196. 17,
  141197. };
  141198. static static_codebook _huff_book__44cn1_sm_long = {
  141199. 2, 81,
  141200. _huff_lengthlist__44cn1_sm_long,
  141201. 0, 0, 0, 0, 0,
  141202. NULL,
  141203. NULL,
  141204. NULL,
  141205. NULL,
  141206. 0
  141207. };
  141208. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141209. 1,
  141210. 0,
  141211. 2,
  141212. };
  141213. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141214. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141215. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141219. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141220. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141224. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141225. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141260. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141265. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141270. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141305. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141306. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141311. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141316. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141624. 0,
  141625. };
  141626. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141627. -0.5, 0.5,
  141628. };
  141629. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141630. 1, 0, 2,
  141631. };
  141632. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141633. _vq_quantthresh__44cn1_sm_p1_0,
  141634. _vq_quantmap__44cn1_sm_p1_0,
  141635. 3,
  141636. 3
  141637. };
  141638. static static_codebook _44cn1_sm_p1_0 = {
  141639. 8, 6561,
  141640. _vq_lengthlist__44cn1_sm_p1_0,
  141641. 1, -535822336, 1611661312, 2, 0,
  141642. _vq_quantlist__44cn1_sm_p1_0,
  141643. NULL,
  141644. &_vq_auxt__44cn1_sm_p1_0,
  141645. NULL,
  141646. 0
  141647. };
  141648. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141649. 2,
  141650. 1,
  141651. 3,
  141652. 0,
  141653. 4,
  141654. };
  141655. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141656. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141659. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141662. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0,
  141696. };
  141697. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141698. -1.5, -0.5, 0.5, 1.5,
  141699. };
  141700. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141701. 3, 1, 0, 2, 4,
  141702. };
  141703. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141704. _vq_quantthresh__44cn1_sm_p2_0,
  141705. _vq_quantmap__44cn1_sm_p2_0,
  141706. 5,
  141707. 5
  141708. };
  141709. static static_codebook _44cn1_sm_p2_0 = {
  141710. 4, 625,
  141711. _vq_lengthlist__44cn1_sm_p2_0,
  141712. 1, -533725184, 1611661312, 3, 0,
  141713. _vq_quantlist__44cn1_sm_p2_0,
  141714. NULL,
  141715. &_vq_auxt__44cn1_sm_p2_0,
  141716. NULL,
  141717. 0
  141718. };
  141719. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141720. 4,
  141721. 3,
  141722. 5,
  141723. 2,
  141724. 6,
  141725. 1,
  141726. 7,
  141727. 0,
  141728. 8,
  141729. };
  141730. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141731. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141732. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141733. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141734. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141735. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141736. 0,
  141737. };
  141738. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141739. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141740. };
  141741. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141742. 7, 5, 3, 1, 0, 2, 4, 6,
  141743. 8,
  141744. };
  141745. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141746. _vq_quantthresh__44cn1_sm_p3_0,
  141747. _vq_quantmap__44cn1_sm_p3_0,
  141748. 9,
  141749. 9
  141750. };
  141751. static static_codebook _44cn1_sm_p3_0 = {
  141752. 2, 81,
  141753. _vq_lengthlist__44cn1_sm_p3_0,
  141754. 1, -531628032, 1611661312, 4, 0,
  141755. _vq_quantlist__44cn1_sm_p3_0,
  141756. NULL,
  141757. &_vq_auxt__44cn1_sm_p3_0,
  141758. NULL,
  141759. 0
  141760. };
  141761. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141762. 4,
  141763. 3,
  141764. 5,
  141765. 2,
  141766. 6,
  141767. 1,
  141768. 7,
  141769. 0,
  141770. 8,
  141771. };
  141772. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141773. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141774. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141775. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141776. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141777. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141778. 11,
  141779. };
  141780. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141781. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141782. };
  141783. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141784. 7, 5, 3, 1, 0, 2, 4, 6,
  141785. 8,
  141786. };
  141787. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141788. _vq_quantthresh__44cn1_sm_p4_0,
  141789. _vq_quantmap__44cn1_sm_p4_0,
  141790. 9,
  141791. 9
  141792. };
  141793. static static_codebook _44cn1_sm_p4_0 = {
  141794. 2, 81,
  141795. _vq_lengthlist__44cn1_sm_p4_0,
  141796. 1, -531628032, 1611661312, 4, 0,
  141797. _vq_quantlist__44cn1_sm_p4_0,
  141798. NULL,
  141799. &_vq_auxt__44cn1_sm_p4_0,
  141800. NULL,
  141801. 0
  141802. };
  141803. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141804. 8,
  141805. 7,
  141806. 9,
  141807. 6,
  141808. 10,
  141809. 5,
  141810. 11,
  141811. 4,
  141812. 12,
  141813. 3,
  141814. 13,
  141815. 2,
  141816. 14,
  141817. 1,
  141818. 15,
  141819. 0,
  141820. 16,
  141821. };
  141822. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141823. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141824. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141825. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141826. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141827. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141828. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141829. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141830. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141831. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141832. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141833. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141834. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141835. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141836. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141837. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141838. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141839. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141840. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141841. 14,
  141842. };
  141843. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141844. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141845. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141846. };
  141847. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141848. 15, 13, 11, 9, 7, 5, 3, 1,
  141849. 0, 2, 4, 6, 8, 10, 12, 14,
  141850. 16,
  141851. };
  141852. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141853. _vq_quantthresh__44cn1_sm_p5_0,
  141854. _vq_quantmap__44cn1_sm_p5_0,
  141855. 17,
  141856. 17
  141857. };
  141858. static static_codebook _44cn1_sm_p5_0 = {
  141859. 2, 289,
  141860. _vq_lengthlist__44cn1_sm_p5_0,
  141861. 1, -529530880, 1611661312, 5, 0,
  141862. _vq_quantlist__44cn1_sm_p5_0,
  141863. NULL,
  141864. &_vq_auxt__44cn1_sm_p5_0,
  141865. NULL,
  141866. 0
  141867. };
  141868. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141869. 1,
  141870. 0,
  141871. 2,
  141872. };
  141873. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141874. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141875. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141876. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141877. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141878. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141879. 10,
  141880. };
  141881. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141882. -5.5, 5.5,
  141883. };
  141884. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141885. 1, 0, 2,
  141886. };
  141887. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141888. _vq_quantthresh__44cn1_sm_p6_0,
  141889. _vq_quantmap__44cn1_sm_p6_0,
  141890. 3,
  141891. 3
  141892. };
  141893. static static_codebook _44cn1_sm_p6_0 = {
  141894. 4, 81,
  141895. _vq_lengthlist__44cn1_sm_p6_0,
  141896. 1, -529137664, 1618345984, 2, 0,
  141897. _vq_quantlist__44cn1_sm_p6_0,
  141898. NULL,
  141899. &_vq_auxt__44cn1_sm_p6_0,
  141900. NULL,
  141901. 0
  141902. };
  141903. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141904. 5,
  141905. 4,
  141906. 6,
  141907. 3,
  141908. 7,
  141909. 2,
  141910. 8,
  141911. 1,
  141912. 9,
  141913. 0,
  141914. 10,
  141915. };
  141916. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141917. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141918. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141919. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141920. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141921. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141922. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141923. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141924. 10,10,10, 8, 9, 8, 8, 9, 8,
  141925. };
  141926. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141927. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141928. 3.5, 4.5,
  141929. };
  141930. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141931. 9, 7, 5, 3, 1, 0, 2, 4,
  141932. 6, 8, 10,
  141933. };
  141934. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141935. _vq_quantthresh__44cn1_sm_p6_1,
  141936. _vq_quantmap__44cn1_sm_p6_1,
  141937. 11,
  141938. 11
  141939. };
  141940. static static_codebook _44cn1_sm_p6_1 = {
  141941. 2, 121,
  141942. _vq_lengthlist__44cn1_sm_p6_1,
  141943. 1, -531365888, 1611661312, 4, 0,
  141944. _vq_quantlist__44cn1_sm_p6_1,
  141945. NULL,
  141946. &_vq_auxt__44cn1_sm_p6_1,
  141947. NULL,
  141948. 0
  141949. };
  141950. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141951. 6,
  141952. 5,
  141953. 7,
  141954. 4,
  141955. 8,
  141956. 3,
  141957. 9,
  141958. 2,
  141959. 10,
  141960. 1,
  141961. 11,
  141962. 0,
  141963. 12,
  141964. };
  141965. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141966. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141967. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141968. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141969. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141970. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141971. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141972. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141973. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141974. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141975. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141976. 0,13,12,12,12,13,13,13,14,
  141977. };
  141978. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141979. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141980. 12.5, 17.5, 22.5, 27.5,
  141981. };
  141982. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141983. 11, 9, 7, 5, 3, 1, 0, 2,
  141984. 4, 6, 8, 10, 12,
  141985. };
  141986. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141987. _vq_quantthresh__44cn1_sm_p7_0,
  141988. _vq_quantmap__44cn1_sm_p7_0,
  141989. 13,
  141990. 13
  141991. };
  141992. static static_codebook _44cn1_sm_p7_0 = {
  141993. 2, 169,
  141994. _vq_lengthlist__44cn1_sm_p7_0,
  141995. 1, -526516224, 1616117760, 4, 0,
  141996. _vq_quantlist__44cn1_sm_p7_0,
  141997. NULL,
  141998. &_vq_auxt__44cn1_sm_p7_0,
  141999. NULL,
  142000. 0
  142001. };
  142002. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  142003. 2,
  142004. 1,
  142005. 3,
  142006. 0,
  142007. 4,
  142008. };
  142009. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142010. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142011. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142012. };
  142013. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142014. -1.5, -0.5, 0.5, 1.5,
  142015. };
  142016. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142017. 3, 1, 0, 2, 4,
  142018. };
  142019. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142020. _vq_quantthresh__44cn1_sm_p7_1,
  142021. _vq_quantmap__44cn1_sm_p7_1,
  142022. 5,
  142023. 5
  142024. };
  142025. static static_codebook _44cn1_sm_p7_1 = {
  142026. 2, 25,
  142027. _vq_lengthlist__44cn1_sm_p7_1,
  142028. 1, -533725184, 1611661312, 3, 0,
  142029. _vq_quantlist__44cn1_sm_p7_1,
  142030. NULL,
  142031. &_vq_auxt__44cn1_sm_p7_1,
  142032. NULL,
  142033. 0
  142034. };
  142035. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142036. 4,
  142037. 3,
  142038. 5,
  142039. 2,
  142040. 6,
  142041. 1,
  142042. 7,
  142043. 0,
  142044. 8,
  142045. };
  142046. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142047. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142048. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142049. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142050. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142051. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142052. 14,
  142053. };
  142054. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142055. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142056. };
  142057. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142058. 7, 5, 3, 1, 0, 2, 4, 6,
  142059. 8,
  142060. };
  142061. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142062. _vq_quantthresh__44cn1_sm_p8_0,
  142063. _vq_quantmap__44cn1_sm_p8_0,
  142064. 9,
  142065. 9
  142066. };
  142067. static static_codebook _44cn1_sm_p8_0 = {
  142068. 2, 81,
  142069. _vq_lengthlist__44cn1_sm_p8_0,
  142070. 1, -516186112, 1627103232, 4, 0,
  142071. _vq_quantlist__44cn1_sm_p8_0,
  142072. NULL,
  142073. &_vq_auxt__44cn1_sm_p8_0,
  142074. NULL,
  142075. 0
  142076. };
  142077. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142078. 6,
  142079. 5,
  142080. 7,
  142081. 4,
  142082. 8,
  142083. 3,
  142084. 9,
  142085. 2,
  142086. 10,
  142087. 1,
  142088. 11,
  142089. 0,
  142090. 12,
  142091. };
  142092. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142093. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142094. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142095. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142096. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142097. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142098. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142099. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142100. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142101. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142102. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142103. 17,12,12,11,10,13,11,13,13,
  142104. };
  142105. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142106. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142107. 42.5, 59.5, 76.5, 93.5,
  142108. };
  142109. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142110. 11, 9, 7, 5, 3, 1, 0, 2,
  142111. 4, 6, 8, 10, 12,
  142112. };
  142113. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142114. _vq_quantthresh__44cn1_sm_p8_1,
  142115. _vq_quantmap__44cn1_sm_p8_1,
  142116. 13,
  142117. 13
  142118. };
  142119. static static_codebook _44cn1_sm_p8_1 = {
  142120. 2, 169,
  142121. _vq_lengthlist__44cn1_sm_p8_1,
  142122. 1, -522616832, 1620115456, 4, 0,
  142123. _vq_quantlist__44cn1_sm_p8_1,
  142124. NULL,
  142125. &_vq_auxt__44cn1_sm_p8_1,
  142126. NULL,
  142127. 0
  142128. };
  142129. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142130. 8,
  142131. 7,
  142132. 9,
  142133. 6,
  142134. 10,
  142135. 5,
  142136. 11,
  142137. 4,
  142138. 12,
  142139. 3,
  142140. 13,
  142141. 2,
  142142. 14,
  142143. 1,
  142144. 15,
  142145. 0,
  142146. 16,
  142147. };
  142148. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142149. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142150. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142151. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142152. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142153. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142154. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142155. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142156. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142157. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142158. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142159. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142160. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142161. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142162. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142163. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142164. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142165. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142166. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142167. 9,
  142168. };
  142169. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142170. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142171. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142172. };
  142173. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142174. 15, 13, 11, 9, 7, 5, 3, 1,
  142175. 0, 2, 4, 6, 8, 10, 12, 14,
  142176. 16,
  142177. };
  142178. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142179. _vq_quantthresh__44cn1_sm_p8_2,
  142180. _vq_quantmap__44cn1_sm_p8_2,
  142181. 17,
  142182. 17
  142183. };
  142184. static static_codebook _44cn1_sm_p8_2 = {
  142185. 2, 289,
  142186. _vq_lengthlist__44cn1_sm_p8_2,
  142187. 1, -529530880, 1611661312, 5, 0,
  142188. _vq_quantlist__44cn1_sm_p8_2,
  142189. NULL,
  142190. &_vq_auxt__44cn1_sm_p8_2,
  142191. NULL,
  142192. 0
  142193. };
  142194. static long _huff_lengthlist__44cn1_sm_short[] = {
  142195. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142196. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142197. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142198. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142199. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142200. 9,
  142201. };
  142202. static static_codebook _huff_book__44cn1_sm_short = {
  142203. 2, 81,
  142204. _huff_lengthlist__44cn1_sm_short,
  142205. 0, 0, 0, 0, 0,
  142206. NULL,
  142207. NULL,
  142208. NULL,
  142209. NULL,
  142210. 0
  142211. };
  142212. /*** End of inlined file: res_books_stereo.h ***/
  142213. /***** residue backends *********************************************/
  142214. static vorbis_info_residue0 _residue_44_low={
  142215. 0,-1, -1, 9,-1,
  142216. /* 0 1 2 3 4 5 6 7 */
  142217. {0},
  142218. {-1},
  142219. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142220. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142221. };
  142222. static vorbis_info_residue0 _residue_44_mid={
  142223. 0,-1, -1, 10,-1,
  142224. /* 0 1 2 3 4 5 6 7 8 */
  142225. {0},
  142226. {-1},
  142227. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142228. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142229. };
  142230. static vorbis_info_residue0 _residue_44_high={
  142231. 0,-1, -1, 10,-1,
  142232. /* 0 1 2 3 4 5 6 7 8 */
  142233. {0},
  142234. {-1},
  142235. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142236. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142237. };
  142238. static static_bookblock _resbook_44s_n1={
  142239. {
  142240. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142241. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142242. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142243. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142244. }
  142245. };
  142246. static static_bookblock _resbook_44sm_n1={
  142247. {
  142248. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142249. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142250. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142251. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142252. }
  142253. };
  142254. static static_bookblock _resbook_44s_0={
  142255. {
  142256. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142257. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142258. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142259. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142260. }
  142261. };
  142262. static static_bookblock _resbook_44sm_0={
  142263. {
  142264. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142265. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142266. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142267. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142268. }
  142269. };
  142270. static static_bookblock _resbook_44s_1={
  142271. {
  142272. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142273. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142274. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142275. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142276. }
  142277. };
  142278. static static_bookblock _resbook_44sm_1={
  142279. {
  142280. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142281. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142282. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142283. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142284. }
  142285. };
  142286. static static_bookblock _resbook_44s_2={
  142287. {
  142288. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142289. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142290. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142291. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142292. }
  142293. };
  142294. static static_bookblock _resbook_44s_3={
  142295. {
  142296. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142297. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142298. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142299. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142300. }
  142301. };
  142302. static static_bookblock _resbook_44s_4={
  142303. {
  142304. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142305. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142306. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142307. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142308. }
  142309. };
  142310. static static_bookblock _resbook_44s_5={
  142311. {
  142312. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142313. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142314. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142315. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142316. }
  142317. };
  142318. static static_bookblock _resbook_44s_6={
  142319. {
  142320. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142321. {0,0,&_44c6_s_p4_0},
  142322. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142323. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142324. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142325. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142326. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142327. }
  142328. };
  142329. static static_bookblock _resbook_44s_7={
  142330. {
  142331. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142332. {0,0,&_44c7_s_p4_0},
  142333. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142334. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142335. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142336. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142337. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142338. }
  142339. };
  142340. static static_bookblock _resbook_44s_8={
  142341. {
  142342. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142343. {0,0,&_44c8_s_p4_0},
  142344. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142345. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142346. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142347. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142348. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142349. }
  142350. };
  142351. static static_bookblock _resbook_44s_9={
  142352. {
  142353. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142354. {0,0,&_44c9_s_p4_0},
  142355. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142356. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142357. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142358. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142359. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142360. }
  142361. };
  142362. static vorbis_residue_template _res_44s_n1[]={
  142363. {2,0, &_residue_44_low,
  142364. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142365. &_resbook_44s_n1,&_resbook_44sm_n1},
  142366. {2,0, &_residue_44_low,
  142367. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142368. &_resbook_44s_n1,&_resbook_44sm_n1}
  142369. };
  142370. static vorbis_residue_template _res_44s_0[]={
  142371. {2,0, &_residue_44_low,
  142372. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142373. &_resbook_44s_0,&_resbook_44sm_0},
  142374. {2,0, &_residue_44_low,
  142375. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142376. &_resbook_44s_0,&_resbook_44sm_0}
  142377. };
  142378. static vorbis_residue_template _res_44s_1[]={
  142379. {2,0, &_residue_44_low,
  142380. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142381. &_resbook_44s_1,&_resbook_44sm_1},
  142382. {2,0, &_residue_44_low,
  142383. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142384. &_resbook_44s_1,&_resbook_44sm_1}
  142385. };
  142386. static vorbis_residue_template _res_44s_2[]={
  142387. {2,0, &_residue_44_mid,
  142388. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142389. &_resbook_44s_2,&_resbook_44s_2},
  142390. {2,0, &_residue_44_mid,
  142391. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142392. &_resbook_44s_2,&_resbook_44s_2}
  142393. };
  142394. static vorbis_residue_template _res_44s_3[]={
  142395. {2,0, &_residue_44_mid,
  142396. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142397. &_resbook_44s_3,&_resbook_44s_3},
  142398. {2,0, &_residue_44_mid,
  142399. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142400. &_resbook_44s_3,&_resbook_44s_3}
  142401. };
  142402. static vorbis_residue_template _res_44s_4[]={
  142403. {2,0, &_residue_44_mid,
  142404. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142405. &_resbook_44s_4,&_resbook_44s_4},
  142406. {2,0, &_residue_44_mid,
  142407. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142408. &_resbook_44s_4,&_resbook_44s_4}
  142409. };
  142410. static vorbis_residue_template _res_44s_5[]={
  142411. {2,0, &_residue_44_mid,
  142412. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142413. &_resbook_44s_5,&_resbook_44s_5},
  142414. {2,0, &_residue_44_mid,
  142415. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142416. &_resbook_44s_5,&_resbook_44s_5}
  142417. };
  142418. static vorbis_residue_template _res_44s_6[]={
  142419. {2,0, &_residue_44_high,
  142420. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142421. &_resbook_44s_6,&_resbook_44s_6},
  142422. {2,0, &_residue_44_high,
  142423. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142424. &_resbook_44s_6,&_resbook_44s_6}
  142425. };
  142426. static vorbis_residue_template _res_44s_7[]={
  142427. {2,0, &_residue_44_high,
  142428. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142429. &_resbook_44s_7,&_resbook_44s_7},
  142430. {2,0, &_residue_44_high,
  142431. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142432. &_resbook_44s_7,&_resbook_44s_7}
  142433. };
  142434. static vorbis_residue_template _res_44s_8[]={
  142435. {2,0, &_residue_44_high,
  142436. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142437. &_resbook_44s_8,&_resbook_44s_8},
  142438. {2,0, &_residue_44_high,
  142439. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142440. &_resbook_44s_8,&_resbook_44s_8}
  142441. };
  142442. static vorbis_residue_template _res_44s_9[]={
  142443. {2,0, &_residue_44_high,
  142444. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142445. &_resbook_44s_9,&_resbook_44s_9},
  142446. {2,0, &_residue_44_high,
  142447. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142448. &_resbook_44s_9,&_resbook_44s_9}
  142449. };
  142450. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142451. { _map_nominal, _res_44s_n1 }, /* -1 */
  142452. { _map_nominal, _res_44s_0 }, /* 0 */
  142453. { _map_nominal, _res_44s_1 }, /* 1 */
  142454. { _map_nominal, _res_44s_2 }, /* 2 */
  142455. { _map_nominal, _res_44s_3 }, /* 3 */
  142456. { _map_nominal, _res_44s_4 }, /* 4 */
  142457. { _map_nominal, _res_44s_5 }, /* 5 */
  142458. { _map_nominal, _res_44s_6 }, /* 6 */
  142459. { _map_nominal, _res_44s_7 }, /* 7 */
  142460. { _map_nominal, _res_44s_8 }, /* 8 */
  142461. { _map_nominal, _res_44s_9 }, /* 9 */
  142462. };
  142463. /*** End of inlined file: residue_44.h ***/
  142464. /*** Start of inlined file: psych_44.h ***/
  142465. /* preecho trigger settings *****************************************/
  142466. static vorbis_info_psy_global _psy_global_44[5]={
  142467. {8, /* lines per eighth octave */
  142468. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142469. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142470. -6.f,
  142471. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142472. },
  142473. {8, /* lines per eighth octave */
  142474. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142475. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142476. -6.f,
  142477. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142478. },
  142479. {8, /* lines per eighth octave */
  142480. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142481. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142482. -6.f,
  142483. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142484. },
  142485. {8, /* lines per eighth octave */
  142486. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142487. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142488. -6.f,
  142489. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142490. },
  142491. {8, /* lines per eighth octave */
  142492. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142493. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142494. -6.f,
  142495. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142496. },
  142497. };
  142498. /* noise compander lookups * low, mid, high quality ****************/
  142499. static compandblock _psy_compand_44[6]={
  142500. /* sub-mode Z short */
  142501. {{
  142502. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142503. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142504. 16,17,18,19,20,21,22, 23, /* 23dB */
  142505. 24,25,26,27,28,29,30, 31, /* 31dB */
  142506. 32,33,34,35,36,37,38, 39, /* 39dB */
  142507. }},
  142508. /* mode_Z nominal short */
  142509. {{
  142510. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142511. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142512. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142513. 15,16,17,17,17,18,18, 19, /* 31dB */
  142514. 19,19,20,21,22,23,24, 25, /* 39dB */
  142515. }},
  142516. /* mode A short */
  142517. {{
  142518. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142519. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142520. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142521. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142522. 11,12,13,14,15,16,17, 18, /* 39dB */
  142523. }},
  142524. /* sub-mode Z long */
  142525. {{
  142526. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142527. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142528. 16,17,18,19,20,21,22, 23, /* 23dB */
  142529. 24,25,26,27,28,29,30, 31, /* 31dB */
  142530. 32,33,34,35,36,37,38, 39, /* 39dB */
  142531. }},
  142532. /* mode_Z nominal long */
  142533. {{
  142534. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142535. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142536. 13,14,14,14,15,15,15, 15, /* 23dB */
  142537. 16,16,17,17,17,18,18, 19, /* 31dB */
  142538. 19,19,20,21,22,23,24, 25, /* 39dB */
  142539. }},
  142540. /* mode A long */
  142541. {{
  142542. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142543. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142544. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142545. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142546. 11,12,13,14,15,16,17, 18, /* 39dB */
  142547. }}
  142548. };
  142549. /* tonal masking curve level adjustments *************************/
  142550. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142551. /* 63 125 250 500 1 2 4 8 16 */
  142552. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142553. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142554. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142555. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142556. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142557. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142558. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142559. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142560. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142561. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142562. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142563. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142564. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142565. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142566. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142567. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142568. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142569. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142570. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142571. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142572. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142573. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142574. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142575. };
  142576. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142577. /* 63 125 250 500 1 2 4 8 16 */
  142578. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142579. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142580. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142581. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142582. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142583. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142584. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142585. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142586. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142587. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142588. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142589. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142590. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142591. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142592. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142593. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142594. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142595. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142596. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142597. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142598. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142599. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142600. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142601. };
  142602. /* noise bias (transition block) */
  142603. static noise3 _psy_noisebias_trans[12]={
  142604. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142605. /* -1 */
  142606. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142607. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142608. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142609. /* 0
  142610. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142611. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142612. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142613. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142614. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142615. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142616. /* 1
  142617. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142618. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142619. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142620. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142621. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142622. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142623. /* 2
  142624. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142625. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142626. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142627. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142628. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142629. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142630. /* 3
  142631. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142632. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142633. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142634. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142635. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142636. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142637. /* 4
  142638. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142639. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142640. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142641. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142642. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142643. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142644. /* 5
  142645. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142646. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142647. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142648. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142649. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142650. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142651. /* 6
  142652. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142653. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142654. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142655. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142656. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142657. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142658. /* 7
  142659. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142660. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142661. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142662. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142663. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142664. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142665. /* 8
  142666. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142667. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142668. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142669. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142670. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142671. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142672. /* 9
  142673. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142674. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142675. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142676. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142677. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142678. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142679. /* 10 */
  142680. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142681. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142682. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142683. };
  142684. /* noise bias (long block) */
  142685. static noise3 _psy_noisebias_long[12]={
  142686. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142687. /* -1 */
  142688. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142689. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142690. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142691. /* 0 */
  142692. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142693. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142694. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142695. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142696. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142697. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142698. /* 1 */
  142699. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142700. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142701. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142702. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142703. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142704. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142705. /* 2 */
  142706. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142707. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142708. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142709. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142710. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142711. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142712. /* 3 */
  142713. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142714. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142715. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142716. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142717. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142718. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142719. /* 4 */
  142720. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142721. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142722. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142723. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142724. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142725. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142726. /* 5 */
  142727. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142728. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142729. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142730. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142731. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142732. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142733. /* 6 */
  142734. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142735. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142736. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142737. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142738. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142739. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142740. /* 7 */
  142741. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142742. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142743. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142744. /* 8 */
  142745. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142746. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142747. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142748. /* 9 */
  142749. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142750. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142751. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142752. /* 10 */
  142753. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142754. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142755. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142756. };
  142757. /* noise bias (impulse block) */
  142758. static noise3 _psy_noisebias_impulse[12]={
  142759. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142760. /* -1 */
  142761. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142762. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142763. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142764. /* 0 */
  142765. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142766. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142767. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142768. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142769. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142770. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142771. /* 1 */
  142772. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142773. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142774. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142775. /* 2 */
  142776. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142777. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142778. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142779. /* 3 */
  142780. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142781. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142782. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142783. /* 4 */
  142784. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142785. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142786. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142787. /* 5 */
  142788. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142789. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142790. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142791. /* 6
  142792. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142793. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142794. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142795. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142796. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142797. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142798. /* 7 */
  142799. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142800. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142801. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142802. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142803. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142804. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142805. /* 8 */
  142806. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142807. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142808. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142809. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142810. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142811. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142812. /* 9 */
  142813. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142814. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142815. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142816. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142817. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142818. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142819. /* 10 */
  142820. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142821. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142822. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142823. };
  142824. /* noise bias (padding block) */
  142825. static noise3 _psy_noisebias_padding[12]={
  142826. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142827. /* -1 */
  142828. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142829. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142830. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142831. /* 0 */
  142832. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142833. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142834. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142835. /* 1 */
  142836. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142837. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142838. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142839. /* 2 */
  142840. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142841. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142842. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142843. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142844. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142845. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142846. /* 3 */
  142847. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142848. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142849. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142850. /* 4 */
  142851. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142852. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142853. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142854. /* 5 */
  142855. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142856. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142857. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142858. /* 6 */
  142859. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142860. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142861. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142862. /* 7 */
  142863. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142864. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142865. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142866. /* 8 */
  142867. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142868. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142869. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142870. /* 9 */
  142871. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142872. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142873. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142874. /* 10 */
  142875. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142876. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142877. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142878. };
  142879. static noiseguard _psy_noiseguards_44[4]={
  142880. {3,3,15},
  142881. {3,3,15},
  142882. {10,10,100},
  142883. {10,10,100},
  142884. };
  142885. static int _psy_tone_suppress[12]={
  142886. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142887. };
  142888. static int _psy_tone_0dB[12]={
  142889. 90,90,95,95,95,95,105,105,105,105,105,105,
  142890. };
  142891. static int _psy_noise_suppress[12]={
  142892. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142893. };
  142894. static vorbis_info_psy _psy_info_template={
  142895. /* blockflag */
  142896. -1,
  142897. /* ath_adjatt, ath_maxatt */
  142898. -140.,-140.,
  142899. /* tonemask att boost/decay,suppr,curves */
  142900. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142901. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142902. 1, -0.f, .5f, .5f, 0,0,0,
  142903. /* noiseoffset*3, noisecompand, max_curve_dB */
  142904. {{-1},{-1},{-1}},{-1},105.f,
  142905. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142906. 0,0,-1,-1,0.,
  142907. };
  142908. /* ath ****************/
  142909. static int _psy_ath_floater[12]={
  142910. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142911. };
  142912. static int _psy_ath_abs[12]={
  142913. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142914. };
  142915. /* stereo setup. These don't map directly to quality level, there's
  142916. an additional indirection as several of the below may be used in a
  142917. single bitmanaged stream
  142918. ****************/
  142919. /* various stereo possibilities */
  142920. /* stereo mode by base quality level */
  142921. static adj_stereo _psy_stereo_modes_44[12]={
  142922. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142923. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142924. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142925. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142926. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142927. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142928. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142929. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142930. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142931. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142932. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142933. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142934. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142935. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142936. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142937. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142938. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142939. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142940. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142941. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142942. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142943. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142944. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142945. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142946. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142947. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142948. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142949. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142950. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142951. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142952. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142953. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142954. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142955. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142956. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142957. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142958. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142959. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142960. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142961. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142962. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142963. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142964. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142965. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142966. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142967. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142968. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142969. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142970. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142971. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142972. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142973. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142974. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142975. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142976. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142977. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142978. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142979. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142980. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142981. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142982. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142983. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142984. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142985. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142986. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142987. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142988. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142989. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142990. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142991. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142992. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142993. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142994. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142995. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142996. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142997. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142998. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142999. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143000. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143001. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  143002. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143003. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143004. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143005. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143006. };
  143007. /* tone master attenuation by base quality mode and bitrate tweak */
  143008. static att3 _psy_tone_masteratt_44[12]={
  143009. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143010. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143011. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143012. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143013. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143014. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143015. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143016. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143017. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143018. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143019. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143020. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143021. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143022. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143023. };
  143024. /* lowpass by mode **************/
  143025. static double _psy_lowpass_44[12]={
  143026. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143027. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143028. };
  143029. /* noise normalization **********/
  143030. static int _noise_start_short_44[11]={
  143031. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143032. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143033. };
  143034. static int _noise_start_long_44[11]={
  143035. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143036. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143037. };
  143038. static int _noise_part_short_44[11]={
  143039. 8,8,8,8,8,8,8,8,8,8,8
  143040. };
  143041. static int _noise_part_long_44[11]={
  143042. 32,32,32,32,32,32,32,32,32,32,32
  143043. };
  143044. static double _noise_thresh_44[11]={
  143045. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143046. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143047. };
  143048. static double _noise_thresh_5only[2]={
  143049. .5,.5,
  143050. };
  143051. /*** End of inlined file: psych_44.h ***/
  143052. static double rate_mapping_44_stereo[12]={
  143053. 22500.,32000.,40000.,48000.,56000.,64000.,
  143054. 80000.,96000.,112000.,128000.,160000.,250001.
  143055. };
  143056. static double quality_mapping_44[12]={
  143057. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143058. };
  143059. static int blocksize_short_44[11]={
  143060. 512,256,256,256,256,256,256,256,256,256,256
  143061. };
  143062. static int blocksize_long_44[11]={
  143063. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143064. };
  143065. static double _psy_compand_short_mapping[12]={
  143066. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143067. };
  143068. static double _psy_compand_long_mapping[12]={
  143069. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143070. };
  143071. static double _global_mapping_44[12]={
  143072. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143073. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143074. };
  143075. static int _floor_short_mapping_44[11]={
  143076. 1,0,0,2,2,4,5,5,5,5,5
  143077. };
  143078. static int _floor_long_mapping_44[11]={
  143079. 8,7,7,7,7,7,7,7,7,7,7
  143080. };
  143081. ve_setup_data_template ve_setup_44_stereo={
  143082. 11,
  143083. rate_mapping_44_stereo,
  143084. quality_mapping_44,
  143085. 2,
  143086. 40000,
  143087. 50000,
  143088. blocksize_short_44,
  143089. blocksize_long_44,
  143090. _psy_tone_masteratt_44,
  143091. _psy_tone_0dB,
  143092. _psy_tone_suppress,
  143093. _vp_tonemask_adj_otherblock,
  143094. _vp_tonemask_adj_longblock,
  143095. _vp_tonemask_adj_otherblock,
  143096. _psy_noiseguards_44,
  143097. _psy_noisebias_impulse,
  143098. _psy_noisebias_padding,
  143099. _psy_noisebias_trans,
  143100. _psy_noisebias_long,
  143101. _psy_noise_suppress,
  143102. _psy_compand_44,
  143103. _psy_compand_short_mapping,
  143104. _psy_compand_long_mapping,
  143105. {_noise_start_short_44,_noise_start_long_44},
  143106. {_noise_part_short_44,_noise_part_long_44},
  143107. _noise_thresh_44,
  143108. _psy_ath_floater,
  143109. _psy_ath_abs,
  143110. _psy_lowpass_44,
  143111. _psy_global_44,
  143112. _global_mapping_44,
  143113. _psy_stereo_modes_44,
  143114. _floor_books,
  143115. _floor,
  143116. _floor_short_mapping_44,
  143117. _floor_long_mapping_44,
  143118. _mapres_template_44_stereo
  143119. };
  143120. /*** End of inlined file: setup_44.h ***/
  143121. /*** Start of inlined file: setup_44u.h ***/
  143122. /*** Start of inlined file: residue_44u.h ***/
  143123. /*** Start of inlined file: res_books_uncoupled.h ***/
  143124. static long _vq_quantlist__16u0__p1_0[] = {
  143125. 1,
  143126. 0,
  143127. 2,
  143128. };
  143129. static long _vq_lengthlist__16u0__p1_0[] = {
  143130. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143131. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143132. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143133. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143134. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143135. 12,
  143136. };
  143137. static float _vq_quantthresh__16u0__p1_0[] = {
  143138. -0.5, 0.5,
  143139. };
  143140. static long _vq_quantmap__16u0__p1_0[] = {
  143141. 1, 0, 2,
  143142. };
  143143. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143144. _vq_quantthresh__16u0__p1_0,
  143145. _vq_quantmap__16u0__p1_0,
  143146. 3,
  143147. 3
  143148. };
  143149. static static_codebook _16u0__p1_0 = {
  143150. 4, 81,
  143151. _vq_lengthlist__16u0__p1_0,
  143152. 1, -535822336, 1611661312, 2, 0,
  143153. _vq_quantlist__16u0__p1_0,
  143154. NULL,
  143155. &_vq_auxt__16u0__p1_0,
  143156. NULL,
  143157. 0
  143158. };
  143159. static long _vq_quantlist__16u0__p2_0[] = {
  143160. 1,
  143161. 0,
  143162. 2,
  143163. };
  143164. static long _vq_lengthlist__16u0__p2_0[] = {
  143165. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143166. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143167. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143168. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143169. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143170. 8,
  143171. };
  143172. static float _vq_quantthresh__16u0__p2_0[] = {
  143173. -0.5, 0.5,
  143174. };
  143175. static long _vq_quantmap__16u0__p2_0[] = {
  143176. 1, 0, 2,
  143177. };
  143178. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143179. _vq_quantthresh__16u0__p2_0,
  143180. _vq_quantmap__16u0__p2_0,
  143181. 3,
  143182. 3
  143183. };
  143184. static static_codebook _16u0__p2_0 = {
  143185. 4, 81,
  143186. _vq_lengthlist__16u0__p2_0,
  143187. 1, -535822336, 1611661312, 2, 0,
  143188. _vq_quantlist__16u0__p2_0,
  143189. NULL,
  143190. &_vq_auxt__16u0__p2_0,
  143191. NULL,
  143192. 0
  143193. };
  143194. static long _vq_quantlist__16u0__p3_0[] = {
  143195. 2,
  143196. 1,
  143197. 3,
  143198. 0,
  143199. 4,
  143200. };
  143201. static long _vq_lengthlist__16u0__p3_0[] = {
  143202. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143203. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143204. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143205. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143206. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143207. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143208. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143209. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143210. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143211. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143212. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143213. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143214. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143215. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143216. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143217. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143218. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143219. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143220. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143221. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143222. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143223. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143224. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143225. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143226. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143227. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143228. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143229. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143230. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143231. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143232. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143233. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143234. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143235. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143236. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143237. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143238. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143239. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143240. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143241. 18,
  143242. };
  143243. static float _vq_quantthresh__16u0__p3_0[] = {
  143244. -1.5, -0.5, 0.5, 1.5,
  143245. };
  143246. static long _vq_quantmap__16u0__p3_0[] = {
  143247. 3, 1, 0, 2, 4,
  143248. };
  143249. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143250. _vq_quantthresh__16u0__p3_0,
  143251. _vq_quantmap__16u0__p3_0,
  143252. 5,
  143253. 5
  143254. };
  143255. static static_codebook _16u0__p3_0 = {
  143256. 4, 625,
  143257. _vq_lengthlist__16u0__p3_0,
  143258. 1, -533725184, 1611661312, 3, 0,
  143259. _vq_quantlist__16u0__p3_0,
  143260. NULL,
  143261. &_vq_auxt__16u0__p3_0,
  143262. NULL,
  143263. 0
  143264. };
  143265. static long _vq_quantlist__16u0__p4_0[] = {
  143266. 2,
  143267. 1,
  143268. 3,
  143269. 0,
  143270. 4,
  143271. };
  143272. static long _vq_lengthlist__16u0__p4_0[] = {
  143273. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143274. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143275. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143276. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143277. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143278. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143279. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143280. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143281. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143282. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143283. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143284. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143285. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143286. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143287. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143288. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143289. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143290. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143291. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143292. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143293. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143294. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143295. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143296. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143297. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143298. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143299. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143300. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143301. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143302. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143303. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143304. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143305. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143306. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143307. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143308. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143309. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143310. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143311. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143312. 11,
  143313. };
  143314. static float _vq_quantthresh__16u0__p4_0[] = {
  143315. -1.5, -0.5, 0.5, 1.5,
  143316. };
  143317. static long _vq_quantmap__16u0__p4_0[] = {
  143318. 3, 1, 0, 2, 4,
  143319. };
  143320. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143321. _vq_quantthresh__16u0__p4_0,
  143322. _vq_quantmap__16u0__p4_0,
  143323. 5,
  143324. 5
  143325. };
  143326. static static_codebook _16u0__p4_0 = {
  143327. 4, 625,
  143328. _vq_lengthlist__16u0__p4_0,
  143329. 1, -533725184, 1611661312, 3, 0,
  143330. _vq_quantlist__16u0__p4_0,
  143331. NULL,
  143332. &_vq_auxt__16u0__p4_0,
  143333. NULL,
  143334. 0
  143335. };
  143336. static long _vq_quantlist__16u0__p5_0[] = {
  143337. 4,
  143338. 3,
  143339. 5,
  143340. 2,
  143341. 6,
  143342. 1,
  143343. 7,
  143344. 0,
  143345. 8,
  143346. };
  143347. static long _vq_lengthlist__16u0__p5_0[] = {
  143348. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143349. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143350. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143351. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143352. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143353. 12,
  143354. };
  143355. static float _vq_quantthresh__16u0__p5_0[] = {
  143356. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143357. };
  143358. static long _vq_quantmap__16u0__p5_0[] = {
  143359. 7, 5, 3, 1, 0, 2, 4, 6,
  143360. 8,
  143361. };
  143362. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143363. _vq_quantthresh__16u0__p5_0,
  143364. _vq_quantmap__16u0__p5_0,
  143365. 9,
  143366. 9
  143367. };
  143368. static static_codebook _16u0__p5_0 = {
  143369. 2, 81,
  143370. _vq_lengthlist__16u0__p5_0,
  143371. 1, -531628032, 1611661312, 4, 0,
  143372. _vq_quantlist__16u0__p5_0,
  143373. NULL,
  143374. &_vq_auxt__16u0__p5_0,
  143375. NULL,
  143376. 0
  143377. };
  143378. static long _vq_quantlist__16u0__p6_0[] = {
  143379. 6,
  143380. 5,
  143381. 7,
  143382. 4,
  143383. 8,
  143384. 3,
  143385. 9,
  143386. 2,
  143387. 10,
  143388. 1,
  143389. 11,
  143390. 0,
  143391. 12,
  143392. };
  143393. static long _vq_lengthlist__16u0__p6_0[] = {
  143394. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143395. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143396. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143397. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143398. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143399. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143400. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143401. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143402. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143403. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143404. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143405. };
  143406. static float _vq_quantthresh__16u0__p6_0[] = {
  143407. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143408. 12.5, 17.5, 22.5, 27.5,
  143409. };
  143410. static long _vq_quantmap__16u0__p6_0[] = {
  143411. 11, 9, 7, 5, 3, 1, 0, 2,
  143412. 4, 6, 8, 10, 12,
  143413. };
  143414. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143415. _vq_quantthresh__16u0__p6_0,
  143416. _vq_quantmap__16u0__p6_0,
  143417. 13,
  143418. 13
  143419. };
  143420. static static_codebook _16u0__p6_0 = {
  143421. 2, 169,
  143422. _vq_lengthlist__16u0__p6_0,
  143423. 1, -526516224, 1616117760, 4, 0,
  143424. _vq_quantlist__16u0__p6_0,
  143425. NULL,
  143426. &_vq_auxt__16u0__p6_0,
  143427. NULL,
  143428. 0
  143429. };
  143430. static long _vq_quantlist__16u0__p6_1[] = {
  143431. 2,
  143432. 1,
  143433. 3,
  143434. 0,
  143435. 4,
  143436. };
  143437. static long _vq_lengthlist__16u0__p6_1[] = {
  143438. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143439. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143440. };
  143441. static float _vq_quantthresh__16u0__p6_1[] = {
  143442. -1.5, -0.5, 0.5, 1.5,
  143443. };
  143444. static long _vq_quantmap__16u0__p6_1[] = {
  143445. 3, 1, 0, 2, 4,
  143446. };
  143447. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143448. _vq_quantthresh__16u0__p6_1,
  143449. _vq_quantmap__16u0__p6_1,
  143450. 5,
  143451. 5
  143452. };
  143453. static static_codebook _16u0__p6_1 = {
  143454. 2, 25,
  143455. _vq_lengthlist__16u0__p6_1,
  143456. 1, -533725184, 1611661312, 3, 0,
  143457. _vq_quantlist__16u0__p6_1,
  143458. NULL,
  143459. &_vq_auxt__16u0__p6_1,
  143460. NULL,
  143461. 0
  143462. };
  143463. static long _vq_quantlist__16u0__p7_0[] = {
  143464. 1,
  143465. 0,
  143466. 2,
  143467. };
  143468. static long _vq_lengthlist__16u0__p7_0[] = {
  143469. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143470. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143471. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143472. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143473. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143474. 7,
  143475. };
  143476. static float _vq_quantthresh__16u0__p7_0[] = {
  143477. -157.5, 157.5,
  143478. };
  143479. static long _vq_quantmap__16u0__p7_0[] = {
  143480. 1, 0, 2,
  143481. };
  143482. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143483. _vq_quantthresh__16u0__p7_0,
  143484. _vq_quantmap__16u0__p7_0,
  143485. 3,
  143486. 3
  143487. };
  143488. static static_codebook _16u0__p7_0 = {
  143489. 4, 81,
  143490. _vq_lengthlist__16u0__p7_0,
  143491. 1, -518803456, 1628680192, 2, 0,
  143492. _vq_quantlist__16u0__p7_0,
  143493. NULL,
  143494. &_vq_auxt__16u0__p7_0,
  143495. NULL,
  143496. 0
  143497. };
  143498. static long _vq_quantlist__16u0__p7_1[] = {
  143499. 7,
  143500. 6,
  143501. 8,
  143502. 5,
  143503. 9,
  143504. 4,
  143505. 10,
  143506. 3,
  143507. 11,
  143508. 2,
  143509. 12,
  143510. 1,
  143511. 13,
  143512. 0,
  143513. 14,
  143514. };
  143515. static long _vq_lengthlist__16u0__p7_1[] = {
  143516. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143517. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143518. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143519. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143520. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143521. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143522. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143523. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143524. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143525. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143526. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143527. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143528. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143529. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143530. 10,
  143531. };
  143532. static float _vq_quantthresh__16u0__p7_1[] = {
  143533. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143534. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143535. };
  143536. static long _vq_quantmap__16u0__p7_1[] = {
  143537. 13, 11, 9, 7, 5, 3, 1, 0,
  143538. 2, 4, 6, 8, 10, 12, 14,
  143539. };
  143540. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143541. _vq_quantthresh__16u0__p7_1,
  143542. _vq_quantmap__16u0__p7_1,
  143543. 15,
  143544. 15
  143545. };
  143546. static static_codebook _16u0__p7_1 = {
  143547. 2, 225,
  143548. _vq_lengthlist__16u0__p7_1,
  143549. 1, -520986624, 1620377600, 4, 0,
  143550. _vq_quantlist__16u0__p7_1,
  143551. NULL,
  143552. &_vq_auxt__16u0__p7_1,
  143553. NULL,
  143554. 0
  143555. };
  143556. static long _vq_quantlist__16u0__p7_2[] = {
  143557. 10,
  143558. 9,
  143559. 11,
  143560. 8,
  143561. 12,
  143562. 7,
  143563. 13,
  143564. 6,
  143565. 14,
  143566. 5,
  143567. 15,
  143568. 4,
  143569. 16,
  143570. 3,
  143571. 17,
  143572. 2,
  143573. 18,
  143574. 1,
  143575. 19,
  143576. 0,
  143577. 20,
  143578. };
  143579. static long _vq_lengthlist__16u0__p7_2[] = {
  143580. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143581. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143582. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143583. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143584. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143585. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143586. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143587. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143588. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143589. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143590. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143591. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143592. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143593. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143594. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143595. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143596. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143597. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143598. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143599. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143600. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143601. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143602. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143603. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143604. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143605. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143606. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143607. 10,10,12,11,10,11,11,11,10,
  143608. };
  143609. static float _vq_quantthresh__16u0__p7_2[] = {
  143610. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143611. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143612. 6.5, 7.5, 8.5, 9.5,
  143613. };
  143614. static long _vq_quantmap__16u0__p7_2[] = {
  143615. 19, 17, 15, 13, 11, 9, 7, 5,
  143616. 3, 1, 0, 2, 4, 6, 8, 10,
  143617. 12, 14, 16, 18, 20,
  143618. };
  143619. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143620. _vq_quantthresh__16u0__p7_2,
  143621. _vq_quantmap__16u0__p7_2,
  143622. 21,
  143623. 21
  143624. };
  143625. static static_codebook _16u0__p7_2 = {
  143626. 2, 441,
  143627. _vq_lengthlist__16u0__p7_2,
  143628. 1, -529268736, 1611661312, 5, 0,
  143629. _vq_quantlist__16u0__p7_2,
  143630. NULL,
  143631. &_vq_auxt__16u0__p7_2,
  143632. NULL,
  143633. 0
  143634. };
  143635. static long _huff_lengthlist__16u0__single[] = {
  143636. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143637. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143638. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143639. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143640. };
  143641. static static_codebook _huff_book__16u0__single = {
  143642. 2, 64,
  143643. _huff_lengthlist__16u0__single,
  143644. 0, 0, 0, 0, 0,
  143645. NULL,
  143646. NULL,
  143647. NULL,
  143648. NULL,
  143649. 0
  143650. };
  143651. static long _huff_lengthlist__16u1__long[] = {
  143652. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143653. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143654. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143655. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143656. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143657. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143658. 16,13,16,18,
  143659. };
  143660. static static_codebook _huff_book__16u1__long = {
  143661. 2, 100,
  143662. _huff_lengthlist__16u1__long,
  143663. 0, 0, 0, 0, 0,
  143664. NULL,
  143665. NULL,
  143666. NULL,
  143667. NULL,
  143668. 0
  143669. };
  143670. static long _vq_quantlist__16u1__p1_0[] = {
  143671. 1,
  143672. 0,
  143673. 2,
  143674. };
  143675. static long _vq_lengthlist__16u1__p1_0[] = {
  143676. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143677. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143678. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143679. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143680. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143681. 11,
  143682. };
  143683. static float _vq_quantthresh__16u1__p1_0[] = {
  143684. -0.5, 0.5,
  143685. };
  143686. static long _vq_quantmap__16u1__p1_0[] = {
  143687. 1, 0, 2,
  143688. };
  143689. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143690. _vq_quantthresh__16u1__p1_0,
  143691. _vq_quantmap__16u1__p1_0,
  143692. 3,
  143693. 3
  143694. };
  143695. static static_codebook _16u1__p1_0 = {
  143696. 4, 81,
  143697. _vq_lengthlist__16u1__p1_0,
  143698. 1, -535822336, 1611661312, 2, 0,
  143699. _vq_quantlist__16u1__p1_0,
  143700. NULL,
  143701. &_vq_auxt__16u1__p1_0,
  143702. NULL,
  143703. 0
  143704. };
  143705. static long _vq_quantlist__16u1__p2_0[] = {
  143706. 1,
  143707. 0,
  143708. 2,
  143709. };
  143710. static long _vq_lengthlist__16u1__p2_0[] = {
  143711. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143712. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143713. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143714. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143715. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143716. 8,
  143717. };
  143718. static float _vq_quantthresh__16u1__p2_0[] = {
  143719. -0.5, 0.5,
  143720. };
  143721. static long _vq_quantmap__16u1__p2_0[] = {
  143722. 1, 0, 2,
  143723. };
  143724. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143725. _vq_quantthresh__16u1__p2_0,
  143726. _vq_quantmap__16u1__p2_0,
  143727. 3,
  143728. 3
  143729. };
  143730. static static_codebook _16u1__p2_0 = {
  143731. 4, 81,
  143732. _vq_lengthlist__16u1__p2_0,
  143733. 1, -535822336, 1611661312, 2, 0,
  143734. _vq_quantlist__16u1__p2_0,
  143735. NULL,
  143736. &_vq_auxt__16u1__p2_0,
  143737. NULL,
  143738. 0
  143739. };
  143740. static long _vq_quantlist__16u1__p3_0[] = {
  143741. 2,
  143742. 1,
  143743. 3,
  143744. 0,
  143745. 4,
  143746. };
  143747. static long _vq_lengthlist__16u1__p3_0[] = {
  143748. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143749. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143750. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143751. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143752. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143753. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143754. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143755. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143756. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143757. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143758. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143759. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143760. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143761. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143762. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143763. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143764. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143765. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143766. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143767. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143768. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143769. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143770. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143771. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143772. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143773. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143774. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143775. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143776. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143777. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143778. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143779. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143780. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143781. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143782. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143783. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143784. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143785. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143786. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143787. 16,
  143788. };
  143789. static float _vq_quantthresh__16u1__p3_0[] = {
  143790. -1.5, -0.5, 0.5, 1.5,
  143791. };
  143792. static long _vq_quantmap__16u1__p3_0[] = {
  143793. 3, 1, 0, 2, 4,
  143794. };
  143795. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143796. _vq_quantthresh__16u1__p3_0,
  143797. _vq_quantmap__16u1__p3_0,
  143798. 5,
  143799. 5
  143800. };
  143801. static static_codebook _16u1__p3_0 = {
  143802. 4, 625,
  143803. _vq_lengthlist__16u1__p3_0,
  143804. 1, -533725184, 1611661312, 3, 0,
  143805. _vq_quantlist__16u1__p3_0,
  143806. NULL,
  143807. &_vq_auxt__16u1__p3_0,
  143808. NULL,
  143809. 0
  143810. };
  143811. static long _vq_quantlist__16u1__p4_0[] = {
  143812. 2,
  143813. 1,
  143814. 3,
  143815. 0,
  143816. 4,
  143817. };
  143818. static long _vq_lengthlist__16u1__p4_0[] = {
  143819. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143820. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143821. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143822. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143823. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143824. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143825. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143826. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143827. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143828. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143829. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143830. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143831. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143832. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143833. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143834. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143835. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143836. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143837. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143838. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143839. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143840. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143841. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143842. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143843. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143844. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143845. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143846. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143847. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143848. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143849. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143850. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143851. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143852. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143853. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143854. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143855. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143856. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143857. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143858. 11,
  143859. };
  143860. static float _vq_quantthresh__16u1__p4_0[] = {
  143861. -1.5, -0.5, 0.5, 1.5,
  143862. };
  143863. static long _vq_quantmap__16u1__p4_0[] = {
  143864. 3, 1, 0, 2, 4,
  143865. };
  143866. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143867. _vq_quantthresh__16u1__p4_0,
  143868. _vq_quantmap__16u1__p4_0,
  143869. 5,
  143870. 5
  143871. };
  143872. static static_codebook _16u1__p4_0 = {
  143873. 4, 625,
  143874. _vq_lengthlist__16u1__p4_0,
  143875. 1, -533725184, 1611661312, 3, 0,
  143876. _vq_quantlist__16u1__p4_0,
  143877. NULL,
  143878. &_vq_auxt__16u1__p4_0,
  143879. NULL,
  143880. 0
  143881. };
  143882. static long _vq_quantlist__16u1__p5_0[] = {
  143883. 4,
  143884. 3,
  143885. 5,
  143886. 2,
  143887. 6,
  143888. 1,
  143889. 7,
  143890. 0,
  143891. 8,
  143892. };
  143893. static long _vq_lengthlist__16u1__p5_0[] = {
  143894. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143895. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143896. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143897. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143898. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143899. 13,
  143900. };
  143901. static float _vq_quantthresh__16u1__p5_0[] = {
  143902. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143903. };
  143904. static long _vq_quantmap__16u1__p5_0[] = {
  143905. 7, 5, 3, 1, 0, 2, 4, 6,
  143906. 8,
  143907. };
  143908. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143909. _vq_quantthresh__16u1__p5_0,
  143910. _vq_quantmap__16u1__p5_0,
  143911. 9,
  143912. 9
  143913. };
  143914. static static_codebook _16u1__p5_0 = {
  143915. 2, 81,
  143916. _vq_lengthlist__16u1__p5_0,
  143917. 1, -531628032, 1611661312, 4, 0,
  143918. _vq_quantlist__16u1__p5_0,
  143919. NULL,
  143920. &_vq_auxt__16u1__p5_0,
  143921. NULL,
  143922. 0
  143923. };
  143924. static long _vq_quantlist__16u1__p6_0[] = {
  143925. 4,
  143926. 3,
  143927. 5,
  143928. 2,
  143929. 6,
  143930. 1,
  143931. 7,
  143932. 0,
  143933. 8,
  143934. };
  143935. static long _vq_lengthlist__16u1__p6_0[] = {
  143936. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143937. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143938. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143939. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143940. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143941. 11,
  143942. };
  143943. static float _vq_quantthresh__16u1__p6_0[] = {
  143944. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143945. };
  143946. static long _vq_quantmap__16u1__p6_0[] = {
  143947. 7, 5, 3, 1, 0, 2, 4, 6,
  143948. 8,
  143949. };
  143950. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143951. _vq_quantthresh__16u1__p6_0,
  143952. _vq_quantmap__16u1__p6_0,
  143953. 9,
  143954. 9
  143955. };
  143956. static static_codebook _16u1__p6_0 = {
  143957. 2, 81,
  143958. _vq_lengthlist__16u1__p6_0,
  143959. 1, -531628032, 1611661312, 4, 0,
  143960. _vq_quantlist__16u1__p6_0,
  143961. NULL,
  143962. &_vq_auxt__16u1__p6_0,
  143963. NULL,
  143964. 0
  143965. };
  143966. static long _vq_quantlist__16u1__p7_0[] = {
  143967. 1,
  143968. 0,
  143969. 2,
  143970. };
  143971. static long _vq_lengthlist__16u1__p7_0[] = {
  143972. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143973. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143974. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143975. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143976. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143977. 13,
  143978. };
  143979. static float _vq_quantthresh__16u1__p7_0[] = {
  143980. -5.5, 5.5,
  143981. };
  143982. static long _vq_quantmap__16u1__p7_0[] = {
  143983. 1, 0, 2,
  143984. };
  143985. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143986. _vq_quantthresh__16u1__p7_0,
  143987. _vq_quantmap__16u1__p7_0,
  143988. 3,
  143989. 3
  143990. };
  143991. static static_codebook _16u1__p7_0 = {
  143992. 4, 81,
  143993. _vq_lengthlist__16u1__p7_0,
  143994. 1, -529137664, 1618345984, 2, 0,
  143995. _vq_quantlist__16u1__p7_0,
  143996. NULL,
  143997. &_vq_auxt__16u1__p7_0,
  143998. NULL,
  143999. 0
  144000. };
  144001. static long _vq_quantlist__16u1__p7_1[] = {
  144002. 5,
  144003. 4,
  144004. 6,
  144005. 3,
  144006. 7,
  144007. 2,
  144008. 8,
  144009. 1,
  144010. 9,
  144011. 0,
  144012. 10,
  144013. };
  144014. static long _vq_lengthlist__16u1__p7_1[] = {
  144015. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144016. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144017. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144018. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144019. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144020. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144021. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144022. 8, 9, 9,10,10,10,10,10,10,
  144023. };
  144024. static float _vq_quantthresh__16u1__p7_1[] = {
  144025. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144026. 3.5, 4.5,
  144027. };
  144028. static long _vq_quantmap__16u1__p7_1[] = {
  144029. 9, 7, 5, 3, 1, 0, 2, 4,
  144030. 6, 8, 10,
  144031. };
  144032. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144033. _vq_quantthresh__16u1__p7_1,
  144034. _vq_quantmap__16u1__p7_1,
  144035. 11,
  144036. 11
  144037. };
  144038. static static_codebook _16u1__p7_1 = {
  144039. 2, 121,
  144040. _vq_lengthlist__16u1__p7_1,
  144041. 1, -531365888, 1611661312, 4, 0,
  144042. _vq_quantlist__16u1__p7_1,
  144043. NULL,
  144044. &_vq_auxt__16u1__p7_1,
  144045. NULL,
  144046. 0
  144047. };
  144048. static long _vq_quantlist__16u1__p8_0[] = {
  144049. 5,
  144050. 4,
  144051. 6,
  144052. 3,
  144053. 7,
  144054. 2,
  144055. 8,
  144056. 1,
  144057. 9,
  144058. 0,
  144059. 10,
  144060. };
  144061. static long _vq_lengthlist__16u1__p8_0[] = {
  144062. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144063. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144064. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144065. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144066. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144067. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144068. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144069. 13,14,14,15,15,16,16,15,16,
  144070. };
  144071. static float _vq_quantthresh__16u1__p8_0[] = {
  144072. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144073. 38.5, 49.5,
  144074. };
  144075. static long _vq_quantmap__16u1__p8_0[] = {
  144076. 9, 7, 5, 3, 1, 0, 2, 4,
  144077. 6, 8, 10,
  144078. };
  144079. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144080. _vq_quantthresh__16u1__p8_0,
  144081. _vq_quantmap__16u1__p8_0,
  144082. 11,
  144083. 11
  144084. };
  144085. static static_codebook _16u1__p8_0 = {
  144086. 2, 121,
  144087. _vq_lengthlist__16u1__p8_0,
  144088. 1, -524582912, 1618345984, 4, 0,
  144089. _vq_quantlist__16u1__p8_0,
  144090. NULL,
  144091. &_vq_auxt__16u1__p8_0,
  144092. NULL,
  144093. 0
  144094. };
  144095. static long _vq_quantlist__16u1__p8_1[] = {
  144096. 5,
  144097. 4,
  144098. 6,
  144099. 3,
  144100. 7,
  144101. 2,
  144102. 8,
  144103. 1,
  144104. 9,
  144105. 0,
  144106. 10,
  144107. };
  144108. static long _vq_lengthlist__16u1__p8_1[] = {
  144109. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144110. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144111. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144112. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144113. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144114. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144115. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144116. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144117. };
  144118. static float _vq_quantthresh__16u1__p8_1[] = {
  144119. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144120. 3.5, 4.5,
  144121. };
  144122. static long _vq_quantmap__16u1__p8_1[] = {
  144123. 9, 7, 5, 3, 1, 0, 2, 4,
  144124. 6, 8, 10,
  144125. };
  144126. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144127. _vq_quantthresh__16u1__p8_1,
  144128. _vq_quantmap__16u1__p8_1,
  144129. 11,
  144130. 11
  144131. };
  144132. static static_codebook _16u1__p8_1 = {
  144133. 2, 121,
  144134. _vq_lengthlist__16u1__p8_1,
  144135. 1, -531365888, 1611661312, 4, 0,
  144136. _vq_quantlist__16u1__p8_1,
  144137. NULL,
  144138. &_vq_auxt__16u1__p8_1,
  144139. NULL,
  144140. 0
  144141. };
  144142. static long _vq_quantlist__16u1__p9_0[] = {
  144143. 7,
  144144. 6,
  144145. 8,
  144146. 5,
  144147. 9,
  144148. 4,
  144149. 10,
  144150. 3,
  144151. 11,
  144152. 2,
  144153. 12,
  144154. 1,
  144155. 13,
  144156. 0,
  144157. 14,
  144158. };
  144159. static long _vq_lengthlist__16u1__p9_0[] = {
  144160. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144161. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144165. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144166. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144167. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144168. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144169. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144170. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144171. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144172. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144173. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144174. 8,
  144175. };
  144176. static float _vq_quantthresh__16u1__p9_0[] = {
  144177. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144178. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144179. };
  144180. static long _vq_quantmap__16u1__p9_0[] = {
  144181. 13, 11, 9, 7, 5, 3, 1, 0,
  144182. 2, 4, 6, 8, 10, 12, 14,
  144183. };
  144184. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144185. _vq_quantthresh__16u1__p9_0,
  144186. _vq_quantmap__16u1__p9_0,
  144187. 15,
  144188. 15
  144189. };
  144190. static static_codebook _16u1__p9_0 = {
  144191. 2, 225,
  144192. _vq_lengthlist__16u1__p9_0,
  144193. 1, -514071552, 1627381760, 4, 0,
  144194. _vq_quantlist__16u1__p9_0,
  144195. NULL,
  144196. &_vq_auxt__16u1__p9_0,
  144197. NULL,
  144198. 0
  144199. };
  144200. static long _vq_quantlist__16u1__p9_1[] = {
  144201. 7,
  144202. 6,
  144203. 8,
  144204. 5,
  144205. 9,
  144206. 4,
  144207. 10,
  144208. 3,
  144209. 11,
  144210. 2,
  144211. 12,
  144212. 1,
  144213. 13,
  144214. 0,
  144215. 14,
  144216. };
  144217. static long _vq_lengthlist__16u1__p9_1[] = {
  144218. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144219. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144220. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144221. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144222. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144223. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144224. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144225. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144226. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144227. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144228. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144229. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144230. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144231. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144232. 9,
  144233. };
  144234. static float _vq_quantthresh__16u1__p9_1[] = {
  144235. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144236. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144237. };
  144238. static long _vq_quantmap__16u1__p9_1[] = {
  144239. 13, 11, 9, 7, 5, 3, 1, 0,
  144240. 2, 4, 6, 8, 10, 12, 14,
  144241. };
  144242. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144243. _vq_quantthresh__16u1__p9_1,
  144244. _vq_quantmap__16u1__p9_1,
  144245. 15,
  144246. 15
  144247. };
  144248. static static_codebook _16u1__p9_1 = {
  144249. 2, 225,
  144250. _vq_lengthlist__16u1__p9_1,
  144251. 1, -522338304, 1620115456, 4, 0,
  144252. _vq_quantlist__16u1__p9_1,
  144253. NULL,
  144254. &_vq_auxt__16u1__p9_1,
  144255. NULL,
  144256. 0
  144257. };
  144258. static long _vq_quantlist__16u1__p9_2[] = {
  144259. 8,
  144260. 7,
  144261. 9,
  144262. 6,
  144263. 10,
  144264. 5,
  144265. 11,
  144266. 4,
  144267. 12,
  144268. 3,
  144269. 13,
  144270. 2,
  144271. 14,
  144272. 1,
  144273. 15,
  144274. 0,
  144275. 16,
  144276. };
  144277. static long _vq_lengthlist__16u1__p9_2[] = {
  144278. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144279. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144280. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144281. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144282. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144283. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144284. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144285. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144286. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144287. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144288. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144289. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144290. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144291. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144292. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144293. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144294. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144295. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144296. 10,
  144297. };
  144298. static float _vq_quantthresh__16u1__p9_2[] = {
  144299. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144300. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144301. };
  144302. static long _vq_quantmap__16u1__p9_2[] = {
  144303. 15, 13, 11, 9, 7, 5, 3, 1,
  144304. 0, 2, 4, 6, 8, 10, 12, 14,
  144305. 16,
  144306. };
  144307. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144308. _vq_quantthresh__16u1__p9_2,
  144309. _vq_quantmap__16u1__p9_2,
  144310. 17,
  144311. 17
  144312. };
  144313. static static_codebook _16u1__p9_2 = {
  144314. 2, 289,
  144315. _vq_lengthlist__16u1__p9_2,
  144316. 1, -529530880, 1611661312, 5, 0,
  144317. _vq_quantlist__16u1__p9_2,
  144318. NULL,
  144319. &_vq_auxt__16u1__p9_2,
  144320. NULL,
  144321. 0
  144322. };
  144323. static long _huff_lengthlist__16u1__short[] = {
  144324. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144325. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144326. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144327. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144328. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144329. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144330. 16,16,16,16,
  144331. };
  144332. static static_codebook _huff_book__16u1__short = {
  144333. 2, 100,
  144334. _huff_lengthlist__16u1__short,
  144335. 0, 0, 0, 0, 0,
  144336. NULL,
  144337. NULL,
  144338. NULL,
  144339. NULL,
  144340. 0
  144341. };
  144342. static long _huff_lengthlist__16u2__long[] = {
  144343. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144344. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144345. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144346. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144347. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144348. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144349. 13,14,18,18,
  144350. };
  144351. static static_codebook _huff_book__16u2__long = {
  144352. 2, 100,
  144353. _huff_lengthlist__16u2__long,
  144354. 0, 0, 0, 0, 0,
  144355. NULL,
  144356. NULL,
  144357. NULL,
  144358. NULL,
  144359. 0
  144360. };
  144361. static long _huff_lengthlist__16u2__short[] = {
  144362. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144363. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144364. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144365. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144366. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144367. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144368. 16,16,16,16,
  144369. };
  144370. static static_codebook _huff_book__16u2__short = {
  144371. 2, 100,
  144372. _huff_lengthlist__16u2__short,
  144373. 0, 0, 0, 0, 0,
  144374. NULL,
  144375. NULL,
  144376. NULL,
  144377. NULL,
  144378. 0
  144379. };
  144380. static long _vq_quantlist__16u2_p1_0[] = {
  144381. 1,
  144382. 0,
  144383. 2,
  144384. };
  144385. static long _vq_lengthlist__16u2_p1_0[] = {
  144386. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144387. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144388. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144389. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144390. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144391. 10,
  144392. };
  144393. static float _vq_quantthresh__16u2_p1_0[] = {
  144394. -0.5, 0.5,
  144395. };
  144396. static long _vq_quantmap__16u2_p1_0[] = {
  144397. 1, 0, 2,
  144398. };
  144399. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144400. _vq_quantthresh__16u2_p1_0,
  144401. _vq_quantmap__16u2_p1_0,
  144402. 3,
  144403. 3
  144404. };
  144405. static static_codebook _16u2_p1_0 = {
  144406. 4, 81,
  144407. _vq_lengthlist__16u2_p1_0,
  144408. 1, -535822336, 1611661312, 2, 0,
  144409. _vq_quantlist__16u2_p1_0,
  144410. NULL,
  144411. &_vq_auxt__16u2_p1_0,
  144412. NULL,
  144413. 0
  144414. };
  144415. static long _vq_quantlist__16u2_p2_0[] = {
  144416. 2,
  144417. 1,
  144418. 3,
  144419. 0,
  144420. 4,
  144421. };
  144422. static long _vq_lengthlist__16u2_p2_0[] = {
  144423. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144424. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144425. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144426. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144427. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144428. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144429. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144430. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144431. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144432. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144433. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144434. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144435. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144436. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144437. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144438. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144439. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144440. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144441. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144442. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144443. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144444. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144445. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144446. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144447. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144448. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144449. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144450. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144451. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144452. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144453. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144454. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144455. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144456. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144457. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144458. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144459. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144460. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144461. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144462. 13,
  144463. };
  144464. static float _vq_quantthresh__16u2_p2_0[] = {
  144465. -1.5, -0.5, 0.5, 1.5,
  144466. };
  144467. static long _vq_quantmap__16u2_p2_0[] = {
  144468. 3, 1, 0, 2, 4,
  144469. };
  144470. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144471. _vq_quantthresh__16u2_p2_0,
  144472. _vq_quantmap__16u2_p2_0,
  144473. 5,
  144474. 5
  144475. };
  144476. static static_codebook _16u2_p2_0 = {
  144477. 4, 625,
  144478. _vq_lengthlist__16u2_p2_0,
  144479. 1, -533725184, 1611661312, 3, 0,
  144480. _vq_quantlist__16u2_p2_0,
  144481. NULL,
  144482. &_vq_auxt__16u2_p2_0,
  144483. NULL,
  144484. 0
  144485. };
  144486. static long _vq_quantlist__16u2_p3_0[] = {
  144487. 4,
  144488. 3,
  144489. 5,
  144490. 2,
  144491. 6,
  144492. 1,
  144493. 7,
  144494. 0,
  144495. 8,
  144496. };
  144497. static long _vq_lengthlist__16u2_p3_0[] = {
  144498. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144499. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144500. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144501. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144502. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144503. 11,
  144504. };
  144505. static float _vq_quantthresh__16u2_p3_0[] = {
  144506. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144507. };
  144508. static long _vq_quantmap__16u2_p3_0[] = {
  144509. 7, 5, 3, 1, 0, 2, 4, 6,
  144510. 8,
  144511. };
  144512. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144513. _vq_quantthresh__16u2_p3_0,
  144514. _vq_quantmap__16u2_p3_0,
  144515. 9,
  144516. 9
  144517. };
  144518. static static_codebook _16u2_p3_0 = {
  144519. 2, 81,
  144520. _vq_lengthlist__16u2_p3_0,
  144521. 1, -531628032, 1611661312, 4, 0,
  144522. _vq_quantlist__16u2_p3_0,
  144523. NULL,
  144524. &_vq_auxt__16u2_p3_0,
  144525. NULL,
  144526. 0
  144527. };
  144528. static long _vq_quantlist__16u2_p4_0[] = {
  144529. 8,
  144530. 7,
  144531. 9,
  144532. 6,
  144533. 10,
  144534. 5,
  144535. 11,
  144536. 4,
  144537. 12,
  144538. 3,
  144539. 13,
  144540. 2,
  144541. 14,
  144542. 1,
  144543. 15,
  144544. 0,
  144545. 16,
  144546. };
  144547. static long _vq_lengthlist__16u2_p4_0[] = {
  144548. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144549. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144550. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144551. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144552. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144553. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144554. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144555. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144556. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144557. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144558. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144559. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144560. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144561. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144562. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144563. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144564. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144565. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144566. 14,
  144567. };
  144568. static float _vq_quantthresh__16u2_p4_0[] = {
  144569. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144570. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144571. };
  144572. static long _vq_quantmap__16u2_p4_0[] = {
  144573. 15, 13, 11, 9, 7, 5, 3, 1,
  144574. 0, 2, 4, 6, 8, 10, 12, 14,
  144575. 16,
  144576. };
  144577. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144578. _vq_quantthresh__16u2_p4_0,
  144579. _vq_quantmap__16u2_p4_0,
  144580. 17,
  144581. 17
  144582. };
  144583. static static_codebook _16u2_p4_0 = {
  144584. 2, 289,
  144585. _vq_lengthlist__16u2_p4_0,
  144586. 1, -529530880, 1611661312, 5, 0,
  144587. _vq_quantlist__16u2_p4_0,
  144588. NULL,
  144589. &_vq_auxt__16u2_p4_0,
  144590. NULL,
  144591. 0
  144592. };
  144593. static long _vq_quantlist__16u2_p5_0[] = {
  144594. 1,
  144595. 0,
  144596. 2,
  144597. };
  144598. static long _vq_lengthlist__16u2_p5_0[] = {
  144599. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144600. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144601. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144602. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144603. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144604. 10,
  144605. };
  144606. static float _vq_quantthresh__16u2_p5_0[] = {
  144607. -5.5, 5.5,
  144608. };
  144609. static long _vq_quantmap__16u2_p5_0[] = {
  144610. 1, 0, 2,
  144611. };
  144612. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144613. _vq_quantthresh__16u2_p5_0,
  144614. _vq_quantmap__16u2_p5_0,
  144615. 3,
  144616. 3
  144617. };
  144618. static static_codebook _16u2_p5_0 = {
  144619. 4, 81,
  144620. _vq_lengthlist__16u2_p5_0,
  144621. 1, -529137664, 1618345984, 2, 0,
  144622. _vq_quantlist__16u2_p5_0,
  144623. NULL,
  144624. &_vq_auxt__16u2_p5_0,
  144625. NULL,
  144626. 0
  144627. };
  144628. static long _vq_quantlist__16u2_p5_1[] = {
  144629. 5,
  144630. 4,
  144631. 6,
  144632. 3,
  144633. 7,
  144634. 2,
  144635. 8,
  144636. 1,
  144637. 9,
  144638. 0,
  144639. 10,
  144640. };
  144641. static long _vq_lengthlist__16u2_p5_1[] = {
  144642. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144643. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144644. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144645. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144646. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144647. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144648. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144649. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144650. };
  144651. static float _vq_quantthresh__16u2_p5_1[] = {
  144652. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144653. 3.5, 4.5,
  144654. };
  144655. static long _vq_quantmap__16u2_p5_1[] = {
  144656. 9, 7, 5, 3, 1, 0, 2, 4,
  144657. 6, 8, 10,
  144658. };
  144659. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144660. _vq_quantthresh__16u2_p5_1,
  144661. _vq_quantmap__16u2_p5_1,
  144662. 11,
  144663. 11
  144664. };
  144665. static static_codebook _16u2_p5_1 = {
  144666. 2, 121,
  144667. _vq_lengthlist__16u2_p5_1,
  144668. 1, -531365888, 1611661312, 4, 0,
  144669. _vq_quantlist__16u2_p5_1,
  144670. NULL,
  144671. &_vq_auxt__16u2_p5_1,
  144672. NULL,
  144673. 0
  144674. };
  144675. static long _vq_quantlist__16u2_p6_0[] = {
  144676. 6,
  144677. 5,
  144678. 7,
  144679. 4,
  144680. 8,
  144681. 3,
  144682. 9,
  144683. 2,
  144684. 10,
  144685. 1,
  144686. 11,
  144687. 0,
  144688. 12,
  144689. };
  144690. static long _vq_lengthlist__16u2_p6_0[] = {
  144691. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144692. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144693. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144694. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144695. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144696. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144697. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144698. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144699. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144700. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144701. 12,13,13,14,14,14,14,15,15,
  144702. };
  144703. static float _vq_quantthresh__16u2_p6_0[] = {
  144704. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144705. 12.5, 17.5, 22.5, 27.5,
  144706. };
  144707. static long _vq_quantmap__16u2_p6_0[] = {
  144708. 11, 9, 7, 5, 3, 1, 0, 2,
  144709. 4, 6, 8, 10, 12,
  144710. };
  144711. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144712. _vq_quantthresh__16u2_p6_0,
  144713. _vq_quantmap__16u2_p6_0,
  144714. 13,
  144715. 13
  144716. };
  144717. static static_codebook _16u2_p6_0 = {
  144718. 2, 169,
  144719. _vq_lengthlist__16u2_p6_0,
  144720. 1, -526516224, 1616117760, 4, 0,
  144721. _vq_quantlist__16u2_p6_0,
  144722. NULL,
  144723. &_vq_auxt__16u2_p6_0,
  144724. NULL,
  144725. 0
  144726. };
  144727. static long _vq_quantlist__16u2_p6_1[] = {
  144728. 2,
  144729. 1,
  144730. 3,
  144731. 0,
  144732. 4,
  144733. };
  144734. static long _vq_lengthlist__16u2_p6_1[] = {
  144735. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144736. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144737. };
  144738. static float _vq_quantthresh__16u2_p6_1[] = {
  144739. -1.5, -0.5, 0.5, 1.5,
  144740. };
  144741. static long _vq_quantmap__16u2_p6_1[] = {
  144742. 3, 1, 0, 2, 4,
  144743. };
  144744. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144745. _vq_quantthresh__16u2_p6_1,
  144746. _vq_quantmap__16u2_p6_1,
  144747. 5,
  144748. 5
  144749. };
  144750. static static_codebook _16u2_p6_1 = {
  144751. 2, 25,
  144752. _vq_lengthlist__16u2_p6_1,
  144753. 1, -533725184, 1611661312, 3, 0,
  144754. _vq_quantlist__16u2_p6_1,
  144755. NULL,
  144756. &_vq_auxt__16u2_p6_1,
  144757. NULL,
  144758. 0
  144759. };
  144760. static long _vq_quantlist__16u2_p7_0[] = {
  144761. 6,
  144762. 5,
  144763. 7,
  144764. 4,
  144765. 8,
  144766. 3,
  144767. 9,
  144768. 2,
  144769. 10,
  144770. 1,
  144771. 11,
  144772. 0,
  144773. 12,
  144774. };
  144775. static long _vq_lengthlist__16u2_p7_0[] = {
  144776. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144777. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144778. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144779. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144780. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144781. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144782. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144783. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144784. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144785. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144786. 12,13,13,13,14,14,14,15,14,
  144787. };
  144788. static float _vq_quantthresh__16u2_p7_0[] = {
  144789. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144790. 27.5, 38.5, 49.5, 60.5,
  144791. };
  144792. static long _vq_quantmap__16u2_p7_0[] = {
  144793. 11, 9, 7, 5, 3, 1, 0, 2,
  144794. 4, 6, 8, 10, 12,
  144795. };
  144796. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144797. _vq_quantthresh__16u2_p7_0,
  144798. _vq_quantmap__16u2_p7_0,
  144799. 13,
  144800. 13
  144801. };
  144802. static static_codebook _16u2_p7_0 = {
  144803. 2, 169,
  144804. _vq_lengthlist__16u2_p7_0,
  144805. 1, -523206656, 1618345984, 4, 0,
  144806. _vq_quantlist__16u2_p7_0,
  144807. NULL,
  144808. &_vq_auxt__16u2_p7_0,
  144809. NULL,
  144810. 0
  144811. };
  144812. static long _vq_quantlist__16u2_p7_1[] = {
  144813. 5,
  144814. 4,
  144815. 6,
  144816. 3,
  144817. 7,
  144818. 2,
  144819. 8,
  144820. 1,
  144821. 9,
  144822. 0,
  144823. 10,
  144824. };
  144825. static long _vq_lengthlist__16u2_p7_1[] = {
  144826. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144827. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144828. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144829. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144830. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144831. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144832. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144833. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144834. };
  144835. static float _vq_quantthresh__16u2_p7_1[] = {
  144836. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144837. 3.5, 4.5,
  144838. };
  144839. static long _vq_quantmap__16u2_p7_1[] = {
  144840. 9, 7, 5, 3, 1, 0, 2, 4,
  144841. 6, 8, 10,
  144842. };
  144843. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144844. _vq_quantthresh__16u2_p7_1,
  144845. _vq_quantmap__16u2_p7_1,
  144846. 11,
  144847. 11
  144848. };
  144849. static static_codebook _16u2_p7_1 = {
  144850. 2, 121,
  144851. _vq_lengthlist__16u2_p7_1,
  144852. 1, -531365888, 1611661312, 4, 0,
  144853. _vq_quantlist__16u2_p7_1,
  144854. NULL,
  144855. &_vq_auxt__16u2_p7_1,
  144856. NULL,
  144857. 0
  144858. };
  144859. static long _vq_quantlist__16u2_p8_0[] = {
  144860. 7,
  144861. 6,
  144862. 8,
  144863. 5,
  144864. 9,
  144865. 4,
  144866. 10,
  144867. 3,
  144868. 11,
  144869. 2,
  144870. 12,
  144871. 1,
  144872. 13,
  144873. 0,
  144874. 14,
  144875. };
  144876. static long _vq_lengthlist__16u2_p8_0[] = {
  144877. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144878. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144879. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144880. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144881. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144882. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144883. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144884. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144885. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144886. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144887. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144888. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144889. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144890. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144891. 14,
  144892. };
  144893. static float _vq_quantthresh__16u2_p8_0[] = {
  144894. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144895. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144896. };
  144897. static long _vq_quantmap__16u2_p8_0[] = {
  144898. 13, 11, 9, 7, 5, 3, 1, 0,
  144899. 2, 4, 6, 8, 10, 12, 14,
  144900. };
  144901. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144902. _vq_quantthresh__16u2_p8_0,
  144903. _vq_quantmap__16u2_p8_0,
  144904. 15,
  144905. 15
  144906. };
  144907. static static_codebook _16u2_p8_0 = {
  144908. 2, 225,
  144909. _vq_lengthlist__16u2_p8_0,
  144910. 1, -520986624, 1620377600, 4, 0,
  144911. _vq_quantlist__16u2_p8_0,
  144912. NULL,
  144913. &_vq_auxt__16u2_p8_0,
  144914. NULL,
  144915. 0
  144916. };
  144917. static long _vq_quantlist__16u2_p8_1[] = {
  144918. 10,
  144919. 9,
  144920. 11,
  144921. 8,
  144922. 12,
  144923. 7,
  144924. 13,
  144925. 6,
  144926. 14,
  144927. 5,
  144928. 15,
  144929. 4,
  144930. 16,
  144931. 3,
  144932. 17,
  144933. 2,
  144934. 18,
  144935. 1,
  144936. 19,
  144937. 0,
  144938. 20,
  144939. };
  144940. static long _vq_lengthlist__16u2_p8_1[] = {
  144941. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144942. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144943. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144944. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144945. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144946. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144947. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144948. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144949. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144950. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144951. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144952. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144953. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144954. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144955. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144956. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144957. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144958. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144959. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144960. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144961. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144962. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144963. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144964. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144966. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144967. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144968. 11,11,10,11,11,11,10,11,11,
  144969. };
  144970. static float _vq_quantthresh__16u2_p8_1[] = {
  144971. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144972. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144973. 6.5, 7.5, 8.5, 9.5,
  144974. };
  144975. static long _vq_quantmap__16u2_p8_1[] = {
  144976. 19, 17, 15, 13, 11, 9, 7, 5,
  144977. 3, 1, 0, 2, 4, 6, 8, 10,
  144978. 12, 14, 16, 18, 20,
  144979. };
  144980. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144981. _vq_quantthresh__16u2_p8_1,
  144982. _vq_quantmap__16u2_p8_1,
  144983. 21,
  144984. 21
  144985. };
  144986. static static_codebook _16u2_p8_1 = {
  144987. 2, 441,
  144988. _vq_lengthlist__16u2_p8_1,
  144989. 1, -529268736, 1611661312, 5, 0,
  144990. _vq_quantlist__16u2_p8_1,
  144991. NULL,
  144992. &_vq_auxt__16u2_p8_1,
  144993. NULL,
  144994. 0
  144995. };
  144996. static long _vq_quantlist__16u2_p9_0[] = {
  144997. 5586,
  144998. 4655,
  144999. 6517,
  145000. 3724,
  145001. 7448,
  145002. 2793,
  145003. 8379,
  145004. 1862,
  145005. 9310,
  145006. 931,
  145007. 10241,
  145008. 0,
  145009. 11172,
  145010. 5521,
  145011. 5651,
  145012. };
  145013. static long _vq_lengthlist__16u2_p9_0[] = {
  145014. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145017. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145019. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145021. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145023. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145024. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145026. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145027. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145028. 5,
  145029. };
  145030. static float _vq_quantthresh__16u2_p9_0[] = {
  145031. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145032. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145033. };
  145034. static long _vq_quantmap__16u2_p9_0[] = {
  145035. 11, 9, 7, 5, 3, 1, 13, 0,
  145036. 14, 2, 4, 6, 8, 10, 12,
  145037. };
  145038. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145039. _vq_quantthresh__16u2_p9_0,
  145040. _vq_quantmap__16u2_p9_0,
  145041. 15,
  145042. 15
  145043. };
  145044. static static_codebook _16u2_p9_0 = {
  145045. 2, 225,
  145046. _vq_lengthlist__16u2_p9_0,
  145047. 1, -510275072, 1611661312, 14, 0,
  145048. _vq_quantlist__16u2_p9_0,
  145049. NULL,
  145050. &_vq_auxt__16u2_p9_0,
  145051. NULL,
  145052. 0
  145053. };
  145054. static long _vq_quantlist__16u2_p9_1[] = {
  145055. 392,
  145056. 343,
  145057. 441,
  145058. 294,
  145059. 490,
  145060. 245,
  145061. 539,
  145062. 196,
  145063. 588,
  145064. 147,
  145065. 637,
  145066. 98,
  145067. 686,
  145068. 49,
  145069. 735,
  145070. 0,
  145071. 784,
  145072. 388,
  145073. 396,
  145074. };
  145075. static long _vq_lengthlist__16u2_p9_1[] = {
  145076. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145077. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145078. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145079. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145080. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145081. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145082. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145083. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145084. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145085. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145086. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145087. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145088. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145089. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145090. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145093. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145094. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145095. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145096. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145097. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145098. 11,11,11,11,11,11,11, 5, 4,
  145099. };
  145100. static float _vq_quantthresh__16u2_p9_1[] = {
  145101. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145102. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145103. 318.5, 367.5,
  145104. };
  145105. static long _vq_quantmap__16u2_p9_1[] = {
  145106. 15, 13, 11, 9, 7, 5, 3, 1,
  145107. 17, 0, 18, 2, 4, 6, 8, 10,
  145108. 12, 14, 16,
  145109. };
  145110. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145111. _vq_quantthresh__16u2_p9_1,
  145112. _vq_quantmap__16u2_p9_1,
  145113. 19,
  145114. 19
  145115. };
  145116. static static_codebook _16u2_p9_1 = {
  145117. 2, 361,
  145118. _vq_lengthlist__16u2_p9_1,
  145119. 1, -518488064, 1611661312, 10, 0,
  145120. _vq_quantlist__16u2_p9_1,
  145121. NULL,
  145122. &_vq_auxt__16u2_p9_1,
  145123. NULL,
  145124. 0
  145125. };
  145126. static long _vq_quantlist__16u2_p9_2[] = {
  145127. 24,
  145128. 23,
  145129. 25,
  145130. 22,
  145131. 26,
  145132. 21,
  145133. 27,
  145134. 20,
  145135. 28,
  145136. 19,
  145137. 29,
  145138. 18,
  145139. 30,
  145140. 17,
  145141. 31,
  145142. 16,
  145143. 32,
  145144. 15,
  145145. 33,
  145146. 14,
  145147. 34,
  145148. 13,
  145149. 35,
  145150. 12,
  145151. 36,
  145152. 11,
  145153. 37,
  145154. 10,
  145155. 38,
  145156. 9,
  145157. 39,
  145158. 8,
  145159. 40,
  145160. 7,
  145161. 41,
  145162. 6,
  145163. 42,
  145164. 5,
  145165. 43,
  145166. 4,
  145167. 44,
  145168. 3,
  145169. 45,
  145170. 2,
  145171. 46,
  145172. 1,
  145173. 47,
  145174. 0,
  145175. 48,
  145176. };
  145177. static long _vq_lengthlist__16u2_p9_2[] = {
  145178. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145179. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145180. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145181. 11,
  145182. };
  145183. static float _vq_quantthresh__16u2_p9_2[] = {
  145184. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145185. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145186. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145187. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145188. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145189. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145190. };
  145191. static long _vq_quantmap__16u2_p9_2[] = {
  145192. 47, 45, 43, 41, 39, 37, 35, 33,
  145193. 31, 29, 27, 25, 23, 21, 19, 17,
  145194. 15, 13, 11, 9, 7, 5, 3, 1,
  145195. 0, 2, 4, 6, 8, 10, 12, 14,
  145196. 16, 18, 20, 22, 24, 26, 28, 30,
  145197. 32, 34, 36, 38, 40, 42, 44, 46,
  145198. 48,
  145199. };
  145200. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145201. _vq_quantthresh__16u2_p9_2,
  145202. _vq_quantmap__16u2_p9_2,
  145203. 49,
  145204. 49
  145205. };
  145206. static static_codebook _16u2_p9_2 = {
  145207. 1, 49,
  145208. _vq_lengthlist__16u2_p9_2,
  145209. 1, -526909440, 1611661312, 6, 0,
  145210. _vq_quantlist__16u2_p9_2,
  145211. NULL,
  145212. &_vq_auxt__16u2_p9_2,
  145213. NULL,
  145214. 0
  145215. };
  145216. static long _vq_quantlist__8u0__p1_0[] = {
  145217. 1,
  145218. 0,
  145219. 2,
  145220. };
  145221. static long _vq_lengthlist__8u0__p1_0[] = {
  145222. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145223. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145224. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145225. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145226. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145227. 11,
  145228. };
  145229. static float _vq_quantthresh__8u0__p1_0[] = {
  145230. -0.5, 0.5,
  145231. };
  145232. static long _vq_quantmap__8u0__p1_0[] = {
  145233. 1, 0, 2,
  145234. };
  145235. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145236. _vq_quantthresh__8u0__p1_0,
  145237. _vq_quantmap__8u0__p1_0,
  145238. 3,
  145239. 3
  145240. };
  145241. static static_codebook _8u0__p1_0 = {
  145242. 4, 81,
  145243. _vq_lengthlist__8u0__p1_0,
  145244. 1, -535822336, 1611661312, 2, 0,
  145245. _vq_quantlist__8u0__p1_0,
  145246. NULL,
  145247. &_vq_auxt__8u0__p1_0,
  145248. NULL,
  145249. 0
  145250. };
  145251. static long _vq_quantlist__8u0__p2_0[] = {
  145252. 1,
  145253. 0,
  145254. 2,
  145255. };
  145256. static long _vq_lengthlist__8u0__p2_0[] = {
  145257. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145258. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145259. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145260. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145261. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145262. 8,
  145263. };
  145264. static float _vq_quantthresh__8u0__p2_0[] = {
  145265. -0.5, 0.5,
  145266. };
  145267. static long _vq_quantmap__8u0__p2_0[] = {
  145268. 1, 0, 2,
  145269. };
  145270. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145271. _vq_quantthresh__8u0__p2_0,
  145272. _vq_quantmap__8u0__p2_0,
  145273. 3,
  145274. 3
  145275. };
  145276. static static_codebook _8u0__p2_0 = {
  145277. 4, 81,
  145278. _vq_lengthlist__8u0__p2_0,
  145279. 1, -535822336, 1611661312, 2, 0,
  145280. _vq_quantlist__8u0__p2_0,
  145281. NULL,
  145282. &_vq_auxt__8u0__p2_0,
  145283. NULL,
  145284. 0
  145285. };
  145286. static long _vq_quantlist__8u0__p3_0[] = {
  145287. 2,
  145288. 1,
  145289. 3,
  145290. 0,
  145291. 4,
  145292. };
  145293. static long _vq_lengthlist__8u0__p3_0[] = {
  145294. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145295. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145296. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145297. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145298. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145299. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145300. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145301. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145302. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145303. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145304. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145305. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145306. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145307. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145308. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145309. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145310. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145311. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145312. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145313. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145314. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145315. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145316. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145317. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145318. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145319. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145320. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145321. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145322. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145323. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145324. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145325. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145326. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145327. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145328. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145329. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145330. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145331. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145332. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145333. 16,
  145334. };
  145335. static float _vq_quantthresh__8u0__p3_0[] = {
  145336. -1.5, -0.5, 0.5, 1.5,
  145337. };
  145338. static long _vq_quantmap__8u0__p3_0[] = {
  145339. 3, 1, 0, 2, 4,
  145340. };
  145341. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145342. _vq_quantthresh__8u0__p3_0,
  145343. _vq_quantmap__8u0__p3_0,
  145344. 5,
  145345. 5
  145346. };
  145347. static static_codebook _8u0__p3_0 = {
  145348. 4, 625,
  145349. _vq_lengthlist__8u0__p3_0,
  145350. 1, -533725184, 1611661312, 3, 0,
  145351. _vq_quantlist__8u0__p3_0,
  145352. NULL,
  145353. &_vq_auxt__8u0__p3_0,
  145354. NULL,
  145355. 0
  145356. };
  145357. static long _vq_quantlist__8u0__p4_0[] = {
  145358. 2,
  145359. 1,
  145360. 3,
  145361. 0,
  145362. 4,
  145363. };
  145364. static long _vq_lengthlist__8u0__p4_0[] = {
  145365. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145366. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145367. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145368. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145369. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145370. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145371. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145372. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145373. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145374. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145375. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145376. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145377. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145378. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145379. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145380. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145381. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145382. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145383. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145384. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145385. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145386. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145387. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145388. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145389. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145390. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145391. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145392. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145393. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145394. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145395. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145396. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145397. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145398. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145399. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145400. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145401. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145402. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145403. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145404. 12,
  145405. };
  145406. static float _vq_quantthresh__8u0__p4_0[] = {
  145407. -1.5, -0.5, 0.5, 1.5,
  145408. };
  145409. static long _vq_quantmap__8u0__p4_0[] = {
  145410. 3, 1, 0, 2, 4,
  145411. };
  145412. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145413. _vq_quantthresh__8u0__p4_0,
  145414. _vq_quantmap__8u0__p4_0,
  145415. 5,
  145416. 5
  145417. };
  145418. static static_codebook _8u0__p4_0 = {
  145419. 4, 625,
  145420. _vq_lengthlist__8u0__p4_0,
  145421. 1, -533725184, 1611661312, 3, 0,
  145422. _vq_quantlist__8u0__p4_0,
  145423. NULL,
  145424. &_vq_auxt__8u0__p4_0,
  145425. NULL,
  145426. 0
  145427. };
  145428. static long _vq_quantlist__8u0__p5_0[] = {
  145429. 4,
  145430. 3,
  145431. 5,
  145432. 2,
  145433. 6,
  145434. 1,
  145435. 7,
  145436. 0,
  145437. 8,
  145438. };
  145439. static long _vq_lengthlist__8u0__p5_0[] = {
  145440. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145441. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145442. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145443. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145444. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145445. 12,
  145446. };
  145447. static float _vq_quantthresh__8u0__p5_0[] = {
  145448. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145449. };
  145450. static long _vq_quantmap__8u0__p5_0[] = {
  145451. 7, 5, 3, 1, 0, 2, 4, 6,
  145452. 8,
  145453. };
  145454. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145455. _vq_quantthresh__8u0__p5_0,
  145456. _vq_quantmap__8u0__p5_0,
  145457. 9,
  145458. 9
  145459. };
  145460. static static_codebook _8u0__p5_0 = {
  145461. 2, 81,
  145462. _vq_lengthlist__8u0__p5_0,
  145463. 1, -531628032, 1611661312, 4, 0,
  145464. _vq_quantlist__8u0__p5_0,
  145465. NULL,
  145466. &_vq_auxt__8u0__p5_0,
  145467. NULL,
  145468. 0
  145469. };
  145470. static long _vq_quantlist__8u0__p6_0[] = {
  145471. 6,
  145472. 5,
  145473. 7,
  145474. 4,
  145475. 8,
  145476. 3,
  145477. 9,
  145478. 2,
  145479. 10,
  145480. 1,
  145481. 11,
  145482. 0,
  145483. 12,
  145484. };
  145485. static long _vq_lengthlist__8u0__p6_0[] = {
  145486. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145487. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145488. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145489. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145490. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145491. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145492. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145493. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145494. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145495. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145496. 16, 0,15, 0,17, 0, 0, 0, 0,
  145497. };
  145498. static float _vq_quantthresh__8u0__p6_0[] = {
  145499. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145500. 12.5, 17.5, 22.5, 27.5,
  145501. };
  145502. static long _vq_quantmap__8u0__p6_0[] = {
  145503. 11, 9, 7, 5, 3, 1, 0, 2,
  145504. 4, 6, 8, 10, 12,
  145505. };
  145506. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145507. _vq_quantthresh__8u0__p6_0,
  145508. _vq_quantmap__8u0__p6_0,
  145509. 13,
  145510. 13
  145511. };
  145512. static static_codebook _8u0__p6_0 = {
  145513. 2, 169,
  145514. _vq_lengthlist__8u0__p6_0,
  145515. 1, -526516224, 1616117760, 4, 0,
  145516. _vq_quantlist__8u0__p6_0,
  145517. NULL,
  145518. &_vq_auxt__8u0__p6_0,
  145519. NULL,
  145520. 0
  145521. };
  145522. static long _vq_quantlist__8u0__p6_1[] = {
  145523. 2,
  145524. 1,
  145525. 3,
  145526. 0,
  145527. 4,
  145528. };
  145529. static long _vq_lengthlist__8u0__p6_1[] = {
  145530. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145531. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145532. };
  145533. static float _vq_quantthresh__8u0__p6_1[] = {
  145534. -1.5, -0.5, 0.5, 1.5,
  145535. };
  145536. static long _vq_quantmap__8u0__p6_1[] = {
  145537. 3, 1, 0, 2, 4,
  145538. };
  145539. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145540. _vq_quantthresh__8u0__p6_1,
  145541. _vq_quantmap__8u0__p6_1,
  145542. 5,
  145543. 5
  145544. };
  145545. static static_codebook _8u0__p6_1 = {
  145546. 2, 25,
  145547. _vq_lengthlist__8u0__p6_1,
  145548. 1, -533725184, 1611661312, 3, 0,
  145549. _vq_quantlist__8u0__p6_1,
  145550. NULL,
  145551. &_vq_auxt__8u0__p6_1,
  145552. NULL,
  145553. 0
  145554. };
  145555. static long _vq_quantlist__8u0__p7_0[] = {
  145556. 1,
  145557. 0,
  145558. 2,
  145559. };
  145560. static long _vq_lengthlist__8u0__p7_0[] = {
  145561. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145562. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145563. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145564. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145565. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145566. 7,
  145567. };
  145568. static float _vq_quantthresh__8u0__p7_0[] = {
  145569. -157.5, 157.5,
  145570. };
  145571. static long _vq_quantmap__8u0__p7_0[] = {
  145572. 1, 0, 2,
  145573. };
  145574. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145575. _vq_quantthresh__8u0__p7_0,
  145576. _vq_quantmap__8u0__p7_0,
  145577. 3,
  145578. 3
  145579. };
  145580. static static_codebook _8u0__p7_0 = {
  145581. 4, 81,
  145582. _vq_lengthlist__8u0__p7_0,
  145583. 1, -518803456, 1628680192, 2, 0,
  145584. _vq_quantlist__8u0__p7_0,
  145585. NULL,
  145586. &_vq_auxt__8u0__p7_0,
  145587. NULL,
  145588. 0
  145589. };
  145590. static long _vq_quantlist__8u0__p7_1[] = {
  145591. 7,
  145592. 6,
  145593. 8,
  145594. 5,
  145595. 9,
  145596. 4,
  145597. 10,
  145598. 3,
  145599. 11,
  145600. 2,
  145601. 12,
  145602. 1,
  145603. 13,
  145604. 0,
  145605. 14,
  145606. };
  145607. static long _vq_lengthlist__8u0__p7_1[] = {
  145608. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145609. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145610. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145611. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145612. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145613. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145614. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145615. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145616. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145617. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145618. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145619. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145620. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145622. 10,
  145623. };
  145624. static float _vq_quantthresh__8u0__p7_1[] = {
  145625. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145626. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145627. };
  145628. static long _vq_quantmap__8u0__p7_1[] = {
  145629. 13, 11, 9, 7, 5, 3, 1, 0,
  145630. 2, 4, 6, 8, 10, 12, 14,
  145631. };
  145632. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145633. _vq_quantthresh__8u0__p7_1,
  145634. _vq_quantmap__8u0__p7_1,
  145635. 15,
  145636. 15
  145637. };
  145638. static static_codebook _8u0__p7_1 = {
  145639. 2, 225,
  145640. _vq_lengthlist__8u0__p7_1,
  145641. 1, -520986624, 1620377600, 4, 0,
  145642. _vq_quantlist__8u0__p7_1,
  145643. NULL,
  145644. &_vq_auxt__8u0__p7_1,
  145645. NULL,
  145646. 0
  145647. };
  145648. static long _vq_quantlist__8u0__p7_2[] = {
  145649. 10,
  145650. 9,
  145651. 11,
  145652. 8,
  145653. 12,
  145654. 7,
  145655. 13,
  145656. 6,
  145657. 14,
  145658. 5,
  145659. 15,
  145660. 4,
  145661. 16,
  145662. 3,
  145663. 17,
  145664. 2,
  145665. 18,
  145666. 1,
  145667. 19,
  145668. 0,
  145669. 20,
  145670. };
  145671. static long _vq_lengthlist__8u0__p7_2[] = {
  145672. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145673. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145674. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145675. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145676. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145677. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145678. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145679. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145680. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145681. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145682. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145683. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145684. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145685. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145686. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145687. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145688. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145689. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145690. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145691. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145692. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145693. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145694. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145695. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145696. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145697. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145698. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145699. 11,12,11,11,11,10,10,11,11,
  145700. };
  145701. static float _vq_quantthresh__8u0__p7_2[] = {
  145702. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145703. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145704. 6.5, 7.5, 8.5, 9.5,
  145705. };
  145706. static long _vq_quantmap__8u0__p7_2[] = {
  145707. 19, 17, 15, 13, 11, 9, 7, 5,
  145708. 3, 1, 0, 2, 4, 6, 8, 10,
  145709. 12, 14, 16, 18, 20,
  145710. };
  145711. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145712. _vq_quantthresh__8u0__p7_2,
  145713. _vq_quantmap__8u0__p7_2,
  145714. 21,
  145715. 21
  145716. };
  145717. static static_codebook _8u0__p7_2 = {
  145718. 2, 441,
  145719. _vq_lengthlist__8u0__p7_2,
  145720. 1, -529268736, 1611661312, 5, 0,
  145721. _vq_quantlist__8u0__p7_2,
  145722. NULL,
  145723. &_vq_auxt__8u0__p7_2,
  145724. NULL,
  145725. 0
  145726. };
  145727. static long _huff_lengthlist__8u0__single[] = {
  145728. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145729. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145730. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145731. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145732. };
  145733. static static_codebook _huff_book__8u0__single = {
  145734. 2, 64,
  145735. _huff_lengthlist__8u0__single,
  145736. 0, 0, 0, 0, 0,
  145737. NULL,
  145738. NULL,
  145739. NULL,
  145740. NULL,
  145741. 0
  145742. };
  145743. static long _vq_quantlist__8u1__p1_0[] = {
  145744. 1,
  145745. 0,
  145746. 2,
  145747. };
  145748. static long _vq_lengthlist__8u1__p1_0[] = {
  145749. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145750. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145751. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145752. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145753. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145754. 10,
  145755. };
  145756. static float _vq_quantthresh__8u1__p1_0[] = {
  145757. -0.5, 0.5,
  145758. };
  145759. static long _vq_quantmap__8u1__p1_0[] = {
  145760. 1, 0, 2,
  145761. };
  145762. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145763. _vq_quantthresh__8u1__p1_0,
  145764. _vq_quantmap__8u1__p1_0,
  145765. 3,
  145766. 3
  145767. };
  145768. static static_codebook _8u1__p1_0 = {
  145769. 4, 81,
  145770. _vq_lengthlist__8u1__p1_0,
  145771. 1, -535822336, 1611661312, 2, 0,
  145772. _vq_quantlist__8u1__p1_0,
  145773. NULL,
  145774. &_vq_auxt__8u1__p1_0,
  145775. NULL,
  145776. 0
  145777. };
  145778. static long _vq_quantlist__8u1__p2_0[] = {
  145779. 1,
  145780. 0,
  145781. 2,
  145782. };
  145783. static long _vq_lengthlist__8u1__p2_0[] = {
  145784. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145785. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145786. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145787. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145788. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145789. 7,
  145790. };
  145791. static float _vq_quantthresh__8u1__p2_0[] = {
  145792. -0.5, 0.5,
  145793. };
  145794. static long _vq_quantmap__8u1__p2_0[] = {
  145795. 1, 0, 2,
  145796. };
  145797. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145798. _vq_quantthresh__8u1__p2_0,
  145799. _vq_quantmap__8u1__p2_0,
  145800. 3,
  145801. 3
  145802. };
  145803. static static_codebook _8u1__p2_0 = {
  145804. 4, 81,
  145805. _vq_lengthlist__8u1__p2_0,
  145806. 1, -535822336, 1611661312, 2, 0,
  145807. _vq_quantlist__8u1__p2_0,
  145808. NULL,
  145809. &_vq_auxt__8u1__p2_0,
  145810. NULL,
  145811. 0
  145812. };
  145813. static long _vq_quantlist__8u1__p3_0[] = {
  145814. 2,
  145815. 1,
  145816. 3,
  145817. 0,
  145818. 4,
  145819. };
  145820. static long _vq_lengthlist__8u1__p3_0[] = {
  145821. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145822. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145823. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145824. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145825. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145826. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145827. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145828. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145829. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145830. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145831. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145832. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145833. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145834. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145835. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145836. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145837. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145838. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145839. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145840. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145841. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145842. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145843. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145844. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145845. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145846. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145847. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145848. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145849. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145850. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145851. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145852. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145853. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145854. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145855. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145856. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145857. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145858. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145859. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145860. 16,
  145861. };
  145862. static float _vq_quantthresh__8u1__p3_0[] = {
  145863. -1.5, -0.5, 0.5, 1.5,
  145864. };
  145865. static long _vq_quantmap__8u1__p3_0[] = {
  145866. 3, 1, 0, 2, 4,
  145867. };
  145868. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145869. _vq_quantthresh__8u1__p3_0,
  145870. _vq_quantmap__8u1__p3_0,
  145871. 5,
  145872. 5
  145873. };
  145874. static static_codebook _8u1__p3_0 = {
  145875. 4, 625,
  145876. _vq_lengthlist__8u1__p3_0,
  145877. 1, -533725184, 1611661312, 3, 0,
  145878. _vq_quantlist__8u1__p3_0,
  145879. NULL,
  145880. &_vq_auxt__8u1__p3_0,
  145881. NULL,
  145882. 0
  145883. };
  145884. static long _vq_quantlist__8u1__p4_0[] = {
  145885. 2,
  145886. 1,
  145887. 3,
  145888. 0,
  145889. 4,
  145890. };
  145891. static long _vq_lengthlist__8u1__p4_0[] = {
  145892. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145893. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145894. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145895. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145896. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145897. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145898. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145899. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145900. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145901. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145902. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145903. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145904. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145905. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145906. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145907. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145908. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145909. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145910. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145911. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145912. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145913. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145914. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145915. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145916. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145917. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145918. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145919. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145920. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145921. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145922. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145923. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145924. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145925. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145926. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145927. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145928. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145929. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145930. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145931. 10,
  145932. };
  145933. static float _vq_quantthresh__8u1__p4_0[] = {
  145934. -1.5, -0.5, 0.5, 1.5,
  145935. };
  145936. static long _vq_quantmap__8u1__p4_0[] = {
  145937. 3, 1, 0, 2, 4,
  145938. };
  145939. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145940. _vq_quantthresh__8u1__p4_0,
  145941. _vq_quantmap__8u1__p4_0,
  145942. 5,
  145943. 5
  145944. };
  145945. static static_codebook _8u1__p4_0 = {
  145946. 4, 625,
  145947. _vq_lengthlist__8u1__p4_0,
  145948. 1, -533725184, 1611661312, 3, 0,
  145949. _vq_quantlist__8u1__p4_0,
  145950. NULL,
  145951. &_vq_auxt__8u1__p4_0,
  145952. NULL,
  145953. 0
  145954. };
  145955. static long _vq_quantlist__8u1__p5_0[] = {
  145956. 4,
  145957. 3,
  145958. 5,
  145959. 2,
  145960. 6,
  145961. 1,
  145962. 7,
  145963. 0,
  145964. 8,
  145965. };
  145966. static long _vq_lengthlist__8u1__p5_0[] = {
  145967. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145968. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145969. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145970. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145971. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145972. 13,
  145973. };
  145974. static float _vq_quantthresh__8u1__p5_0[] = {
  145975. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145976. };
  145977. static long _vq_quantmap__8u1__p5_0[] = {
  145978. 7, 5, 3, 1, 0, 2, 4, 6,
  145979. 8,
  145980. };
  145981. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145982. _vq_quantthresh__8u1__p5_0,
  145983. _vq_quantmap__8u1__p5_0,
  145984. 9,
  145985. 9
  145986. };
  145987. static static_codebook _8u1__p5_0 = {
  145988. 2, 81,
  145989. _vq_lengthlist__8u1__p5_0,
  145990. 1, -531628032, 1611661312, 4, 0,
  145991. _vq_quantlist__8u1__p5_0,
  145992. NULL,
  145993. &_vq_auxt__8u1__p5_0,
  145994. NULL,
  145995. 0
  145996. };
  145997. static long _vq_quantlist__8u1__p6_0[] = {
  145998. 4,
  145999. 3,
  146000. 5,
  146001. 2,
  146002. 6,
  146003. 1,
  146004. 7,
  146005. 0,
  146006. 8,
  146007. };
  146008. static long _vq_lengthlist__8u1__p6_0[] = {
  146009. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146010. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146011. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146012. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146013. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146014. 10,
  146015. };
  146016. static float _vq_quantthresh__8u1__p6_0[] = {
  146017. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146018. };
  146019. static long _vq_quantmap__8u1__p6_0[] = {
  146020. 7, 5, 3, 1, 0, 2, 4, 6,
  146021. 8,
  146022. };
  146023. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146024. _vq_quantthresh__8u1__p6_0,
  146025. _vq_quantmap__8u1__p6_0,
  146026. 9,
  146027. 9
  146028. };
  146029. static static_codebook _8u1__p6_0 = {
  146030. 2, 81,
  146031. _vq_lengthlist__8u1__p6_0,
  146032. 1, -531628032, 1611661312, 4, 0,
  146033. _vq_quantlist__8u1__p6_0,
  146034. NULL,
  146035. &_vq_auxt__8u1__p6_0,
  146036. NULL,
  146037. 0
  146038. };
  146039. static long _vq_quantlist__8u1__p7_0[] = {
  146040. 1,
  146041. 0,
  146042. 2,
  146043. };
  146044. static long _vq_lengthlist__8u1__p7_0[] = {
  146045. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146046. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146047. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146048. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146049. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146050. 11,
  146051. };
  146052. static float _vq_quantthresh__8u1__p7_0[] = {
  146053. -5.5, 5.5,
  146054. };
  146055. static long _vq_quantmap__8u1__p7_0[] = {
  146056. 1, 0, 2,
  146057. };
  146058. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146059. _vq_quantthresh__8u1__p7_0,
  146060. _vq_quantmap__8u1__p7_0,
  146061. 3,
  146062. 3
  146063. };
  146064. static static_codebook _8u1__p7_0 = {
  146065. 4, 81,
  146066. _vq_lengthlist__8u1__p7_0,
  146067. 1, -529137664, 1618345984, 2, 0,
  146068. _vq_quantlist__8u1__p7_0,
  146069. NULL,
  146070. &_vq_auxt__8u1__p7_0,
  146071. NULL,
  146072. 0
  146073. };
  146074. static long _vq_quantlist__8u1__p7_1[] = {
  146075. 5,
  146076. 4,
  146077. 6,
  146078. 3,
  146079. 7,
  146080. 2,
  146081. 8,
  146082. 1,
  146083. 9,
  146084. 0,
  146085. 10,
  146086. };
  146087. static long _vq_lengthlist__8u1__p7_1[] = {
  146088. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146089. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146090. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146091. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146092. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146093. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146094. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146095. 9, 9, 9, 9, 9,10,10,10,10,
  146096. };
  146097. static float _vq_quantthresh__8u1__p7_1[] = {
  146098. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146099. 3.5, 4.5,
  146100. };
  146101. static long _vq_quantmap__8u1__p7_1[] = {
  146102. 9, 7, 5, 3, 1, 0, 2, 4,
  146103. 6, 8, 10,
  146104. };
  146105. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146106. _vq_quantthresh__8u1__p7_1,
  146107. _vq_quantmap__8u1__p7_1,
  146108. 11,
  146109. 11
  146110. };
  146111. static static_codebook _8u1__p7_1 = {
  146112. 2, 121,
  146113. _vq_lengthlist__8u1__p7_1,
  146114. 1, -531365888, 1611661312, 4, 0,
  146115. _vq_quantlist__8u1__p7_1,
  146116. NULL,
  146117. &_vq_auxt__8u1__p7_1,
  146118. NULL,
  146119. 0
  146120. };
  146121. static long _vq_quantlist__8u1__p8_0[] = {
  146122. 5,
  146123. 4,
  146124. 6,
  146125. 3,
  146126. 7,
  146127. 2,
  146128. 8,
  146129. 1,
  146130. 9,
  146131. 0,
  146132. 10,
  146133. };
  146134. static long _vq_lengthlist__8u1__p8_0[] = {
  146135. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146136. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146137. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146138. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146139. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146140. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146141. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146142. 12,13,13,14,14,15,15,15,15,
  146143. };
  146144. static float _vq_quantthresh__8u1__p8_0[] = {
  146145. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146146. 38.5, 49.5,
  146147. };
  146148. static long _vq_quantmap__8u1__p8_0[] = {
  146149. 9, 7, 5, 3, 1, 0, 2, 4,
  146150. 6, 8, 10,
  146151. };
  146152. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146153. _vq_quantthresh__8u1__p8_0,
  146154. _vq_quantmap__8u1__p8_0,
  146155. 11,
  146156. 11
  146157. };
  146158. static static_codebook _8u1__p8_0 = {
  146159. 2, 121,
  146160. _vq_lengthlist__8u1__p8_0,
  146161. 1, -524582912, 1618345984, 4, 0,
  146162. _vq_quantlist__8u1__p8_0,
  146163. NULL,
  146164. &_vq_auxt__8u1__p8_0,
  146165. NULL,
  146166. 0
  146167. };
  146168. static long _vq_quantlist__8u1__p8_1[] = {
  146169. 5,
  146170. 4,
  146171. 6,
  146172. 3,
  146173. 7,
  146174. 2,
  146175. 8,
  146176. 1,
  146177. 9,
  146178. 0,
  146179. 10,
  146180. };
  146181. static long _vq_lengthlist__8u1__p8_1[] = {
  146182. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146183. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146184. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146185. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146186. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146187. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146188. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146189. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146190. };
  146191. static float _vq_quantthresh__8u1__p8_1[] = {
  146192. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146193. 3.5, 4.5,
  146194. };
  146195. static long _vq_quantmap__8u1__p8_1[] = {
  146196. 9, 7, 5, 3, 1, 0, 2, 4,
  146197. 6, 8, 10,
  146198. };
  146199. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146200. _vq_quantthresh__8u1__p8_1,
  146201. _vq_quantmap__8u1__p8_1,
  146202. 11,
  146203. 11
  146204. };
  146205. static static_codebook _8u1__p8_1 = {
  146206. 2, 121,
  146207. _vq_lengthlist__8u1__p8_1,
  146208. 1, -531365888, 1611661312, 4, 0,
  146209. _vq_quantlist__8u1__p8_1,
  146210. NULL,
  146211. &_vq_auxt__8u1__p8_1,
  146212. NULL,
  146213. 0
  146214. };
  146215. static long _vq_quantlist__8u1__p9_0[] = {
  146216. 7,
  146217. 6,
  146218. 8,
  146219. 5,
  146220. 9,
  146221. 4,
  146222. 10,
  146223. 3,
  146224. 11,
  146225. 2,
  146226. 12,
  146227. 1,
  146228. 13,
  146229. 0,
  146230. 14,
  146231. };
  146232. static long _vq_lengthlist__8u1__p9_0[] = {
  146233. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146234. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146235. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146236. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146237. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146245. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146246. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146247. 10,
  146248. };
  146249. static float _vq_quantthresh__8u1__p9_0[] = {
  146250. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146251. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146252. };
  146253. static long _vq_quantmap__8u1__p9_0[] = {
  146254. 13, 11, 9, 7, 5, 3, 1, 0,
  146255. 2, 4, 6, 8, 10, 12, 14,
  146256. };
  146257. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146258. _vq_quantthresh__8u1__p9_0,
  146259. _vq_quantmap__8u1__p9_0,
  146260. 15,
  146261. 15
  146262. };
  146263. static static_codebook _8u1__p9_0 = {
  146264. 2, 225,
  146265. _vq_lengthlist__8u1__p9_0,
  146266. 1, -514071552, 1627381760, 4, 0,
  146267. _vq_quantlist__8u1__p9_0,
  146268. NULL,
  146269. &_vq_auxt__8u1__p9_0,
  146270. NULL,
  146271. 0
  146272. };
  146273. static long _vq_quantlist__8u1__p9_1[] = {
  146274. 7,
  146275. 6,
  146276. 8,
  146277. 5,
  146278. 9,
  146279. 4,
  146280. 10,
  146281. 3,
  146282. 11,
  146283. 2,
  146284. 12,
  146285. 1,
  146286. 13,
  146287. 0,
  146288. 14,
  146289. };
  146290. static long _vq_lengthlist__8u1__p9_1[] = {
  146291. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146292. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146293. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146294. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146295. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146296. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146297. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146298. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146299. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146300. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146301. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146302. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146303. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146304. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146305. 13,
  146306. };
  146307. static float _vq_quantthresh__8u1__p9_1[] = {
  146308. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146309. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146310. };
  146311. static long _vq_quantmap__8u1__p9_1[] = {
  146312. 13, 11, 9, 7, 5, 3, 1, 0,
  146313. 2, 4, 6, 8, 10, 12, 14,
  146314. };
  146315. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146316. _vq_quantthresh__8u1__p9_1,
  146317. _vq_quantmap__8u1__p9_1,
  146318. 15,
  146319. 15
  146320. };
  146321. static static_codebook _8u1__p9_1 = {
  146322. 2, 225,
  146323. _vq_lengthlist__8u1__p9_1,
  146324. 1, -522338304, 1620115456, 4, 0,
  146325. _vq_quantlist__8u1__p9_1,
  146326. NULL,
  146327. &_vq_auxt__8u1__p9_1,
  146328. NULL,
  146329. 0
  146330. };
  146331. static long _vq_quantlist__8u1__p9_2[] = {
  146332. 8,
  146333. 7,
  146334. 9,
  146335. 6,
  146336. 10,
  146337. 5,
  146338. 11,
  146339. 4,
  146340. 12,
  146341. 3,
  146342. 13,
  146343. 2,
  146344. 14,
  146345. 1,
  146346. 15,
  146347. 0,
  146348. 16,
  146349. };
  146350. static long _vq_lengthlist__8u1__p9_2[] = {
  146351. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146352. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146353. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146354. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146355. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146356. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146357. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146358. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146359. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146360. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146361. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146362. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146363. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146364. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146365. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146366. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146367. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146368. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146369. 10,
  146370. };
  146371. static float _vq_quantthresh__8u1__p9_2[] = {
  146372. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146373. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146374. };
  146375. static long _vq_quantmap__8u1__p9_2[] = {
  146376. 15, 13, 11, 9, 7, 5, 3, 1,
  146377. 0, 2, 4, 6, 8, 10, 12, 14,
  146378. 16,
  146379. };
  146380. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146381. _vq_quantthresh__8u1__p9_2,
  146382. _vq_quantmap__8u1__p9_2,
  146383. 17,
  146384. 17
  146385. };
  146386. static static_codebook _8u1__p9_2 = {
  146387. 2, 289,
  146388. _vq_lengthlist__8u1__p9_2,
  146389. 1, -529530880, 1611661312, 5, 0,
  146390. _vq_quantlist__8u1__p9_2,
  146391. NULL,
  146392. &_vq_auxt__8u1__p9_2,
  146393. NULL,
  146394. 0
  146395. };
  146396. static long _huff_lengthlist__8u1__single[] = {
  146397. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146398. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146399. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146400. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146401. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146402. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146403. 13, 8, 8,15,
  146404. };
  146405. static static_codebook _huff_book__8u1__single = {
  146406. 2, 100,
  146407. _huff_lengthlist__8u1__single,
  146408. 0, 0, 0, 0, 0,
  146409. NULL,
  146410. NULL,
  146411. NULL,
  146412. NULL,
  146413. 0
  146414. };
  146415. static long _huff_lengthlist__44u0__long[] = {
  146416. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146417. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146418. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146419. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146420. };
  146421. static static_codebook _huff_book__44u0__long = {
  146422. 2, 64,
  146423. _huff_lengthlist__44u0__long,
  146424. 0, 0, 0, 0, 0,
  146425. NULL,
  146426. NULL,
  146427. NULL,
  146428. NULL,
  146429. 0
  146430. };
  146431. static long _vq_quantlist__44u0__p1_0[] = {
  146432. 1,
  146433. 0,
  146434. 2,
  146435. };
  146436. static long _vq_lengthlist__44u0__p1_0[] = {
  146437. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146438. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146439. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146440. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146441. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146442. 13,
  146443. };
  146444. static float _vq_quantthresh__44u0__p1_0[] = {
  146445. -0.5, 0.5,
  146446. };
  146447. static long _vq_quantmap__44u0__p1_0[] = {
  146448. 1, 0, 2,
  146449. };
  146450. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146451. _vq_quantthresh__44u0__p1_0,
  146452. _vq_quantmap__44u0__p1_0,
  146453. 3,
  146454. 3
  146455. };
  146456. static static_codebook _44u0__p1_0 = {
  146457. 4, 81,
  146458. _vq_lengthlist__44u0__p1_0,
  146459. 1, -535822336, 1611661312, 2, 0,
  146460. _vq_quantlist__44u0__p1_0,
  146461. NULL,
  146462. &_vq_auxt__44u0__p1_0,
  146463. NULL,
  146464. 0
  146465. };
  146466. static long _vq_quantlist__44u0__p2_0[] = {
  146467. 1,
  146468. 0,
  146469. 2,
  146470. };
  146471. static long _vq_lengthlist__44u0__p2_0[] = {
  146472. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146473. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146474. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146475. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146476. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146477. 9,
  146478. };
  146479. static float _vq_quantthresh__44u0__p2_0[] = {
  146480. -0.5, 0.5,
  146481. };
  146482. static long _vq_quantmap__44u0__p2_0[] = {
  146483. 1, 0, 2,
  146484. };
  146485. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146486. _vq_quantthresh__44u0__p2_0,
  146487. _vq_quantmap__44u0__p2_0,
  146488. 3,
  146489. 3
  146490. };
  146491. static static_codebook _44u0__p2_0 = {
  146492. 4, 81,
  146493. _vq_lengthlist__44u0__p2_0,
  146494. 1, -535822336, 1611661312, 2, 0,
  146495. _vq_quantlist__44u0__p2_0,
  146496. NULL,
  146497. &_vq_auxt__44u0__p2_0,
  146498. NULL,
  146499. 0
  146500. };
  146501. static long _vq_quantlist__44u0__p3_0[] = {
  146502. 2,
  146503. 1,
  146504. 3,
  146505. 0,
  146506. 4,
  146507. };
  146508. static long _vq_lengthlist__44u0__p3_0[] = {
  146509. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146510. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146511. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146512. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146513. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146514. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146515. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146516. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146517. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146518. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146519. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146520. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146521. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146522. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146523. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146524. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146525. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146526. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146527. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146528. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146529. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146530. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146531. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146532. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146533. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146534. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146535. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146536. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146537. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146538. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146539. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146540. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146541. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146542. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146543. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146544. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146545. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146546. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146547. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146548. 19,
  146549. };
  146550. static float _vq_quantthresh__44u0__p3_0[] = {
  146551. -1.5, -0.5, 0.5, 1.5,
  146552. };
  146553. static long _vq_quantmap__44u0__p3_0[] = {
  146554. 3, 1, 0, 2, 4,
  146555. };
  146556. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146557. _vq_quantthresh__44u0__p3_0,
  146558. _vq_quantmap__44u0__p3_0,
  146559. 5,
  146560. 5
  146561. };
  146562. static static_codebook _44u0__p3_0 = {
  146563. 4, 625,
  146564. _vq_lengthlist__44u0__p3_0,
  146565. 1, -533725184, 1611661312, 3, 0,
  146566. _vq_quantlist__44u0__p3_0,
  146567. NULL,
  146568. &_vq_auxt__44u0__p3_0,
  146569. NULL,
  146570. 0
  146571. };
  146572. static long _vq_quantlist__44u0__p4_0[] = {
  146573. 2,
  146574. 1,
  146575. 3,
  146576. 0,
  146577. 4,
  146578. };
  146579. static long _vq_lengthlist__44u0__p4_0[] = {
  146580. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146581. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146582. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146583. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146584. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146585. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146586. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146587. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146588. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146589. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146590. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146591. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146592. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146593. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146594. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146595. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146596. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146597. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146598. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146599. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146600. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146601. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146602. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146603. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146604. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146605. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146606. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146607. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146608. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146609. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146610. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146611. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146612. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146613. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146614. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146615. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146616. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146617. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146618. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146619. 12,
  146620. };
  146621. static float _vq_quantthresh__44u0__p4_0[] = {
  146622. -1.5, -0.5, 0.5, 1.5,
  146623. };
  146624. static long _vq_quantmap__44u0__p4_0[] = {
  146625. 3, 1, 0, 2, 4,
  146626. };
  146627. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146628. _vq_quantthresh__44u0__p4_0,
  146629. _vq_quantmap__44u0__p4_0,
  146630. 5,
  146631. 5
  146632. };
  146633. static static_codebook _44u0__p4_0 = {
  146634. 4, 625,
  146635. _vq_lengthlist__44u0__p4_0,
  146636. 1, -533725184, 1611661312, 3, 0,
  146637. _vq_quantlist__44u0__p4_0,
  146638. NULL,
  146639. &_vq_auxt__44u0__p4_0,
  146640. NULL,
  146641. 0
  146642. };
  146643. static long _vq_quantlist__44u0__p5_0[] = {
  146644. 4,
  146645. 3,
  146646. 5,
  146647. 2,
  146648. 6,
  146649. 1,
  146650. 7,
  146651. 0,
  146652. 8,
  146653. };
  146654. static long _vq_lengthlist__44u0__p5_0[] = {
  146655. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146656. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146657. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146658. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146659. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146660. 12,
  146661. };
  146662. static float _vq_quantthresh__44u0__p5_0[] = {
  146663. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146664. };
  146665. static long _vq_quantmap__44u0__p5_0[] = {
  146666. 7, 5, 3, 1, 0, 2, 4, 6,
  146667. 8,
  146668. };
  146669. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146670. _vq_quantthresh__44u0__p5_0,
  146671. _vq_quantmap__44u0__p5_0,
  146672. 9,
  146673. 9
  146674. };
  146675. static static_codebook _44u0__p5_0 = {
  146676. 2, 81,
  146677. _vq_lengthlist__44u0__p5_0,
  146678. 1, -531628032, 1611661312, 4, 0,
  146679. _vq_quantlist__44u0__p5_0,
  146680. NULL,
  146681. &_vq_auxt__44u0__p5_0,
  146682. NULL,
  146683. 0
  146684. };
  146685. static long _vq_quantlist__44u0__p6_0[] = {
  146686. 6,
  146687. 5,
  146688. 7,
  146689. 4,
  146690. 8,
  146691. 3,
  146692. 9,
  146693. 2,
  146694. 10,
  146695. 1,
  146696. 11,
  146697. 0,
  146698. 12,
  146699. };
  146700. static long _vq_lengthlist__44u0__p6_0[] = {
  146701. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146702. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146703. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146704. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146705. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146706. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146707. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146708. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146709. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146710. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146711. 15,17,16,17,18,17,17,18, 0,
  146712. };
  146713. static float _vq_quantthresh__44u0__p6_0[] = {
  146714. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146715. 12.5, 17.5, 22.5, 27.5,
  146716. };
  146717. static long _vq_quantmap__44u0__p6_0[] = {
  146718. 11, 9, 7, 5, 3, 1, 0, 2,
  146719. 4, 6, 8, 10, 12,
  146720. };
  146721. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146722. _vq_quantthresh__44u0__p6_0,
  146723. _vq_quantmap__44u0__p6_0,
  146724. 13,
  146725. 13
  146726. };
  146727. static static_codebook _44u0__p6_0 = {
  146728. 2, 169,
  146729. _vq_lengthlist__44u0__p6_0,
  146730. 1, -526516224, 1616117760, 4, 0,
  146731. _vq_quantlist__44u0__p6_0,
  146732. NULL,
  146733. &_vq_auxt__44u0__p6_0,
  146734. NULL,
  146735. 0
  146736. };
  146737. static long _vq_quantlist__44u0__p6_1[] = {
  146738. 2,
  146739. 1,
  146740. 3,
  146741. 0,
  146742. 4,
  146743. };
  146744. static long _vq_lengthlist__44u0__p6_1[] = {
  146745. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146746. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146747. };
  146748. static float _vq_quantthresh__44u0__p6_1[] = {
  146749. -1.5, -0.5, 0.5, 1.5,
  146750. };
  146751. static long _vq_quantmap__44u0__p6_1[] = {
  146752. 3, 1, 0, 2, 4,
  146753. };
  146754. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146755. _vq_quantthresh__44u0__p6_1,
  146756. _vq_quantmap__44u0__p6_1,
  146757. 5,
  146758. 5
  146759. };
  146760. static static_codebook _44u0__p6_1 = {
  146761. 2, 25,
  146762. _vq_lengthlist__44u0__p6_1,
  146763. 1, -533725184, 1611661312, 3, 0,
  146764. _vq_quantlist__44u0__p6_1,
  146765. NULL,
  146766. &_vq_auxt__44u0__p6_1,
  146767. NULL,
  146768. 0
  146769. };
  146770. static long _vq_quantlist__44u0__p7_0[] = {
  146771. 2,
  146772. 1,
  146773. 3,
  146774. 0,
  146775. 4,
  146776. };
  146777. static long _vq_lengthlist__44u0__p7_0[] = {
  146778. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146779. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146780. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146781. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146782. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146783. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146784. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146785. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146786. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146787. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146788. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146789. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146790. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146791. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146792. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146793. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146794. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146795. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146796. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146797. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146798. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146799. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146800. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146801. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146808. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146809. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146810. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146812. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146813. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146814. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146815. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146816. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146817. 10,
  146818. };
  146819. static float _vq_quantthresh__44u0__p7_0[] = {
  146820. -253.5, -84.5, 84.5, 253.5,
  146821. };
  146822. static long _vq_quantmap__44u0__p7_0[] = {
  146823. 3, 1, 0, 2, 4,
  146824. };
  146825. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146826. _vq_quantthresh__44u0__p7_0,
  146827. _vq_quantmap__44u0__p7_0,
  146828. 5,
  146829. 5
  146830. };
  146831. static static_codebook _44u0__p7_0 = {
  146832. 4, 625,
  146833. _vq_lengthlist__44u0__p7_0,
  146834. 1, -518709248, 1626677248, 3, 0,
  146835. _vq_quantlist__44u0__p7_0,
  146836. NULL,
  146837. &_vq_auxt__44u0__p7_0,
  146838. NULL,
  146839. 0
  146840. };
  146841. static long _vq_quantlist__44u0__p7_1[] = {
  146842. 6,
  146843. 5,
  146844. 7,
  146845. 4,
  146846. 8,
  146847. 3,
  146848. 9,
  146849. 2,
  146850. 10,
  146851. 1,
  146852. 11,
  146853. 0,
  146854. 12,
  146855. };
  146856. static long _vq_lengthlist__44u0__p7_1[] = {
  146857. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146858. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146859. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146860. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146861. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146862. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146863. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146864. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146865. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146866. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146867. 15,15,15,15,15,15,15,15,15,
  146868. };
  146869. static float _vq_quantthresh__44u0__p7_1[] = {
  146870. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146871. 32.5, 45.5, 58.5, 71.5,
  146872. };
  146873. static long _vq_quantmap__44u0__p7_1[] = {
  146874. 11, 9, 7, 5, 3, 1, 0, 2,
  146875. 4, 6, 8, 10, 12,
  146876. };
  146877. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146878. _vq_quantthresh__44u0__p7_1,
  146879. _vq_quantmap__44u0__p7_1,
  146880. 13,
  146881. 13
  146882. };
  146883. static static_codebook _44u0__p7_1 = {
  146884. 2, 169,
  146885. _vq_lengthlist__44u0__p7_1,
  146886. 1, -523010048, 1618608128, 4, 0,
  146887. _vq_quantlist__44u0__p7_1,
  146888. NULL,
  146889. &_vq_auxt__44u0__p7_1,
  146890. NULL,
  146891. 0
  146892. };
  146893. static long _vq_quantlist__44u0__p7_2[] = {
  146894. 6,
  146895. 5,
  146896. 7,
  146897. 4,
  146898. 8,
  146899. 3,
  146900. 9,
  146901. 2,
  146902. 10,
  146903. 1,
  146904. 11,
  146905. 0,
  146906. 12,
  146907. };
  146908. static long _vq_lengthlist__44u0__p7_2[] = {
  146909. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146910. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146911. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146912. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146913. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146914. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146915. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146916. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146917. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146918. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146919. 9, 9, 9,10, 9, 9,10,10, 9,
  146920. };
  146921. static float _vq_quantthresh__44u0__p7_2[] = {
  146922. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146923. 2.5, 3.5, 4.5, 5.5,
  146924. };
  146925. static long _vq_quantmap__44u0__p7_2[] = {
  146926. 11, 9, 7, 5, 3, 1, 0, 2,
  146927. 4, 6, 8, 10, 12,
  146928. };
  146929. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146930. _vq_quantthresh__44u0__p7_2,
  146931. _vq_quantmap__44u0__p7_2,
  146932. 13,
  146933. 13
  146934. };
  146935. static static_codebook _44u0__p7_2 = {
  146936. 2, 169,
  146937. _vq_lengthlist__44u0__p7_2,
  146938. 1, -531103744, 1611661312, 4, 0,
  146939. _vq_quantlist__44u0__p7_2,
  146940. NULL,
  146941. &_vq_auxt__44u0__p7_2,
  146942. NULL,
  146943. 0
  146944. };
  146945. static long _huff_lengthlist__44u0__short[] = {
  146946. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146947. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146948. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146949. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146950. };
  146951. static static_codebook _huff_book__44u0__short = {
  146952. 2, 64,
  146953. _huff_lengthlist__44u0__short,
  146954. 0, 0, 0, 0, 0,
  146955. NULL,
  146956. NULL,
  146957. NULL,
  146958. NULL,
  146959. 0
  146960. };
  146961. static long _huff_lengthlist__44u1__long[] = {
  146962. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146963. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146964. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146965. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146966. };
  146967. static static_codebook _huff_book__44u1__long = {
  146968. 2, 64,
  146969. _huff_lengthlist__44u1__long,
  146970. 0, 0, 0, 0, 0,
  146971. NULL,
  146972. NULL,
  146973. NULL,
  146974. NULL,
  146975. 0
  146976. };
  146977. static long _vq_quantlist__44u1__p1_0[] = {
  146978. 1,
  146979. 0,
  146980. 2,
  146981. };
  146982. static long _vq_lengthlist__44u1__p1_0[] = {
  146983. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146984. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146985. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146986. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146987. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146988. 13,
  146989. };
  146990. static float _vq_quantthresh__44u1__p1_0[] = {
  146991. -0.5, 0.5,
  146992. };
  146993. static long _vq_quantmap__44u1__p1_0[] = {
  146994. 1, 0, 2,
  146995. };
  146996. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146997. _vq_quantthresh__44u1__p1_0,
  146998. _vq_quantmap__44u1__p1_0,
  146999. 3,
  147000. 3
  147001. };
  147002. static static_codebook _44u1__p1_0 = {
  147003. 4, 81,
  147004. _vq_lengthlist__44u1__p1_0,
  147005. 1, -535822336, 1611661312, 2, 0,
  147006. _vq_quantlist__44u1__p1_0,
  147007. NULL,
  147008. &_vq_auxt__44u1__p1_0,
  147009. NULL,
  147010. 0
  147011. };
  147012. static long _vq_quantlist__44u1__p2_0[] = {
  147013. 1,
  147014. 0,
  147015. 2,
  147016. };
  147017. static long _vq_lengthlist__44u1__p2_0[] = {
  147018. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147019. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147020. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147021. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147022. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147023. 9,
  147024. };
  147025. static float _vq_quantthresh__44u1__p2_0[] = {
  147026. -0.5, 0.5,
  147027. };
  147028. static long _vq_quantmap__44u1__p2_0[] = {
  147029. 1, 0, 2,
  147030. };
  147031. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147032. _vq_quantthresh__44u1__p2_0,
  147033. _vq_quantmap__44u1__p2_0,
  147034. 3,
  147035. 3
  147036. };
  147037. static static_codebook _44u1__p2_0 = {
  147038. 4, 81,
  147039. _vq_lengthlist__44u1__p2_0,
  147040. 1, -535822336, 1611661312, 2, 0,
  147041. _vq_quantlist__44u1__p2_0,
  147042. NULL,
  147043. &_vq_auxt__44u1__p2_0,
  147044. NULL,
  147045. 0
  147046. };
  147047. static long _vq_quantlist__44u1__p3_0[] = {
  147048. 2,
  147049. 1,
  147050. 3,
  147051. 0,
  147052. 4,
  147053. };
  147054. static long _vq_lengthlist__44u1__p3_0[] = {
  147055. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147056. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147057. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147058. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147059. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147060. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147061. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147062. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147063. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147064. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147065. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147066. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147067. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147068. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147069. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147070. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147071. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147072. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147073. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147074. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147075. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147076. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147077. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147078. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147079. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147080. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147081. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147082. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147083. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147084. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147085. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147086. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147087. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147088. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147089. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147090. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147091. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147092. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147093. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147094. 19,
  147095. };
  147096. static float _vq_quantthresh__44u1__p3_0[] = {
  147097. -1.5, -0.5, 0.5, 1.5,
  147098. };
  147099. static long _vq_quantmap__44u1__p3_0[] = {
  147100. 3, 1, 0, 2, 4,
  147101. };
  147102. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147103. _vq_quantthresh__44u1__p3_0,
  147104. _vq_quantmap__44u1__p3_0,
  147105. 5,
  147106. 5
  147107. };
  147108. static static_codebook _44u1__p3_0 = {
  147109. 4, 625,
  147110. _vq_lengthlist__44u1__p3_0,
  147111. 1, -533725184, 1611661312, 3, 0,
  147112. _vq_quantlist__44u1__p3_0,
  147113. NULL,
  147114. &_vq_auxt__44u1__p3_0,
  147115. NULL,
  147116. 0
  147117. };
  147118. static long _vq_quantlist__44u1__p4_0[] = {
  147119. 2,
  147120. 1,
  147121. 3,
  147122. 0,
  147123. 4,
  147124. };
  147125. static long _vq_lengthlist__44u1__p4_0[] = {
  147126. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147127. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147128. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147129. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147130. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147131. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147132. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147133. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147134. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147135. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147136. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147137. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147138. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147139. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147140. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147141. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147142. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147143. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147144. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147145. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147146. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147147. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147148. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147149. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147150. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147151. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147152. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147153. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147154. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147155. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147156. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147157. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147158. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147159. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147160. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147161. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147162. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147163. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147164. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147165. 12,
  147166. };
  147167. static float _vq_quantthresh__44u1__p4_0[] = {
  147168. -1.5, -0.5, 0.5, 1.5,
  147169. };
  147170. static long _vq_quantmap__44u1__p4_0[] = {
  147171. 3, 1, 0, 2, 4,
  147172. };
  147173. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147174. _vq_quantthresh__44u1__p4_0,
  147175. _vq_quantmap__44u1__p4_0,
  147176. 5,
  147177. 5
  147178. };
  147179. static static_codebook _44u1__p4_0 = {
  147180. 4, 625,
  147181. _vq_lengthlist__44u1__p4_0,
  147182. 1, -533725184, 1611661312, 3, 0,
  147183. _vq_quantlist__44u1__p4_0,
  147184. NULL,
  147185. &_vq_auxt__44u1__p4_0,
  147186. NULL,
  147187. 0
  147188. };
  147189. static long _vq_quantlist__44u1__p5_0[] = {
  147190. 4,
  147191. 3,
  147192. 5,
  147193. 2,
  147194. 6,
  147195. 1,
  147196. 7,
  147197. 0,
  147198. 8,
  147199. };
  147200. static long _vq_lengthlist__44u1__p5_0[] = {
  147201. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147202. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147203. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147204. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147205. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147206. 12,
  147207. };
  147208. static float _vq_quantthresh__44u1__p5_0[] = {
  147209. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147210. };
  147211. static long _vq_quantmap__44u1__p5_0[] = {
  147212. 7, 5, 3, 1, 0, 2, 4, 6,
  147213. 8,
  147214. };
  147215. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147216. _vq_quantthresh__44u1__p5_0,
  147217. _vq_quantmap__44u1__p5_0,
  147218. 9,
  147219. 9
  147220. };
  147221. static static_codebook _44u1__p5_0 = {
  147222. 2, 81,
  147223. _vq_lengthlist__44u1__p5_0,
  147224. 1, -531628032, 1611661312, 4, 0,
  147225. _vq_quantlist__44u1__p5_0,
  147226. NULL,
  147227. &_vq_auxt__44u1__p5_0,
  147228. NULL,
  147229. 0
  147230. };
  147231. static long _vq_quantlist__44u1__p6_0[] = {
  147232. 6,
  147233. 5,
  147234. 7,
  147235. 4,
  147236. 8,
  147237. 3,
  147238. 9,
  147239. 2,
  147240. 10,
  147241. 1,
  147242. 11,
  147243. 0,
  147244. 12,
  147245. };
  147246. static long _vq_lengthlist__44u1__p6_0[] = {
  147247. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147248. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147249. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147250. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147251. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147252. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147253. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147254. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147255. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147256. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147257. 15,17,16,17,18,17,17,18, 0,
  147258. };
  147259. static float _vq_quantthresh__44u1__p6_0[] = {
  147260. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147261. 12.5, 17.5, 22.5, 27.5,
  147262. };
  147263. static long _vq_quantmap__44u1__p6_0[] = {
  147264. 11, 9, 7, 5, 3, 1, 0, 2,
  147265. 4, 6, 8, 10, 12,
  147266. };
  147267. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147268. _vq_quantthresh__44u1__p6_0,
  147269. _vq_quantmap__44u1__p6_0,
  147270. 13,
  147271. 13
  147272. };
  147273. static static_codebook _44u1__p6_0 = {
  147274. 2, 169,
  147275. _vq_lengthlist__44u1__p6_0,
  147276. 1, -526516224, 1616117760, 4, 0,
  147277. _vq_quantlist__44u1__p6_0,
  147278. NULL,
  147279. &_vq_auxt__44u1__p6_0,
  147280. NULL,
  147281. 0
  147282. };
  147283. static long _vq_quantlist__44u1__p6_1[] = {
  147284. 2,
  147285. 1,
  147286. 3,
  147287. 0,
  147288. 4,
  147289. };
  147290. static long _vq_lengthlist__44u1__p6_1[] = {
  147291. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147292. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147293. };
  147294. static float _vq_quantthresh__44u1__p6_1[] = {
  147295. -1.5, -0.5, 0.5, 1.5,
  147296. };
  147297. static long _vq_quantmap__44u1__p6_1[] = {
  147298. 3, 1, 0, 2, 4,
  147299. };
  147300. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147301. _vq_quantthresh__44u1__p6_1,
  147302. _vq_quantmap__44u1__p6_1,
  147303. 5,
  147304. 5
  147305. };
  147306. static static_codebook _44u1__p6_1 = {
  147307. 2, 25,
  147308. _vq_lengthlist__44u1__p6_1,
  147309. 1, -533725184, 1611661312, 3, 0,
  147310. _vq_quantlist__44u1__p6_1,
  147311. NULL,
  147312. &_vq_auxt__44u1__p6_1,
  147313. NULL,
  147314. 0
  147315. };
  147316. static long _vq_quantlist__44u1__p7_0[] = {
  147317. 3,
  147318. 2,
  147319. 4,
  147320. 1,
  147321. 5,
  147322. 0,
  147323. 6,
  147324. };
  147325. static long _vq_lengthlist__44u1__p7_0[] = {
  147326. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147327. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147328. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147329. 8,
  147330. };
  147331. static float _vq_quantthresh__44u1__p7_0[] = {
  147332. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147333. };
  147334. static long _vq_quantmap__44u1__p7_0[] = {
  147335. 5, 3, 1, 0, 2, 4, 6,
  147336. };
  147337. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147338. _vq_quantthresh__44u1__p7_0,
  147339. _vq_quantmap__44u1__p7_0,
  147340. 7,
  147341. 7
  147342. };
  147343. static static_codebook _44u1__p7_0 = {
  147344. 2, 49,
  147345. _vq_lengthlist__44u1__p7_0,
  147346. 1, -518017024, 1626677248, 3, 0,
  147347. _vq_quantlist__44u1__p7_0,
  147348. NULL,
  147349. &_vq_auxt__44u1__p7_0,
  147350. NULL,
  147351. 0
  147352. };
  147353. static long _vq_quantlist__44u1__p7_1[] = {
  147354. 6,
  147355. 5,
  147356. 7,
  147357. 4,
  147358. 8,
  147359. 3,
  147360. 9,
  147361. 2,
  147362. 10,
  147363. 1,
  147364. 11,
  147365. 0,
  147366. 12,
  147367. };
  147368. static long _vq_lengthlist__44u1__p7_1[] = {
  147369. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147370. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147371. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147372. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147373. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147374. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147375. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147376. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147377. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147378. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147379. 15,15,15,15,15,15,15,15,15,
  147380. };
  147381. static float _vq_quantthresh__44u1__p7_1[] = {
  147382. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147383. 32.5, 45.5, 58.5, 71.5,
  147384. };
  147385. static long _vq_quantmap__44u1__p7_1[] = {
  147386. 11, 9, 7, 5, 3, 1, 0, 2,
  147387. 4, 6, 8, 10, 12,
  147388. };
  147389. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147390. _vq_quantthresh__44u1__p7_1,
  147391. _vq_quantmap__44u1__p7_1,
  147392. 13,
  147393. 13
  147394. };
  147395. static static_codebook _44u1__p7_1 = {
  147396. 2, 169,
  147397. _vq_lengthlist__44u1__p7_1,
  147398. 1, -523010048, 1618608128, 4, 0,
  147399. _vq_quantlist__44u1__p7_1,
  147400. NULL,
  147401. &_vq_auxt__44u1__p7_1,
  147402. NULL,
  147403. 0
  147404. };
  147405. static long _vq_quantlist__44u1__p7_2[] = {
  147406. 6,
  147407. 5,
  147408. 7,
  147409. 4,
  147410. 8,
  147411. 3,
  147412. 9,
  147413. 2,
  147414. 10,
  147415. 1,
  147416. 11,
  147417. 0,
  147418. 12,
  147419. };
  147420. static long _vq_lengthlist__44u1__p7_2[] = {
  147421. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147422. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147423. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147424. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147425. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147426. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147427. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147428. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147429. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147430. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147431. 9, 9, 9,10, 9, 9,10,10, 9,
  147432. };
  147433. static float _vq_quantthresh__44u1__p7_2[] = {
  147434. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147435. 2.5, 3.5, 4.5, 5.5,
  147436. };
  147437. static long _vq_quantmap__44u1__p7_2[] = {
  147438. 11, 9, 7, 5, 3, 1, 0, 2,
  147439. 4, 6, 8, 10, 12,
  147440. };
  147441. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147442. _vq_quantthresh__44u1__p7_2,
  147443. _vq_quantmap__44u1__p7_2,
  147444. 13,
  147445. 13
  147446. };
  147447. static static_codebook _44u1__p7_2 = {
  147448. 2, 169,
  147449. _vq_lengthlist__44u1__p7_2,
  147450. 1, -531103744, 1611661312, 4, 0,
  147451. _vq_quantlist__44u1__p7_2,
  147452. NULL,
  147453. &_vq_auxt__44u1__p7_2,
  147454. NULL,
  147455. 0
  147456. };
  147457. static long _huff_lengthlist__44u1__short[] = {
  147458. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147459. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147460. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147461. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147462. };
  147463. static static_codebook _huff_book__44u1__short = {
  147464. 2, 64,
  147465. _huff_lengthlist__44u1__short,
  147466. 0, 0, 0, 0, 0,
  147467. NULL,
  147468. NULL,
  147469. NULL,
  147470. NULL,
  147471. 0
  147472. };
  147473. static long _huff_lengthlist__44u2__long[] = {
  147474. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147475. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147476. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147477. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147478. };
  147479. static static_codebook _huff_book__44u2__long = {
  147480. 2, 64,
  147481. _huff_lengthlist__44u2__long,
  147482. 0, 0, 0, 0, 0,
  147483. NULL,
  147484. NULL,
  147485. NULL,
  147486. NULL,
  147487. 0
  147488. };
  147489. static long _vq_quantlist__44u2__p1_0[] = {
  147490. 1,
  147491. 0,
  147492. 2,
  147493. };
  147494. static long _vq_lengthlist__44u2__p1_0[] = {
  147495. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147496. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147497. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147498. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147499. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147500. 13,
  147501. };
  147502. static float _vq_quantthresh__44u2__p1_0[] = {
  147503. -0.5, 0.5,
  147504. };
  147505. static long _vq_quantmap__44u2__p1_0[] = {
  147506. 1, 0, 2,
  147507. };
  147508. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147509. _vq_quantthresh__44u2__p1_0,
  147510. _vq_quantmap__44u2__p1_0,
  147511. 3,
  147512. 3
  147513. };
  147514. static static_codebook _44u2__p1_0 = {
  147515. 4, 81,
  147516. _vq_lengthlist__44u2__p1_0,
  147517. 1, -535822336, 1611661312, 2, 0,
  147518. _vq_quantlist__44u2__p1_0,
  147519. NULL,
  147520. &_vq_auxt__44u2__p1_0,
  147521. NULL,
  147522. 0
  147523. };
  147524. static long _vq_quantlist__44u2__p2_0[] = {
  147525. 1,
  147526. 0,
  147527. 2,
  147528. };
  147529. static long _vq_lengthlist__44u2__p2_0[] = {
  147530. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147531. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147532. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147533. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147534. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147535. 9,
  147536. };
  147537. static float _vq_quantthresh__44u2__p2_0[] = {
  147538. -0.5, 0.5,
  147539. };
  147540. static long _vq_quantmap__44u2__p2_0[] = {
  147541. 1, 0, 2,
  147542. };
  147543. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147544. _vq_quantthresh__44u2__p2_0,
  147545. _vq_quantmap__44u2__p2_0,
  147546. 3,
  147547. 3
  147548. };
  147549. static static_codebook _44u2__p2_0 = {
  147550. 4, 81,
  147551. _vq_lengthlist__44u2__p2_0,
  147552. 1, -535822336, 1611661312, 2, 0,
  147553. _vq_quantlist__44u2__p2_0,
  147554. NULL,
  147555. &_vq_auxt__44u2__p2_0,
  147556. NULL,
  147557. 0
  147558. };
  147559. static long _vq_quantlist__44u2__p3_0[] = {
  147560. 2,
  147561. 1,
  147562. 3,
  147563. 0,
  147564. 4,
  147565. };
  147566. static long _vq_lengthlist__44u2__p3_0[] = {
  147567. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147568. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147569. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147570. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147571. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147572. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147573. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147574. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147575. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147576. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147577. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147578. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147579. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147580. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147581. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147582. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147583. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147584. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147585. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147586. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147587. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147588. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147589. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147590. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147591. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147592. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147593. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147594. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147595. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147596. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147597. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147598. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147599. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147600. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147601. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147602. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147603. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147604. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147605. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147606. 0,
  147607. };
  147608. static float _vq_quantthresh__44u2__p3_0[] = {
  147609. -1.5, -0.5, 0.5, 1.5,
  147610. };
  147611. static long _vq_quantmap__44u2__p3_0[] = {
  147612. 3, 1, 0, 2, 4,
  147613. };
  147614. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147615. _vq_quantthresh__44u2__p3_0,
  147616. _vq_quantmap__44u2__p3_0,
  147617. 5,
  147618. 5
  147619. };
  147620. static static_codebook _44u2__p3_0 = {
  147621. 4, 625,
  147622. _vq_lengthlist__44u2__p3_0,
  147623. 1, -533725184, 1611661312, 3, 0,
  147624. _vq_quantlist__44u2__p3_0,
  147625. NULL,
  147626. &_vq_auxt__44u2__p3_0,
  147627. NULL,
  147628. 0
  147629. };
  147630. static long _vq_quantlist__44u2__p4_0[] = {
  147631. 2,
  147632. 1,
  147633. 3,
  147634. 0,
  147635. 4,
  147636. };
  147637. static long _vq_lengthlist__44u2__p4_0[] = {
  147638. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147639. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147640. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147641. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147642. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147643. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147644. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147645. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147646. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147647. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147648. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147649. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147650. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147651. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147652. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147653. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147654. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147655. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147656. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147657. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147658. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147659. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147660. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147661. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147662. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147663. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147664. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147665. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147666. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147667. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147668. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147669. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147670. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147671. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147672. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147673. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147674. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147675. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147676. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147677. 13,
  147678. };
  147679. static float _vq_quantthresh__44u2__p4_0[] = {
  147680. -1.5, -0.5, 0.5, 1.5,
  147681. };
  147682. static long _vq_quantmap__44u2__p4_0[] = {
  147683. 3, 1, 0, 2, 4,
  147684. };
  147685. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147686. _vq_quantthresh__44u2__p4_0,
  147687. _vq_quantmap__44u2__p4_0,
  147688. 5,
  147689. 5
  147690. };
  147691. static static_codebook _44u2__p4_0 = {
  147692. 4, 625,
  147693. _vq_lengthlist__44u2__p4_0,
  147694. 1, -533725184, 1611661312, 3, 0,
  147695. _vq_quantlist__44u2__p4_0,
  147696. NULL,
  147697. &_vq_auxt__44u2__p4_0,
  147698. NULL,
  147699. 0
  147700. };
  147701. static long _vq_quantlist__44u2__p5_0[] = {
  147702. 4,
  147703. 3,
  147704. 5,
  147705. 2,
  147706. 6,
  147707. 1,
  147708. 7,
  147709. 0,
  147710. 8,
  147711. };
  147712. static long _vq_lengthlist__44u2__p5_0[] = {
  147713. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147714. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147715. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147716. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147717. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147718. 13,
  147719. };
  147720. static float _vq_quantthresh__44u2__p5_0[] = {
  147721. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147722. };
  147723. static long _vq_quantmap__44u2__p5_0[] = {
  147724. 7, 5, 3, 1, 0, 2, 4, 6,
  147725. 8,
  147726. };
  147727. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147728. _vq_quantthresh__44u2__p5_0,
  147729. _vq_quantmap__44u2__p5_0,
  147730. 9,
  147731. 9
  147732. };
  147733. static static_codebook _44u2__p5_0 = {
  147734. 2, 81,
  147735. _vq_lengthlist__44u2__p5_0,
  147736. 1, -531628032, 1611661312, 4, 0,
  147737. _vq_quantlist__44u2__p5_0,
  147738. NULL,
  147739. &_vq_auxt__44u2__p5_0,
  147740. NULL,
  147741. 0
  147742. };
  147743. static long _vq_quantlist__44u2__p6_0[] = {
  147744. 6,
  147745. 5,
  147746. 7,
  147747. 4,
  147748. 8,
  147749. 3,
  147750. 9,
  147751. 2,
  147752. 10,
  147753. 1,
  147754. 11,
  147755. 0,
  147756. 12,
  147757. };
  147758. static long _vq_lengthlist__44u2__p6_0[] = {
  147759. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147760. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147761. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147762. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147763. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147764. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147765. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147766. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147767. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147768. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147769. 15,17,17,16,18,17,18, 0, 0,
  147770. };
  147771. static float _vq_quantthresh__44u2__p6_0[] = {
  147772. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147773. 12.5, 17.5, 22.5, 27.5,
  147774. };
  147775. static long _vq_quantmap__44u2__p6_0[] = {
  147776. 11, 9, 7, 5, 3, 1, 0, 2,
  147777. 4, 6, 8, 10, 12,
  147778. };
  147779. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147780. _vq_quantthresh__44u2__p6_0,
  147781. _vq_quantmap__44u2__p6_0,
  147782. 13,
  147783. 13
  147784. };
  147785. static static_codebook _44u2__p6_0 = {
  147786. 2, 169,
  147787. _vq_lengthlist__44u2__p6_0,
  147788. 1, -526516224, 1616117760, 4, 0,
  147789. _vq_quantlist__44u2__p6_0,
  147790. NULL,
  147791. &_vq_auxt__44u2__p6_0,
  147792. NULL,
  147793. 0
  147794. };
  147795. static long _vq_quantlist__44u2__p6_1[] = {
  147796. 2,
  147797. 1,
  147798. 3,
  147799. 0,
  147800. 4,
  147801. };
  147802. static long _vq_lengthlist__44u2__p6_1[] = {
  147803. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147804. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147805. };
  147806. static float _vq_quantthresh__44u2__p6_1[] = {
  147807. -1.5, -0.5, 0.5, 1.5,
  147808. };
  147809. static long _vq_quantmap__44u2__p6_1[] = {
  147810. 3, 1, 0, 2, 4,
  147811. };
  147812. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147813. _vq_quantthresh__44u2__p6_1,
  147814. _vq_quantmap__44u2__p6_1,
  147815. 5,
  147816. 5
  147817. };
  147818. static static_codebook _44u2__p6_1 = {
  147819. 2, 25,
  147820. _vq_lengthlist__44u2__p6_1,
  147821. 1, -533725184, 1611661312, 3, 0,
  147822. _vq_quantlist__44u2__p6_1,
  147823. NULL,
  147824. &_vq_auxt__44u2__p6_1,
  147825. NULL,
  147826. 0
  147827. };
  147828. static long _vq_quantlist__44u2__p7_0[] = {
  147829. 4,
  147830. 3,
  147831. 5,
  147832. 2,
  147833. 6,
  147834. 1,
  147835. 7,
  147836. 0,
  147837. 8,
  147838. };
  147839. static long _vq_lengthlist__44u2__p7_0[] = {
  147840. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147841. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147844. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147845. 11,
  147846. };
  147847. static float _vq_quantthresh__44u2__p7_0[] = {
  147848. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147849. };
  147850. static long _vq_quantmap__44u2__p7_0[] = {
  147851. 7, 5, 3, 1, 0, 2, 4, 6,
  147852. 8,
  147853. };
  147854. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147855. _vq_quantthresh__44u2__p7_0,
  147856. _vq_quantmap__44u2__p7_0,
  147857. 9,
  147858. 9
  147859. };
  147860. static static_codebook _44u2__p7_0 = {
  147861. 2, 81,
  147862. _vq_lengthlist__44u2__p7_0,
  147863. 1, -516612096, 1626677248, 4, 0,
  147864. _vq_quantlist__44u2__p7_0,
  147865. NULL,
  147866. &_vq_auxt__44u2__p7_0,
  147867. NULL,
  147868. 0
  147869. };
  147870. static long _vq_quantlist__44u2__p7_1[] = {
  147871. 6,
  147872. 5,
  147873. 7,
  147874. 4,
  147875. 8,
  147876. 3,
  147877. 9,
  147878. 2,
  147879. 10,
  147880. 1,
  147881. 11,
  147882. 0,
  147883. 12,
  147884. };
  147885. static long _vq_lengthlist__44u2__p7_1[] = {
  147886. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147887. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147888. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147889. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147890. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147891. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147892. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147893. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147894. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147895. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147896. 14,14,14,17,15,17,17,17,17,
  147897. };
  147898. static float _vq_quantthresh__44u2__p7_1[] = {
  147899. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147900. 32.5, 45.5, 58.5, 71.5,
  147901. };
  147902. static long _vq_quantmap__44u2__p7_1[] = {
  147903. 11, 9, 7, 5, 3, 1, 0, 2,
  147904. 4, 6, 8, 10, 12,
  147905. };
  147906. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147907. _vq_quantthresh__44u2__p7_1,
  147908. _vq_quantmap__44u2__p7_1,
  147909. 13,
  147910. 13
  147911. };
  147912. static static_codebook _44u2__p7_1 = {
  147913. 2, 169,
  147914. _vq_lengthlist__44u2__p7_1,
  147915. 1, -523010048, 1618608128, 4, 0,
  147916. _vq_quantlist__44u2__p7_1,
  147917. NULL,
  147918. &_vq_auxt__44u2__p7_1,
  147919. NULL,
  147920. 0
  147921. };
  147922. static long _vq_quantlist__44u2__p7_2[] = {
  147923. 6,
  147924. 5,
  147925. 7,
  147926. 4,
  147927. 8,
  147928. 3,
  147929. 9,
  147930. 2,
  147931. 10,
  147932. 1,
  147933. 11,
  147934. 0,
  147935. 12,
  147936. };
  147937. static long _vq_lengthlist__44u2__p7_2[] = {
  147938. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147939. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147940. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147941. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147942. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147943. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147944. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147945. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147946. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147947. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147948. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147949. };
  147950. static float _vq_quantthresh__44u2__p7_2[] = {
  147951. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147952. 2.5, 3.5, 4.5, 5.5,
  147953. };
  147954. static long _vq_quantmap__44u2__p7_2[] = {
  147955. 11, 9, 7, 5, 3, 1, 0, 2,
  147956. 4, 6, 8, 10, 12,
  147957. };
  147958. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147959. _vq_quantthresh__44u2__p7_2,
  147960. _vq_quantmap__44u2__p7_2,
  147961. 13,
  147962. 13
  147963. };
  147964. static static_codebook _44u2__p7_2 = {
  147965. 2, 169,
  147966. _vq_lengthlist__44u2__p7_2,
  147967. 1, -531103744, 1611661312, 4, 0,
  147968. _vq_quantlist__44u2__p7_2,
  147969. NULL,
  147970. &_vq_auxt__44u2__p7_2,
  147971. NULL,
  147972. 0
  147973. };
  147974. static long _huff_lengthlist__44u2__short[] = {
  147975. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147976. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147977. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147978. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147979. };
  147980. static static_codebook _huff_book__44u2__short = {
  147981. 2, 64,
  147982. _huff_lengthlist__44u2__short,
  147983. 0, 0, 0, 0, 0,
  147984. NULL,
  147985. NULL,
  147986. NULL,
  147987. NULL,
  147988. 0
  147989. };
  147990. static long _huff_lengthlist__44u3__long[] = {
  147991. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147992. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147993. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147994. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147995. };
  147996. static static_codebook _huff_book__44u3__long = {
  147997. 2, 64,
  147998. _huff_lengthlist__44u3__long,
  147999. 0, 0, 0, 0, 0,
  148000. NULL,
  148001. NULL,
  148002. NULL,
  148003. NULL,
  148004. 0
  148005. };
  148006. static long _vq_quantlist__44u3__p1_0[] = {
  148007. 1,
  148008. 0,
  148009. 2,
  148010. };
  148011. static long _vq_lengthlist__44u3__p1_0[] = {
  148012. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148013. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148014. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148015. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148016. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148017. 13,
  148018. };
  148019. static float _vq_quantthresh__44u3__p1_0[] = {
  148020. -0.5, 0.5,
  148021. };
  148022. static long _vq_quantmap__44u3__p1_0[] = {
  148023. 1, 0, 2,
  148024. };
  148025. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148026. _vq_quantthresh__44u3__p1_0,
  148027. _vq_quantmap__44u3__p1_0,
  148028. 3,
  148029. 3
  148030. };
  148031. static static_codebook _44u3__p1_0 = {
  148032. 4, 81,
  148033. _vq_lengthlist__44u3__p1_0,
  148034. 1, -535822336, 1611661312, 2, 0,
  148035. _vq_quantlist__44u3__p1_0,
  148036. NULL,
  148037. &_vq_auxt__44u3__p1_0,
  148038. NULL,
  148039. 0
  148040. };
  148041. static long _vq_quantlist__44u3__p2_0[] = {
  148042. 1,
  148043. 0,
  148044. 2,
  148045. };
  148046. static long _vq_lengthlist__44u3__p2_0[] = {
  148047. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148048. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148049. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148050. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148051. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148052. 9,
  148053. };
  148054. static float _vq_quantthresh__44u3__p2_0[] = {
  148055. -0.5, 0.5,
  148056. };
  148057. static long _vq_quantmap__44u3__p2_0[] = {
  148058. 1, 0, 2,
  148059. };
  148060. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148061. _vq_quantthresh__44u3__p2_0,
  148062. _vq_quantmap__44u3__p2_0,
  148063. 3,
  148064. 3
  148065. };
  148066. static static_codebook _44u3__p2_0 = {
  148067. 4, 81,
  148068. _vq_lengthlist__44u3__p2_0,
  148069. 1, -535822336, 1611661312, 2, 0,
  148070. _vq_quantlist__44u3__p2_0,
  148071. NULL,
  148072. &_vq_auxt__44u3__p2_0,
  148073. NULL,
  148074. 0
  148075. };
  148076. static long _vq_quantlist__44u3__p3_0[] = {
  148077. 2,
  148078. 1,
  148079. 3,
  148080. 0,
  148081. 4,
  148082. };
  148083. static long _vq_lengthlist__44u3__p3_0[] = {
  148084. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148085. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148086. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148087. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148088. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148089. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148090. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148091. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148092. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148093. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148094. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148095. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148096. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148097. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148098. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148099. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148100. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148101. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148102. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148103. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148104. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148105. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148106. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148107. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148108. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148109. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148110. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148111. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148112. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148113. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148114. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148115. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148116. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148117. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148118. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148119. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148120. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148121. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148122. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148123. 0,
  148124. };
  148125. static float _vq_quantthresh__44u3__p3_0[] = {
  148126. -1.5, -0.5, 0.5, 1.5,
  148127. };
  148128. static long _vq_quantmap__44u3__p3_0[] = {
  148129. 3, 1, 0, 2, 4,
  148130. };
  148131. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148132. _vq_quantthresh__44u3__p3_0,
  148133. _vq_quantmap__44u3__p3_0,
  148134. 5,
  148135. 5
  148136. };
  148137. static static_codebook _44u3__p3_0 = {
  148138. 4, 625,
  148139. _vq_lengthlist__44u3__p3_0,
  148140. 1, -533725184, 1611661312, 3, 0,
  148141. _vq_quantlist__44u3__p3_0,
  148142. NULL,
  148143. &_vq_auxt__44u3__p3_0,
  148144. NULL,
  148145. 0
  148146. };
  148147. static long _vq_quantlist__44u3__p4_0[] = {
  148148. 2,
  148149. 1,
  148150. 3,
  148151. 0,
  148152. 4,
  148153. };
  148154. static long _vq_lengthlist__44u3__p4_0[] = {
  148155. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148156. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148157. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148158. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148159. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148160. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148161. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148162. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148163. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148164. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148165. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148166. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148167. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148168. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148169. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148170. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148171. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148172. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148173. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148174. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148175. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148176. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148177. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148178. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148179. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148180. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148181. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148182. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148183. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148184. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148185. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148186. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148187. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148188. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148189. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148190. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148191. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148192. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148193. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148194. 13,
  148195. };
  148196. static float _vq_quantthresh__44u3__p4_0[] = {
  148197. -1.5, -0.5, 0.5, 1.5,
  148198. };
  148199. static long _vq_quantmap__44u3__p4_0[] = {
  148200. 3, 1, 0, 2, 4,
  148201. };
  148202. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148203. _vq_quantthresh__44u3__p4_0,
  148204. _vq_quantmap__44u3__p4_0,
  148205. 5,
  148206. 5
  148207. };
  148208. static static_codebook _44u3__p4_0 = {
  148209. 4, 625,
  148210. _vq_lengthlist__44u3__p4_0,
  148211. 1, -533725184, 1611661312, 3, 0,
  148212. _vq_quantlist__44u3__p4_0,
  148213. NULL,
  148214. &_vq_auxt__44u3__p4_0,
  148215. NULL,
  148216. 0
  148217. };
  148218. static long _vq_quantlist__44u3__p5_0[] = {
  148219. 4,
  148220. 3,
  148221. 5,
  148222. 2,
  148223. 6,
  148224. 1,
  148225. 7,
  148226. 0,
  148227. 8,
  148228. };
  148229. static long _vq_lengthlist__44u3__p5_0[] = {
  148230. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148231. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148232. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148233. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148234. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148235. 12,
  148236. };
  148237. static float _vq_quantthresh__44u3__p5_0[] = {
  148238. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148239. };
  148240. static long _vq_quantmap__44u3__p5_0[] = {
  148241. 7, 5, 3, 1, 0, 2, 4, 6,
  148242. 8,
  148243. };
  148244. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148245. _vq_quantthresh__44u3__p5_0,
  148246. _vq_quantmap__44u3__p5_0,
  148247. 9,
  148248. 9
  148249. };
  148250. static static_codebook _44u3__p5_0 = {
  148251. 2, 81,
  148252. _vq_lengthlist__44u3__p5_0,
  148253. 1, -531628032, 1611661312, 4, 0,
  148254. _vq_quantlist__44u3__p5_0,
  148255. NULL,
  148256. &_vq_auxt__44u3__p5_0,
  148257. NULL,
  148258. 0
  148259. };
  148260. static long _vq_quantlist__44u3__p6_0[] = {
  148261. 6,
  148262. 5,
  148263. 7,
  148264. 4,
  148265. 8,
  148266. 3,
  148267. 9,
  148268. 2,
  148269. 10,
  148270. 1,
  148271. 11,
  148272. 0,
  148273. 12,
  148274. };
  148275. static long _vq_lengthlist__44u3__p6_0[] = {
  148276. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148277. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148278. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148279. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148280. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148281. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148282. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148283. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148284. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148285. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148286. 15,16,16,16,17,18,16,20,18,
  148287. };
  148288. static float _vq_quantthresh__44u3__p6_0[] = {
  148289. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148290. 12.5, 17.5, 22.5, 27.5,
  148291. };
  148292. static long _vq_quantmap__44u3__p6_0[] = {
  148293. 11, 9, 7, 5, 3, 1, 0, 2,
  148294. 4, 6, 8, 10, 12,
  148295. };
  148296. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148297. _vq_quantthresh__44u3__p6_0,
  148298. _vq_quantmap__44u3__p6_0,
  148299. 13,
  148300. 13
  148301. };
  148302. static static_codebook _44u3__p6_0 = {
  148303. 2, 169,
  148304. _vq_lengthlist__44u3__p6_0,
  148305. 1, -526516224, 1616117760, 4, 0,
  148306. _vq_quantlist__44u3__p6_0,
  148307. NULL,
  148308. &_vq_auxt__44u3__p6_0,
  148309. NULL,
  148310. 0
  148311. };
  148312. static long _vq_quantlist__44u3__p6_1[] = {
  148313. 2,
  148314. 1,
  148315. 3,
  148316. 0,
  148317. 4,
  148318. };
  148319. static long _vq_lengthlist__44u3__p6_1[] = {
  148320. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148321. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148322. };
  148323. static float _vq_quantthresh__44u3__p6_1[] = {
  148324. -1.5, -0.5, 0.5, 1.5,
  148325. };
  148326. static long _vq_quantmap__44u3__p6_1[] = {
  148327. 3, 1, 0, 2, 4,
  148328. };
  148329. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148330. _vq_quantthresh__44u3__p6_1,
  148331. _vq_quantmap__44u3__p6_1,
  148332. 5,
  148333. 5
  148334. };
  148335. static static_codebook _44u3__p6_1 = {
  148336. 2, 25,
  148337. _vq_lengthlist__44u3__p6_1,
  148338. 1, -533725184, 1611661312, 3, 0,
  148339. _vq_quantlist__44u3__p6_1,
  148340. NULL,
  148341. &_vq_auxt__44u3__p6_1,
  148342. NULL,
  148343. 0
  148344. };
  148345. static long _vq_quantlist__44u3__p7_0[] = {
  148346. 4,
  148347. 3,
  148348. 5,
  148349. 2,
  148350. 6,
  148351. 1,
  148352. 7,
  148353. 0,
  148354. 8,
  148355. };
  148356. static long _vq_lengthlist__44u3__p7_0[] = {
  148357. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148358. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148359. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148360. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148361. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148362. 9,
  148363. };
  148364. static float _vq_quantthresh__44u3__p7_0[] = {
  148365. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148366. };
  148367. static long _vq_quantmap__44u3__p7_0[] = {
  148368. 7, 5, 3, 1, 0, 2, 4, 6,
  148369. 8,
  148370. };
  148371. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148372. _vq_quantthresh__44u3__p7_0,
  148373. _vq_quantmap__44u3__p7_0,
  148374. 9,
  148375. 9
  148376. };
  148377. static static_codebook _44u3__p7_0 = {
  148378. 2, 81,
  148379. _vq_lengthlist__44u3__p7_0,
  148380. 1, -515907584, 1627381760, 4, 0,
  148381. _vq_quantlist__44u3__p7_0,
  148382. NULL,
  148383. &_vq_auxt__44u3__p7_0,
  148384. NULL,
  148385. 0
  148386. };
  148387. static long _vq_quantlist__44u3__p7_1[] = {
  148388. 7,
  148389. 6,
  148390. 8,
  148391. 5,
  148392. 9,
  148393. 4,
  148394. 10,
  148395. 3,
  148396. 11,
  148397. 2,
  148398. 12,
  148399. 1,
  148400. 13,
  148401. 0,
  148402. 14,
  148403. };
  148404. static long _vq_lengthlist__44u3__p7_1[] = {
  148405. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148406. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148407. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148408. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148409. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148410. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148411. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148412. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148413. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148414. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148415. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148416. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148417. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148418. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148419. 17,
  148420. };
  148421. static float _vq_quantthresh__44u3__p7_1[] = {
  148422. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148423. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148424. };
  148425. static long _vq_quantmap__44u3__p7_1[] = {
  148426. 13, 11, 9, 7, 5, 3, 1, 0,
  148427. 2, 4, 6, 8, 10, 12, 14,
  148428. };
  148429. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148430. _vq_quantthresh__44u3__p7_1,
  148431. _vq_quantmap__44u3__p7_1,
  148432. 15,
  148433. 15
  148434. };
  148435. static static_codebook _44u3__p7_1 = {
  148436. 2, 225,
  148437. _vq_lengthlist__44u3__p7_1,
  148438. 1, -522338304, 1620115456, 4, 0,
  148439. _vq_quantlist__44u3__p7_1,
  148440. NULL,
  148441. &_vq_auxt__44u3__p7_1,
  148442. NULL,
  148443. 0
  148444. };
  148445. static long _vq_quantlist__44u3__p7_2[] = {
  148446. 8,
  148447. 7,
  148448. 9,
  148449. 6,
  148450. 10,
  148451. 5,
  148452. 11,
  148453. 4,
  148454. 12,
  148455. 3,
  148456. 13,
  148457. 2,
  148458. 14,
  148459. 1,
  148460. 15,
  148461. 0,
  148462. 16,
  148463. };
  148464. static long _vq_lengthlist__44u3__p7_2[] = {
  148465. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148466. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148467. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148468. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148469. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148470. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148471. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148472. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148473. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148474. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148475. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148476. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148477. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148478. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148479. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148480. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148481. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148482. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148483. 11,
  148484. };
  148485. static float _vq_quantthresh__44u3__p7_2[] = {
  148486. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148487. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148488. };
  148489. static long _vq_quantmap__44u3__p7_2[] = {
  148490. 15, 13, 11, 9, 7, 5, 3, 1,
  148491. 0, 2, 4, 6, 8, 10, 12, 14,
  148492. 16,
  148493. };
  148494. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148495. _vq_quantthresh__44u3__p7_2,
  148496. _vq_quantmap__44u3__p7_2,
  148497. 17,
  148498. 17
  148499. };
  148500. static static_codebook _44u3__p7_2 = {
  148501. 2, 289,
  148502. _vq_lengthlist__44u3__p7_2,
  148503. 1, -529530880, 1611661312, 5, 0,
  148504. _vq_quantlist__44u3__p7_2,
  148505. NULL,
  148506. &_vq_auxt__44u3__p7_2,
  148507. NULL,
  148508. 0
  148509. };
  148510. static long _huff_lengthlist__44u3__short[] = {
  148511. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148512. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148513. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148514. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148515. };
  148516. static static_codebook _huff_book__44u3__short = {
  148517. 2, 64,
  148518. _huff_lengthlist__44u3__short,
  148519. 0, 0, 0, 0, 0,
  148520. NULL,
  148521. NULL,
  148522. NULL,
  148523. NULL,
  148524. 0
  148525. };
  148526. static long _huff_lengthlist__44u4__long[] = {
  148527. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148528. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148529. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148530. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148531. };
  148532. static static_codebook _huff_book__44u4__long = {
  148533. 2, 64,
  148534. _huff_lengthlist__44u4__long,
  148535. 0, 0, 0, 0, 0,
  148536. NULL,
  148537. NULL,
  148538. NULL,
  148539. NULL,
  148540. 0
  148541. };
  148542. static long _vq_quantlist__44u4__p1_0[] = {
  148543. 1,
  148544. 0,
  148545. 2,
  148546. };
  148547. static long _vq_lengthlist__44u4__p1_0[] = {
  148548. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148549. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148550. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148551. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148552. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148553. 13,
  148554. };
  148555. static float _vq_quantthresh__44u4__p1_0[] = {
  148556. -0.5, 0.5,
  148557. };
  148558. static long _vq_quantmap__44u4__p1_0[] = {
  148559. 1, 0, 2,
  148560. };
  148561. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148562. _vq_quantthresh__44u4__p1_0,
  148563. _vq_quantmap__44u4__p1_0,
  148564. 3,
  148565. 3
  148566. };
  148567. static static_codebook _44u4__p1_0 = {
  148568. 4, 81,
  148569. _vq_lengthlist__44u4__p1_0,
  148570. 1, -535822336, 1611661312, 2, 0,
  148571. _vq_quantlist__44u4__p1_0,
  148572. NULL,
  148573. &_vq_auxt__44u4__p1_0,
  148574. NULL,
  148575. 0
  148576. };
  148577. static long _vq_quantlist__44u4__p2_0[] = {
  148578. 1,
  148579. 0,
  148580. 2,
  148581. };
  148582. static long _vq_lengthlist__44u4__p2_0[] = {
  148583. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148584. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148585. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148586. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148587. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148588. 9,
  148589. };
  148590. static float _vq_quantthresh__44u4__p2_0[] = {
  148591. -0.5, 0.5,
  148592. };
  148593. static long _vq_quantmap__44u4__p2_0[] = {
  148594. 1, 0, 2,
  148595. };
  148596. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148597. _vq_quantthresh__44u4__p2_0,
  148598. _vq_quantmap__44u4__p2_0,
  148599. 3,
  148600. 3
  148601. };
  148602. static static_codebook _44u4__p2_0 = {
  148603. 4, 81,
  148604. _vq_lengthlist__44u4__p2_0,
  148605. 1, -535822336, 1611661312, 2, 0,
  148606. _vq_quantlist__44u4__p2_0,
  148607. NULL,
  148608. &_vq_auxt__44u4__p2_0,
  148609. NULL,
  148610. 0
  148611. };
  148612. static long _vq_quantlist__44u4__p3_0[] = {
  148613. 2,
  148614. 1,
  148615. 3,
  148616. 0,
  148617. 4,
  148618. };
  148619. static long _vq_lengthlist__44u4__p3_0[] = {
  148620. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148621. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148622. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148623. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148624. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148625. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148626. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148627. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148628. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148629. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148630. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148631. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148632. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148633. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148634. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148635. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148636. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148637. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148638. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148639. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148640. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148641. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148642. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148643. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148644. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148645. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148646. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148647. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148648. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148649. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148650. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148651. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148652. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148653. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148654. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148655. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148656. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148657. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148658. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148659. 0,
  148660. };
  148661. static float _vq_quantthresh__44u4__p3_0[] = {
  148662. -1.5, -0.5, 0.5, 1.5,
  148663. };
  148664. static long _vq_quantmap__44u4__p3_0[] = {
  148665. 3, 1, 0, 2, 4,
  148666. };
  148667. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148668. _vq_quantthresh__44u4__p3_0,
  148669. _vq_quantmap__44u4__p3_0,
  148670. 5,
  148671. 5
  148672. };
  148673. static static_codebook _44u4__p3_0 = {
  148674. 4, 625,
  148675. _vq_lengthlist__44u4__p3_0,
  148676. 1, -533725184, 1611661312, 3, 0,
  148677. _vq_quantlist__44u4__p3_0,
  148678. NULL,
  148679. &_vq_auxt__44u4__p3_0,
  148680. NULL,
  148681. 0
  148682. };
  148683. static long _vq_quantlist__44u4__p4_0[] = {
  148684. 2,
  148685. 1,
  148686. 3,
  148687. 0,
  148688. 4,
  148689. };
  148690. static long _vq_lengthlist__44u4__p4_0[] = {
  148691. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148692. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148693. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148694. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148695. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148696. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148697. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148698. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148699. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148700. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148701. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148702. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148703. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148704. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148705. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148706. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148707. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148708. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148709. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148710. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148711. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148712. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148713. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148714. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148715. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148716. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148717. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148718. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148719. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148720. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148721. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148722. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148723. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148724. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148725. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148726. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148727. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148728. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148729. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148730. 13,
  148731. };
  148732. static float _vq_quantthresh__44u4__p4_0[] = {
  148733. -1.5, -0.5, 0.5, 1.5,
  148734. };
  148735. static long _vq_quantmap__44u4__p4_0[] = {
  148736. 3, 1, 0, 2, 4,
  148737. };
  148738. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148739. _vq_quantthresh__44u4__p4_0,
  148740. _vq_quantmap__44u4__p4_0,
  148741. 5,
  148742. 5
  148743. };
  148744. static static_codebook _44u4__p4_0 = {
  148745. 4, 625,
  148746. _vq_lengthlist__44u4__p4_0,
  148747. 1, -533725184, 1611661312, 3, 0,
  148748. _vq_quantlist__44u4__p4_0,
  148749. NULL,
  148750. &_vq_auxt__44u4__p4_0,
  148751. NULL,
  148752. 0
  148753. };
  148754. static long _vq_quantlist__44u4__p5_0[] = {
  148755. 4,
  148756. 3,
  148757. 5,
  148758. 2,
  148759. 6,
  148760. 1,
  148761. 7,
  148762. 0,
  148763. 8,
  148764. };
  148765. static long _vq_lengthlist__44u4__p5_0[] = {
  148766. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148767. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148768. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148769. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148770. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148771. 12,
  148772. };
  148773. static float _vq_quantthresh__44u4__p5_0[] = {
  148774. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148775. };
  148776. static long _vq_quantmap__44u4__p5_0[] = {
  148777. 7, 5, 3, 1, 0, 2, 4, 6,
  148778. 8,
  148779. };
  148780. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148781. _vq_quantthresh__44u4__p5_0,
  148782. _vq_quantmap__44u4__p5_0,
  148783. 9,
  148784. 9
  148785. };
  148786. static static_codebook _44u4__p5_0 = {
  148787. 2, 81,
  148788. _vq_lengthlist__44u4__p5_0,
  148789. 1, -531628032, 1611661312, 4, 0,
  148790. _vq_quantlist__44u4__p5_0,
  148791. NULL,
  148792. &_vq_auxt__44u4__p5_0,
  148793. NULL,
  148794. 0
  148795. };
  148796. static long _vq_quantlist__44u4__p6_0[] = {
  148797. 6,
  148798. 5,
  148799. 7,
  148800. 4,
  148801. 8,
  148802. 3,
  148803. 9,
  148804. 2,
  148805. 10,
  148806. 1,
  148807. 11,
  148808. 0,
  148809. 12,
  148810. };
  148811. static long _vq_lengthlist__44u4__p6_0[] = {
  148812. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148813. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148814. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148815. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148816. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148817. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148818. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148819. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148820. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148821. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148822. 16,16,16,17,17,18,17,20,21,
  148823. };
  148824. static float _vq_quantthresh__44u4__p6_0[] = {
  148825. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148826. 12.5, 17.5, 22.5, 27.5,
  148827. };
  148828. static long _vq_quantmap__44u4__p6_0[] = {
  148829. 11, 9, 7, 5, 3, 1, 0, 2,
  148830. 4, 6, 8, 10, 12,
  148831. };
  148832. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148833. _vq_quantthresh__44u4__p6_0,
  148834. _vq_quantmap__44u4__p6_0,
  148835. 13,
  148836. 13
  148837. };
  148838. static static_codebook _44u4__p6_0 = {
  148839. 2, 169,
  148840. _vq_lengthlist__44u4__p6_0,
  148841. 1, -526516224, 1616117760, 4, 0,
  148842. _vq_quantlist__44u4__p6_0,
  148843. NULL,
  148844. &_vq_auxt__44u4__p6_0,
  148845. NULL,
  148846. 0
  148847. };
  148848. static long _vq_quantlist__44u4__p6_1[] = {
  148849. 2,
  148850. 1,
  148851. 3,
  148852. 0,
  148853. 4,
  148854. };
  148855. static long _vq_lengthlist__44u4__p6_1[] = {
  148856. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148857. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148858. };
  148859. static float _vq_quantthresh__44u4__p6_1[] = {
  148860. -1.5, -0.5, 0.5, 1.5,
  148861. };
  148862. static long _vq_quantmap__44u4__p6_1[] = {
  148863. 3, 1, 0, 2, 4,
  148864. };
  148865. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148866. _vq_quantthresh__44u4__p6_1,
  148867. _vq_quantmap__44u4__p6_1,
  148868. 5,
  148869. 5
  148870. };
  148871. static static_codebook _44u4__p6_1 = {
  148872. 2, 25,
  148873. _vq_lengthlist__44u4__p6_1,
  148874. 1, -533725184, 1611661312, 3, 0,
  148875. _vq_quantlist__44u4__p6_1,
  148876. NULL,
  148877. &_vq_auxt__44u4__p6_1,
  148878. NULL,
  148879. 0
  148880. };
  148881. static long _vq_quantlist__44u4__p7_0[] = {
  148882. 6,
  148883. 5,
  148884. 7,
  148885. 4,
  148886. 8,
  148887. 3,
  148888. 9,
  148889. 2,
  148890. 10,
  148891. 1,
  148892. 11,
  148893. 0,
  148894. 12,
  148895. };
  148896. static long _vq_lengthlist__44u4__p7_0[] = {
  148897. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148898. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148899. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148900. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148901. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148902. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148905. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148906. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148907. 11,11,11,11,11,11,11,11,11,
  148908. };
  148909. static float _vq_quantthresh__44u4__p7_0[] = {
  148910. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148911. 637.5, 892.5, 1147.5, 1402.5,
  148912. };
  148913. static long _vq_quantmap__44u4__p7_0[] = {
  148914. 11, 9, 7, 5, 3, 1, 0, 2,
  148915. 4, 6, 8, 10, 12,
  148916. };
  148917. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148918. _vq_quantthresh__44u4__p7_0,
  148919. _vq_quantmap__44u4__p7_0,
  148920. 13,
  148921. 13
  148922. };
  148923. static static_codebook _44u4__p7_0 = {
  148924. 2, 169,
  148925. _vq_lengthlist__44u4__p7_0,
  148926. 1, -514332672, 1627381760, 4, 0,
  148927. _vq_quantlist__44u4__p7_0,
  148928. NULL,
  148929. &_vq_auxt__44u4__p7_0,
  148930. NULL,
  148931. 0
  148932. };
  148933. static long _vq_quantlist__44u4__p7_1[] = {
  148934. 7,
  148935. 6,
  148936. 8,
  148937. 5,
  148938. 9,
  148939. 4,
  148940. 10,
  148941. 3,
  148942. 11,
  148943. 2,
  148944. 12,
  148945. 1,
  148946. 13,
  148947. 0,
  148948. 14,
  148949. };
  148950. static long _vq_lengthlist__44u4__p7_1[] = {
  148951. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148952. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148953. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148954. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148955. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148956. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148957. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148958. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148959. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148960. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148961. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148962. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148963. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148964. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148965. 16,
  148966. };
  148967. static float _vq_quantthresh__44u4__p7_1[] = {
  148968. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148969. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148970. };
  148971. static long _vq_quantmap__44u4__p7_1[] = {
  148972. 13, 11, 9, 7, 5, 3, 1, 0,
  148973. 2, 4, 6, 8, 10, 12, 14,
  148974. };
  148975. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148976. _vq_quantthresh__44u4__p7_1,
  148977. _vq_quantmap__44u4__p7_1,
  148978. 15,
  148979. 15
  148980. };
  148981. static static_codebook _44u4__p7_1 = {
  148982. 2, 225,
  148983. _vq_lengthlist__44u4__p7_1,
  148984. 1, -522338304, 1620115456, 4, 0,
  148985. _vq_quantlist__44u4__p7_1,
  148986. NULL,
  148987. &_vq_auxt__44u4__p7_1,
  148988. NULL,
  148989. 0
  148990. };
  148991. static long _vq_quantlist__44u4__p7_2[] = {
  148992. 8,
  148993. 7,
  148994. 9,
  148995. 6,
  148996. 10,
  148997. 5,
  148998. 11,
  148999. 4,
  149000. 12,
  149001. 3,
  149002. 13,
  149003. 2,
  149004. 14,
  149005. 1,
  149006. 15,
  149007. 0,
  149008. 16,
  149009. };
  149010. static long _vq_lengthlist__44u4__p7_2[] = {
  149011. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149012. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149013. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149014. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149015. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149016. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149017. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149018. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149019. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149020. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149021. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149022. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149023. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149024. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149026. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149027. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149028. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149029. 10,
  149030. };
  149031. static float _vq_quantthresh__44u4__p7_2[] = {
  149032. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149033. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149034. };
  149035. static long _vq_quantmap__44u4__p7_2[] = {
  149036. 15, 13, 11, 9, 7, 5, 3, 1,
  149037. 0, 2, 4, 6, 8, 10, 12, 14,
  149038. 16,
  149039. };
  149040. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149041. _vq_quantthresh__44u4__p7_2,
  149042. _vq_quantmap__44u4__p7_2,
  149043. 17,
  149044. 17
  149045. };
  149046. static static_codebook _44u4__p7_2 = {
  149047. 2, 289,
  149048. _vq_lengthlist__44u4__p7_2,
  149049. 1, -529530880, 1611661312, 5, 0,
  149050. _vq_quantlist__44u4__p7_2,
  149051. NULL,
  149052. &_vq_auxt__44u4__p7_2,
  149053. NULL,
  149054. 0
  149055. };
  149056. static long _huff_lengthlist__44u4__short[] = {
  149057. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149058. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149059. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149060. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149061. };
  149062. static static_codebook _huff_book__44u4__short = {
  149063. 2, 64,
  149064. _huff_lengthlist__44u4__short,
  149065. 0, 0, 0, 0, 0,
  149066. NULL,
  149067. NULL,
  149068. NULL,
  149069. NULL,
  149070. 0
  149071. };
  149072. static long _huff_lengthlist__44u5__long[] = {
  149073. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149074. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149075. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149076. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149077. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149078. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149079. 14, 8, 7, 8,
  149080. };
  149081. static static_codebook _huff_book__44u5__long = {
  149082. 2, 100,
  149083. _huff_lengthlist__44u5__long,
  149084. 0, 0, 0, 0, 0,
  149085. NULL,
  149086. NULL,
  149087. NULL,
  149088. NULL,
  149089. 0
  149090. };
  149091. static long _vq_quantlist__44u5__p1_0[] = {
  149092. 1,
  149093. 0,
  149094. 2,
  149095. };
  149096. static long _vq_lengthlist__44u5__p1_0[] = {
  149097. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149098. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149099. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149100. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149101. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149102. 12,
  149103. };
  149104. static float _vq_quantthresh__44u5__p1_0[] = {
  149105. -0.5, 0.5,
  149106. };
  149107. static long _vq_quantmap__44u5__p1_0[] = {
  149108. 1, 0, 2,
  149109. };
  149110. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149111. _vq_quantthresh__44u5__p1_0,
  149112. _vq_quantmap__44u5__p1_0,
  149113. 3,
  149114. 3
  149115. };
  149116. static static_codebook _44u5__p1_0 = {
  149117. 4, 81,
  149118. _vq_lengthlist__44u5__p1_0,
  149119. 1, -535822336, 1611661312, 2, 0,
  149120. _vq_quantlist__44u5__p1_0,
  149121. NULL,
  149122. &_vq_auxt__44u5__p1_0,
  149123. NULL,
  149124. 0
  149125. };
  149126. static long _vq_quantlist__44u5__p2_0[] = {
  149127. 1,
  149128. 0,
  149129. 2,
  149130. };
  149131. static long _vq_lengthlist__44u5__p2_0[] = {
  149132. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149133. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149134. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149135. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149136. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149137. 9,
  149138. };
  149139. static float _vq_quantthresh__44u5__p2_0[] = {
  149140. -0.5, 0.5,
  149141. };
  149142. static long _vq_quantmap__44u5__p2_0[] = {
  149143. 1, 0, 2,
  149144. };
  149145. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149146. _vq_quantthresh__44u5__p2_0,
  149147. _vq_quantmap__44u5__p2_0,
  149148. 3,
  149149. 3
  149150. };
  149151. static static_codebook _44u5__p2_0 = {
  149152. 4, 81,
  149153. _vq_lengthlist__44u5__p2_0,
  149154. 1, -535822336, 1611661312, 2, 0,
  149155. _vq_quantlist__44u5__p2_0,
  149156. NULL,
  149157. &_vq_auxt__44u5__p2_0,
  149158. NULL,
  149159. 0
  149160. };
  149161. static long _vq_quantlist__44u5__p3_0[] = {
  149162. 2,
  149163. 1,
  149164. 3,
  149165. 0,
  149166. 4,
  149167. };
  149168. static long _vq_lengthlist__44u5__p3_0[] = {
  149169. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149170. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149171. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149172. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149173. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149174. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149175. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149176. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149177. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149178. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149179. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149180. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149181. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149182. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149183. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149184. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149185. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149186. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149187. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149188. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149189. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149190. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149191. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149192. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149193. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149194. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149195. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149196. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149197. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149198. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149199. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149200. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149201. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149202. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149203. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149204. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149205. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149206. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149207. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149208. 0,
  149209. };
  149210. static float _vq_quantthresh__44u5__p3_0[] = {
  149211. -1.5, -0.5, 0.5, 1.5,
  149212. };
  149213. static long _vq_quantmap__44u5__p3_0[] = {
  149214. 3, 1, 0, 2, 4,
  149215. };
  149216. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149217. _vq_quantthresh__44u5__p3_0,
  149218. _vq_quantmap__44u5__p3_0,
  149219. 5,
  149220. 5
  149221. };
  149222. static static_codebook _44u5__p3_0 = {
  149223. 4, 625,
  149224. _vq_lengthlist__44u5__p3_0,
  149225. 1, -533725184, 1611661312, 3, 0,
  149226. _vq_quantlist__44u5__p3_0,
  149227. NULL,
  149228. &_vq_auxt__44u5__p3_0,
  149229. NULL,
  149230. 0
  149231. };
  149232. static long _vq_quantlist__44u5__p4_0[] = {
  149233. 2,
  149234. 1,
  149235. 3,
  149236. 0,
  149237. 4,
  149238. };
  149239. static long _vq_lengthlist__44u5__p4_0[] = {
  149240. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149241. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149242. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149243. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149244. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149245. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149246. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149247. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149248. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149249. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149250. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149251. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149252. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149253. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149254. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149255. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149256. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149257. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149258. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149259. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149260. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149261. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149262. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149263. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149264. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149265. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149266. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149267. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149268. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149269. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149270. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149271. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149272. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149273. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149274. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149275. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149276. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149277. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149278. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149279. 12,
  149280. };
  149281. static float _vq_quantthresh__44u5__p4_0[] = {
  149282. -1.5, -0.5, 0.5, 1.5,
  149283. };
  149284. static long _vq_quantmap__44u5__p4_0[] = {
  149285. 3, 1, 0, 2, 4,
  149286. };
  149287. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149288. _vq_quantthresh__44u5__p4_0,
  149289. _vq_quantmap__44u5__p4_0,
  149290. 5,
  149291. 5
  149292. };
  149293. static static_codebook _44u5__p4_0 = {
  149294. 4, 625,
  149295. _vq_lengthlist__44u5__p4_0,
  149296. 1, -533725184, 1611661312, 3, 0,
  149297. _vq_quantlist__44u5__p4_0,
  149298. NULL,
  149299. &_vq_auxt__44u5__p4_0,
  149300. NULL,
  149301. 0
  149302. };
  149303. static long _vq_quantlist__44u5__p5_0[] = {
  149304. 4,
  149305. 3,
  149306. 5,
  149307. 2,
  149308. 6,
  149309. 1,
  149310. 7,
  149311. 0,
  149312. 8,
  149313. };
  149314. static long _vq_lengthlist__44u5__p5_0[] = {
  149315. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149316. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149317. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149318. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149319. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149320. 14,
  149321. };
  149322. static float _vq_quantthresh__44u5__p5_0[] = {
  149323. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149324. };
  149325. static long _vq_quantmap__44u5__p5_0[] = {
  149326. 7, 5, 3, 1, 0, 2, 4, 6,
  149327. 8,
  149328. };
  149329. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149330. _vq_quantthresh__44u5__p5_0,
  149331. _vq_quantmap__44u5__p5_0,
  149332. 9,
  149333. 9
  149334. };
  149335. static static_codebook _44u5__p5_0 = {
  149336. 2, 81,
  149337. _vq_lengthlist__44u5__p5_0,
  149338. 1, -531628032, 1611661312, 4, 0,
  149339. _vq_quantlist__44u5__p5_0,
  149340. NULL,
  149341. &_vq_auxt__44u5__p5_0,
  149342. NULL,
  149343. 0
  149344. };
  149345. static long _vq_quantlist__44u5__p6_0[] = {
  149346. 4,
  149347. 3,
  149348. 5,
  149349. 2,
  149350. 6,
  149351. 1,
  149352. 7,
  149353. 0,
  149354. 8,
  149355. };
  149356. static long _vq_lengthlist__44u5__p6_0[] = {
  149357. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149358. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149359. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149360. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149361. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149362. 11,
  149363. };
  149364. static float _vq_quantthresh__44u5__p6_0[] = {
  149365. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149366. };
  149367. static long _vq_quantmap__44u5__p6_0[] = {
  149368. 7, 5, 3, 1, 0, 2, 4, 6,
  149369. 8,
  149370. };
  149371. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149372. _vq_quantthresh__44u5__p6_0,
  149373. _vq_quantmap__44u5__p6_0,
  149374. 9,
  149375. 9
  149376. };
  149377. static static_codebook _44u5__p6_0 = {
  149378. 2, 81,
  149379. _vq_lengthlist__44u5__p6_0,
  149380. 1, -531628032, 1611661312, 4, 0,
  149381. _vq_quantlist__44u5__p6_0,
  149382. NULL,
  149383. &_vq_auxt__44u5__p6_0,
  149384. NULL,
  149385. 0
  149386. };
  149387. static long _vq_quantlist__44u5__p7_0[] = {
  149388. 1,
  149389. 0,
  149390. 2,
  149391. };
  149392. static long _vq_lengthlist__44u5__p7_0[] = {
  149393. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149394. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149395. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149396. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149397. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149398. 12,
  149399. };
  149400. static float _vq_quantthresh__44u5__p7_0[] = {
  149401. -5.5, 5.5,
  149402. };
  149403. static long _vq_quantmap__44u5__p7_0[] = {
  149404. 1, 0, 2,
  149405. };
  149406. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149407. _vq_quantthresh__44u5__p7_0,
  149408. _vq_quantmap__44u5__p7_0,
  149409. 3,
  149410. 3
  149411. };
  149412. static static_codebook _44u5__p7_0 = {
  149413. 4, 81,
  149414. _vq_lengthlist__44u5__p7_0,
  149415. 1, -529137664, 1618345984, 2, 0,
  149416. _vq_quantlist__44u5__p7_0,
  149417. NULL,
  149418. &_vq_auxt__44u5__p7_0,
  149419. NULL,
  149420. 0
  149421. };
  149422. static long _vq_quantlist__44u5__p7_1[] = {
  149423. 5,
  149424. 4,
  149425. 6,
  149426. 3,
  149427. 7,
  149428. 2,
  149429. 8,
  149430. 1,
  149431. 9,
  149432. 0,
  149433. 10,
  149434. };
  149435. static long _vq_lengthlist__44u5__p7_1[] = {
  149436. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149437. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149438. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149439. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149440. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149441. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149442. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149443. 9, 9, 9, 9, 9,10,10,10,10,
  149444. };
  149445. static float _vq_quantthresh__44u5__p7_1[] = {
  149446. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149447. 3.5, 4.5,
  149448. };
  149449. static long _vq_quantmap__44u5__p7_1[] = {
  149450. 9, 7, 5, 3, 1, 0, 2, 4,
  149451. 6, 8, 10,
  149452. };
  149453. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149454. _vq_quantthresh__44u5__p7_1,
  149455. _vq_quantmap__44u5__p7_1,
  149456. 11,
  149457. 11
  149458. };
  149459. static static_codebook _44u5__p7_1 = {
  149460. 2, 121,
  149461. _vq_lengthlist__44u5__p7_1,
  149462. 1, -531365888, 1611661312, 4, 0,
  149463. _vq_quantlist__44u5__p7_1,
  149464. NULL,
  149465. &_vq_auxt__44u5__p7_1,
  149466. NULL,
  149467. 0
  149468. };
  149469. static long _vq_quantlist__44u5__p8_0[] = {
  149470. 5,
  149471. 4,
  149472. 6,
  149473. 3,
  149474. 7,
  149475. 2,
  149476. 8,
  149477. 1,
  149478. 9,
  149479. 0,
  149480. 10,
  149481. };
  149482. static long _vq_lengthlist__44u5__p8_0[] = {
  149483. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149484. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149485. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149486. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149487. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149488. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149489. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149490. 12,13,13,14,14,14,14,15,15,
  149491. };
  149492. static float _vq_quantthresh__44u5__p8_0[] = {
  149493. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149494. 38.5, 49.5,
  149495. };
  149496. static long _vq_quantmap__44u5__p8_0[] = {
  149497. 9, 7, 5, 3, 1, 0, 2, 4,
  149498. 6, 8, 10,
  149499. };
  149500. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149501. _vq_quantthresh__44u5__p8_0,
  149502. _vq_quantmap__44u5__p8_0,
  149503. 11,
  149504. 11
  149505. };
  149506. static static_codebook _44u5__p8_0 = {
  149507. 2, 121,
  149508. _vq_lengthlist__44u5__p8_0,
  149509. 1, -524582912, 1618345984, 4, 0,
  149510. _vq_quantlist__44u5__p8_0,
  149511. NULL,
  149512. &_vq_auxt__44u5__p8_0,
  149513. NULL,
  149514. 0
  149515. };
  149516. static long _vq_quantlist__44u5__p8_1[] = {
  149517. 5,
  149518. 4,
  149519. 6,
  149520. 3,
  149521. 7,
  149522. 2,
  149523. 8,
  149524. 1,
  149525. 9,
  149526. 0,
  149527. 10,
  149528. };
  149529. static long _vq_lengthlist__44u5__p8_1[] = {
  149530. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149531. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149532. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149533. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149534. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149535. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149536. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149537. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149538. };
  149539. static float _vq_quantthresh__44u5__p8_1[] = {
  149540. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149541. 3.5, 4.5,
  149542. };
  149543. static long _vq_quantmap__44u5__p8_1[] = {
  149544. 9, 7, 5, 3, 1, 0, 2, 4,
  149545. 6, 8, 10,
  149546. };
  149547. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149548. _vq_quantthresh__44u5__p8_1,
  149549. _vq_quantmap__44u5__p8_1,
  149550. 11,
  149551. 11
  149552. };
  149553. static static_codebook _44u5__p8_1 = {
  149554. 2, 121,
  149555. _vq_lengthlist__44u5__p8_1,
  149556. 1, -531365888, 1611661312, 4, 0,
  149557. _vq_quantlist__44u5__p8_1,
  149558. NULL,
  149559. &_vq_auxt__44u5__p8_1,
  149560. NULL,
  149561. 0
  149562. };
  149563. static long _vq_quantlist__44u5__p9_0[] = {
  149564. 6,
  149565. 5,
  149566. 7,
  149567. 4,
  149568. 8,
  149569. 3,
  149570. 9,
  149571. 2,
  149572. 10,
  149573. 1,
  149574. 11,
  149575. 0,
  149576. 12,
  149577. };
  149578. static long _vq_lengthlist__44u5__p9_0[] = {
  149579. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149580. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149581. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149582. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149583. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149584. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149585. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149586. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149587. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149588. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149589. 12,12,12,12,12,12,12,12,12,
  149590. };
  149591. static float _vq_quantthresh__44u5__p9_0[] = {
  149592. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149593. 637.5, 892.5, 1147.5, 1402.5,
  149594. };
  149595. static long _vq_quantmap__44u5__p9_0[] = {
  149596. 11, 9, 7, 5, 3, 1, 0, 2,
  149597. 4, 6, 8, 10, 12,
  149598. };
  149599. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149600. _vq_quantthresh__44u5__p9_0,
  149601. _vq_quantmap__44u5__p9_0,
  149602. 13,
  149603. 13
  149604. };
  149605. static static_codebook _44u5__p9_0 = {
  149606. 2, 169,
  149607. _vq_lengthlist__44u5__p9_0,
  149608. 1, -514332672, 1627381760, 4, 0,
  149609. _vq_quantlist__44u5__p9_0,
  149610. NULL,
  149611. &_vq_auxt__44u5__p9_0,
  149612. NULL,
  149613. 0
  149614. };
  149615. static long _vq_quantlist__44u5__p9_1[] = {
  149616. 7,
  149617. 6,
  149618. 8,
  149619. 5,
  149620. 9,
  149621. 4,
  149622. 10,
  149623. 3,
  149624. 11,
  149625. 2,
  149626. 12,
  149627. 1,
  149628. 13,
  149629. 0,
  149630. 14,
  149631. };
  149632. static long _vq_lengthlist__44u5__p9_1[] = {
  149633. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149634. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149635. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149636. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149637. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149638. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149639. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149640. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149641. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149642. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149643. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149644. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149645. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149646. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149647. 14,
  149648. };
  149649. static float _vq_quantthresh__44u5__p9_1[] = {
  149650. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149651. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149652. };
  149653. static long _vq_quantmap__44u5__p9_1[] = {
  149654. 13, 11, 9, 7, 5, 3, 1, 0,
  149655. 2, 4, 6, 8, 10, 12, 14,
  149656. };
  149657. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149658. _vq_quantthresh__44u5__p9_1,
  149659. _vq_quantmap__44u5__p9_1,
  149660. 15,
  149661. 15
  149662. };
  149663. static static_codebook _44u5__p9_1 = {
  149664. 2, 225,
  149665. _vq_lengthlist__44u5__p9_1,
  149666. 1, -522338304, 1620115456, 4, 0,
  149667. _vq_quantlist__44u5__p9_1,
  149668. NULL,
  149669. &_vq_auxt__44u5__p9_1,
  149670. NULL,
  149671. 0
  149672. };
  149673. static long _vq_quantlist__44u5__p9_2[] = {
  149674. 8,
  149675. 7,
  149676. 9,
  149677. 6,
  149678. 10,
  149679. 5,
  149680. 11,
  149681. 4,
  149682. 12,
  149683. 3,
  149684. 13,
  149685. 2,
  149686. 14,
  149687. 1,
  149688. 15,
  149689. 0,
  149690. 16,
  149691. };
  149692. static long _vq_lengthlist__44u5__p9_2[] = {
  149693. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149694. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149695. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149696. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149697. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149698. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149699. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149700. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149701. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149702. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149703. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149704. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149705. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149706. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149707. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149708. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149709. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149710. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149711. 10,
  149712. };
  149713. static float _vq_quantthresh__44u5__p9_2[] = {
  149714. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149715. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149716. };
  149717. static long _vq_quantmap__44u5__p9_2[] = {
  149718. 15, 13, 11, 9, 7, 5, 3, 1,
  149719. 0, 2, 4, 6, 8, 10, 12, 14,
  149720. 16,
  149721. };
  149722. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149723. _vq_quantthresh__44u5__p9_2,
  149724. _vq_quantmap__44u5__p9_2,
  149725. 17,
  149726. 17
  149727. };
  149728. static static_codebook _44u5__p9_2 = {
  149729. 2, 289,
  149730. _vq_lengthlist__44u5__p9_2,
  149731. 1, -529530880, 1611661312, 5, 0,
  149732. _vq_quantlist__44u5__p9_2,
  149733. NULL,
  149734. &_vq_auxt__44u5__p9_2,
  149735. NULL,
  149736. 0
  149737. };
  149738. static long _huff_lengthlist__44u5__short[] = {
  149739. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149740. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149741. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149742. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149743. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149744. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149745. 6, 8,15,17,
  149746. };
  149747. static static_codebook _huff_book__44u5__short = {
  149748. 2, 100,
  149749. _huff_lengthlist__44u5__short,
  149750. 0, 0, 0, 0, 0,
  149751. NULL,
  149752. NULL,
  149753. NULL,
  149754. NULL,
  149755. 0
  149756. };
  149757. static long _huff_lengthlist__44u6__long[] = {
  149758. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149759. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149760. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149761. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149762. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149763. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149764. 13, 8, 7, 7,
  149765. };
  149766. static static_codebook _huff_book__44u6__long = {
  149767. 2, 100,
  149768. _huff_lengthlist__44u6__long,
  149769. 0, 0, 0, 0, 0,
  149770. NULL,
  149771. NULL,
  149772. NULL,
  149773. NULL,
  149774. 0
  149775. };
  149776. static long _vq_quantlist__44u6__p1_0[] = {
  149777. 1,
  149778. 0,
  149779. 2,
  149780. };
  149781. static long _vq_lengthlist__44u6__p1_0[] = {
  149782. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149783. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149784. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149785. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149786. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149787. 12,
  149788. };
  149789. static float _vq_quantthresh__44u6__p1_0[] = {
  149790. -0.5, 0.5,
  149791. };
  149792. static long _vq_quantmap__44u6__p1_0[] = {
  149793. 1, 0, 2,
  149794. };
  149795. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149796. _vq_quantthresh__44u6__p1_0,
  149797. _vq_quantmap__44u6__p1_0,
  149798. 3,
  149799. 3
  149800. };
  149801. static static_codebook _44u6__p1_0 = {
  149802. 4, 81,
  149803. _vq_lengthlist__44u6__p1_0,
  149804. 1, -535822336, 1611661312, 2, 0,
  149805. _vq_quantlist__44u6__p1_0,
  149806. NULL,
  149807. &_vq_auxt__44u6__p1_0,
  149808. NULL,
  149809. 0
  149810. };
  149811. static long _vq_quantlist__44u6__p2_0[] = {
  149812. 1,
  149813. 0,
  149814. 2,
  149815. };
  149816. static long _vq_lengthlist__44u6__p2_0[] = {
  149817. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149818. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149819. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149820. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149821. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149822. 9,
  149823. };
  149824. static float _vq_quantthresh__44u6__p2_0[] = {
  149825. -0.5, 0.5,
  149826. };
  149827. static long _vq_quantmap__44u6__p2_0[] = {
  149828. 1, 0, 2,
  149829. };
  149830. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149831. _vq_quantthresh__44u6__p2_0,
  149832. _vq_quantmap__44u6__p2_0,
  149833. 3,
  149834. 3
  149835. };
  149836. static static_codebook _44u6__p2_0 = {
  149837. 4, 81,
  149838. _vq_lengthlist__44u6__p2_0,
  149839. 1, -535822336, 1611661312, 2, 0,
  149840. _vq_quantlist__44u6__p2_0,
  149841. NULL,
  149842. &_vq_auxt__44u6__p2_0,
  149843. NULL,
  149844. 0
  149845. };
  149846. static long _vq_quantlist__44u6__p3_0[] = {
  149847. 2,
  149848. 1,
  149849. 3,
  149850. 0,
  149851. 4,
  149852. };
  149853. static long _vq_lengthlist__44u6__p3_0[] = {
  149854. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149855. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149856. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149857. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149858. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149859. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149860. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149861. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149862. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149863. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149864. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149865. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149866. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149867. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149868. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149869. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149870. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149871. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149872. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149873. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149874. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149875. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149876. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149877. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149878. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149879. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149880. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149881. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149882. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149883. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149884. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149885. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149886. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149887. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149888. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149889. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149890. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149891. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149892. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149893. 19,
  149894. };
  149895. static float _vq_quantthresh__44u6__p3_0[] = {
  149896. -1.5, -0.5, 0.5, 1.5,
  149897. };
  149898. static long _vq_quantmap__44u6__p3_0[] = {
  149899. 3, 1, 0, 2, 4,
  149900. };
  149901. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149902. _vq_quantthresh__44u6__p3_0,
  149903. _vq_quantmap__44u6__p3_0,
  149904. 5,
  149905. 5
  149906. };
  149907. static static_codebook _44u6__p3_0 = {
  149908. 4, 625,
  149909. _vq_lengthlist__44u6__p3_0,
  149910. 1, -533725184, 1611661312, 3, 0,
  149911. _vq_quantlist__44u6__p3_0,
  149912. NULL,
  149913. &_vq_auxt__44u6__p3_0,
  149914. NULL,
  149915. 0
  149916. };
  149917. static long _vq_quantlist__44u6__p4_0[] = {
  149918. 2,
  149919. 1,
  149920. 3,
  149921. 0,
  149922. 4,
  149923. };
  149924. static long _vq_lengthlist__44u6__p4_0[] = {
  149925. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149926. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149927. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149928. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149929. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149930. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149931. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149932. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149933. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149934. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149935. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149936. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149937. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149938. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149939. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149940. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149941. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149942. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149943. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149944. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149945. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149946. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149947. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149948. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149949. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149950. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149951. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149952. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149953. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149954. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149955. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149956. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149957. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149958. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149959. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149960. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149961. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149962. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149963. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149964. 13,
  149965. };
  149966. static float _vq_quantthresh__44u6__p4_0[] = {
  149967. -1.5, -0.5, 0.5, 1.5,
  149968. };
  149969. static long _vq_quantmap__44u6__p4_0[] = {
  149970. 3, 1, 0, 2, 4,
  149971. };
  149972. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149973. _vq_quantthresh__44u6__p4_0,
  149974. _vq_quantmap__44u6__p4_0,
  149975. 5,
  149976. 5
  149977. };
  149978. static static_codebook _44u6__p4_0 = {
  149979. 4, 625,
  149980. _vq_lengthlist__44u6__p4_0,
  149981. 1, -533725184, 1611661312, 3, 0,
  149982. _vq_quantlist__44u6__p4_0,
  149983. NULL,
  149984. &_vq_auxt__44u6__p4_0,
  149985. NULL,
  149986. 0
  149987. };
  149988. static long _vq_quantlist__44u6__p5_0[] = {
  149989. 4,
  149990. 3,
  149991. 5,
  149992. 2,
  149993. 6,
  149994. 1,
  149995. 7,
  149996. 0,
  149997. 8,
  149998. };
  149999. static long _vq_lengthlist__44u6__p5_0[] = {
  150000. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150001. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  150002. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  150003. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  150004. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150005. 14,
  150006. };
  150007. static float _vq_quantthresh__44u6__p5_0[] = {
  150008. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150009. };
  150010. static long _vq_quantmap__44u6__p5_0[] = {
  150011. 7, 5, 3, 1, 0, 2, 4, 6,
  150012. 8,
  150013. };
  150014. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150015. _vq_quantthresh__44u6__p5_0,
  150016. _vq_quantmap__44u6__p5_0,
  150017. 9,
  150018. 9
  150019. };
  150020. static static_codebook _44u6__p5_0 = {
  150021. 2, 81,
  150022. _vq_lengthlist__44u6__p5_0,
  150023. 1, -531628032, 1611661312, 4, 0,
  150024. _vq_quantlist__44u6__p5_0,
  150025. NULL,
  150026. &_vq_auxt__44u6__p5_0,
  150027. NULL,
  150028. 0
  150029. };
  150030. static long _vq_quantlist__44u6__p6_0[] = {
  150031. 4,
  150032. 3,
  150033. 5,
  150034. 2,
  150035. 6,
  150036. 1,
  150037. 7,
  150038. 0,
  150039. 8,
  150040. };
  150041. static long _vq_lengthlist__44u6__p6_0[] = {
  150042. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150043. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150044. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150045. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150046. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150047. 12,
  150048. };
  150049. static float _vq_quantthresh__44u6__p6_0[] = {
  150050. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150051. };
  150052. static long _vq_quantmap__44u6__p6_0[] = {
  150053. 7, 5, 3, 1, 0, 2, 4, 6,
  150054. 8,
  150055. };
  150056. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150057. _vq_quantthresh__44u6__p6_0,
  150058. _vq_quantmap__44u6__p6_0,
  150059. 9,
  150060. 9
  150061. };
  150062. static static_codebook _44u6__p6_0 = {
  150063. 2, 81,
  150064. _vq_lengthlist__44u6__p6_0,
  150065. 1, -531628032, 1611661312, 4, 0,
  150066. _vq_quantlist__44u6__p6_0,
  150067. NULL,
  150068. &_vq_auxt__44u6__p6_0,
  150069. NULL,
  150070. 0
  150071. };
  150072. static long _vq_quantlist__44u6__p7_0[] = {
  150073. 1,
  150074. 0,
  150075. 2,
  150076. };
  150077. static long _vq_lengthlist__44u6__p7_0[] = {
  150078. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150079. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150080. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150081. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150082. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150083. 10,
  150084. };
  150085. static float _vq_quantthresh__44u6__p7_0[] = {
  150086. -5.5, 5.5,
  150087. };
  150088. static long _vq_quantmap__44u6__p7_0[] = {
  150089. 1, 0, 2,
  150090. };
  150091. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150092. _vq_quantthresh__44u6__p7_0,
  150093. _vq_quantmap__44u6__p7_0,
  150094. 3,
  150095. 3
  150096. };
  150097. static static_codebook _44u6__p7_0 = {
  150098. 4, 81,
  150099. _vq_lengthlist__44u6__p7_0,
  150100. 1, -529137664, 1618345984, 2, 0,
  150101. _vq_quantlist__44u6__p7_0,
  150102. NULL,
  150103. &_vq_auxt__44u6__p7_0,
  150104. NULL,
  150105. 0
  150106. };
  150107. static long _vq_quantlist__44u6__p7_1[] = {
  150108. 5,
  150109. 4,
  150110. 6,
  150111. 3,
  150112. 7,
  150113. 2,
  150114. 8,
  150115. 1,
  150116. 9,
  150117. 0,
  150118. 10,
  150119. };
  150120. static long _vq_lengthlist__44u6__p7_1[] = {
  150121. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150122. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150123. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150124. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150125. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150126. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150127. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150128. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150129. };
  150130. static float _vq_quantthresh__44u6__p7_1[] = {
  150131. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150132. 3.5, 4.5,
  150133. };
  150134. static long _vq_quantmap__44u6__p7_1[] = {
  150135. 9, 7, 5, 3, 1, 0, 2, 4,
  150136. 6, 8, 10,
  150137. };
  150138. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150139. _vq_quantthresh__44u6__p7_1,
  150140. _vq_quantmap__44u6__p7_1,
  150141. 11,
  150142. 11
  150143. };
  150144. static static_codebook _44u6__p7_1 = {
  150145. 2, 121,
  150146. _vq_lengthlist__44u6__p7_1,
  150147. 1, -531365888, 1611661312, 4, 0,
  150148. _vq_quantlist__44u6__p7_1,
  150149. NULL,
  150150. &_vq_auxt__44u6__p7_1,
  150151. NULL,
  150152. 0
  150153. };
  150154. static long _vq_quantlist__44u6__p8_0[] = {
  150155. 5,
  150156. 4,
  150157. 6,
  150158. 3,
  150159. 7,
  150160. 2,
  150161. 8,
  150162. 1,
  150163. 9,
  150164. 0,
  150165. 10,
  150166. };
  150167. static long _vq_lengthlist__44u6__p8_0[] = {
  150168. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150169. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150170. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150171. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150172. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150173. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150174. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150175. 12,13,13,14,14,14,15,15,15,
  150176. };
  150177. static float _vq_quantthresh__44u6__p8_0[] = {
  150178. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150179. 38.5, 49.5,
  150180. };
  150181. static long _vq_quantmap__44u6__p8_0[] = {
  150182. 9, 7, 5, 3, 1, 0, 2, 4,
  150183. 6, 8, 10,
  150184. };
  150185. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150186. _vq_quantthresh__44u6__p8_0,
  150187. _vq_quantmap__44u6__p8_0,
  150188. 11,
  150189. 11
  150190. };
  150191. static static_codebook _44u6__p8_0 = {
  150192. 2, 121,
  150193. _vq_lengthlist__44u6__p8_0,
  150194. 1, -524582912, 1618345984, 4, 0,
  150195. _vq_quantlist__44u6__p8_0,
  150196. NULL,
  150197. &_vq_auxt__44u6__p8_0,
  150198. NULL,
  150199. 0
  150200. };
  150201. static long _vq_quantlist__44u6__p8_1[] = {
  150202. 5,
  150203. 4,
  150204. 6,
  150205. 3,
  150206. 7,
  150207. 2,
  150208. 8,
  150209. 1,
  150210. 9,
  150211. 0,
  150212. 10,
  150213. };
  150214. static long _vq_lengthlist__44u6__p8_1[] = {
  150215. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150216. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150217. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150218. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150219. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150220. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150221. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150222. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150223. };
  150224. static float _vq_quantthresh__44u6__p8_1[] = {
  150225. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150226. 3.5, 4.5,
  150227. };
  150228. static long _vq_quantmap__44u6__p8_1[] = {
  150229. 9, 7, 5, 3, 1, 0, 2, 4,
  150230. 6, 8, 10,
  150231. };
  150232. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150233. _vq_quantthresh__44u6__p8_1,
  150234. _vq_quantmap__44u6__p8_1,
  150235. 11,
  150236. 11
  150237. };
  150238. static static_codebook _44u6__p8_1 = {
  150239. 2, 121,
  150240. _vq_lengthlist__44u6__p8_1,
  150241. 1, -531365888, 1611661312, 4, 0,
  150242. _vq_quantlist__44u6__p8_1,
  150243. NULL,
  150244. &_vq_auxt__44u6__p8_1,
  150245. NULL,
  150246. 0
  150247. };
  150248. static long _vq_quantlist__44u6__p9_0[] = {
  150249. 7,
  150250. 6,
  150251. 8,
  150252. 5,
  150253. 9,
  150254. 4,
  150255. 10,
  150256. 3,
  150257. 11,
  150258. 2,
  150259. 12,
  150260. 1,
  150261. 13,
  150262. 0,
  150263. 14,
  150264. };
  150265. static long _vq_lengthlist__44u6__p9_0[] = {
  150266. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150267. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150268. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150269. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150270. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150271. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150272. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150273. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150274. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150275. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150276. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150277. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150278. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150279. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150280. 14,
  150281. };
  150282. static float _vq_quantthresh__44u6__p9_0[] = {
  150283. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150284. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150285. };
  150286. static long _vq_quantmap__44u6__p9_0[] = {
  150287. 13, 11, 9, 7, 5, 3, 1, 0,
  150288. 2, 4, 6, 8, 10, 12, 14,
  150289. };
  150290. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150291. _vq_quantthresh__44u6__p9_0,
  150292. _vq_quantmap__44u6__p9_0,
  150293. 15,
  150294. 15
  150295. };
  150296. static static_codebook _44u6__p9_0 = {
  150297. 2, 225,
  150298. _vq_lengthlist__44u6__p9_0,
  150299. 1, -514071552, 1627381760, 4, 0,
  150300. _vq_quantlist__44u6__p9_0,
  150301. NULL,
  150302. &_vq_auxt__44u6__p9_0,
  150303. NULL,
  150304. 0
  150305. };
  150306. static long _vq_quantlist__44u6__p9_1[] = {
  150307. 7,
  150308. 6,
  150309. 8,
  150310. 5,
  150311. 9,
  150312. 4,
  150313. 10,
  150314. 3,
  150315. 11,
  150316. 2,
  150317. 12,
  150318. 1,
  150319. 13,
  150320. 0,
  150321. 14,
  150322. };
  150323. static long _vq_lengthlist__44u6__p9_1[] = {
  150324. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150325. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150326. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150327. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150328. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150329. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150330. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150331. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150332. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150333. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150334. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150335. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150336. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150337. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150338. 13,
  150339. };
  150340. static float _vq_quantthresh__44u6__p9_1[] = {
  150341. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150342. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150343. };
  150344. static long _vq_quantmap__44u6__p9_1[] = {
  150345. 13, 11, 9, 7, 5, 3, 1, 0,
  150346. 2, 4, 6, 8, 10, 12, 14,
  150347. };
  150348. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150349. _vq_quantthresh__44u6__p9_1,
  150350. _vq_quantmap__44u6__p9_1,
  150351. 15,
  150352. 15
  150353. };
  150354. static static_codebook _44u6__p9_1 = {
  150355. 2, 225,
  150356. _vq_lengthlist__44u6__p9_1,
  150357. 1, -522338304, 1620115456, 4, 0,
  150358. _vq_quantlist__44u6__p9_1,
  150359. NULL,
  150360. &_vq_auxt__44u6__p9_1,
  150361. NULL,
  150362. 0
  150363. };
  150364. static long _vq_quantlist__44u6__p9_2[] = {
  150365. 8,
  150366. 7,
  150367. 9,
  150368. 6,
  150369. 10,
  150370. 5,
  150371. 11,
  150372. 4,
  150373. 12,
  150374. 3,
  150375. 13,
  150376. 2,
  150377. 14,
  150378. 1,
  150379. 15,
  150380. 0,
  150381. 16,
  150382. };
  150383. static long _vq_lengthlist__44u6__p9_2[] = {
  150384. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150385. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150386. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150387. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150388. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150389. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150390. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150391. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150392. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150393. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150394. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150395. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150396. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150397. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150398. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150399. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150400. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150401. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150402. 10,
  150403. };
  150404. static float _vq_quantthresh__44u6__p9_2[] = {
  150405. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150406. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150407. };
  150408. static long _vq_quantmap__44u6__p9_2[] = {
  150409. 15, 13, 11, 9, 7, 5, 3, 1,
  150410. 0, 2, 4, 6, 8, 10, 12, 14,
  150411. 16,
  150412. };
  150413. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150414. _vq_quantthresh__44u6__p9_2,
  150415. _vq_quantmap__44u6__p9_2,
  150416. 17,
  150417. 17
  150418. };
  150419. static static_codebook _44u6__p9_2 = {
  150420. 2, 289,
  150421. _vq_lengthlist__44u6__p9_2,
  150422. 1, -529530880, 1611661312, 5, 0,
  150423. _vq_quantlist__44u6__p9_2,
  150424. NULL,
  150425. &_vq_auxt__44u6__p9_2,
  150426. NULL,
  150427. 0
  150428. };
  150429. static long _huff_lengthlist__44u6__short[] = {
  150430. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150431. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150432. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150433. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150434. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150435. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150436. 7, 6, 9,16,
  150437. };
  150438. static static_codebook _huff_book__44u6__short = {
  150439. 2, 100,
  150440. _huff_lengthlist__44u6__short,
  150441. 0, 0, 0, 0, 0,
  150442. NULL,
  150443. NULL,
  150444. NULL,
  150445. NULL,
  150446. 0
  150447. };
  150448. static long _huff_lengthlist__44u7__long[] = {
  150449. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150450. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150451. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150452. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150453. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150454. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150455. 12, 8, 6, 7,
  150456. };
  150457. static static_codebook _huff_book__44u7__long = {
  150458. 2, 100,
  150459. _huff_lengthlist__44u7__long,
  150460. 0, 0, 0, 0, 0,
  150461. NULL,
  150462. NULL,
  150463. NULL,
  150464. NULL,
  150465. 0
  150466. };
  150467. static long _vq_quantlist__44u7__p1_0[] = {
  150468. 1,
  150469. 0,
  150470. 2,
  150471. };
  150472. static long _vq_lengthlist__44u7__p1_0[] = {
  150473. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150474. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150475. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150476. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150477. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150478. 12,
  150479. };
  150480. static float _vq_quantthresh__44u7__p1_0[] = {
  150481. -0.5, 0.5,
  150482. };
  150483. static long _vq_quantmap__44u7__p1_0[] = {
  150484. 1, 0, 2,
  150485. };
  150486. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150487. _vq_quantthresh__44u7__p1_0,
  150488. _vq_quantmap__44u7__p1_0,
  150489. 3,
  150490. 3
  150491. };
  150492. static static_codebook _44u7__p1_0 = {
  150493. 4, 81,
  150494. _vq_lengthlist__44u7__p1_0,
  150495. 1, -535822336, 1611661312, 2, 0,
  150496. _vq_quantlist__44u7__p1_0,
  150497. NULL,
  150498. &_vq_auxt__44u7__p1_0,
  150499. NULL,
  150500. 0
  150501. };
  150502. static long _vq_quantlist__44u7__p2_0[] = {
  150503. 1,
  150504. 0,
  150505. 2,
  150506. };
  150507. static long _vq_lengthlist__44u7__p2_0[] = {
  150508. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150509. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150510. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150511. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150512. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150513. 9,
  150514. };
  150515. static float _vq_quantthresh__44u7__p2_0[] = {
  150516. -0.5, 0.5,
  150517. };
  150518. static long _vq_quantmap__44u7__p2_0[] = {
  150519. 1, 0, 2,
  150520. };
  150521. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150522. _vq_quantthresh__44u7__p2_0,
  150523. _vq_quantmap__44u7__p2_0,
  150524. 3,
  150525. 3
  150526. };
  150527. static static_codebook _44u7__p2_0 = {
  150528. 4, 81,
  150529. _vq_lengthlist__44u7__p2_0,
  150530. 1, -535822336, 1611661312, 2, 0,
  150531. _vq_quantlist__44u7__p2_0,
  150532. NULL,
  150533. &_vq_auxt__44u7__p2_0,
  150534. NULL,
  150535. 0
  150536. };
  150537. static long _vq_quantlist__44u7__p3_0[] = {
  150538. 2,
  150539. 1,
  150540. 3,
  150541. 0,
  150542. 4,
  150543. };
  150544. static long _vq_lengthlist__44u7__p3_0[] = {
  150545. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150546. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150547. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150548. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150549. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150550. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150551. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150552. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150553. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150554. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150555. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150556. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150557. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150558. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150559. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150560. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150561. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150562. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150563. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150564. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150565. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150566. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150567. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150568. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150569. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150570. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150571. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150572. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150573. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150574. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150575. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150576. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150577. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150578. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150579. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150580. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150581. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150582. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150583. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150584. 0,
  150585. };
  150586. static float _vq_quantthresh__44u7__p3_0[] = {
  150587. -1.5, -0.5, 0.5, 1.5,
  150588. };
  150589. static long _vq_quantmap__44u7__p3_0[] = {
  150590. 3, 1, 0, 2, 4,
  150591. };
  150592. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150593. _vq_quantthresh__44u7__p3_0,
  150594. _vq_quantmap__44u7__p3_0,
  150595. 5,
  150596. 5
  150597. };
  150598. static static_codebook _44u7__p3_0 = {
  150599. 4, 625,
  150600. _vq_lengthlist__44u7__p3_0,
  150601. 1, -533725184, 1611661312, 3, 0,
  150602. _vq_quantlist__44u7__p3_0,
  150603. NULL,
  150604. &_vq_auxt__44u7__p3_0,
  150605. NULL,
  150606. 0
  150607. };
  150608. static long _vq_quantlist__44u7__p4_0[] = {
  150609. 2,
  150610. 1,
  150611. 3,
  150612. 0,
  150613. 4,
  150614. };
  150615. static long _vq_lengthlist__44u7__p4_0[] = {
  150616. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150617. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150618. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150619. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150620. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150621. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150622. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150623. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150624. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150625. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150626. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150627. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150628. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150629. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150630. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150631. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150632. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150633. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150634. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150635. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150636. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150637. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150638. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150639. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150640. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150641. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150642. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150643. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150644. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150645. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150646. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150647. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150648. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150649. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150650. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150651. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150652. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150653. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150654. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150655. 14,
  150656. };
  150657. static float _vq_quantthresh__44u7__p4_0[] = {
  150658. -1.5, -0.5, 0.5, 1.5,
  150659. };
  150660. static long _vq_quantmap__44u7__p4_0[] = {
  150661. 3, 1, 0, 2, 4,
  150662. };
  150663. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150664. _vq_quantthresh__44u7__p4_0,
  150665. _vq_quantmap__44u7__p4_0,
  150666. 5,
  150667. 5
  150668. };
  150669. static static_codebook _44u7__p4_0 = {
  150670. 4, 625,
  150671. _vq_lengthlist__44u7__p4_0,
  150672. 1, -533725184, 1611661312, 3, 0,
  150673. _vq_quantlist__44u7__p4_0,
  150674. NULL,
  150675. &_vq_auxt__44u7__p4_0,
  150676. NULL,
  150677. 0
  150678. };
  150679. static long _vq_quantlist__44u7__p5_0[] = {
  150680. 4,
  150681. 3,
  150682. 5,
  150683. 2,
  150684. 6,
  150685. 1,
  150686. 7,
  150687. 0,
  150688. 8,
  150689. };
  150690. static long _vq_lengthlist__44u7__p5_0[] = {
  150691. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150692. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150693. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150694. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150695. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150696. 14,
  150697. };
  150698. static float _vq_quantthresh__44u7__p5_0[] = {
  150699. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150700. };
  150701. static long _vq_quantmap__44u7__p5_0[] = {
  150702. 7, 5, 3, 1, 0, 2, 4, 6,
  150703. 8,
  150704. };
  150705. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150706. _vq_quantthresh__44u7__p5_0,
  150707. _vq_quantmap__44u7__p5_0,
  150708. 9,
  150709. 9
  150710. };
  150711. static static_codebook _44u7__p5_0 = {
  150712. 2, 81,
  150713. _vq_lengthlist__44u7__p5_0,
  150714. 1, -531628032, 1611661312, 4, 0,
  150715. _vq_quantlist__44u7__p5_0,
  150716. NULL,
  150717. &_vq_auxt__44u7__p5_0,
  150718. NULL,
  150719. 0
  150720. };
  150721. static long _vq_quantlist__44u7__p6_0[] = {
  150722. 4,
  150723. 3,
  150724. 5,
  150725. 2,
  150726. 6,
  150727. 1,
  150728. 7,
  150729. 0,
  150730. 8,
  150731. };
  150732. static long _vq_lengthlist__44u7__p6_0[] = {
  150733. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150734. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150735. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150736. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150737. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150738. 12,
  150739. };
  150740. static float _vq_quantthresh__44u7__p6_0[] = {
  150741. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150742. };
  150743. static long _vq_quantmap__44u7__p6_0[] = {
  150744. 7, 5, 3, 1, 0, 2, 4, 6,
  150745. 8,
  150746. };
  150747. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150748. _vq_quantthresh__44u7__p6_0,
  150749. _vq_quantmap__44u7__p6_0,
  150750. 9,
  150751. 9
  150752. };
  150753. static static_codebook _44u7__p6_0 = {
  150754. 2, 81,
  150755. _vq_lengthlist__44u7__p6_0,
  150756. 1, -531628032, 1611661312, 4, 0,
  150757. _vq_quantlist__44u7__p6_0,
  150758. NULL,
  150759. &_vq_auxt__44u7__p6_0,
  150760. NULL,
  150761. 0
  150762. };
  150763. static long _vq_quantlist__44u7__p7_0[] = {
  150764. 1,
  150765. 0,
  150766. 2,
  150767. };
  150768. static long _vq_lengthlist__44u7__p7_0[] = {
  150769. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150770. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150771. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150772. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150773. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150774. 10,
  150775. };
  150776. static float _vq_quantthresh__44u7__p7_0[] = {
  150777. -5.5, 5.5,
  150778. };
  150779. static long _vq_quantmap__44u7__p7_0[] = {
  150780. 1, 0, 2,
  150781. };
  150782. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150783. _vq_quantthresh__44u7__p7_0,
  150784. _vq_quantmap__44u7__p7_0,
  150785. 3,
  150786. 3
  150787. };
  150788. static static_codebook _44u7__p7_0 = {
  150789. 4, 81,
  150790. _vq_lengthlist__44u7__p7_0,
  150791. 1, -529137664, 1618345984, 2, 0,
  150792. _vq_quantlist__44u7__p7_0,
  150793. NULL,
  150794. &_vq_auxt__44u7__p7_0,
  150795. NULL,
  150796. 0
  150797. };
  150798. static long _vq_quantlist__44u7__p7_1[] = {
  150799. 5,
  150800. 4,
  150801. 6,
  150802. 3,
  150803. 7,
  150804. 2,
  150805. 8,
  150806. 1,
  150807. 9,
  150808. 0,
  150809. 10,
  150810. };
  150811. static long _vq_lengthlist__44u7__p7_1[] = {
  150812. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150813. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150814. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150815. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150816. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150817. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150818. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150819. 8, 9, 9, 9, 9, 9,10,10,10,
  150820. };
  150821. static float _vq_quantthresh__44u7__p7_1[] = {
  150822. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150823. 3.5, 4.5,
  150824. };
  150825. static long _vq_quantmap__44u7__p7_1[] = {
  150826. 9, 7, 5, 3, 1, 0, 2, 4,
  150827. 6, 8, 10,
  150828. };
  150829. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150830. _vq_quantthresh__44u7__p7_1,
  150831. _vq_quantmap__44u7__p7_1,
  150832. 11,
  150833. 11
  150834. };
  150835. static static_codebook _44u7__p7_1 = {
  150836. 2, 121,
  150837. _vq_lengthlist__44u7__p7_1,
  150838. 1, -531365888, 1611661312, 4, 0,
  150839. _vq_quantlist__44u7__p7_1,
  150840. NULL,
  150841. &_vq_auxt__44u7__p7_1,
  150842. NULL,
  150843. 0
  150844. };
  150845. static long _vq_quantlist__44u7__p8_0[] = {
  150846. 5,
  150847. 4,
  150848. 6,
  150849. 3,
  150850. 7,
  150851. 2,
  150852. 8,
  150853. 1,
  150854. 9,
  150855. 0,
  150856. 10,
  150857. };
  150858. static long _vq_lengthlist__44u7__p8_0[] = {
  150859. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150860. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150861. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150862. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150863. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150864. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150865. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150866. 12,13,13,14,14,15,15,15,16,
  150867. };
  150868. static float _vq_quantthresh__44u7__p8_0[] = {
  150869. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150870. 38.5, 49.5,
  150871. };
  150872. static long _vq_quantmap__44u7__p8_0[] = {
  150873. 9, 7, 5, 3, 1, 0, 2, 4,
  150874. 6, 8, 10,
  150875. };
  150876. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150877. _vq_quantthresh__44u7__p8_0,
  150878. _vq_quantmap__44u7__p8_0,
  150879. 11,
  150880. 11
  150881. };
  150882. static static_codebook _44u7__p8_0 = {
  150883. 2, 121,
  150884. _vq_lengthlist__44u7__p8_0,
  150885. 1, -524582912, 1618345984, 4, 0,
  150886. _vq_quantlist__44u7__p8_0,
  150887. NULL,
  150888. &_vq_auxt__44u7__p8_0,
  150889. NULL,
  150890. 0
  150891. };
  150892. static long _vq_quantlist__44u7__p8_1[] = {
  150893. 5,
  150894. 4,
  150895. 6,
  150896. 3,
  150897. 7,
  150898. 2,
  150899. 8,
  150900. 1,
  150901. 9,
  150902. 0,
  150903. 10,
  150904. };
  150905. static long _vq_lengthlist__44u7__p8_1[] = {
  150906. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150907. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150908. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150909. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150910. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150911. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150912. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150913. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150914. };
  150915. static float _vq_quantthresh__44u7__p8_1[] = {
  150916. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150917. 3.5, 4.5,
  150918. };
  150919. static long _vq_quantmap__44u7__p8_1[] = {
  150920. 9, 7, 5, 3, 1, 0, 2, 4,
  150921. 6, 8, 10,
  150922. };
  150923. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150924. _vq_quantthresh__44u7__p8_1,
  150925. _vq_quantmap__44u7__p8_1,
  150926. 11,
  150927. 11
  150928. };
  150929. static static_codebook _44u7__p8_1 = {
  150930. 2, 121,
  150931. _vq_lengthlist__44u7__p8_1,
  150932. 1, -531365888, 1611661312, 4, 0,
  150933. _vq_quantlist__44u7__p8_1,
  150934. NULL,
  150935. &_vq_auxt__44u7__p8_1,
  150936. NULL,
  150937. 0
  150938. };
  150939. static long _vq_quantlist__44u7__p9_0[] = {
  150940. 5,
  150941. 4,
  150942. 6,
  150943. 3,
  150944. 7,
  150945. 2,
  150946. 8,
  150947. 1,
  150948. 9,
  150949. 0,
  150950. 10,
  150951. };
  150952. static long _vq_lengthlist__44u7__p9_0[] = {
  150953. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150954. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150955. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150956. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150957. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150958. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150959. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150960. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150961. };
  150962. static float _vq_quantthresh__44u7__p9_0[] = {
  150963. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150964. 2229.5, 2866.5,
  150965. };
  150966. static long _vq_quantmap__44u7__p9_0[] = {
  150967. 9, 7, 5, 3, 1, 0, 2, 4,
  150968. 6, 8, 10,
  150969. };
  150970. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150971. _vq_quantthresh__44u7__p9_0,
  150972. _vq_quantmap__44u7__p9_0,
  150973. 11,
  150974. 11
  150975. };
  150976. static static_codebook _44u7__p9_0 = {
  150977. 2, 121,
  150978. _vq_lengthlist__44u7__p9_0,
  150979. 1, -512171520, 1630791680, 4, 0,
  150980. _vq_quantlist__44u7__p9_0,
  150981. NULL,
  150982. &_vq_auxt__44u7__p9_0,
  150983. NULL,
  150984. 0
  150985. };
  150986. static long _vq_quantlist__44u7__p9_1[] = {
  150987. 6,
  150988. 5,
  150989. 7,
  150990. 4,
  150991. 8,
  150992. 3,
  150993. 9,
  150994. 2,
  150995. 10,
  150996. 1,
  150997. 11,
  150998. 0,
  150999. 12,
  151000. };
  151001. static long _vq_lengthlist__44u7__p9_1[] = {
  151002. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  151003. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  151004. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151005. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151006. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151007. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151008. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151009. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151010. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151011. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151012. 15,15,15,15,17,17,16,17,16,
  151013. };
  151014. static float _vq_quantthresh__44u7__p9_1[] = {
  151015. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151016. 122.5, 171.5, 220.5, 269.5,
  151017. };
  151018. static long _vq_quantmap__44u7__p9_1[] = {
  151019. 11, 9, 7, 5, 3, 1, 0, 2,
  151020. 4, 6, 8, 10, 12,
  151021. };
  151022. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151023. _vq_quantthresh__44u7__p9_1,
  151024. _vq_quantmap__44u7__p9_1,
  151025. 13,
  151026. 13
  151027. };
  151028. static static_codebook _44u7__p9_1 = {
  151029. 2, 169,
  151030. _vq_lengthlist__44u7__p9_1,
  151031. 1, -518889472, 1622704128, 4, 0,
  151032. _vq_quantlist__44u7__p9_1,
  151033. NULL,
  151034. &_vq_auxt__44u7__p9_1,
  151035. NULL,
  151036. 0
  151037. };
  151038. static long _vq_quantlist__44u7__p9_2[] = {
  151039. 24,
  151040. 23,
  151041. 25,
  151042. 22,
  151043. 26,
  151044. 21,
  151045. 27,
  151046. 20,
  151047. 28,
  151048. 19,
  151049. 29,
  151050. 18,
  151051. 30,
  151052. 17,
  151053. 31,
  151054. 16,
  151055. 32,
  151056. 15,
  151057. 33,
  151058. 14,
  151059. 34,
  151060. 13,
  151061. 35,
  151062. 12,
  151063. 36,
  151064. 11,
  151065. 37,
  151066. 10,
  151067. 38,
  151068. 9,
  151069. 39,
  151070. 8,
  151071. 40,
  151072. 7,
  151073. 41,
  151074. 6,
  151075. 42,
  151076. 5,
  151077. 43,
  151078. 4,
  151079. 44,
  151080. 3,
  151081. 45,
  151082. 2,
  151083. 46,
  151084. 1,
  151085. 47,
  151086. 0,
  151087. 48,
  151088. };
  151089. static long _vq_lengthlist__44u7__p9_2[] = {
  151090. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151091. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151092. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151093. 8,
  151094. };
  151095. static float _vq_quantthresh__44u7__p9_2[] = {
  151096. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151097. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151098. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151099. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151100. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151101. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151102. };
  151103. static long _vq_quantmap__44u7__p9_2[] = {
  151104. 47, 45, 43, 41, 39, 37, 35, 33,
  151105. 31, 29, 27, 25, 23, 21, 19, 17,
  151106. 15, 13, 11, 9, 7, 5, 3, 1,
  151107. 0, 2, 4, 6, 8, 10, 12, 14,
  151108. 16, 18, 20, 22, 24, 26, 28, 30,
  151109. 32, 34, 36, 38, 40, 42, 44, 46,
  151110. 48,
  151111. };
  151112. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151113. _vq_quantthresh__44u7__p9_2,
  151114. _vq_quantmap__44u7__p9_2,
  151115. 49,
  151116. 49
  151117. };
  151118. static static_codebook _44u7__p9_2 = {
  151119. 1, 49,
  151120. _vq_lengthlist__44u7__p9_2,
  151121. 1, -526909440, 1611661312, 6, 0,
  151122. _vq_quantlist__44u7__p9_2,
  151123. NULL,
  151124. &_vq_auxt__44u7__p9_2,
  151125. NULL,
  151126. 0
  151127. };
  151128. static long _huff_lengthlist__44u7__short[] = {
  151129. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151130. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151131. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151132. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151133. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151134. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151135. 6, 8, 5, 9,
  151136. };
  151137. static static_codebook _huff_book__44u7__short = {
  151138. 2, 100,
  151139. _huff_lengthlist__44u7__short,
  151140. 0, 0, 0, 0, 0,
  151141. NULL,
  151142. NULL,
  151143. NULL,
  151144. NULL,
  151145. 0
  151146. };
  151147. static long _huff_lengthlist__44u8__long[] = {
  151148. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151149. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151150. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151151. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151152. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151153. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151154. 10, 8, 8, 9,
  151155. };
  151156. static static_codebook _huff_book__44u8__long = {
  151157. 2, 100,
  151158. _huff_lengthlist__44u8__long,
  151159. 0, 0, 0, 0, 0,
  151160. NULL,
  151161. NULL,
  151162. NULL,
  151163. NULL,
  151164. 0
  151165. };
  151166. static long _huff_lengthlist__44u8__short[] = {
  151167. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151168. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151169. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151170. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151171. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151172. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151173. 10,10,15,17,
  151174. };
  151175. static static_codebook _huff_book__44u8__short = {
  151176. 2, 100,
  151177. _huff_lengthlist__44u8__short,
  151178. 0, 0, 0, 0, 0,
  151179. NULL,
  151180. NULL,
  151181. NULL,
  151182. NULL,
  151183. 0
  151184. };
  151185. static long _vq_quantlist__44u8_p1_0[] = {
  151186. 1,
  151187. 0,
  151188. 2,
  151189. };
  151190. static long _vq_lengthlist__44u8_p1_0[] = {
  151191. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151192. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151193. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151194. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151195. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151196. 10,
  151197. };
  151198. static float _vq_quantthresh__44u8_p1_0[] = {
  151199. -0.5, 0.5,
  151200. };
  151201. static long _vq_quantmap__44u8_p1_0[] = {
  151202. 1, 0, 2,
  151203. };
  151204. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151205. _vq_quantthresh__44u8_p1_0,
  151206. _vq_quantmap__44u8_p1_0,
  151207. 3,
  151208. 3
  151209. };
  151210. static static_codebook _44u8_p1_0 = {
  151211. 4, 81,
  151212. _vq_lengthlist__44u8_p1_0,
  151213. 1, -535822336, 1611661312, 2, 0,
  151214. _vq_quantlist__44u8_p1_0,
  151215. NULL,
  151216. &_vq_auxt__44u8_p1_0,
  151217. NULL,
  151218. 0
  151219. };
  151220. static long _vq_quantlist__44u8_p2_0[] = {
  151221. 2,
  151222. 1,
  151223. 3,
  151224. 0,
  151225. 4,
  151226. };
  151227. static long _vq_lengthlist__44u8_p2_0[] = {
  151228. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151229. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151230. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151231. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151232. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151233. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151234. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151235. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151236. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151237. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151238. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151239. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151240. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151241. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151242. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151243. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151244. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151245. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151246. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151247. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151248. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151249. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151250. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151251. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151252. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151253. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151254. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151255. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151256. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151257. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151258. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151259. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151260. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151261. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151262. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151263. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151264. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151265. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151266. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151267. 14,
  151268. };
  151269. static float _vq_quantthresh__44u8_p2_0[] = {
  151270. -1.5, -0.5, 0.5, 1.5,
  151271. };
  151272. static long _vq_quantmap__44u8_p2_0[] = {
  151273. 3, 1, 0, 2, 4,
  151274. };
  151275. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151276. _vq_quantthresh__44u8_p2_0,
  151277. _vq_quantmap__44u8_p2_0,
  151278. 5,
  151279. 5
  151280. };
  151281. static static_codebook _44u8_p2_0 = {
  151282. 4, 625,
  151283. _vq_lengthlist__44u8_p2_0,
  151284. 1, -533725184, 1611661312, 3, 0,
  151285. _vq_quantlist__44u8_p2_0,
  151286. NULL,
  151287. &_vq_auxt__44u8_p2_0,
  151288. NULL,
  151289. 0
  151290. };
  151291. static long _vq_quantlist__44u8_p3_0[] = {
  151292. 4,
  151293. 3,
  151294. 5,
  151295. 2,
  151296. 6,
  151297. 1,
  151298. 7,
  151299. 0,
  151300. 8,
  151301. };
  151302. static long _vq_lengthlist__44u8_p3_0[] = {
  151303. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151304. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151305. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151306. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151307. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151308. 12,
  151309. };
  151310. static float _vq_quantthresh__44u8_p3_0[] = {
  151311. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151312. };
  151313. static long _vq_quantmap__44u8_p3_0[] = {
  151314. 7, 5, 3, 1, 0, 2, 4, 6,
  151315. 8,
  151316. };
  151317. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151318. _vq_quantthresh__44u8_p3_0,
  151319. _vq_quantmap__44u8_p3_0,
  151320. 9,
  151321. 9
  151322. };
  151323. static static_codebook _44u8_p3_0 = {
  151324. 2, 81,
  151325. _vq_lengthlist__44u8_p3_0,
  151326. 1, -531628032, 1611661312, 4, 0,
  151327. _vq_quantlist__44u8_p3_0,
  151328. NULL,
  151329. &_vq_auxt__44u8_p3_0,
  151330. NULL,
  151331. 0
  151332. };
  151333. static long _vq_quantlist__44u8_p4_0[] = {
  151334. 8,
  151335. 7,
  151336. 9,
  151337. 6,
  151338. 10,
  151339. 5,
  151340. 11,
  151341. 4,
  151342. 12,
  151343. 3,
  151344. 13,
  151345. 2,
  151346. 14,
  151347. 1,
  151348. 15,
  151349. 0,
  151350. 16,
  151351. };
  151352. static long _vq_lengthlist__44u8_p4_0[] = {
  151353. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151354. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151355. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151356. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151357. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151358. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151359. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151360. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151361. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151362. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151363. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151364. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151365. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151366. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151367. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151368. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151369. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151370. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151371. 14,
  151372. };
  151373. static float _vq_quantthresh__44u8_p4_0[] = {
  151374. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151375. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151376. };
  151377. static long _vq_quantmap__44u8_p4_0[] = {
  151378. 15, 13, 11, 9, 7, 5, 3, 1,
  151379. 0, 2, 4, 6, 8, 10, 12, 14,
  151380. 16,
  151381. };
  151382. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151383. _vq_quantthresh__44u8_p4_0,
  151384. _vq_quantmap__44u8_p4_0,
  151385. 17,
  151386. 17
  151387. };
  151388. static static_codebook _44u8_p4_0 = {
  151389. 2, 289,
  151390. _vq_lengthlist__44u8_p4_0,
  151391. 1, -529530880, 1611661312, 5, 0,
  151392. _vq_quantlist__44u8_p4_0,
  151393. NULL,
  151394. &_vq_auxt__44u8_p4_0,
  151395. NULL,
  151396. 0
  151397. };
  151398. static long _vq_quantlist__44u8_p5_0[] = {
  151399. 1,
  151400. 0,
  151401. 2,
  151402. };
  151403. static long _vq_lengthlist__44u8_p5_0[] = {
  151404. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151405. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151406. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151407. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151408. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151409. 10,
  151410. };
  151411. static float _vq_quantthresh__44u8_p5_0[] = {
  151412. -5.5, 5.5,
  151413. };
  151414. static long _vq_quantmap__44u8_p5_0[] = {
  151415. 1, 0, 2,
  151416. };
  151417. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151418. _vq_quantthresh__44u8_p5_0,
  151419. _vq_quantmap__44u8_p5_0,
  151420. 3,
  151421. 3
  151422. };
  151423. static static_codebook _44u8_p5_0 = {
  151424. 4, 81,
  151425. _vq_lengthlist__44u8_p5_0,
  151426. 1, -529137664, 1618345984, 2, 0,
  151427. _vq_quantlist__44u8_p5_0,
  151428. NULL,
  151429. &_vq_auxt__44u8_p5_0,
  151430. NULL,
  151431. 0
  151432. };
  151433. static long _vq_quantlist__44u8_p5_1[] = {
  151434. 5,
  151435. 4,
  151436. 6,
  151437. 3,
  151438. 7,
  151439. 2,
  151440. 8,
  151441. 1,
  151442. 9,
  151443. 0,
  151444. 10,
  151445. };
  151446. static long _vq_lengthlist__44u8_p5_1[] = {
  151447. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151448. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151449. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151450. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151451. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151452. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151453. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151454. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151455. };
  151456. static float _vq_quantthresh__44u8_p5_1[] = {
  151457. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151458. 3.5, 4.5,
  151459. };
  151460. static long _vq_quantmap__44u8_p5_1[] = {
  151461. 9, 7, 5, 3, 1, 0, 2, 4,
  151462. 6, 8, 10,
  151463. };
  151464. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151465. _vq_quantthresh__44u8_p5_1,
  151466. _vq_quantmap__44u8_p5_1,
  151467. 11,
  151468. 11
  151469. };
  151470. static static_codebook _44u8_p5_1 = {
  151471. 2, 121,
  151472. _vq_lengthlist__44u8_p5_1,
  151473. 1, -531365888, 1611661312, 4, 0,
  151474. _vq_quantlist__44u8_p5_1,
  151475. NULL,
  151476. &_vq_auxt__44u8_p5_1,
  151477. NULL,
  151478. 0
  151479. };
  151480. static long _vq_quantlist__44u8_p6_0[] = {
  151481. 6,
  151482. 5,
  151483. 7,
  151484. 4,
  151485. 8,
  151486. 3,
  151487. 9,
  151488. 2,
  151489. 10,
  151490. 1,
  151491. 11,
  151492. 0,
  151493. 12,
  151494. };
  151495. static long _vq_lengthlist__44u8_p6_0[] = {
  151496. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151497. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151498. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151499. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151500. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151501. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151502. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151503. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151504. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151505. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151506. 11,11,11,11,11,12,11,12,12,
  151507. };
  151508. static float _vq_quantthresh__44u8_p6_0[] = {
  151509. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151510. 12.5, 17.5, 22.5, 27.5,
  151511. };
  151512. static long _vq_quantmap__44u8_p6_0[] = {
  151513. 11, 9, 7, 5, 3, 1, 0, 2,
  151514. 4, 6, 8, 10, 12,
  151515. };
  151516. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151517. _vq_quantthresh__44u8_p6_0,
  151518. _vq_quantmap__44u8_p6_0,
  151519. 13,
  151520. 13
  151521. };
  151522. static static_codebook _44u8_p6_0 = {
  151523. 2, 169,
  151524. _vq_lengthlist__44u8_p6_0,
  151525. 1, -526516224, 1616117760, 4, 0,
  151526. _vq_quantlist__44u8_p6_0,
  151527. NULL,
  151528. &_vq_auxt__44u8_p6_0,
  151529. NULL,
  151530. 0
  151531. };
  151532. static long _vq_quantlist__44u8_p6_1[] = {
  151533. 2,
  151534. 1,
  151535. 3,
  151536. 0,
  151537. 4,
  151538. };
  151539. static long _vq_lengthlist__44u8_p6_1[] = {
  151540. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151541. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151542. };
  151543. static float _vq_quantthresh__44u8_p6_1[] = {
  151544. -1.5, -0.5, 0.5, 1.5,
  151545. };
  151546. static long _vq_quantmap__44u8_p6_1[] = {
  151547. 3, 1, 0, 2, 4,
  151548. };
  151549. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151550. _vq_quantthresh__44u8_p6_1,
  151551. _vq_quantmap__44u8_p6_1,
  151552. 5,
  151553. 5
  151554. };
  151555. static static_codebook _44u8_p6_1 = {
  151556. 2, 25,
  151557. _vq_lengthlist__44u8_p6_1,
  151558. 1, -533725184, 1611661312, 3, 0,
  151559. _vq_quantlist__44u8_p6_1,
  151560. NULL,
  151561. &_vq_auxt__44u8_p6_1,
  151562. NULL,
  151563. 0
  151564. };
  151565. static long _vq_quantlist__44u8_p7_0[] = {
  151566. 6,
  151567. 5,
  151568. 7,
  151569. 4,
  151570. 8,
  151571. 3,
  151572. 9,
  151573. 2,
  151574. 10,
  151575. 1,
  151576. 11,
  151577. 0,
  151578. 12,
  151579. };
  151580. static long _vq_lengthlist__44u8_p7_0[] = {
  151581. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151582. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151583. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151584. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151585. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151586. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151587. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151588. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151589. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151590. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151591. 13,13,14,14,14,15,15,15,16,
  151592. };
  151593. static float _vq_quantthresh__44u8_p7_0[] = {
  151594. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151595. 27.5, 38.5, 49.5, 60.5,
  151596. };
  151597. static long _vq_quantmap__44u8_p7_0[] = {
  151598. 11, 9, 7, 5, 3, 1, 0, 2,
  151599. 4, 6, 8, 10, 12,
  151600. };
  151601. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151602. _vq_quantthresh__44u8_p7_0,
  151603. _vq_quantmap__44u8_p7_0,
  151604. 13,
  151605. 13
  151606. };
  151607. static static_codebook _44u8_p7_0 = {
  151608. 2, 169,
  151609. _vq_lengthlist__44u8_p7_0,
  151610. 1, -523206656, 1618345984, 4, 0,
  151611. _vq_quantlist__44u8_p7_0,
  151612. NULL,
  151613. &_vq_auxt__44u8_p7_0,
  151614. NULL,
  151615. 0
  151616. };
  151617. static long _vq_quantlist__44u8_p7_1[] = {
  151618. 5,
  151619. 4,
  151620. 6,
  151621. 3,
  151622. 7,
  151623. 2,
  151624. 8,
  151625. 1,
  151626. 9,
  151627. 0,
  151628. 10,
  151629. };
  151630. static long _vq_lengthlist__44u8_p7_1[] = {
  151631. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151632. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151633. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151634. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151635. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151636. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151637. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151638. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151639. };
  151640. static float _vq_quantthresh__44u8_p7_1[] = {
  151641. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151642. 3.5, 4.5,
  151643. };
  151644. static long _vq_quantmap__44u8_p7_1[] = {
  151645. 9, 7, 5, 3, 1, 0, 2, 4,
  151646. 6, 8, 10,
  151647. };
  151648. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151649. _vq_quantthresh__44u8_p7_1,
  151650. _vq_quantmap__44u8_p7_1,
  151651. 11,
  151652. 11
  151653. };
  151654. static static_codebook _44u8_p7_1 = {
  151655. 2, 121,
  151656. _vq_lengthlist__44u8_p7_1,
  151657. 1, -531365888, 1611661312, 4, 0,
  151658. _vq_quantlist__44u8_p7_1,
  151659. NULL,
  151660. &_vq_auxt__44u8_p7_1,
  151661. NULL,
  151662. 0
  151663. };
  151664. static long _vq_quantlist__44u8_p8_0[] = {
  151665. 7,
  151666. 6,
  151667. 8,
  151668. 5,
  151669. 9,
  151670. 4,
  151671. 10,
  151672. 3,
  151673. 11,
  151674. 2,
  151675. 12,
  151676. 1,
  151677. 13,
  151678. 0,
  151679. 14,
  151680. };
  151681. static long _vq_lengthlist__44u8_p8_0[] = {
  151682. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151683. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151684. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151685. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151686. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151687. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151688. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151689. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151690. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151691. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151692. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151693. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151694. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151695. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151696. 17,
  151697. };
  151698. static float _vq_quantthresh__44u8_p8_0[] = {
  151699. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151700. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151701. };
  151702. static long _vq_quantmap__44u8_p8_0[] = {
  151703. 13, 11, 9, 7, 5, 3, 1, 0,
  151704. 2, 4, 6, 8, 10, 12, 14,
  151705. };
  151706. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151707. _vq_quantthresh__44u8_p8_0,
  151708. _vq_quantmap__44u8_p8_0,
  151709. 15,
  151710. 15
  151711. };
  151712. static static_codebook _44u8_p8_0 = {
  151713. 2, 225,
  151714. _vq_lengthlist__44u8_p8_0,
  151715. 1, -520986624, 1620377600, 4, 0,
  151716. _vq_quantlist__44u8_p8_0,
  151717. NULL,
  151718. &_vq_auxt__44u8_p8_0,
  151719. NULL,
  151720. 0
  151721. };
  151722. static long _vq_quantlist__44u8_p8_1[] = {
  151723. 10,
  151724. 9,
  151725. 11,
  151726. 8,
  151727. 12,
  151728. 7,
  151729. 13,
  151730. 6,
  151731. 14,
  151732. 5,
  151733. 15,
  151734. 4,
  151735. 16,
  151736. 3,
  151737. 17,
  151738. 2,
  151739. 18,
  151740. 1,
  151741. 19,
  151742. 0,
  151743. 20,
  151744. };
  151745. static long _vq_lengthlist__44u8_p8_1[] = {
  151746. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151747. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151748. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151749. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151750. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151751. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151752. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151753. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151754. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151755. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151756. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151757. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151758. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151759. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151760. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151761. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151762. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151763. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151764. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151765. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151766. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151767. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151768. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151769. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151770. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151771. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151772. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151773. 10,10,10,10,10,10,10,10,10,
  151774. };
  151775. static float _vq_quantthresh__44u8_p8_1[] = {
  151776. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151777. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151778. 6.5, 7.5, 8.5, 9.5,
  151779. };
  151780. static long _vq_quantmap__44u8_p8_1[] = {
  151781. 19, 17, 15, 13, 11, 9, 7, 5,
  151782. 3, 1, 0, 2, 4, 6, 8, 10,
  151783. 12, 14, 16, 18, 20,
  151784. };
  151785. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151786. _vq_quantthresh__44u8_p8_1,
  151787. _vq_quantmap__44u8_p8_1,
  151788. 21,
  151789. 21
  151790. };
  151791. static static_codebook _44u8_p8_1 = {
  151792. 2, 441,
  151793. _vq_lengthlist__44u8_p8_1,
  151794. 1, -529268736, 1611661312, 5, 0,
  151795. _vq_quantlist__44u8_p8_1,
  151796. NULL,
  151797. &_vq_auxt__44u8_p8_1,
  151798. NULL,
  151799. 0
  151800. };
  151801. static long _vq_quantlist__44u8_p9_0[] = {
  151802. 4,
  151803. 3,
  151804. 5,
  151805. 2,
  151806. 6,
  151807. 1,
  151808. 7,
  151809. 0,
  151810. 8,
  151811. };
  151812. static long _vq_lengthlist__44u8_p9_0[] = {
  151813. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151814. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151815. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151816. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151817. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151818. 8,
  151819. };
  151820. static float _vq_quantthresh__44u8_p9_0[] = {
  151821. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151822. };
  151823. static long _vq_quantmap__44u8_p9_0[] = {
  151824. 7, 5, 3, 1, 0, 2, 4, 6,
  151825. 8,
  151826. };
  151827. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151828. _vq_quantthresh__44u8_p9_0,
  151829. _vq_quantmap__44u8_p9_0,
  151830. 9,
  151831. 9
  151832. };
  151833. static static_codebook _44u8_p9_0 = {
  151834. 2, 81,
  151835. _vq_lengthlist__44u8_p9_0,
  151836. 1, -511895552, 1631393792, 4, 0,
  151837. _vq_quantlist__44u8_p9_0,
  151838. NULL,
  151839. &_vq_auxt__44u8_p9_0,
  151840. NULL,
  151841. 0
  151842. };
  151843. static long _vq_quantlist__44u8_p9_1[] = {
  151844. 9,
  151845. 8,
  151846. 10,
  151847. 7,
  151848. 11,
  151849. 6,
  151850. 12,
  151851. 5,
  151852. 13,
  151853. 4,
  151854. 14,
  151855. 3,
  151856. 15,
  151857. 2,
  151858. 16,
  151859. 1,
  151860. 17,
  151861. 0,
  151862. 18,
  151863. };
  151864. static long _vq_lengthlist__44u8_p9_1[] = {
  151865. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151866. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151867. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151868. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151869. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151870. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151871. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151872. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151873. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151874. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151875. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151876. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151877. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151878. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151879. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151880. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151881. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151882. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151883. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151884. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151885. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151886. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151887. 16,15,16,16,16,16,16,16,16,
  151888. };
  151889. static float _vq_quantthresh__44u8_p9_1[] = {
  151890. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151891. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151892. 367.5, 416.5,
  151893. };
  151894. static long _vq_quantmap__44u8_p9_1[] = {
  151895. 17, 15, 13, 11, 9, 7, 5, 3,
  151896. 1, 0, 2, 4, 6, 8, 10, 12,
  151897. 14, 16, 18,
  151898. };
  151899. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151900. _vq_quantthresh__44u8_p9_1,
  151901. _vq_quantmap__44u8_p9_1,
  151902. 19,
  151903. 19
  151904. };
  151905. static static_codebook _44u8_p9_1 = {
  151906. 2, 361,
  151907. _vq_lengthlist__44u8_p9_1,
  151908. 1, -518287360, 1622704128, 5, 0,
  151909. _vq_quantlist__44u8_p9_1,
  151910. NULL,
  151911. &_vq_auxt__44u8_p9_1,
  151912. NULL,
  151913. 0
  151914. };
  151915. static long _vq_quantlist__44u8_p9_2[] = {
  151916. 24,
  151917. 23,
  151918. 25,
  151919. 22,
  151920. 26,
  151921. 21,
  151922. 27,
  151923. 20,
  151924. 28,
  151925. 19,
  151926. 29,
  151927. 18,
  151928. 30,
  151929. 17,
  151930. 31,
  151931. 16,
  151932. 32,
  151933. 15,
  151934. 33,
  151935. 14,
  151936. 34,
  151937. 13,
  151938. 35,
  151939. 12,
  151940. 36,
  151941. 11,
  151942. 37,
  151943. 10,
  151944. 38,
  151945. 9,
  151946. 39,
  151947. 8,
  151948. 40,
  151949. 7,
  151950. 41,
  151951. 6,
  151952. 42,
  151953. 5,
  151954. 43,
  151955. 4,
  151956. 44,
  151957. 3,
  151958. 45,
  151959. 2,
  151960. 46,
  151961. 1,
  151962. 47,
  151963. 0,
  151964. 48,
  151965. };
  151966. static long _vq_lengthlist__44u8_p9_2[] = {
  151967. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151968. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151969. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151970. 7,
  151971. };
  151972. static float _vq_quantthresh__44u8_p9_2[] = {
  151973. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151974. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151975. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151976. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151977. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151978. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151979. };
  151980. static long _vq_quantmap__44u8_p9_2[] = {
  151981. 47, 45, 43, 41, 39, 37, 35, 33,
  151982. 31, 29, 27, 25, 23, 21, 19, 17,
  151983. 15, 13, 11, 9, 7, 5, 3, 1,
  151984. 0, 2, 4, 6, 8, 10, 12, 14,
  151985. 16, 18, 20, 22, 24, 26, 28, 30,
  151986. 32, 34, 36, 38, 40, 42, 44, 46,
  151987. 48,
  151988. };
  151989. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151990. _vq_quantthresh__44u8_p9_2,
  151991. _vq_quantmap__44u8_p9_2,
  151992. 49,
  151993. 49
  151994. };
  151995. static static_codebook _44u8_p9_2 = {
  151996. 1, 49,
  151997. _vq_lengthlist__44u8_p9_2,
  151998. 1, -526909440, 1611661312, 6, 0,
  151999. _vq_quantlist__44u8_p9_2,
  152000. NULL,
  152001. &_vq_auxt__44u8_p9_2,
  152002. NULL,
  152003. 0
  152004. };
  152005. static long _huff_lengthlist__44u9__long[] = {
  152006. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152007. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152008. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152009. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152010. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152011. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152012. 10, 8, 8, 9,
  152013. };
  152014. static static_codebook _huff_book__44u9__long = {
  152015. 2, 100,
  152016. _huff_lengthlist__44u9__long,
  152017. 0, 0, 0, 0, 0,
  152018. NULL,
  152019. NULL,
  152020. NULL,
  152021. NULL,
  152022. 0
  152023. };
  152024. static long _huff_lengthlist__44u9__short[] = {
  152025. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152026. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152027. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152028. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152029. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152030. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152031. 9, 9,12,15,
  152032. };
  152033. static static_codebook _huff_book__44u9__short = {
  152034. 2, 100,
  152035. _huff_lengthlist__44u9__short,
  152036. 0, 0, 0, 0, 0,
  152037. NULL,
  152038. NULL,
  152039. NULL,
  152040. NULL,
  152041. 0
  152042. };
  152043. static long _vq_quantlist__44u9_p1_0[] = {
  152044. 1,
  152045. 0,
  152046. 2,
  152047. };
  152048. static long _vq_lengthlist__44u9_p1_0[] = {
  152049. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152050. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152051. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152052. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152053. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152054. 10,
  152055. };
  152056. static float _vq_quantthresh__44u9_p1_0[] = {
  152057. -0.5, 0.5,
  152058. };
  152059. static long _vq_quantmap__44u9_p1_0[] = {
  152060. 1, 0, 2,
  152061. };
  152062. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152063. _vq_quantthresh__44u9_p1_0,
  152064. _vq_quantmap__44u9_p1_0,
  152065. 3,
  152066. 3
  152067. };
  152068. static static_codebook _44u9_p1_0 = {
  152069. 4, 81,
  152070. _vq_lengthlist__44u9_p1_0,
  152071. 1, -535822336, 1611661312, 2, 0,
  152072. _vq_quantlist__44u9_p1_0,
  152073. NULL,
  152074. &_vq_auxt__44u9_p1_0,
  152075. NULL,
  152076. 0
  152077. };
  152078. static long _vq_quantlist__44u9_p2_0[] = {
  152079. 2,
  152080. 1,
  152081. 3,
  152082. 0,
  152083. 4,
  152084. };
  152085. static long _vq_lengthlist__44u9_p2_0[] = {
  152086. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152087. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152088. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152089. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152090. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152091. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152092. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152093. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152094. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152095. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152096. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152097. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152098. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152099. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152100. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152101. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152102. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152103. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152104. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152105. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152106. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152107. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152108. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152109. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152110. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152111. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152112. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152113. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152114. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152115. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152116. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152117. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152118. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152119. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152120. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152121. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152122. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152123. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152124. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152125. 14,
  152126. };
  152127. static float _vq_quantthresh__44u9_p2_0[] = {
  152128. -1.5, -0.5, 0.5, 1.5,
  152129. };
  152130. static long _vq_quantmap__44u9_p2_0[] = {
  152131. 3, 1, 0, 2, 4,
  152132. };
  152133. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152134. _vq_quantthresh__44u9_p2_0,
  152135. _vq_quantmap__44u9_p2_0,
  152136. 5,
  152137. 5
  152138. };
  152139. static static_codebook _44u9_p2_0 = {
  152140. 4, 625,
  152141. _vq_lengthlist__44u9_p2_0,
  152142. 1, -533725184, 1611661312, 3, 0,
  152143. _vq_quantlist__44u9_p2_0,
  152144. NULL,
  152145. &_vq_auxt__44u9_p2_0,
  152146. NULL,
  152147. 0
  152148. };
  152149. static long _vq_quantlist__44u9_p3_0[] = {
  152150. 4,
  152151. 3,
  152152. 5,
  152153. 2,
  152154. 6,
  152155. 1,
  152156. 7,
  152157. 0,
  152158. 8,
  152159. };
  152160. static long _vq_lengthlist__44u9_p3_0[] = {
  152161. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152162. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152163. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152164. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152165. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152166. 11,
  152167. };
  152168. static float _vq_quantthresh__44u9_p3_0[] = {
  152169. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152170. };
  152171. static long _vq_quantmap__44u9_p3_0[] = {
  152172. 7, 5, 3, 1, 0, 2, 4, 6,
  152173. 8,
  152174. };
  152175. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152176. _vq_quantthresh__44u9_p3_0,
  152177. _vq_quantmap__44u9_p3_0,
  152178. 9,
  152179. 9
  152180. };
  152181. static static_codebook _44u9_p3_0 = {
  152182. 2, 81,
  152183. _vq_lengthlist__44u9_p3_0,
  152184. 1, -531628032, 1611661312, 4, 0,
  152185. _vq_quantlist__44u9_p3_0,
  152186. NULL,
  152187. &_vq_auxt__44u9_p3_0,
  152188. NULL,
  152189. 0
  152190. };
  152191. static long _vq_quantlist__44u9_p4_0[] = {
  152192. 8,
  152193. 7,
  152194. 9,
  152195. 6,
  152196. 10,
  152197. 5,
  152198. 11,
  152199. 4,
  152200. 12,
  152201. 3,
  152202. 13,
  152203. 2,
  152204. 14,
  152205. 1,
  152206. 15,
  152207. 0,
  152208. 16,
  152209. };
  152210. static long _vq_lengthlist__44u9_p4_0[] = {
  152211. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152212. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152213. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152214. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152215. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152216. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152217. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152218. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152219. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152220. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152221. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152222. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152223. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152224. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152225. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152226. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152227. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152228. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152229. 14,
  152230. };
  152231. static float _vq_quantthresh__44u9_p4_0[] = {
  152232. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152233. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152234. };
  152235. static long _vq_quantmap__44u9_p4_0[] = {
  152236. 15, 13, 11, 9, 7, 5, 3, 1,
  152237. 0, 2, 4, 6, 8, 10, 12, 14,
  152238. 16,
  152239. };
  152240. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152241. _vq_quantthresh__44u9_p4_0,
  152242. _vq_quantmap__44u9_p4_0,
  152243. 17,
  152244. 17
  152245. };
  152246. static static_codebook _44u9_p4_0 = {
  152247. 2, 289,
  152248. _vq_lengthlist__44u9_p4_0,
  152249. 1, -529530880, 1611661312, 5, 0,
  152250. _vq_quantlist__44u9_p4_0,
  152251. NULL,
  152252. &_vq_auxt__44u9_p4_0,
  152253. NULL,
  152254. 0
  152255. };
  152256. static long _vq_quantlist__44u9_p5_0[] = {
  152257. 1,
  152258. 0,
  152259. 2,
  152260. };
  152261. static long _vq_lengthlist__44u9_p5_0[] = {
  152262. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152263. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152264. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152265. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152266. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152267. 10,
  152268. };
  152269. static float _vq_quantthresh__44u9_p5_0[] = {
  152270. -5.5, 5.5,
  152271. };
  152272. static long _vq_quantmap__44u9_p5_0[] = {
  152273. 1, 0, 2,
  152274. };
  152275. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152276. _vq_quantthresh__44u9_p5_0,
  152277. _vq_quantmap__44u9_p5_0,
  152278. 3,
  152279. 3
  152280. };
  152281. static static_codebook _44u9_p5_0 = {
  152282. 4, 81,
  152283. _vq_lengthlist__44u9_p5_0,
  152284. 1, -529137664, 1618345984, 2, 0,
  152285. _vq_quantlist__44u9_p5_0,
  152286. NULL,
  152287. &_vq_auxt__44u9_p5_0,
  152288. NULL,
  152289. 0
  152290. };
  152291. static long _vq_quantlist__44u9_p5_1[] = {
  152292. 5,
  152293. 4,
  152294. 6,
  152295. 3,
  152296. 7,
  152297. 2,
  152298. 8,
  152299. 1,
  152300. 9,
  152301. 0,
  152302. 10,
  152303. };
  152304. static long _vq_lengthlist__44u9_p5_1[] = {
  152305. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152306. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152307. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152308. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152309. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152310. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152311. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152312. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152313. };
  152314. static float _vq_quantthresh__44u9_p5_1[] = {
  152315. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152316. 3.5, 4.5,
  152317. };
  152318. static long _vq_quantmap__44u9_p5_1[] = {
  152319. 9, 7, 5, 3, 1, 0, 2, 4,
  152320. 6, 8, 10,
  152321. };
  152322. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152323. _vq_quantthresh__44u9_p5_1,
  152324. _vq_quantmap__44u9_p5_1,
  152325. 11,
  152326. 11
  152327. };
  152328. static static_codebook _44u9_p5_1 = {
  152329. 2, 121,
  152330. _vq_lengthlist__44u9_p5_1,
  152331. 1, -531365888, 1611661312, 4, 0,
  152332. _vq_quantlist__44u9_p5_1,
  152333. NULL,
  152334. &_vq_auxt__44u9_p5_1,
  152335. NULL,
  152336. 0
  152337. };
  152338. static long _vq_quantlist__44u9_p6_0[] = {
  152339. 6,
  152340. 5,
  152341. 7,
  152342. 4,
  152343. 8,
  152344. 3,
  152345. 9,
  152346. 2,
  152347. 10,
  152348. 1,
  152349. 11,
  152350. 0,
  152351. 12,
  152352. };
  152353. static long _vq_lengthlist__44u9_p6_0[] = {
  152354. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152355. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152356. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152357. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152358. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152359. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152360. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152361. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152362. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152363. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152364. 10,11,11,11,11,12,11,12,12,
  152365. };
  152366. static float _vq_quantthresh__44u9_p6_0[] = {
  152367. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152368. 12.5, 17.5, 22.5, 27.5,
  152369. };
  152370. static long _vq_quantmap__44u9_p6_0[] = {
  152371. 11, 9, 7, 5, 3, 1, 0, 2,
  152372. 4, 6, 8, 10, 12,
  152373. };
  152374. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152375. _vq_quantthresh__44u9_p6_0,
  152376. _vq_quantmap__44u9_p6_0,
  152377. 13,
  152378. 13
  152379. };
  152380. static static_codebook _44u9_p6_0 = {
  152381. 2, 169,
  152382. _vq_lengthlist__44u9_p6_0,
  152383. 1, -526516224, 1616117760, 4, 0,
  152384. _vq_quantlist__44u9_p6_0,
  152385. NULL,
  152386. &_vq_auxt__44u9_p6_0,
  152387. NULL,
  152388. 0
  152389. };
  152390. static long _vq_quantlist__44u9_p6_1[] = {
  152391. 2,
  152392. 1,
  152393. 3,
  152394. 0,
  152395. 4,
  152396. };
  152397. static long _vq_lengthlist__44u9_p6_1[] = {
  152398. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152399. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152400. };
  152401. static float _vq_quantthresh__44u9_p6_1[] = {
  152402. -1.5, -0.5, 0.5, 1.5,
  152403. };
  152404. static long _vq_quantmap__44u9_p6_1[] = {
  152405. 3, 1, 0, 2, 4,
  152406. };
  152407. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152408. _vq_quantthresh__44u9_p6_1,
  152409. _vq_quantmap__44u9_p6_1,
  152410. 5,
  152411. 5
  152412. };
  152413. static static_codebook _44u9_p6_1 = {
  152414. 2, 25,
  152415. _vq_lengthlist__44u9_p6_1,
  152416. 1, -533725184, 1611661312, 3, 0,
  152417. _vq_quantlist__44u9_p6_1,
  152418. NULL,
  152419. &_vq_auxt__44u9_p6_1,
  152420. NULL,
  152421. 0
  152422. };
  152423. static long _vq_quantlist__44u9_p7_0[] = {
  152424. 6,
  152425. 5,
  152426. 7,
  152427. 4,
  152428. 8,
  152429. 3,
  152430. 9,
  152431. 2,
  152432. 10,
  152433. 1,
  152434. 11,
  152435. 0,
  152436. 12,
  152437. };
  152438. static long _vq_lengthlist__44u9_p7_0[] = {
  152439. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152440. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152441. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152442. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152443. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152444. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152445. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152446. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152447. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152448. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152449. 12,13,13,14,14,14,15,15,15,
  152450. };
  152451. static float _vq_quantthresh__44u9_p7_0[] = {
  152452. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152453. 27.5, 38.5, 49.5, 60.5,
  152454. };
  152455. static long _vq_quantmap__44u9_p7_0[] = {
  152456. 11, 9, 7, 5, 3, 1, 0, 2,
  152457. 4, 6, 8, 10, 12,
  152458. };
  152459. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152460. _vq_quantthresh__44u9_p7_0,
  152461. _vq_quantmap__44u9_p7_0,
  152462. 13,
  152463. 13
  152464. };
  152465. static static_codebook _44u9_p7_0 = {
  152466. 2, 169,
  152467. _vq_lengthlist__44u9_p7_0,
  152468. 1, -523206656, 1618345984, 4, 0,
  152469. _vq_quantlist__44u9_p7_0,
  152470. NULL,
  152471. &_vq_auxt__44u9_p7_0,
  152472. NULL,
  152473. 0
  152474. };
  152475. static long _vq_quantlist__44u9_p7_1[] = {
  152476. 5,
  152477. 4,
  152478. 6,
  152479. 3,
  152480. 7,
  152481. 2,
  152482. 8,
  152483. 1,
  152484. 9,
  152485. 0,
  152486. 10,
  152487. };
  152488. static long _vq_lengthlist__44u9_p7_1[] = {
  152489. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152490. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152491. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152492. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152493. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152494. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152495. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152496. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152497. };
  152498. static float _vq_quantthresh__44u9_p7_1[] = {
  152499. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152500. 3.5, 4.5,
  152501. };
  152502. static long _vq_quantmap__44u9_p7_1[] = {
  152503. 9, 7, 5, 3, 1, 0, 2, 4,
  152504. 6, 8, 10,
  152505. };
  152506. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152507. _vq_quantthresh__44u9_p7_1,
  152508. _vq_quantmap__44u9_p7_1,
  152509. 11,
  152510. 11
  152511. };
  152512. static static_codebook _44u9_p7_1 = {
  152513. 2, 121,
  152514. _vq_lengthlist__44u9_p7_1,
  152515. 1, -531365888, 1611661312, 4, 0,
  152516. _vq_quantlist__44u9_p7_1,
  152517. NULL,
  152518. &_vq_auxt__44u9_p7_1,
  152519. NULL,
  152520. 0
  152521. };
  152522. static long _vq_quantlist__44u9_p8_0[] = {
  152523. 7,
  152524. 6,
  152525. 8,
  152526. 5,
  152527. 9,
  152528. 4,
  152529. 10,
  152530. 3,
  152531. 11,
  152532. 2,
  152533. 12,
  152534. 1,
  152535. 13,
  152536. 0,
  152537. 14,
  152538. };
  152539. static long _vq_lengthlist__44u9_p8_0[] = {
  152540. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152541. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152542. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152543. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152544. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152545. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152546. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152547. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152548. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152549. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152550. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152551. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152552. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152553. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152554. 15,
  152555. };
  152556. static float _vq_quantthresh__44u9_p8_0[] = {
  152557. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152558. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152559. };
  152560. static long _vq_quantmap__44u9_p8_0[] = {
  152561. 13, 11, 9, 7, 5, 3, 1, 0,
  152562. 2, 4, 6, 8, 10, 12, 14,
  152563. };
  152564. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152565. _vq_quantthresh__44u9_p8_0,
  152566. _vq_quantmap__44u9_p8_0,
  152567. 15,
  152568. 15
  152569. };
  152570. static static_codebook _44u9_p8_0 = {
  152571. 2, 225,
  152572. _vq_lengthlist__44u9_p8_0,
  152573. 1, -520986624, 1620377600, 4, 0,
  152574. _vq_quantlist__44u9_p8_0,
  152575. NULL,
  152576. &_vq_auxt__44u9_p8_0,
  152577. NULL,
  152578. 0
  152579. };
  152580. static long _vq_quantlist__44u9_p8_1[] = {
  152581. 10,
  152582. 9,
  152583. 11,
  152584. 8,
  152585. 12,
  152586. 7,
  152587. 13,
  152588. 6,
  152589. 14,
  152590. 5,
  152591. 15,
  152592. 4,
  152593. 16,
  152594. 3,
  152595. 17,
  152596. 2,
  152597. 18,
  152598. 1,
  152599. 19,
  152600. 0,
  152601. 20,
  152602. };
  152603. static long _vq_lengthlist__44u9_p8_1[] = {
  152604. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152605. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152606. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152607. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152608. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152609. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152610. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152611. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152612. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152613. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152614. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152615. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152616. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152617. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152618. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152619. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152620. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152621. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152622. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152623. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152625. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152626. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152627. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152628. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152629. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152630. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152631. 10,10,10,10,10,10,10,10,10,
  152632. };
  152633. static float _vq_quantthresh__44u9_p8_1[] = {
  152634. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152635. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152636. 6.5, 7.5, 8.5, 9.5,
  152637. };
  152638. static long _vq_quantmap__44u9_p8_1[] = {
  152639. 19, 17, 15, 13, 11, 9, 7, 5,
  152640. 3, 1, 0, 2, 4, 6, 8, 10,
  152641. 12, 14, 16, 18, 20,
  152642. };
  152643. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152644. _vq_quantthresh__44u9_p8_1,
  152645. _vq_quantmap__44u9_p8_1,
  152646. 21,
  152647. 21
  152648. };
  152649. static static_codebook _44u9_p8_1 = {
  152650. 2, 441,
  152651. _vq_lengthlist__44u9_p8_1,
  152652. 1, -529268736, 1611661312, 5, 0,
  152653. _vq_quantlist__44u9_p8_1,
  152654. NULL,
  152655. &_vq_auxt__44u9_p8_1,
  152656. NULL,
  152657. 0
  152658. };
  152659. static long _vq_quantlist__44u9_p9_0[] = {
  152660. 7,
  152661. 6,
  152662. 8,
  152663. 5,
  152664. 9,
  152665. 4,
  152666. 10,
  152667. 3,
  152668. 11,
  152669. 2,
  152670. 12,
  152671. 1,
  152672. 13,
  152673. 0,
  152674. 14,
  152675. };
  152676. static long _vq_lengthlist__44u9_p9_0[] = {
  152677. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152678. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152679. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152689. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152690. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152691. 10,
  152692. };
  152693. static float _vq_quantthresh__44u9_p9_0[] = {
  152694. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152695. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152696. };
  152697. static long _vq_quantmap__44u9_p9_0[] = {
  152698. 13, 11, 9, 7, 5, 3, 1, 0,
  152699. 2, 4, 6, 8, 10, 12, 14,
  152700. };
  152701. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152702. _vq_quantthresh__44u9_p9_0,
  152703. _vq_quantmap__44u9_p9_0,
  152704. 15,
  152705. 15
  152706. };
  152707. static static_codebook _44u9_p9_0 = {
  152708. 2, 225,
  152709. _vq_lengthlist__44u9_p9_0,
  152710. 1, -510036736, 1631393792, 4, 0,
  152711. _vq_quantlist__44u9_p9_0,
  152712. NULL,
  152713. &_vq_auxt__44u9_p9_0,
  152714. NULL,
  152715. 0
  152716. };
  152717. static long _vq_quantlist__44u9_p9_1[] = {
  152718. 9,
  152719. 8,
  152720. 10,
  152721. 7,
  152722. 11,
  152723. 6,
  152724. 12,
  152725. 5,
  152726. 13,
  152727. 4,
  152728. 14,
  152729. 3,
  152730. 15,
  152731. 2,
  152732. 16,
  152733. 1,
  152734. 17,
  152735. 0,
  152736. 18,
  152737. };
  152738. static long _vq_lengthlist__44u9_p9_1[] = {
  152739. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152740. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152741. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152742. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152743. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152744. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152745. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152746. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152747. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152748. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152749. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152750. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152751. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152752. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152753. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152754. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152755. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152756. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152757. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152758. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152759. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152760. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152761. 17,17,15,17,15,17,16,16,17,
  152762. };
  152763. static float _vq_quantthresh__44u9_p9_1[] = {
  152764. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152765. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152766. 367.5, 416.5,
  152767. };
  152768. static long _vq_quantmap__44u9_p9_1[] = {
  152769. 17, 15, 13, 11, 9, 7, 5, 3,
  152770. 1, 0, 2, 4, 6, 8, 10, 12,
  152771. 14, 16, 18,
  152772. };
  152773. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152774. _vq_quantthresh__44u9_p9_1,
  152775. _vq_quantmap__44u9_p9_1,
  152776. 19,
  152777. 19
  152778. };
  152779. static static_codebook _44u9_p9_1 = {
  152780. 2, 361,
  152781. _vq_lengthlist__44u9_p9_1,
  152782. 1, -518287360, 1622704128, 5, 0,
  152783. _vq_quantlist__44u9_p9_1,
  152784. NULL,
  152785. &_vq_auxt__44u9_p9_1,
  152786. NULL,
  152787. 0
  152788. };
  152789. static long _vq_quantlist__44u9_p9_2[] = {
  152790. 24,
  152791. 23,
  152792. 25,
  152793. 22,
  152794. 26,
  152795. 21,
  152796. 27,
  152797. 20,
  152798. 28,
  152799. 19,
  152800. 29,
  152801. 18,
  152802. 30,
  152803. 17,
  152804. 31,
  152805. 16,
  152806. 32,
  152807. 15,
  152808. 33,
  152809. 14,
  152810. 34,
  152811. 13,
  152812. 35,
  152813. 12,
  152814. 36,
  152815. 11,
  152816. 37,
  152817. 10,
  152818. 38,
  152819. 9,
  152820. 39,
  152821. 8,
  152822. 40,
  152823. 7,
  152824. 41,
  152825. 6,
  152826. 42,
  152827. 5,
  152828. 43,
  152829. 4,
  152830. 44,
  152831. 3,
  152832. 45,
  152833. 2,
  152834. 46,
  152835. 1,
  152836. 47,
  152837. 0,
  152838. 48,
  152839. };
  152840. static long _vq_lengthlist__44u9_p9_2[] = {
  152841. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152842. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152843. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152844. 7,
  152845. };
  152846. static float _vq_quantthresh__44u9_p9_2[] = {
  152847. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152848. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152849. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152850. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152851. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152852. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152853. };
  152854. static long _vq_quantmap__44u9_p9_2[] = {
  152855. 47, 45, 43, 41, 39, 37, 35, 33,
  152856. 31, 29, 27, 25, 23, 21, 19, 17,
  152857. 15, 13, 11, 9, 7, 5, 3, 1,
  152858. 0, 2, 4, 6, 8, 10, 12, 14,
  152859. 16, 18, 20, 22, 24, 26, 28, 30,
  152860. 32, 34, 36, 38, 40, 42, 44, 46,
  152861. 48,
  152862. };
  152863. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152864. _vq_quantthresh__44u9_p9_2,
  152865. _vq_quantmap__44u9_p9_2,
  152866. 49,
  152867. 49
  152868. };
  152869. static static_codebook _44u9_p9_2 = {
  152870. 1, 49,
  152871. _vq_lengthlist__44u9_p9_2,
  152872. 1, -526909440, 1611661312, 6, 0,
  152873. _vq_quantlist__44u9_p9_2,
  152874. NULL,
  152875. &_vq_auxt__44u9_p9_2,
  152876. NULL,
  152877. 0
  152878. };
  152879. static long _huff_lengthlist__44un1__long[] = {
  152880. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152881. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152882. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152883. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152884. };
  152885. static static_codebook _huff_book__44un1__long = {
  152886. 2, 64,
  152887. _huff_lengthlist__44un1__long,
  152888. 0, 0, 0, 0, 0,
  152889. NULL,
  152890. NULL,
  152891. NULL,
  152892. NULL,
  152893. 0
  152894. };
  152895. static long _vq_quantlist__44un1__p1_0[] = {
  152896. 1,
  152897. 0,
  152898. 2,
  152899. };
  152900. static long _vq_lengthlist__44un1__p1_0[] = {
  152901. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152902. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152903. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152904. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152905. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152906. 12,
  152907. };
  152908. static float _vq_quantthresh__44un1__p1_0[] = {
  152909. -0.5, 0.5,
  152910. };
  152911. static long _vq_quantmap__44un1__p1_0[] = {
  152912. 1, 0, 2,
  152913. };
  152914. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152915. _vq_quantthresh__44un1__p1_0,
  152916. _vq_quantmap__44un1__p1_0,
  152917. 3,
  152918. 3
  152919. };
  152920. static static_codebook _44un1__p1_0 = {
  152921. 4, 81,
  152922. _vq_lengthlist__44un1__p1_0,
  152923. 1, -535822336, 1611661312, 2, 0,
  152924. _vq_quantlist__44un1__p1_0,
  152925. NULL,
  152926. &_vq_auxt__44un1__p1_0,
  152927. NULL,
  152928. 0
  152929. };
  152930. static long _vq_quantlist__44un1__p2_0[] = {
  152931. 1,
  152932. 0,
  152933. 2,
  152934. };
  152935. static long _vq_lengthlist__44un1__p2_0[] = {
  152936. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152937. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152938. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152939. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152940. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152941. 8,
  152942. };
  152943. static float _vq_quantthresh__44un1__p2_0[] = {
  152944. -0.5, 0.5,
  152945. };
  152946. static long _vq_quantmap__44un1__p2_0[] = {
  152947. 1, 0, 2,
  152948. };
  152949. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152950. _vq_quantthresh__44un1__p2_0,
  152951. _vq_quantmap__44un1__p2_0,
  152952. 3,
  152953. 3
  152954. };
  152955. static static_codebook _44un1__p2_0 = {
  152956. 4, 81,
  152957. _vq_lengthlist__44un1__p2_0,
  152958. 1, -535822336, 1611661312, 2, 0,
  152959. _vq_quantlist__44un1__p2_0,
  152960. NULL,
  152961. &_vq_auxt__44un1__p2_0,
  152962. NULL,
  152963. 0
  152964. };
  152965. static long _vq_quantlist__44un1__p3_0[] = {
  152966. 2,
  152967. 1,
  152968. 3,
  152969. 0,
  152970. 4,
  152971. };
  152972. static long _vq_lengthlist__44un1__p3_0[] = {
  152973. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152974. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152975. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152976. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152977. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152978. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152979. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152980. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152981. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152982. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152983. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152984. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152985. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152986. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152987. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152988. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152989. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152990. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152991. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152992. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152993. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152994. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152995. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152996. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152997. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152998. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152999. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  153000. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  153001. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  153002. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  153003. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  153004. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153005. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153006. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153007. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153008. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153009. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153010. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153011. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153012. 17,
  153013. };
  153014. static float _vq_quantthresh__44un1__p3_0[] = {
  153015. -1.5, -0.5, 0.5, 1.5,
  153016. };
  153017. static long _vq_quantmap__44un1__p3_0[] = {
  153018. 3, 1, 0, 2, 4,
  153019. };
  153020. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153021. _vq_quantthresh__44un1__p3_0,
  153022. _vq_quantmap__44un1__p3_0,
  153023. 5,
  153024. 5
  153025. };
  153026. static static_codebook _44un1__p3_0 = {
  153027. 4, 625,
  153028. _vq_lengthlist__44un1__p3_0,
  153029. 1, -533725184, 1611661312, 3, 0,
  153030. _vq_quantlist__44un1__p3_0,
  153031. NULL,
  153032. &_vq_auxt__44un1__p3_0,
  153033. NULL,
  153034. 0
  153035. };
  153036. static long _vq_quantlist__44un1__p4_0[] = {
  153037. 2,
  153038. 1,
  153039. 3,
  153040. 0,
  153041. 4,
  153042. };
  153043. static long _vq_lengthlist__44un1__p4_0[] = {
  153044. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153045. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153046. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153047. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153048. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153049. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153050. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153051. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153052. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153053. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153054. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153055. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153056. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153057. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153058. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153059. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153060. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153061. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153062. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153063. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153064. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153065. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153066. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153067. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153068. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153069. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153070. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153071. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153072. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153073. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153074. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153075. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153076. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153077. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153078. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153079. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153080. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153081. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153082. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153083. 12,
  153084. };
  153085. static float _vq_quantthresh__44un1__p4_0[] = {
  153086. -1.5, -0.5, 0.5, 1.5,
  153087. };
  153088. static long _vq_quantmap__44un1__p4_0[] = {
  153089. 3, 1, 0, 2, 4,
  153090. };
  153091. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153092. _vq_quantthresh__44un1__p4_0,
  153093. _vq_quantmap__44un1__p4_0,
  153094. 5,
  153095. 5
  153096. };
  153097. static static_codebook _44un1__p4_0 = {
  153098. 4, 625,
  153099. _vq_lengthlist__44un1__p4_0,
  153100. 1, -533725184, 1611661312, 3, 0,
  153101. _vq_quantlist__44un1__p4_0,
  153102. NULL,
  153103. &_vq_auxt__44un1__p4_0,
  153104. NULL,
  153105. 0
  153106. };
  153107. static long _vq_quantlist__44un1__p5_0[] = {
  153108. 4,
  153109. 3,
  153110. 5,
  153111. 2,
  153112. 6,
  153113. 1,
  153114. 7,
  153115. 0,
  153116. 8,
  153117. };
  153118. static long _vq_lengthlist__44un1__p5_0[] = {
  153119. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153120. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153121. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153122. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153123. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153124. 12,
  153125. };
  153126. static float _vq_quantthresh__44un1__p5_0[] = {
  153127. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153128. };
  153129. static long _vq_quantmap__44un1__p5_0[] = {
  153130. 7, 5, 3, 1, 0, 2, 4, 6,
  153131. 8,
  153132. };
  153133. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153134. _vq_quantthresh__44un1__p5_0,
  153135. _vq_quantmap__44un1__p5_0,
  153136. 9,
  153137. 9
  153138. };
  153139. static static_codebook _44un1__p5_0 = {
  153140. 2, 81,
  153141. _vq_lengthlist__44un1__p5_0,
  153142. 1, -531628032, 1611661312, 4, 0,
  153143. _vq_quantlist__44un1__p5_0,
  153144. NULL,
  153145. &_vq_auxt__44un1__p5_0,
  153146. NULL,
  153147. 0
  153148. };
  153149. static long _vq_quantlist__44un1__p6_0[] = {
  153150. 6,
  153151. 5,
  153152. 7,
  153153. 4,
  153154. 8,
  153155. 3,
  153156. 9,
  153157. 2,
  153158. 10,
  153159. 1,
  153160. 11,
  153161. 0,
  153162. 12,
  153163. };
  153164. static long _vq_lengthlist__44un1__p6_0[] = {
  153165. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153166. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153167. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153168. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153169. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153170. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153171. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153172. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153173. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153174. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153175. 16, 0,15,18,18, 0,16, 0, 0,
  153176. };
  153177. static float _vq_quantthresh__44un1__p6_0[] = {
  153178. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153179. 12.5, 17.5, 22.5, 27.5,
  153180. };
  153181. static long _vq_quantmap__44un1__p6_0[] = {
  153182. 11, 9, 7, 5, 3, 1, 0, 2,
  153183. 4, 6, 8, 10, 12,
  153184. };
  153185. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153186. _vq_quantthresh__44un1__p6_0,
  153187. _vq_quantmap__44un1__p6_0,
  153188. 13,
  153189. 13
  153190. };
  153191. static static_codebook _44un1__p6_0 = {
  153192. 2, 169,
  153193. _vq_lengthlist__44un1__p6_0,
  153194. 1, -526516224, 1616117760, 4, 0,
  153195. _vq_quantlist__44un1__p6_0,
  153196. NULL,
  153197. &_vq_auxt__44un1__p6_0,
  153198. NULL,
  153199. 0
  153200. };
  153201. static long _vq_quantlist__44un1__p6_1[] = {
  153202. 2,
  153203. 1,
  153204. 3,
  153205. 0,
  153206. 4,
  153207. };
  153208. static long _vq_lengthlist__44un1__p6_1[] = {
  153209. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153210. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153211. };
  153212. static float _vq_quantthresh__44un1__p6_1[] = {
  153213. -1.5, -0.5, 0.5, 1.5,
  153214. };
  153215. static long _vq_quantmap__44un1__p6_1[] = {
  153216. 3, 1, 0, 2, 4,
  153217. };
  153218. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153219. _vq_quantthresh__44un1__p6_1,
  153220. _vq_quantmap__44un1__p6_1,
  153221. 5,
  153222. 5
  153223. };
  153224. static static_codebook _44un1__p6_1 = {
  153225. 2, 25,
  153226. _vq_lengthlist__44un1__p6_1,
  153227. 1, -533725184, 1611661312, 3, 0,
  153228. _vq_quantlist__44un1__p6_1,
  153229. NULL,
  153230. &_vq_auxt__44un1__p6_1,
  153231. NULL,
  153232. 0
  153233. };
  153234. static long _vq_quantlist__44un1__p7_0[] = {
  153235. 2,
  153236. 1,
  153237. 3,
  153238. 0,
  153239. 4,
  153240. };
  153241. static long _vq_lengthlist__44un1__p7_0[] = {
  153242. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153243. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153245. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153249. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153254. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153257. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153259. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153281. 10,
  153282. };
  153283. static float _vq_quantthresh__44un1__p7_0[] = {
  153284. -253.5, -84.5, 84.5, 253.5,
  153285. };
  153286. static long _vq_quantmap__44un1__p7_0[] = {
  153287. 3, 1, 0, 2, 4,
  153288. };
  153289. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153290. _vq_quantthresh__44un1__p7_0,
  153291. _vq_quantmap__44un1__p7_0,
  153292. 5,
  153293. 5
  153294. };
  153295. static static_codebook _44un1__p7_0 = {
  153296. 4, 625,
  153297. _vq_lengthlist__44un1__p7_0,
  153298. 1, -518709248, 1626677248, 3, 0,
  153299. _vq_quantlist__44un1__p7_0,
  153300. NULL,
  153301. &_vq_auxt__44un1__p7_0,
  153302. NULL,
  153303. 0
  153304. };
  153305. static long _vq_quantlist__44un1__p7_1[] = {
  153306. 6,
  153307. 5,
  153308. 7,
  153309. 4,
  153310. 8,
  153311. 3,
  153312. 9,
  153313. 2,
  153314. 10,
  153315. 1,
  153316. 11,
  153317. 0,
  153318. 12,
  153319. };
  153320. static long _vq_lengthlist__44un1__p7_1[] = {
  153321. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153322. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153323. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153324. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153325. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153326. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153327. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153328. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153329. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153330. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153331. 12,13,13,12,13,13,14,14,14,
  153332. };
  153333. static float _vq_quantthresh__44un1__p7_1[] = {
  153334. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153335. 32.5, 45.5, 58.5, 71.5,
  153336. };
  153337. static long _vq_quantmap__44un1__p7_1[] = {
  153338. 11, 9, 7, 5, 3, 1, 0, 2,
  153339. 4, 6, 8, 10, 12,
  153340. };
  153341. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153342. _vq_quantthresh__44un1__p7_1,
  153343. _vq_quantmap__44un1__p7_1,
  153344. 13,
  153345. 13
  153346. };
  153347. static static_codebook _44un1__p7_1 = {
  153348. 2, 169,
  153349. _vq_lengthlist__44un1__p7_1,
  153350. 1, -523010048, 1618608128, 4, 0,
  153351. _vq_quantlist__44un1__p7_1,
  153352. NULL,
  153353. &_vq_auxt__44un1__p7_1,
  153354. NULL,
  153355. 0
  153356. };
  153357. static long _vq_quantlist__44un1__p7_2[] = {
  153358. 6,
  153359. 5,
  153360. 7,
  153361. 4,
  153362. 8,
  153363. 3,
  153364. 9,
  153365. 2,
  153366. 10,
  153367. 1,
  153368. 11,
  153369. 0,
  153370. 12,
  153371. };
  153372. static long _vq_lengthlist__44un1__p7_2[] = {
  153373. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153374. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153375. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153376. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153377. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153378. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153379. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153380. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153381. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153382. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153383. 9, 9, 9,10,10,10,10,10,10,
  153384. };
  153385. static float _vq_quantthresh__44un1__p7_2[] = {
  153386. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153387. 2.5, 3.5, 4.5, 5.5,
  153388. };
  153389. static long _vq_quantmap__44un1__p7_2[] = {
  153390. 11, 9, 7, 5, 3, 1, 0, 2,
  153391. 4, 6, 8, 10, 12,
  153392. };
  153393. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153394. _vq_quantthresh__44un1__p7_2,
  153395. _vq_quantmap__44un1__p7_2,
  153396. 13,
  153397. 13
  153398. };
  153399. static static_codebook _44un1__p7_2 = {
  153400. 2, 169,
  153401. _vq_lengthlist__44un1__p7_2,
  153402. 1, -531103744, 1611661312, 4, 0,
  153403. _vq_quantlist__44un1__p7_2,
  153404. NULL,
  153405. &_vq_auxt__44un1__p7_2,
  153406. NULL,
  153407. 0
  153408. };
  153409. static long _huff_lengthlist__44un1__short[] = {
  153410. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153411. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153412. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153413. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153414. };
  153415. static static_codebook _huff_book__44un1__short = {
  153416. 2, 64,
  153417. _huff_lengthlist__44un1__short,
  153418. 0, 0, 0, 0, 0,
  153419. NULL,
  153420. NULL,
  153421. NULL,
  153422. NULL,
  153423. 0
  153424. };
  153425. /*** End of inlined file: res_books_uncoupled.h ***/
  153426. /***** residue backends *********************************************/
  153427. static vorbis_info_residue0 _residue_44_low_un={
  153428. 0,-1, -1, 8,-1,
  153429. {0},
  153430. {-1},
  153431. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153432. { -1, 25, -1, 45, -1, -1, -1}
  153433. };
  153434. static vorbis_info_residue0 _residue_44_mid_un={
  153435. 0,-1, -1, 10,-1,
  153436. /* 0 1 2 3 4 5 6 7 8 9 */
  153437. {0},
  153438. {-1},
  153439. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153440. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153441. };
  153442. static vorbis_info_residue0 _residue_44_hi_un={
  153443. 0,-1, -1, 10,-1,
  153444. /* 0 1 2 3 4 5 6 7 8 9 */
  153445. {0},
  153446. {-1},
  153447. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153448. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153449. };
  153450. /* mapping conventions:
  153451. only one submap (this would change for efficient 5.1 support for example)*/
  153452. /* Four psychoacoustic profiles are used, one for each blocktype */
  153453. static vorbis_info_mapping0 _map_nominal_u[2]={
  153454. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153455. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153456. };
  153457. static static_bookblock _resbook_44u_n1={
  153458. {
  153459. {0},
  153460. {0,0,&_44un1__p1_0},
  153461. {0,0,&_44un1__p2_0},
  153462. {0,0,&_44un1__p3_0},
  153463. {0,0,&_44un1__p4_0},
  153464. {0,0,&_44un1__p5_0},
  153465. {&_44un1__p6_0,&_44un1__p6_1},
  153466. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153467. }
  153468. };
  153469. static static_bookblock _resbook_44u_0={
  153470. {
  153471. {0},
  153472. {0,0,&_44u0__p1_0},
  153473. {0,0,&_44u0__p2_0},
  153474. {0,0,&_44u0__p3_0},
  153475. {0,0,&_44u0__p4_0},
  153476. {0,0,&_44u0__p5_0},
  153477. {&_44u0__p6_0,&_44u0__p6_1},
  153478. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153479. }
  153480. };
  153481. static static_bookblock _resbook_44u_1={
  153482. {
  153483. {0},
  153484. {0,0,&_44u1__p1_0},
  153485. {0,0,&_44u1__p2_0},
  153486. {0,0,&_44u1__p3_0},
  153487. {0,0,&_44u1__p4_0},
  153488. {0,0,&_44u1__p5_0},
  153489. {&_44u1__p6_0,&_44u1__p6_1},
  153490. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153491. }
  153492. };
  153493. static static_bookblock _resbook_44u_2={
  153494. {
  153495. {0},
  153496. {0,0,&_44u2__p1_0},
  153497. {0,0,&_44u2__p2_0},
  153498. {0,0,&_44u2__p3_0},
  153499. {0,0,&_44u2__p4_0},
  153500. {0,0,&_44u2__p5_0},
  153501. {&_44u2__p6_0,&_44u2__p6_1},
  153502. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153503. }
  153504. };
  153505. static static_bookblock _resbook_44u_3={
  153506. {
  153507. {0},
  153508. {0,0,&_44u3__p1_0},
  153509. {0,0,&_44u3__p2_0},
  153510. {0,0,&_44u3__p3_0},
  153511. {0,0,&_44u3__p4_0},
  153512. {0,0,&_44u3__p5_0},
  153513. {&_44u3__p6_0,&_44u3__p6_1},
  153514. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153515. }
  153516. };
  153517. static static_bookblock _resbook_44u_4={
  153518. {
  153519. {0},
  153520. {0,0,&_44u4__p1_0},
  153521. {0,0,&_44u4__p2_0},
  153522. {0,0,&_44u4__p3_0},
  153523. {0,0,&_44u4__p4_0},
  153524. {0,0,&_44u4__p5_0},
  153525. {&_44u4__p6_0,&_44u4__p6_1},
  153526. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153527. }
  153528. };
  153529. static static_bookblock _resbook_44u_5={
  153530. {
  153531. {0},
  153532. {0,0,&_44u5__p1_0},
  153533. {0,0,&_44u5__p2_0},
  153534. {0,0,&_44u5__p3_0},
  153535. {0,0,&_44u5__p4_0},
  153536. {0,0,&_44u5__p5_0},
  153537. {0,0,&_44u5__p6_0},
  153538. {&_44u5__p7_0,&_44u5__p7_1},
  153539. {&_44u5__p8_0,&_44u5__p8_1},
  153540. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153541. }
  153542. };
  153543. static static_bookblock _resbook_44u_6={
  153544. {
  153545. {0},
  153546. {0,0,&_44u6__p1_0},
  153547. {0,0,&_44u6__p2_0},
  153548. {0,0,&_44u6__p3_0},
  153549. {0,0,&_44u6__p4_0},
  153550. {0,0,&_44u6__p5_0},
  153551. {0,0,&_44u6__p6_0},
  153552. {&_44u6__p7_0,&_44u6__p7_1},
  153553. {&_44u6__p8_0,&_44u6__p8_1},
  153554. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153555. }
  153556. };
  153557. static static_bookblock _resbook_44u_7={
  153558. {
  153559. {0},
  153560. {0,0,&_44u7__p1_0},
  153561. {0,0,&_44u7__p2_0},
  153562. {0,0,&_44u7__p3_0},
  153563. {0,0,&_44u7__p4_0},
  153564. {0,0,&_44u7__p5_0},
  153565. {0,0,&_44u7__p6_0},
  153566. {&_44u7__p7_0,&_44u7__p7_1},
  153567. {&_44u7__p8_0,&_44u7__p8_1},
  153568. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153569. }
  153570. };
  153571. static static_bookblock _resbook_44u_8={
  153572. {
  153573. {0},
  153574. {0,0,&_44u8_p1_0},
  153575. {0,0,&_44u8_p2_0},
  153576. {0,0,&_44u8_p3_0},
  153577. {0,0,&_44u8_p4_0},
  153578. {&_44u8_p5_0,&_44u8_p5_1},
  153579. {&_44u8_p6_0,&_44u8_p6_1},
  153580. {&_44u8_p7_0,&_44u8_p7_1},
  153581. {&_44u8_p8_0,&_44u8_p8_1},
  153582. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153583. }
  153584. };
  153585. static static_bookblock _resbook_44u_9={
  153586. {
  153587. {0},
  153588. {0,0,&_44u9_p1_0},
  153589. {0,0,&_44u9_p2_0},
  153590. {0,0,&_44u9_p3_0},
  153591. {0,0,&_44u9_p4_0},
  153592. {&_44u9_p5_0,&_44u9_p5_1},
  153593. {&_44u9_p6_0,&_44u9_p6_1},
  153594. {&_44u9_p7_0,&_44u9_p7_1},
  153595. {&_44u9_p8_0,&_44u9_p8_1},
  153596. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153597. }
  153598. };
  153599. static vorbis_residue_template _res_44u_n1[]={
  153600. {1,0, &_residue_44_low_un,
  153601. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153602. &_resbook_44u_n1,&_resbook_44u_n1},
  153603. {1,0, &_residue_44_low_un,
  153604. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153605. &_resbook_44u_n1,&_resbook_44u_n1}
  153606. };
  153607. static vorbis_residue_template _res_44u_0[]={
  153608. {1,0, &_residue_44_low_un,
  153609. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153610. &_resbook_44u_0,&_resbook_44u_0},
  153611. {1,0, &_residue_44_low_un,
  153612. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153613. &_resbook_44u_0,&_resbook_44u_0}
  153614. };
  153615. static vorbis_residue_template _res_44u_1[]={
  153616. {1,0, &_residue_44_low_un,
  153617. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153618. &_resbook_44u_1,&_resbook_44u_1},
  153619. {1,0, &_residue_44_low_un,
  153620. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153621. &_resbook_44u_1,&_resbook_44u_1}
  153622. };
  153623. static vorbis_residue_template _res_44u_2[]={
  153624. {1,0, &_residue_44_low_un,
  153625. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153626. &_resbook_44u_2,&_resbook_44u_2},
  153627. {1,0, &_residue_44_low_un,
  153628. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153629. &_resbook_44u_2,&_resbook_44u_2}
  153630. };
  153631. static vorbis_residue_template _res_44u_3[]={
  153632. {1,0, &_residue_44_low_un,
  153633. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153634. &_resbook_44u_3,&_resbook_44u_3},
  153635. {1,0, &_residue_44_low_un,
  153636. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153637. &_resbook_44u_3,&_resbook_44u_3}
  153638. };
  153639. static vorbis_residue_template _res_44u_4[]={
  153640. {1,0, &_residue_44_low_un,
  153641. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153642. &_resbook_44u_4,&_resbook_44u_4},
  153643. {1,0, &_residue_44_low_un,
  153644. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153645. &_resbook_44u_4,&_resbook_44u_4}
  153646. };
  153647. static vorbis_residue_template _res_44u_5[]={
  153648. {1,0, &_residue_44_mid_un,
  153649. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153650. &_resbook_44u_5,&_resbook_44u_5},
  153651. {1,0, &_residue_44_mid_un,
  153652. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153653. &_resbook_44u_5,&_resbook_44u_5}
  153654. };
  153655. static vorbis_residue_template _res_44u_6[]={
  153656. {1,0, &_residue_44_mid_un,
  153657. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153658. &_resbook_44u_6,&_resbook_44u_6},
  153659. {1,0, &_residue_44_mid_un,
  153660. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153661. &_resbook_44u_6,&_resbook_44u_6}
  153662. };
  153663. static vorbis_residue_template _res_44u_7[]={
  153664. {1,0, &_residue_44_mid_un,
  153665. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153666. &_resbook_44u_7,&_resbook_44u_7},
  153667. {1,0, &_residue_44_mid_un,
  153668. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153669. &_resbook_44u_7,&_resbook_44u_7}
  153670. };
  153671. static vorbis_residue_template _res_44u_8[]={
  153672. {1,0, &_residue_44_hi_un,
  153673. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153674. &_resbook_44u_8,&_resbook_44u_8},
  153675. {1,0, &_residue_44_hi_un,
  153676. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153677. &_resbook_44u_8,&_resbook_44u_8}
  153678. };
  153679. static vorbis_residue_template _res_44u_9[]={
  153680. {1,0, &_residue_44_hi_un,
  153681. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153682. &_resbook_44u_9,&_resbook_44u_9},
  153683. {1,0, &_residue_44_hi_un,
  153684. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153685. &_resbook_44u_9,&_resbook_44u_9}
  153686. };
  153687. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153688. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153689. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153690. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153691. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153692. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153693. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153694. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153695. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153696. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153697. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153698. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153699. };
  153700. /*** End of inlined file: residue_44u.h ***/
  153701. static double rate_mapping_44_un[12]={
  153702. 32000.,48000.,60000.,70000.,80000.,86000.,
  153703. 96000.,110000.,120000.,140000.,160000.,240001.
  153704. };
  153705. ve_setup_data_template ve_setup_44_uncoupled={
  153706. 11,
  153707. rate_mapping_44_un,
  153708. quality_mapping_44,
  153709. -1,
  153710. 40000,
  153711. 50000,
  153712. blocksize_short_44,
  153713. blocksize_long_44,
  153714. _psy_tone_masteratt_44,
  153715. _psy_tone_0dB,
  153716. _psy_tone_suppress,
  153717. _vp_tonemask_adj_otherblock,
  153718. _vp_tonemask_adj_longblock,
  153719. _vp_tonemask_adj_otherblock,
  153720. _psy_noiseguards_44,
  153721. _psy_noisebias_impulse,
  153722. _psy_noisebias_padding,
  153723. _psy_noisebias_trans,
  153724. _psy_noisebias_long,
  153725. _psy_noise_suppress,
  153726. _psy_compand_44,
  153727. _psy_compand_short_mapping,
  153728. _psy_compand_long_mapping,
  153729. {_noise_start_short_44,_noise_start_long_44},
  153730. {_noise_part_short_44,_noise_part_long_44},
  153731. _noise_thresh_44,
  153732. _psy_ath_floater,
  153733. _psy_ath_abs,
  153734. _psy_lowpass_44,
  153735. _psy_global_44,
  153736. _global_mapping_44,
  153737. NULL,
  153738. _floor_books,
  153739. _floor,
  153740. _floor_short_mapping_44,
  153741. _floor_long_mapping_44,
  153742. _mapres_template_44_uncoupled
  153743. };
  153744. /*** End of inlined file: setup_44u.h ***/
  153745. /*** Start of inlined file: setup_32.h ***/
  153746. static double rate_mapping_32[12]={
  153747. 18000.,28000.,35000.,45000.,56000.,60000.,
  153748. 75000.,90000.,100000.,115000.,150000.,190000.,
  153749. };
  153750. static double rate_mapping_32_un[12]={
  153751. 30000.,42000.,52000.,64000.,72000.,78000.,
  153752. 86000.,92000.,110000.,120000.,140000.,190000.,
  153753. };
  153754. static double _psy_lowpass_32[12]={
  153755. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153756. };
  153757. ve_setup_data_template ve_setup_32_stereo={
  153758. 11,
  153759. rate_mapping_32,
  153760. quality_mapping_44,
  153761. 2,
  153762. 26000,
  153763. 40000,
  153764. blocksize_short_44,
  153765. blocksize_long_44,
  153766. _psy_tone_masteratt_44,
  153767. _psy_tone_0dB,
  153768. _psy_tone_suppress,
  153769. _vp_tonemask_adj_otherblock,
  153770. _vp_tonemask_adj_longblock,
  153771. _vp_tonemask_adj_otherblock,
  153772. _psy_noiseguards_44,
  153773. _psy_noisebias_impulse,
  153774. _psy_noisebias_padding,
  153775. _psy_noisebias_trans,
  153776. _psy_noisebias_long,
  153777. _psy_noise_suppress,
  153778. _psy_compand_44,
  153779. _psy_compand_short_mapping,
  153780. _psy_compand_long_mapping,
  153781. {_noise_start_short_44,_noise_start_long_44},
  153782. {_noise_part_short_44,_noise_part_long_44},
  153783. _noise_thresh_44,
  153784. _psy_ath_floater,
  153785. _psy_ath_abs,
  153786. _psy_lowpass_32,
  153787. _psy_global_44,
  153788. _global_mapping_44,
  153789. _psy_stereo_modes_44,
  153790. _floor_books,
  153791. _floor,
  153792. _floor_short_mapping_44,
  153793. _floor_long_mapping_44,
  153794. _mapres_template_44_stereo
  153795. };
  153796. ve_setup_data_template ve_setup_32_uncoupled={
  153797. 11,
  153798. rate_mapping_32_un,
  153799. quality_mapping_44,
  153800. -1,
  153801. 26000,
  153802. 40000,
  153803. blocksize_short_44,
  153804. blocksize_long_44,
  153805. _psy_tone_masteratt_44,
  153806. _psy_tone_0dB,
  153807. _psy_tone_suppress,
  153808. _vp_tonemask_adj_otherblock,
  153809. _vp_tonemask_adj_longblock,
  153810. _vp_tonemask_adj_otherblock,
  153811. _psy_noiseguards_44,
  153812. _psy_noisebias_impulse,
  153813. _psy_noisebias_padding,
  153814. _psy_noisebias_trans,
  153815. _psy_noisebias_long,
  153816. _psy_noise_suppress,
  153817. _psy_compand_44,
  153818. _psy_compand_short_mapping,
  153819. _psy_compand_long_mapping,
  153820. {_noise_start_short_44,_noise_start_long_44},
  153821. {_noise_part_short_44,_noise_part_long_44},
  153822. _noise_thresh_44,
  153823. _psy_ath_floater,
  153824. _psy_ath_abs,
  153825. _psy_lowpass_32,
  153826. _psy_global_44,
  153827. _global_mapping_44,
  153828. NULL,
  153829. _floor_books,
  153830. _floor,
  153831. _floor_short_mapping_44,
  153832. _floor_long_mapping_44,
  153833. _mapres_template_44_uncoupled
  153834. };
  153835. /*** End of inlined file: setup_32.h ***/
  153836. /*** Start of inlined file: setup_8.h ***/
  153837. /*** Start of inlined file: psych_8.h ***/
  153838. static att3 _psy_tone_masteratt_8[3]={
  153839. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153840. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153841. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153842. };
  153843. static vp_adjblock _vp_tonemask_adj_8[3]={
  153844. /* adjust for mode zero */
  153845. /* 63 125 250 500 1 2 4 8 16 */
  153846. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153847. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153848. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153849. };
  153850. static noise3 _psy_noisebias_8[3]={
  153851. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153852. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153853. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153854. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153855. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153856. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153857. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153858. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153859. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153860. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153861. };
  153862. /* stereo mode by base quality level */
  153863. static adj_stereo _psy_stereo_modes_8[3]={
  153864. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153865. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153866. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153867. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153868. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153869. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153870. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153871. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153872. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153873. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153874. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153875. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153876. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153877. };
  153878. static noiseguard _psy_noiseguards_8[2]={
  153879. {10,10,-1},
  153880. {10,10,-1},
  153881. };
  153882. static compandblock _psy_compand_8[2]={
  153883. {{
  153884. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153885. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153886. 12,12,13,13,14,14,15, 15, /* 23dB */
  153887. 16,16,17,17,17,18,18, 19, /* 31dB */
  153888. 19,19,20,21,22,23,24, 25, /* 39dB */
  153889. }},
  153890. {{
  153891. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153892. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153893. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153894. 9,10,11,12,13,14,15, 16, /* 31dB */
  153895. 17,18,19,20,21,22,23, 24, /* 39dB */
  153896. }},
  153897. };
  153898. static double _psy_lowpass_8[3]={3.,4.,4.};
  153899. static int _noise_start_8[2]={
  153900. 64,64,
  153901. };
  153902. static int _noise_part_8[2]={
  153903. 8,8,
  153904. };
  153905. static int _psy_ath_floater_8[3]={
  153906. -100,-100,-105,
  153907. };
  153908. static int _psy_ath_abs_8[3]={
  153909. -130,-130,-140,
  153910. };
  153911. /*** End of inlined file: psych_8.h ***/
  153912. /*** Start of inlined file: residue_8.h ***/
  153913. /***** residue backends *********************************************/
  153914. static static_bookblock _resbook_8s_0={
  153915. {
  153916. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153917. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153918. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153919. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153920. }
  153921. };
  153922. static static_bookblock _resbook_8s_1={
  153923. {
  153924. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153925. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153926. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153927. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153928. }
  153929. };
  153930. static vorbis_residue_template _res_8s_0[]={
  153931. {2,0, &_residue_44_mid,
  153932. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153933. &_resbook_8s_0,&_resbook_8s_0},
  153934. };
  153935. static vorbis_residue_template _res_8s_1[]={
  153936. {2,0, &_residue_44_mid,
  153937. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153938. &_resbook_8s_1,&_resbook_8s_1},
  153939. };
  153940. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153941. { _map_nominal, _res_8s_0 }, /* 0 */
  153942. { _map_nominal, _res_8s_1 }, /* 1 */
  153943. };
  153944. static static_bookblock _resbook_8u_0={
  153945. {
  153946. {0},
  153947. {0,0,&_8u0__p1_0},
  153948. {0,0,&_8u0__p2_0},
  153949. {0,0,&_8u0__p3_0},
  153950. {0,0,&_8u0__p4_0},
  153951. {0,0,&_8u0__p5_0},
  153952. {&_8u0__p6_0,&_8u0__p6_1},
  153953. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153954. }
  153955. };
  153956. static static_bookblock _resbook_8u_1={
  153957. {
  153958. {0},
  153959. {0,0,&_8u1__p1_0},
  153960. {0,0,&_8u1__p2_0},
  153961. {0,0,&_8u1__p3_0},
  153962. {0,0,&_8u1__p4_0},
  153963. {0,0,&_8u1__p5_0},
  153964. {0,0,&_8u1__p6_0},
  153965. {&_8u1__p7_0,&_8u1__p7_1},
  153966. {&_8u1__p8_0,&_8u1__p8_1},
  153967. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153968. }
  153969. };
  153970. static vorbis_residue_template _res_8u_0[]={
  153971. {1,0, &_residue_44_low_un,
  153972. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153973. &_resbook_8u_0,&_resbook_8u_0},
  153974. };
  153975. static vorbis_residue_template _res_8u_1[]={
  153976. {1,0, &_residue_44_mid_un,
  153977. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153978. &_resbook_8u_1,&_resbook_8u_1},
  153979. };
  153980. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153981. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153982. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153983. };
  153984. /*** End of inlined file: residue_8.h ***/
  153985. static int blocksize_8[2]={
  153986. 512,512
  153987. };
  153988. static int _floor_mapping_8[2]={
  153989. 6,6,
  153990. };
  153991. static double rate_mapping_8[3]={
  153992. 6000.,9000.,32000.,
  153993. };
  153994. static double rate_mapping_8_uncoupled[3]={
  153995. 8000.,14000.,42000.,
  153996. };
  153997. static double quality_mapping_8[3]={
  153998. -.1,.0,1.
  153999. };
  154000. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  154001. static double _global_mapping_8[3]={ 1., 2., 3. };
  154002. ve_setup_data_template ve_setup_8_stereo={
  154003. 2,
  154004. rate_mapping_8,
  154005. quality_mapping_8,
  154006. 2,
  154007. 8000,
  154008. 9000,
  154009. blocksize_8,
  154010. blocksize_8,
  154011. _psy_tone_masteratt_8,
  154012. _psy_tone_0dB,
  154013. _psy_tone_suppress,
  154014. _vp_tonemask_adj_8,
  154015. NULL,
  154016. _vp_tonemask_adj_8,
  154017. _psy_noiseguards_8,
  154018. _psy_noisebias_8,
  154019. _psy_noisebias_8,
  154020. NULL,
  154021. NULL,
  154022. _psy_noise_suppress,
  154023. _psy_compand_8,
  154024. _psy_compand_8_mapping,
  154025. NULL,
  154026. {_noise_start_8,_noise_start_8},
  154027. {_noise_part_8,_noise_part_8},
  154028. _noise_thresh_5only,
  154029. _psy_ath_floater_8,
  154030. _psy_ath_abs_8,
  154031. _psy_lowpass_8,
  154032. _psy_global_44,
  154033. _global_mapping_8,
  154034. _psy_stereo_modes_8,
  154035. _floor_books,
  154036. _floor,
  154037. _floor_mapping_8,
  154038. NULL,
  154039. _mapres_template_8_stereo
  154040. };
  154041. ve_setup_data_template ve_setup_8_uncoupled={
  154042. 2,
  154043. rate_mapping_8_uncoupled,
  154044. quality_mapping_8,
  154045. -1,
  154046. 8000,
  154047. 9000,
  154048. blocksize_8,
  154049. blocksize_8,
  154050. _psy_tone_masteratt_8,
  154051. _psy_tone_0dB,
  154052. _psy_tone_suppress,
  154053. _vp_tonemask_adj_8,
  154054. NULL,
  154055. _vp_tonemask_adj_8,
  154056. _psy_noiseguards_8,
  154057. _psy_noisebias_8,
  154058. _psy_noisebias_8,
  154059. NULL,
  154060. NULL,
  154061. _psy_noise_suppress,
  154062. _psy_compand_8,
  154063. _psy_compand_8_mapping,
  154064. NULL,
  154065. {_noise_start_8,_noise_start_8},
  154066. {_noise_part_8,_noise_part_8},
  154067. _noise_thresh_5only,
  154068. _psy_ath_floater_8,
  154069. _psy_ath_abs_8,
  154070. _psy_lowpass_8,
  154071. _psy_global_44,
  154072. _global_mapping_8,
  154073. _psy_stereo_modes_8,
  154074. _floor_books,
  154075. _floor,
  154076. _floor_mapping_8,
  154077. NULL,
  154078. _mapres_template_8_uncoupled
  154079. };
  154080. /*** End of inlined file: setup_8.h ***/
  154081. /*** Start of inlined file: setup_11.h ***/
  154082. /*** Start of inlined file: psych_11.h ***/
  154083. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154084. static att3 _psy_tone_masteratt_11[3]={
  154085. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154086. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154087. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154088. };
  154089. static vp_adjblock _vp_tonemask_adj_11[3]={
  154090. /* adjust for mode zero */
  154091. /* 63 125 250 500 1 2 4 8 16 */
  154092. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154093. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154094. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154095. };
  154096. static noise3 _psy_noisebias_11[3]={
  154097. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154098. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154099. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154100. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154101. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154102. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154103. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154104. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154105. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154106. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154107. };
  154108. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154109. /*** End of inlined file: psych_11.h ***/
  154110. static int blocksize_11[2]={
  154111. 512,512
  154112. };
  154113. static int _floor_mapping_11[2]={
  154114. 6,6,
  154115. };
  154116. static double rate_mapping_11[3]={
  154117. 8000.,13000.,44000.,
  154118. };
  154119. static double rate_mapping_11_uncoupled[3]={
  154120. 12000.,20000.,50000.,
  154121. };
  154122. static double quality_mapping_11[3]={
  154123. -.1,.0,1.
  154124. };
  154125. ve_setup_data_template ve_setup_11_stereo={
  154126. 2,
  154127. rate_mapping_11,
  154128. quality_mapping_11,
  154129. 2,
  154130. 9000,
  154131. 15000,
  154132. blocksize_11,
  154133. blocksize_11,
  154134. _psy_tone_masteratt_11,
  154135. _psy_tone_0dB,
  154136. _psy_tone_suppress,
  154137. _vp_tonemask_adj_11,
  154138. NULL,
  154139. _vp_tonemask_adj_11,
  154140. _psy_noiseguards_8,
  154141. _psy_noisebias_11,
  154142. _psy_noisebias_11,
  154143. NULL,
  154144. NULL,
  154145. _psy_noise_suppress,
  154146. _psy_compand_8,
  154147. _psy_compand_8_mapping,
  154148. NULL,
  154149. {_noise_start_8,_noise_start_8},
  154150. {_noise_part_8,_noise_part_8},
  154151. _noise_thresh_11,
  154152. _psy_ath_floater_8,
  154153. _psy_ath_abs_8,
  154154. _psy_lowpass_11,
  154155. _psy_global_44,
  154156. _global_mapping_8,
  154157. _psy_stereo_modes_8,
  154158. _floor_books,
  154159. _floor,
  154160. _floor_mapping_11,
  154161. NULL,
  154162. _mapres_template_8_stereo
  154163. };
  154164. ve_setup_data_template ve_setup_11_uncoupled={
  154165. 2,
  154166. rate_mapping_11_uncoupled,
  154167. quality_mapping_11,
  154168. -1,
  154169. 9000,
  154170. 15000,
  154171. blocksize_11,
  154172. blocksize_11,
  154173. _psy_tone_masteratt_11,
  154174. _psy_tone_0dB,
  154175. _psy_tone_suppress,
  154176. _vp_tonemask_adj_11,
  154177. NULL,
  154178. _vp_tonemask_adj_11,
  154179. _psy_noiseguards_8,
  154180. _psy_noisebias_11,
  154181. _psy_noisebias_11,
  154182. NULL,
  154183. NULL,
  154184. _psy_noise_suppress,
  154185. _psy_compand_8,
  154186. _psy_compand_8_mapping,
  154187. NULL,
  154188. {_noise_start_8,_noise_start_8},
  154189. {_noise_part_8,_noise_part_8},
  154190. _noise_thresh_11,
  154191. _psy_ath_floater_8,
  154192. _psy_ath_abs_8,
  154193. _psy_lowpass_11,
  154194. _psy_global_44,
  154195. _global_mapping_8,
  154196. _psy_stereo_modes_8,
  154197. _floor_books,
  154198. _floor,
  154199. _floor_mapping_11,
  154200. NULL,
  154201. _mapres_template_8_uncoupled
  154202. };
  154203. /*** End of inlined file: setup_11.h ***/
  154204. /*** Start of inlined file: setup_16.h ***/
  154205. /*** Start of inlined file: psych_16.h ***/
  154206. /* stereo mode by base quality level */
  154207. static adj_stereo _psy_stereo_modes_16[4]={
  154208. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154209. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154210. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154211. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154212. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154213. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154214. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154215. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154216. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154217. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154218. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154219. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154220. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154221. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154222. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154223. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154224. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154225. };
  154226. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154227. static att3 _psy_tone_masteratt_16[4]={
  154228. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154229. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154230. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154231. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154232. };
  154233. static vp_adjblock _vp_tonemask_adj_16[4]={
  154234. /* adjust for mode zero */
  154235. /* 63 125 250 500 1 2 4 8 16 */
  154236. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154237. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154238. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154239. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154240. };
  154241. static noise3 _psy_noisebias_16_short[4]={
  154242. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154243. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154244. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154245. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154246. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154247. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154248. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154249. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154250. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154251. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154252. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154253. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154254. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154255. };
  154256. static noise3 _psy_noisebias_16_impulse[4]={
  154257. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154258. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154259. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154260. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154261. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154262. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154263. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154264. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154265. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154266. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154267. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154268. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154269. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154270. };
  154271. static noise3 _psy_noisebias_16[4]={
  154272. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154273. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154274. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154275. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154276. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154277. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154278. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154279. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154280. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154281. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154282. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154283. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154284. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154285. };
  154286. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154287. static int _noise_start_16[3]={ 256,256,9999 };
  154288. static int _noise_part_16[4]={ 8,8,8,8 };
  154289. static int _psy_ath_floater_16[4]={
  154290. -100,-100,-100,-105,
  154291. };
  154292. static int _psy_ath_abs_16[4]={
  154293. -130,-130,-130,-140,
  154294. };
  154295. /*** End of inlined file: psych_16.h ***/
  154296. /*** Start of inlined file: residue_16.h ***/
  154297. /***** residue backends *********************************************/
  154298. static static_bookblock _resbook_16s_0={
  154299. {
  154300. {0},
  154301. {0,0,&_16c0_s_p1_0},
  154302. {0,0,&_16c0_s_p2_0},
  154303. {0,0,&_16c0_s_p3_0},
  154304. {0,0,&_16c0_s_p4_0},
  154305. {0,0,&_16c0_s_p5_0},
  154306. {0,0,&_16c0_s_p6_0},
  154307. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154308. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154309. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154310. }
  154311. };
  154312. static static_bookblock _resbook_16s_1={
  154313. {
  154314. {0},
  154315. {0,0,&_16c1_s_p1_0},
  154316. {0,0,&_16c1_s_p2_0},
  154317. {0,0,&_16c1_s_p3_0},
  154318. {0,0,&_16c1_s_p4_0},
  154319. {0,0,&_16c1_s_p5_0},
  154320. {0,0,&_16c1_s_p6_0},
  154321. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154322. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154323. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154324. }
  154325. };
  154326. static static_bookblock _resbook_16s_2={
  154327. {
  154328. {0},
  154329. {0,0,&_16c2_s_p1_0},
  154330. {0,0,&_16c2_s_p2_0},
  154331. {0,0,&_16c2_s_p3_0},
  154332. {0,0,&_16c2_s_p4_0},
  154333. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154334. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154335. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154336. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154337. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154338. }
  154339. };
  154340. static vorbis_residue_template _res_16s_0[]={
  154341. {2,0, &_residue_44_mid,
  154342. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154343. &_resbook_16s_0,&_resbook_16s_0},
  154344. };
  154345. static vorbis_residue_template _res_16s_1[]={
  154346. {2,0, &_residue_44_mid,
  154347. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154348. &_resbook_16s_1,&_resbook_16s_1},
  154349. {2,0, &_residue_44_mid,
  154350. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154351. &_resbook_16s_1,&_resbook_16s_1}
  154352. };
  154353. static vorbis_residue_template _res_16s_2[]={
  154354. {2,0, &_residue_44_high,
  154355. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154356. &_resbook_16s_2,&_resbook_16s_2},
  154357. {2,0, &_residue_44_high,
  154358. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154359. &_resbook_16s_2,&_resbook_16s_2}
  154360. };
  154361. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154362. { _map_nominal, _res_16s_0 }, /* 0 */
  154363. { _map_nominal, _res_16s_1 }, /* 1 */
  154364. { _map_nominal, _res_16s_2 }, /* 2 */
  154365. };
  154366. static static_bookblock _resbook_16u_0={
  154367. {
  154368. {0},
  154369. {0,0,&_16u0__p1_0},
  154370. {0,0,&_16u0__p2_0},
  154371. {0,0,&_16u0__p3_0},
  154372. {0,0,&_16u0__p4_0},
  154373. {0,0,&_16u0__p5_0},
  154374. {&_16u0__p6_0,&_16u0__p6_1},
  154375. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154376. }
  154377. };
  154378. static static_bookblock _resbook_16u_1={
  154379. {
  154380. {0},
  154381. {0,0,&_16u1__p1_0},
  154382. {0,0,&_16u1__p2_0},
  154383. {0,0,&_16u1__p3_0},
  154384. {0,0,&_16u1__p4_0},
  154385. {0,0,&_16u1__p5_0},
  154386. {0,0,&_16u1__p6_0},
  154387. {&_16u1__p7_0,&_16u1__p7_1},
  154388. {&_16u1__p8_0,&_16u1__p8_1},
  154389. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154390. }
  154391. };
  154392. static static_bookblock _resbook_16u_2={
  154393. {
  154394. {0},
  154395. {0,0,&_16u2_p1_0},
  154396. {0,0,&_16u2_p2_0},
  154397. {0,0,&_16u2_p3_0},
  154398. {0,0,&_16u2_p4_0},
  154399. {&_16u2_p5_0,&_16u2_p5_1},
  154400. {&_16u2_p6_0,&_16u2_p6_1},
  154401. {&_16u2_p7_0,&_16u2_p7_1},
  154402. {&_16u2_p8_0,&_16u2_p8_1},
  154403. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154404. }
  154405. };
  154406. static vorbis_residue_template _res_16u_0[]={
  154407. {1,0, &_residue_44_low_un,
  154408. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154409. &_resbook_16u_0,&_resbook_16u_0},
  154410. };
  154411. static vorbis_residue_template _res_16u_1[]={
  154412. {1,0, &_residue_44_mid_un,
  154413. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154414. &_resbook_16u_1,&_resbook_16u_1},
  154415. {1,0, &_residue_44_mid_un,
  154416. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154417. &_resbook_16u_1,&_resbook_16u_1}
  154418. };
  154419. static vorbis_residue_template _res_16u_2[]={
  154420. {1,0, &_residue_44_hi_un,
  154421. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154422. &_resbook_16u_2,&_resbook_16u_2},
  154423. {1,0, &_residue_44_hi_un,
  154424. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154425. &_resbook_16u_2,&_resbook_16u_2}
  154426. };
  154427. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154428. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154429. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154430. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154431. };
  154432. /*** End of inlined file: residue_16.h ***/
  154433. static int blocksize_16_short[3]={
  154434. 1024,512,512
  154435. };
  154436. static int blocksize_16_long[3]={
  154437. 1024,1024,1024
  154438. };
  154439. static int _floor_mapping_16_short[3]={
  154440. 9,3,3
  154441. };
  154442. static int _floor_mapping_16[3]={
  154443. 9,9,9
  154444. };
  154445. static double rate_mapping_16[4]={
  154446. 12000.,20000.,44000.,86000.
  154447. };
  154448. static double rate_mapping_16_uncoupled[4]={
  154449. 16000.,28000.,64000.,100000.
  154450. };
  154451. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154452. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154453. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154454. ve_setup_data_template ve_setup_16_stereo={
  154455. 3,
  154456. rate_mapping_16,
  154457. quality_mapping_16,
  154458. 2,
  154459. 15000,
  154460. 19000,
  154461. blocksize_16_short,
  154462. blocksize_16_long,
  154463. _psy_tone_masteratt_16,
  154464. _psy_tone_0dB,
  154465. _psy_tone_suppress,
  154466. _vp_tonemask_adj_16,
  154467. _vp_tonemask_adj_16,
  154468. _vp_tonemask_adj_16,
  154469. _psy_noiseguards_8,
  154470. _psy_noisebias_16_impulse,
  154471. _psy_noisebias_16_short,
  154472. _psy_noisebias_16_short,
  154473. _psy_noisebias_16,
  154474. _psy_noise_suppress,
  154475. _psy_compand_8,
  154476. _psy_compand_16_mapping,
  154477. _psy_compand_16_mapping,
  154478. {_noise_start_16,_noise_start_16},
  154479. { _noise_part_16, _noise_part_16},
  154480. _noise_thresh_16,
  154481. _psy_ath_floater_16,
  154482. _psy_ath_abs_16,
  154483. _psy_lowpass_16,
  154484. _psy_global_44,
  154485. _global_mapping_16,
  154486. _psy_stereo_modes_16,
  154487. _floor_books,
  154488. _floor,
  154489. _floor_mapping_16_short,
  154490. _floor_mapping_16,
  154491. _mapres_template_16_stereo
  154492. };
  154493. ve_setup_data_template ve_setup_16_uncoupled={
  154494. 3,
  154495. rate_mapping_16_uncoupled,
  154496. quality_mapping_16,
  154497. -1,
  154498. 15000,
  154499. 19000,
  154500. blocksize_16_short,
  154501. blocksize_16_long,
  154502. _psy_tone_masteratt_16,
  154503. _psy_tone_0dB,
  154504. _psy_tone_suppress,
  154505. _vp_tonemask_adj_16,
  154506. _vp_tonemask_adj_16,
  154507. _vp_tonemask_adj_16,
  154508. _psy_noiseguards_8,
  154509. _psy_noisebias_16_impulse,
  154510. _psy_noisebias_16_short,
  154511. _psy_noisebias_16_short,
  154512. _psy_noisebias_16,
  154513. _psy_noise_suppress,
  154514. _psy_compand_8,
  154515. _psy_compand_16_mapping,
  154516. _psy_compand_16_mapping,
  154517. {_noise_start_16,_noise_start_16},
  154518. { _noise_part_16, _noise_part_16},
  154519. _noise_thresh_16,
  154520. _psy_ath_floater_16,
  154521. _psy_ath_abs_16,
  154522. _psy_lowpass_16,
  154523. _psy_global_44,
  154524. _global_mapping_16,
  154525. _psy_stereo_modes_16,
  154526. _floor_books,
  154527. _floor,
  154528. _floor_mapping_16_short,
  154529. _floor_mapping_16,
  154530. _mapres_template_16_uncoupled
  154531. };
  154532. /*** End of inlined file: setup_16.h ***/
  154533. /*** Start of inlined file: setup_22.h ***/
  154534. static double rate_mapping_22[4]={
  154535. 15000.,20000.,44000.,86000.
  154536. };
  154537. static double rate_mapping_22_uncoupled[4]={
  154538. 16000.,28000.,50000.,90000.
  154539. };
  154540. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154541. ve_setup_data_template ve_setup_22_stereo={
  154542. 3,
  154543. rate_mapping_22,
  154544. quality_mapping_16,
  154545. 2,
  154546. 19000,
  154547. 26000,
  154548. blocksize_16_short,
  154549. blocksize_16_long,
  154550. _psy_tone_masteratt_16,
  154551. _psy_tone_0dB,
  154552. _psy_tone_suppress,
  154553. _vp_tonemask_adj_16,
  154554. _vp_tonemask_adj_16,
  154555. _vp_tonemask_adj_16,
  154556. _psy_noiseguards_8,
  154557. _psy_noisebias_16_impulse,
  154558. _psy_noisebias_16_short,
  154559. _psy_noisebias_16_short,
  154560. _psy_noisebias_16,
  154561. _psy_noise_suppress,
  154562. _psy_compand_8,
  154563. _psy_compand_8_mapping,
  154564. _psy_compand_8_mapping,
  154565. {_noise_start_16,_noise_start_16},
  154566. { _noise_part_16, _noise_part_16},
  154567. _noise_thresh_16,
  154568. _psy_ath_floater_16,
  154569. _psy_ath_abs_16,
  154570. _psy_lowpass_22,
  154571. _psy_global_44,
  154572. _global_mapping_16,
  154573. _psy_stereo_modes_16,
  154574. _floor_books,
  154575. _floor,
  154576. _floor_mapping_16_short,
  154577. _floor_mapping_16,
  154578. _mapres_template_16_stereo
  154579. };
  154580. ve_setup_data_template ve_setup_22_uncoupled={
  154581. 3,
  154582. rate_mapping_22_uncoupled,
  154583. quality_mapping_16,
  154584. -1,
  154585. 19000,
  154586. 26000,
  154587. blocksize_16_short,
  154588. blocksize_16_long,
  154589. _psy_tone_masteratt_16,
  154590. _psy_tone_0dB,
  154591. _psy_tone_suppress,
  154592. _vp_tonemask_adj_16,
  154593. _vp_tonemask_adj_16,
  154594. _vp_tonemask_adj_16,
  154595. _psy_noiseguards_8,
  154596. _psy_noisebias_16_impulse,
  154597. _psy_noisebias_16_short,
  154598. _psy_noisebias_16_short,
  154599. _psy_noisebias_16,
  154600. _psy_noise_suppress,
  154601. _psy_compand_8,
  154602. _psy_compand_8_mapping,
  154603. _psy_compand_8_mapping,
  154604. {_noise_start_16,_noise_start_16},
  154605. { _noise_part_16, _noise_part_16},
  154606. _noise_thresh_16,
  154607. _psy_ath_floater_16,
  154608. _psy_ath_abs_16,
  154609. _psy_lowpass_22,
  154610. _psy_global_44,
  154611. _global_mapping_16,
  154612. _psy_stereo_modes_16,
  154613. _floor_books,
  154614. _floor,
  154615. _floor_mapping_16_short,
  154616. _floor_mapping_16,
  154617. _mapres_template_16_uncoupled
  154618. };
  154619. /*** End of inlined file: setup_22.h ***/
  154620. /*** Start of inlined file: setup_X.h ***/
  154621. static double rate_mapping_X[12]={
  154622. -1.,-1.,-1.,-1.,-1.,-1.,
  154623. -1.,-1.,-1.,-1.,-1.,-1.
  154624. };
  154625. ve_setup_data_template ve_setup_X_stereo={
  154626. 11,
  154627. rate_mapping_X,
  154628. quality_mapping_44,
  154629. 2,
  154630. 50000,
  154631. 200000,
  154632. blocksize_short_44,
  154633. blocksize_long_44,
  154634. _psy_tone_masteratt_44,
  154635. _psy_tone_0dB,
  154636. _psy_tone_suppress,
  154637. _vp_tonemask_adj_otherblock,
  154638. _vp_tonemask_adj_longblock,
  154639. _vp_tonemask_adj_otherblock,
  154640. _psy_noiseguards_44,
  154641. _psy_noisebias_impulse,
  154642. _psy_noisebias_padding,
  154643. _psy_noisebias_trans,
  154644. _psy_noisebias_long,
  154645. _psy_noise_suppress,
  154646. _psy_compand_44,
  154647. _psy_compand_short_mapping,
  154648. _psy_compand_long_mapping,
  154649. {_noise_start_short_44,_noise_start_long_44},
  154650. {_noise_part_short_44,_noise_part_long_44},
  154651. _noise_thresh_44,
  154652. _psy_ath_floater,
  154653. _psy_ath_abs,
  154654. _psy_lowpass_44,
  154655. _psy_global_44,
  154656. _global_mapping_44,
  154657. _psy_stereo_modes_44,
  154658. _floor_books,
  154659. _floor,
  154660. _floor_short_mapping_44,
  154661. _floor_long_mapping_44,
  154662. _mapres_template_44_stereo
  154663. };
  154664. ve_setup_data_template ve_setup_X_uncoupled={
  154665. 11,
  154666. rate_mapping_X,
  154667. quality_mapping_44,
  154668. -1,
  154669. 50000,
  154670. 200000,
  154671. blocksize_short_44,
  154672. blocksize_long_44,
  154673. _psy_tone_masteratt_44,
  154674. _psy_tone_0dB,
  154675. _psy_tone_suppress,
  154676. _vp_tonemask_adj_otherblock,
  154677. _vp_tonemask_adj_longblock,
  154678. _vp_tonemask_adj_otherblock,
  154679. _psy_noiseguards_44,
  154680. _psy_noisebias_impulse,
  154681. _psy_noisebias_padding,
  154682. _psy_noisebias_trans,
  154683. _psy_noisebias_long,
  154684. _psy_noise_suppress,
  154685. _psy_compand_44,
  154686. _psy_compand_short_mapping,
  154687. _psy_compand_long_mapping,
  154688. {_noise_start_short_44,_noise_start_long_44},
  154689. {_noise_part_short_44,_noise_part_long_44},
  154690. _noise_thresh_44,
  154691. _psy_ath_floater,
  154692. _psy_ath_abs,
  154693. _psy_lowpass_44,
  154694. _psy_global_44,
  154695. _global_mapping_44,
  154696. NULL,
  154697. _floor_books,
  154698. _floor,
  154699. _floor_short_mapping_44,
  154700. _floor_long_mapping_44,
  154701. _mapres_template_44_uncoupled
  154702. };
  154703. ve_setup_data_template ve_setup_XX_stereo={
  154704. 2,
  154705. rate_mapping_X,
  154706. quality_mapping_8,
  154707. 2,
  154708. 0,
  154709. 8000,
  154710. blocksize_8,
  154711. blocksize_8,
  154712. _psy_tone_masteratt_8,
  154713. _psy_tone_0dB,
  154714. _psy_tone_suppress,
  154715. _vp_tonemask_adj_8,
  154716. NULL,
  154717. _vp_tonemask_adj_8,
  154718. _psy_noiseguards_8,
  154719. _psy_noisebias_8,
  154720. _psy_noisebias_8,
  154721. NULL,
  154722. NULL,
  154723. _psy_noise_suppress,
  154724. _psy_compand_8,
  154725. _psy_compand_8_mapping,
  154726. NULL,
  154727. {_noise_start_8,_noise_start_8},
  154728. {_noise_part_8,_noise_part_8},
  154729. _noise_thresh_5only,
  154730. _psy_ath_floater_8,
  154731. _psy_ath_abs_8,
  154732. _psy_lowpass_8,
  154733. _psy_global_44,
  154734. _global_mapping_8,
  154735. _psy_stereo_modes_8,
  154736. _floor_books,
  154737. _floor,
  154738. _floor_mapping_8,
  154739. NULL,
  154740. _mapres_template_8_stereo
  154741. };
  154742. ve_setup_data_template ve_setup_XX_uncoupled={
  154743. 2,
  154744. rate_mapping_X,
  154745. quality_mapping_8,
  154746. -1,
  154747. 0,
  154748. 8000,
  154749. blocksize_8,
  154750. blocksize_8,
  154751. _psy_tone_masteratt_8,
  154752. _psy_tone_0dB,
  154753. _psy_tone_suppress,
  154754. _vp_tonemask_adj_8,
  154755. NULL,
  154756. _vp_tonemask_adj_8,
  154757. _psy_noiseguards_8,
  154758. _psy_noisebias_8,
  154759. _psy_noisebias_8,
  154760. NULL,
  154761. NULL,
  154762. _psy_noise_suppress,
  154763. _psy_compand_8,
  154764. _psy_compand_8_mapping,
  154765. NULL,
  154766. {_noise_start_8,_noise_start_8},
  154767. {_noise_part_8,_noise_part_8},
  154768. _noise_thresh_5only,
  154769. _psy_ath_floater_8,
  154770. _psy_ath_abs_8,
  154771. _psy_lowpass_8,
  154772. _psy_global_44,
  154773. _global_mapping_8,
  154774. _psy_stereo_modes_8,
  154775. _floor_books,
  154776. _floor,
  154777. _floor_mapping_8,
  154778. NULL,
  154779. _mapres_template_8_uncoupled
  154780. };
  154781. /*** End of inlined file: setup_X.h ***/
  154782. static ve_setup_data_template *setup_list[]={
  154783. &ve_setup_44_stereo,
  154784. &ve_setup_44_uncoupled,
  154785. &ve_setup_32_stereo,
  154786. &ve_setup_32_uncoupled,
  154787. &ve_setup_22_stereo,
  154788. &ve_setup_22_uncoupled,
  154789. &ve_setup_16_stereo,
  154790. &ve_setup_16_uncoupled,
  154791. &ve_setup_11_stereo,
  154792. &ve_setup_11_uncoupled,
  154793. &ve_setup_8_stereo,
  154794. &ve_setup_8_uncoupled,
  154795. &ve_setup_X_stereo,
  154796. &ve_setup_X_uncoupled,
  154797. &ve_setup_XX_stereo,
  154798. &ve_setup_XX_uncoupled,
  154799. 0
  154800. };
  154801. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154802. if(vi && vi->codec_setup){
  154803. vi->version=0;
  154804. vi->channels=ch;
  154805. vi->rate=rate;
  154806. return(0);
  154807. }
  154808. return(OV_EINVAL);
  154809. }
  154810. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154811. static_codebook ***books,
  154812. vorbis_info_floor1 *in,
  154813. int *x){
  154814. int i,k,is=s;
  154815. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154816. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154817. memcpy(f,in+x[is],sizeof(*f));
  154818. /* fill in the lowpass field, even if it's temporary */
  154819. f->n=ci->blocksizes[block]>>1;
  154820. /* books */
  154821. {
  154822. int partitions=f->partitions;
  154823. int maxclass=-1;
  154824. int maxbook=-1;
  154825. for(i=0;i<partitions;i++)
  154826. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154827. for(i=0;i<=maxclass;i++){
  154828. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154829. f->class_book[i]+=ci->books;
  154830. for(k=0;k<(1<<f->class_subs[i]);k++){
  154831. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154832. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154833. }
  154834. }
  154835. for(i=0;i<=maxbook;i++)
  154836. ci->book_param[ci->books++]=books[x[is]][i];
  154837. }
  154838. /* for now, we're only using floor 1 */
  154839. ci->floor_type[ci->floors]=1;
  154840. ci->floor_param[ci->floors]=f;
  154841. ci->floors++;
  154842. return;
  154843. }
  154844. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154845. vorbis_info_psy_global *in,
  154846. double *x){
  154847. int i,is=s;
  154848. double ds=s-is;
  154849. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154850. vorbis_info_psy_global *g=&ci->psy_g_param;
  154851. memcpy(g,in+(int)x[is],sizeof(*g));
  154852. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154853. is=(int)ds;
  154854. ds-=is;
  154855. if(ds==0 && is>0){
  154856. is--;
  154857. ds=1.;
  154858. }
  154859. /* interpolate the trigger threshholds */
  154860. for(i=0;i<4;i++){
  154861. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154862. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154863. }
  154864. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154865. return;
  154866. }
  154867. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154868. highlevel_encode_setup *hi,
  154869. adj_stereo *p){
  154870. float s=hi->stereo_point_setting;
  154871. int i,is=s;
  154872. double ds=s-is;
  154873. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154874. vorbis_info_psy_global *g=&ci->psy_g_param;
  154875. if(p){
  154876. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154877. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154878. if(hi->managed){
  154879. /* interpolate the kHz threshholds */
  154880. for(i=0;i<PACKETBLOBS;i++){
  154881. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154882. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154883. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154884. g->coupling_pkHz[i]=kHz;
  154885. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154886. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154887. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154888. }
  154889. }else{
  154890. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154891. for(i=0;i<PACKETBLOBS;i++){
  154892. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154893. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154894. g->coupling_pkHz[i]=kHz;
  154895. }
  154896. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154897. for(i=0;i<PACKETBLOBS;i++){
  154898. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154899. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154900. }
  154901. }
  154902. }else{
  154903. for(i=0;i<PACKETBLOBS;i++){
  154904. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154905. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154906. }
  154907. }
  154908. return;
  154909. }
  154910. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154911. int *nn_start,
  154912. int *nn_partition,
  154913. double *nn_thresh,
  154914. int block){
  154915. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154916. vorbis_info_psy *p=ci->psy_param[block];
  154917. highlevel_encode_setup *hi=&ci->hi;
  154918. int is=s;
  154919. if(block>=ci->psys)
  154920. ci->psys=block+1;
  154921. if(!p){
  154922. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154923. ci->psy_param[block]=p;
  154924. }
  154925. memcpy(p,&_psy_info_template,sizeof(*p));
  154926. p->blockflag=block>>1;
  154927. if(hi->noise_normalize_p){
  154928. p->normal_channel_p=1;
  154929. p->normal_point_p=1;
  154930. p->normal_start=nn_start[is];
  154931. p->normal_partition=nn_partition[is];
  154932. p->normal_thresh=nn_thresh[is];
  154933. }
  154934. return;
  154935. }
  154936. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154937. att3 *att,
  154938. int *max,
  154939. vp_adjblock *in){
  154940. int i,is=s;
  154941. double ds=s-is;
  154942. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154943. vorbis_info_psy *p=ci->psy_param[block];
  154944. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154945. filling the values in here */
  154946. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154947. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154948. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154949. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154950. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154951. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154952. for(i=0;i<P_BANDS;i++)
  154953. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154954. return;
  154955. }
  154956. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154957. compandblock *in, double *x){
  154958. int i,is=s;
  154959. double ds=s-is;
  154960. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154961. vorbis_info_psy *p=ci->psy_param[block];
  154962. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154963. is=(int)ds;
  154964. ds-=is;
  154965. if(ds==0 && is>0){
  154966. is--;
  154967. ds=1.;
  154968. }
  154969. /* interpolate the compander settings */
  154970. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154971. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154972. return;
  154973. }
  154974. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154975. int *suppress){
  154976. int is=s;
  154977. double ds=s-is;
  154978. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154979. vorbis_info_psy *p=ci->psy_param[block];
  154980. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154981. return;
  154982. }
  154983. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154984. int *suppress,
  154985. noise3 *in,
  154986. noiseguard *guard,
  154987. double userbias){
  154988. int i,is=s,j;
  154989. double ds=s-is;
  154990. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154991. vorbis_info_psy *p=ci->psy_param[block];
  154992. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154993. p->noisewindowlomin=guard[block].lo;
  154994. p->noisewindowhimin=guard[block].hi;
  154995. p->noisewindowfixed=guard[block].fixed;
  154996. for(j=0;j<P_NOISECURVES;j++)
  154997. for(i=0;i<P_BANDS;i++)
  154998. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154999. /* impulse blocks may take a user specified bias to boost the
  155000. nominal/high noise encoding depth */
  155001. for(j=0;j<P_NOISECURVES;j++){
  155002. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  155003. for(i=0;i<P_BANDS;i++){
  155004. p->noiseoff[j][i]+=userbias;
  155005. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155006. }
  155007. }
  155008. return;
  155009. }
  155010. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155011. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155012. vorbis_info_psy *p=ci->psy_param[block];
  155013. p->ath_adjatt=ci->hi.ath_floating_dB;
  155014. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155015. return;
  155016. }
  155017. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155018. int i;
  155019. for(i=0;i<ci->books;i++)
  155020. if(ci->book_param[i]==book)return(i);
  155021. return(ci->books++);
  155022. }
  155023. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155024. int *shortb,int *longb){
  155025. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155026. int is=s;
  155027. int blockshort=shortb[is];
  155028. int blocklong=longb[is];
  155029. ci->blocksizes[0]=blockshort;
  155030. ci->blocksizes[1]=blocklong;
  155031. }
  155032. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155033. int number, int block,
  155034. vorbis_residue_template *res){
  155035. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155036. int i,n;
  155037. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155038. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155039. memcpy(r,res->res,sizeof(*r));
  155040. if(ci->residues<=number)ci->residues=number+1;
  155041. switch(ci->blocksizes[block]){
  155042. case 64:case 128:case 256:
  155043. r->grouping=16;
  155044. break;
  155045. default:
  155046. r->grouping=32;
  155047. break;
  155048. }
  155049. ci->residue_type[number]=res->res_type;
  155050. /* to be adjusted by lowpass/pointlimit later */
  155051. n=r->end=ci->blocksizes[block]>>1;
  155052. if(res->res_type==2)
  155053. n=r->end*=vi->channels;
  155054. /* fill in all the books */
  155055. {
  155056. int booklist=0,k;
  155057. if(ci->hi.managed){
  155058. for(i=0;i<r->partitions;i++)
  155059. for(k=0;k<3;k++)
  155060. if(res->books_base_managed->books[i][k])
  155061. r->secondstages[i]|=(1<<k);
  155062. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155063. ci->book_param[r->groupbook]=res->book_aux_managed;
  155064. for(i=0;i<r->partitions;i++){
  155065. for(k=0;k<3;k++){
  155066. if(res->books_base_managed->books[i][k]){
  155067. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155068. r->booklist[booklist++]=bookid;
  155069. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155070. }
  155071. }
  155072. }
  155073. }else{
  155074. for(i=0;i<r->partitions;i++)
  155075. for(k=0;k<3;k++)
  155076. if(res->books_base->books[i][k])
  155077. r->secondstages[i]|=(1<<k);
  155078. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155079. ci->book_param[r->groupbook]=res->book_aux;
  155080. for(i=0;i<r->partitions;i++){
  155081. for(k=0;k<3;k++){
  155082. if(res->books_base->books[i][k]){
  155083. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155084. r->booklist[booklist++]=bookid;
  155085. ci->book_param[bookid]=res->books_base->books[i][k];
  155086. }
  155087. }
  155088. }
  155089. }
  155090. }
  155091. /* lowpass setup/pointlimit */
  155092. {
  155093. double freq=ci->hi.lowpass_kHz*1000.;
  155094. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155095. double nyq=vi->rate/2.;
  155096. long blocksize=ci->blocksizes[block]>>1;
  155097. /* lowpass needs to be set in the floor and the residue. */
  155098. if(freq>nyq)freq=nyq;
  155099. /* in the floor, the granularity can be very fine; it doesn't alter
  155100. the encoding structure, only the samples used to fit the floor
  155101. approximation */
  155102. f->n=freq/nyq*blocksize;
  155103. /* this res may by limited by the maximum pointlimit of the mode,
  155104. not the lowpass. the floor is always lowpass limited. */
  155105. if(res->limit_type){
  155106. if(ci->hi.managed)
  155107. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155108. else
  155109. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155110. if(freq>nyq)freq=nyq;
  155111. }
  155112. /* in the residue, we're constrained, physically, by partition
  155113. boundaries. We still lowpass 'wherever', but we have to round up
  155114. here to next boundary, or the vorbis spec will round it *down* to
  155115. previous boundary in encode/decode */
  155116. if(ci->residue_type[block]==2)
  155117. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155118. r->grouping;
  155119. else
  155120. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155121. r->grouping;
  155122. }
  155123. }
  155124. /* we assume two maps in this encoder */
  155125. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155126. vorbis_mapping_template *maps){
  155127. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155128. int i,j,is=s,modes=2;
  155129. vorbis_info_mapping0 *map=maps[is].map;
  155130. vorbis_info_mode *mode=_mode_template;
  155131. vorbis_residue_template *res=maps[is].res;
  155132. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155133. for(i=0;i<modes;i++){
  155134. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155135. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155136. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155137. if(i>=ci->modes)ci->modes=i+1;
  155138. ci->map_type[i]=0;
  155139. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155140. if(i>=ci->maps)ci->maps=i+1;
  155141. for(j=0;j<map[i].submaps;j++)
  155142. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155143. ,res+map[i].residuesubmap[j]);
  155144. }
  155145. }
  155146. static double setting_to_approx_bitrate(vorbis_info *vi){
  155147. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155148. highlevel_encode_setup *hi=&ci->hi;
  155149. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155150. int is=hi->base_setting;
  155151. double ds=hi->base_setting-is;
  155152. int ch=vi->channels;
  155153. double *r=setup->rate_mapping;
  155154. if(r==NULL)
  155155. return(-1);
  155156. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155157. }
  155158. static void get_setup_template(vorbis_info *vi,
  155159. long ch,long srate,
  155160. double req,int q_or_bitrate){
  155161. int i=0,j;
  155162. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155163. highlevel_encode_setup *hi=&ci->hi;
  155164. if(q_or_bitrate)req/=ch;
  155165. while(setup_list[i]){
  155166. if(setup_list[i]->coupling_restriction==-1 ||
  155167. setup_list[i]->coupling_restriction==ch){
  155168. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155169. srate<=setup_list[i]->samplerate_max_restriction){
  155170. int mappings=setup_list[i]->mappings;
  155171. double *map=(q_or_bitrate?
  155172. setup_list[i]->rate_mapping:
  155173. setup_list[i]->quality_mapping);
  155174. /* the template matches. Does the requested quality mode
  155175. fall within this template's modes? */
  155176. if(req<map[0]){++i;continue;}
  155177. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155178. for(j=0;j<mappings;j++)
  155179. if(req>=map[j] && req<map[j+1])break;
  155180. /* an all-points match */
  155181. hi->setup=setup_list[i];
  155182. if(j==mappings)
  155183. hi->base_setting=j-.001;
  155184. else{
  155185. float low=map[j];
  155186. float high=map[j+1];
  155187. float del=(req-low)/(high-low);
  155188. hi->base_setting=j+del;
  155189. }
  155190. return;
  155191. }
  155192. }
  155193. i++;
  155194. }
  155195. hi->setup=NULL;
  155196. }
  155197. /* encoders will need to use vorbis_info_init beforehand and call
  155198. vorbis_info clear when all done */
  155199. /* two interfaces; this, more detailed one, and later a convenience
  155200. layer on top */
  155201. /* the final setup call */
  155202. int vorbis_encode_setup_init(vorbis_info *vi){
  155203. int i0=0,singleblock=0;
  155204. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155205. ve_setup_data_template *setup=NULL;
  155206. highlevel_encode_setup *hi=&ci->hi;
  155207. if(ci==NULL)return(OV_EINVAL);
  155208. if(!hi->impulse_block_p)i0=1;
  155209. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155210. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155211. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155212. /* again, bound this to avoid the app shooting itself int he foot
  155213. too badly */
  155214. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155215. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155216. /* get the appropriate setup template; matches the fetch in previous
  155217. stages */
  155218. setup=(ve_setup_data_template *)hi->setup;
  155219. if(setup==NULL)return(OV_EINVAL);
  155220. hi->set_in_stone=1;
  155221. /* choose block sizes from configured sizes as well as paying
  155222. attention to long_block_p and short_block_p. If the configured
  155223. short and long blocks are the same length, we set long_block_p
  155224. and unset short_block_p */
  155225. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155226. setup->blocksize_short,
  155227. setup->blocksize_long);
  155228. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155229. /* floor setup; choose proper floor params. Allocated on the floor
  155230. stack in order; if we alloc only long floor, it's 0 */
  155231. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155232. setup->floor_books,
  155233. setup->floor_params,
  155234. setup->floor_short_mapping);
  155235. if(!singleblock)
  155236. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155237. setup->floor_books,
  155238. setup->floor_params,
  155239. setup->floor_long_mapping);
  155240. /* setup of [mostly] short block detection and stereo*/
  155241. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155242. setup->global_params,
  155243. setup->global_mapping);
  155244. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155245. /* basic psych setup and noise normalization */
  155246. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155247. setup->psy_noise_normal_start[0],
  155248. setup->psy_noise_normal_partition[0],
  155249. setup->psy_noise_normal_thresh,
  155250. 0);
  155251. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155252. setup->psy_noise_normal_start[0],
  155253. setup->psy_noise_normal_partition[0],
  155254. setup->psy_noise_normal_thresh,
  155255. 1);
  155256. if(!singleblock){
  155257. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155258. setup->psy_noise_normal_start[1],
  155259. setup->psy_noise_normal_partition[1],
  155260. setup->psy_noise_normal_thresh,
  155261. 2);
  155262. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155263. setup->psy_noise_normal_start[1],
  155264. setup->psy_noise_normal_partition[1],
  155265. setup->psy_noise_normal_thresh,
  155266. 3);
  155267. }
  155268. /* tone masking setup */
  155269. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155270. setup->psy_tone_masteratt,
  155271. setup->psy_tone_0dB,
  155272. setup->psy_tone_adj_impulse);
  155273. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155274. setup->psy_tone_masteratt,
  155275. setup->psy_tone_0dB,
  155276. setup->psy_tone_adj_other);
  155277. if(!singleblock){
  155278. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155279. setup->psy_tone_masteratt,
  155280. setup->psy_tone_0dB,
  155281. setup->psy_tone_adj_other);
  155282. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155283. setup->psy_tone_masteratt,
  155284. setup->psy_tone_0dB,
  155285. setup->psy_tone_adj_long);
  155286. }
  155287. /* noise companding setup */
  155288. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155289. setup->psy_noise_compand,
  155290. setup->psy_noise_compand_short_mapping);
  155291. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155292. setup->psy_noise_compand,
  155293. setup->psy_noise_compand_short_mapping);
  155294. if(!singleblock){
  155295. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155296. setup->psy_noise_compand,
  155297. setup->psy_noise_compand_long_mapping);
  155298. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155299. setup->psy_noise_compand,
  155300. setup->psy_noise_compand_long_mapping);
  155301. }
  155302. /* peak guarding setup */
  155303. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155304. setup->psy_tone_dBsuppress);
  155305. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155306. setup->psy_tone_dBsuppress);
  155307. if(!singleblock){
  155308. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155309. setup->psy_tone_dBsuppress);
  155310. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155311. setup->psy_tone_dBsuppress);
  155312. }
  155313. /* noise bias setup */
  155314. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155315. setup->psy_noise_dBsuppress,
  155316. setup->psy_noise_bias_impulse,
  155317. setup->psy_noiseguards,
  155318. (i0==0?hi->impulse_noisetune:0.));
  155319. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155320. setup->psy_noise_dBsuppress,
  155321. setup->psy_noise_bias_padding,
  155322. setup->psy_noiseguards,0.);
  155323. if(!singleblock){
  155324. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155325. setup->psy_noise_dBsuppress,
  155326. setup->psy_noise_bias_trans,
  155327. setup->psy_noiseguards,0.);
  155328. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155329. setup->psy_noise_dBsuppress,
  155330. setup->psy_noise_bias_long,
  155331. setup->psy_noiseguards,0.);
  155332. }
  155333. vorbis_encode_ath_setup(vi,0);
  155334. vorbis_encode_ath_setup(vi,1);
  155335. if(!singleblock){
  155336. vorbis_encode_ath_setup(vi,2);
  155337. vorbis_encode_ath_setup(vi,3);
  155338. }
  155339. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155340. /* set bitrate readonlies and management */
  155341. if(hi->bitrate_av>0)
  155342. vi->bitrate_nominal=hi->bitrate_av;
  155343. else{
  155344. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155345. }
  155346. vi->bitrate_lower=hi->bitrate_min;
  155347. vi->bitrate_upper=hi->bitrate_max;
  155348. if(hi->bitrate_av)
  155349. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155350. else
  155351. vi->bitrate_window=0.;
  155352. if(hi->managed){
  155353. ci->bi.avg_rate=hi->bitrate_av;
  155354. ci->bi.min_rate=hi->bitrate_min;
  155355. ci->bi.max_rate=hi->bitrate_max;
  155356. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155357. ci->bi.reservoir_bias=
  155358. hi->bitrate_reservoir_bias;
  155359. ci->bi.slew_damp=hi->bitrate_av_damp;
  155360. }
  155361. return(0);
  155362. }
  155363. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155364. long channels,
  155365. long rate){
  155366. int ret=0,i,is;
  155367. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155368. highlevel_encode_setup *hi=&ci->hi;
  155369. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155370. double ds;
  155371. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155372. if(ret)return(ret);
  155373. is=hi->base_setting;
  155374. ds=hi->base_setting-is;
  155375. hi->short_setting=hi->base_setting;
  155376. hi->long_setting=hi->base_setting;
  155377. hi->managed=0;
  155378. hi->impulse_block_p=1;
  155379. hi->noise_normalize_p=1;
  155380. hi->stereo_point_setting=hi->base_setting;
  155381. hi->lowpass_kHz=
  155382. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155383. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155384. setup->psy_ath_float[is+1]*ds;
  155385. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155386. setup->psy_ath_abs[is+1]*ds;
  155387. hi->amplitude_track_dBpersec=-6.;
  155388. hi->trigger_setting=hi->base_setting;
  155389. for(i=0;i<4;i++){
  155390. hi->block[i].tone_mask_setting=hi->base_setting;
  155391. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155392. hi->block[i].noise_bias_setting=hi->base_setting;
  155393. hi->block[i].noise_compand_setting=hi->base_setting;
  155394. }
  155395. return(ret);
  155396. }
  155397. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155398. long channels,
  155399. long rate,
  155400. float quality){
  155401. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155402. highlevel_encode_setup *hi=&ci->hi;
  155403. quality+=.0000001;
  155404. if(quality>=1.)quality=.9999;
  155405. get_setup_template(vi,channels,rate,quality,0);
  155406. if(!hi->setup)return OV_EIMPL;
  155407. return vorbis_encode_setup_setting(vi,channels,rate);
  155408. }
  155409. int vorbis_encode_init_vbr(vorbis_info *vi,
  155410. long channels,
  155411. long rate,
  155412. float base_quality /* 0. to 1. */
  155413. ){
  155414. int ret=0;
  155415. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155416. if(ret){
  155417. vorbis_info_clear(vi);
  155418. return ret;
  155419. }
  155420. ret=vorbis_encode_setup_init(vi);
  155421. if(ret)
  155422. vorbis_info_clear(vi);
  155423. return(ret);
  155424. }
  155425. int vorbis_encode_setup_managed(vorbis_info *vi,
  155426. long channels,
  155427. long rate,
  155428. long max_bitrate,
  155429. long nominal_bitrate,
  155430. long min_bitrate){
  155431. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155432. highlevel_encode_setup *hi=&ci->hi;
  155433. double tnominal=nominal_bitrate;
  155434. int ret=0;
  155435. if(nominal_bitrate<=0.){
  155436. if(max_bitrate>0.){
  155437. if(min_bitrate>0.)
  155438. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155439. else
  155440. nominal_bitrate=max_bitrate*.875;
  155441. }else{
  155442. if(min_bitrate>0.){
  155443. nominal_bitrate=min_bitrate;
  155444. }else{
  155445. return(OV_EINVAL);
  155446. }
  155447. }
  155448. }
  155449. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155450. if(!hi->setup)return OV_EIMPL;
  155451. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155452. if(ret){
  155453. vorbis_info_clear(vi);
  155454. return ret;
  155455. }
  155456. /* initialize management with sane defaults */
  155457. hi->managed=1;
  155458. hi->bitrate_min=min_bitrate;
  155459. hi->bitrate_max=max_bitrate;
  155460. hi->bitrate_av=tnominal;
  155461. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155462. hi->bitrate_reservoir=nominal_bitrate*2;
  155463. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155464. return(ret);
  155465. }
  155466. int vorbis_encode_init(vorbis_info *vi,
  155467. long channels,
  155468. long rate,
  155469. long max_bitrate,
  155470. long nominal_bitrate,
  155471. long min_bitrate){
  155472. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155473. max_bitrate,
  155474. nominal_bitrate,
  155475. min_bitrate);
  155476. if(ret){
  155477. vorbis_info_clear(vi);
  155478. return(ret);
  155479. }
  155480. ret=vorbis_encode_setup_init(vi);
  155481. if(ret)
  155482. vorbis_info_clear(vi);
  155483. return(ret);
  155484. }
  155485. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155486. if(vi){
  155487. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155488. highlevel_encode_setup *hi=&ci->hi;
  155489. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155490. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155491. switch(number){
  155492. /* now deprecated *****************/
  155493. case OV_ECTL_RATEMANAGE_GET:
  155494. {
  155495. struct ovectl_ratemanage_arg *ai=
  155496. (struct ovectl_ratemanage_arg *)arg;
  155497. ai->management_active=hi->managed;
  155498. ai->bitrate_hard_window=ai->bitrate_av_window=
  155499. (double)hi->bitrate_reservoir/vi->rate;
  155500. ai->bitrate_av_window_center=1.;
  155501. ai->bitrate_hard_min=hi->bitrate_min;
  155502. ai->bitrate_hard_max=hi->bitrate_max;
  155503. ai->bitrate_av_lo=hi->bitrate_av;
  155504. ai->bitrate_av_hi=hi->bitrate_av;
  155505. }
  155506. return(0);
  155507. /* now deprecated *****************/
  155508. case OV_ECTL_RATEMANAGE_SET:
  155509. {
  155510. struct ovectl_ratemanage_arg *ai=
  155511. (struct ovectl_ratemanage_arg *)arg;
  155512. if(ai==NULL){
  155513. hi->managed=0;
  155514. }else{
  155515. hi->managed=ai->management_active;
  155516. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155517. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155518. }
  155519. }
  155520. return 0;
  155521. /* now deprecated *****************/
  155522. case OV_ECTL_RATEMANAGE_AVG:
  155523. {
  155524. struct ovectl_ratemanage_arg *ai=
  155525. (struct ovectl_ratemanage_arg *)arg;
  155526. if(ai==NULL){
  155527. hi->bitrate_av=0;
  155528. }else{
  155529. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155530. }
  155531. }
  155532. return(0);
  155533. /* now deprecated *****************/
  155534. case OV_ECTL_RATEMANAGE_HARD:
  155535. {
  155536. struct ovectl_ratemanage_arg *ai=
  155537. (struct ovectl_ratemanage_arg *)arg;
  155538. if(ai==NULL){
  155539. hi->bitrate_min=0;
  155540. hi->bitrate_max=0;
  155541. }else{
  155542. hi->bitrate_min=ai->bitrate_hard_min;
  155543. hi->bitrate_max=ai->bitrate_hard_max;
  155544. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155545. (hi->bitrate_max+hi->bitrate_min)*.5;
  155546. }
  155547. if(hi->bitrate_reservoir<128.)
  155548. hi->bitrate_reservoir=128.;
  155549. }
  155550. return(0);
  155551. /* replacement ratemanage interface */
  155552. case OV_ECTL_RATEMANAGE2_GET:
  155553. {
  155554. struct ovectl_ratemanage2_arg *ai=
  155555. (struct ovectl_ratemanage2_arg *)arg;
  155556. if(ai==NULL)return OV_EINVAL;
  155557. ai->management_active=hi->managed;
  155558. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155559. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155560. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155561. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155562. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155563. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155564. }
  155565. return (0);
  155566. case OV_ECTL_RATEMANAGE2_SET:
  155567. {
  155568. struct ovectl_ratemanage2_arg *ai=
  155569. (struct ovectl_ratemanage2_arg *)arg;
  155570. if(ai==NULL){
  155571. hi->managed=0;
  155572. }else{
  155573. /* sanity check; only catch invariant violations */
  155574. if(ai->bitrate_limit_min_kbps>0 &&
  155575. ai->bitrate_average_kbps>0 &&
  155576. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155577. return OV_EINVAL;
  155578. if(ai->bitrate_limit_max_kbps>0 &&
  155579. ai->bitrate_average_kbps>0 &&
  155580. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155581. return OV_EINVAL;
  155582. if(ai->bitrate_limit_min_kbps>0 &&
  155583. ai->bitrate_limit_max_kbps>0 &&
  155584. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155585. return OV_EINVAL;
  155586. if(ai->bitrate_average_damping <= 0.)
  155587. return OV_EINVAL;
  155588. if(ai->bitrate_limit_reservoir_bits < 0)
  155589. return OV_EINVAL;
  155590. if(ai->bitrate_limit_reservoir_bias < 0.)
  155591. return OV_EINVAL;
  155592. if(ai->bitrate_limit_reservoir_bias > 1.)
  155593. return OV_EINVAL;
  155594. hi->managed=ai->management_active;
  155595. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155596. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155597. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155598. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155599. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155600. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155601. }
  155602. }
  155603. return 0;
  155604. case OV_ECTL_LOWPASS_GET:
  155605. {
  155606. double *farg=(double *)arg;
  155607. *farg=hi->lowpass_kHz;
  155608. }
  155609. return(0);
  155610. case OV_ECTL_LOWPASS_SET:
  155611. {
  155612. double *farg=(double *)arg;
  155613. hi->lowpass_kHz=*farg;
  155614. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155615. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155616. }
  155617. return(0);
  155618. case OV_ECTL_IBLOCK_GET:
  155619. {
  155620. double *farg=(double *)arg;
  155621. *farg=hi->impulse_noisetune;
  155622. }
  155623. return(0);
  155624. case OV_ECTL_IBLOCK_SET:
  155625. {
  155626. double *farg=(double *)arg;
  155627. hi->impulse_noisetune=*farg;
  155628. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155629. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155630. }
  155631. return(0);
  155632. }
  155633. return(OV_EIMPL);
  155634. }
  155635. return(OV_EINVAL);
  155636. }
  155637. #endif
  155638. /*** End of inlined file: vorbisenc.c ***/
  155639. /*** Start of inlined file: vorbisfile.c ***/
  155640. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155641. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155642. // tasks..
  155643. #if JUCE_MSVC
  155644. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155645. #endif
  155646. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155647. #if JUCE_USE_OGGVORBIS
  155648. #include <stdlib.h>
  155649. #include <stdio.h>
  155650. #include <errno.h>
  155651. #include <string.h>
  155652. #include <math.h>
  155653. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155654. one logical bitstream arranged end to end (the only form of Ogg
  155655. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155656. multiplexing] is not allowed in Vorbis) */
  155657. /* A Vorbis file can be played beginning to end (streamed) without
  155658. worrying ahead of time about chaining (see decoder_example.c). If
  155659. we have the whole file, however, and want random access
  155660. (seeking/scrubbing) or desire to know the total length/time of a
  155661. file, we need to account for the possibility of chaining. */
  155662. /* We can handle things a number of ways; we can determine the entire
  155663. bitstream structure right off the bat, or find pieces on demand.
  155664. This example determines and caches structure for the entire
  155665. bitstream, but builds a virtual decoder on the fly when moving
  155666. between links in the chain. */
  155667. /* There are also different ways to implement seeking. Enough
  155668. information exists in an Ogg bitstream to seek to
  155669. sample-granularity positions in the output. Or, one can seek by
  155670. picking some portion of the stream roughly in the desired area if
  155671. we only want coarse navigation through the stream. */
  155672. /*************************************************************************
  155673. * Many, many internal helpers. The intention is not to be confusing;
  155674. * rampant duplication and monolithic function implementation would be
  155675. * harder to understand anyway. The high level functions are last. Begin
  155676. * grokking near the end of the file */
  155677. /* read a little more data from the file/pipe into the ogg_sync framer
  155678. */
  155679. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155680. over 8k gets what they deserve */
  155681. static long _get_data(OggVorbis_File *vf){
  155682. errno=0;
  155683. if(vf->datasource){
  155684. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155685. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155686. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155687. if(bytes==0 && errno)return(-1);
  155688. return(bytes);
  155689. }else
  155690. return(0);
  155691. }
  155692. /* save a tiny smidge of verbosity to make the code more readable */
  155693. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155694. if(vf->datasource){
  155695. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155696. vf->offset=offset;
  155697. ogg_sync_reset(&vf->oy);
  155698. }else{
  155699. /* shouldn't happen unless someone writes a broken callback */
  155700. return;
  155701. }
  155702. }
  155703. /* The read/seek functions track absolute position within the stream */
  155704. /* from the head of the stream, get the next page. boundary specifies
  155705. if the function is allowed to fetch more data from the stream (and
  155706. how much) or only use internally buffered data.
  155707. boundary: -1) unbounded search
  155708. 0) read no additional data; use cached only
  155709. n) search for a new page beginning for n bytes
  155710. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155711. n) found a page at absolute offset n */
  155712. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155713. ogg_int64_t boundary){
  155714. if(boundary>0)boundary+=vf->offset;
  155715. while(1){
  155716. long more;
  155717. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155718. more=ogg_sync_pageseek(&vf->oy,og);
  155719. if(more<0){
  155720. /* skipped n bytes */
  155721. vf->offset-=more;
  155722. }else{
  155723. if(more==0){
  155724. /* send more paramedics */
  155725. if(!boundary)return(OV_FALSE);
  155726. {
  155727. long ret=_get_data(vf);
  155728. if(ret==0)return(OV_EOF);
  155729. if(ret<0)return(OV_EREAD);
  155730. }
  155731. }else{
  155732. /* got a page. Return the offset at the page beginning,
  155733. advance the internal offset past the page end */
  155734. ogg_int64_t ret=vf->offset;
  155735. vf->offset+=more;
  155736. return(ret);
  155737. }
  155738. }
  155739. }
  155740. }
  155741. /* find the latest page beginning before the current stream cursor
  155742. position. Much dirtier than the above as Ogg doesn't have any
  155743. backward search linkage. no 'readp' as it will certainly have to
  155744. read. */
  155745. /* returns offset or OV_EREAD, OV_FAULT */
  155746. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155747. ogg_int64_t begin=vf->offset;
  155748. ogg_int64_t end=begin;
  155749. ogg_int64_t ret;
  155750. ogg_int64_t offset=-1;
  155751. while(offset==-1){
  155752. begin-=CHUNKSIZE;
  155753. if(begin<0)
  155754. begin=0;
  155755. _seek_helper(vf,begin);
  155756. while(vf->offset<end){
  155757. ret=_get_next_page(vf,og,end-vf->offset);
  155758. if(ret==OV_EREAD)return(OV_EREAD);
  155759. if(ret<0){
  155760. break;
  155761. }else{
  155762. offset=ret;
  155763. }
  155764. }
  155765. }
  155766. /* we have the offset. Actually snork and hold the page now */
  155767. _seek_helper(vf,offset);
  155768. ret=_get_next_page(vf,og,CHUNKSIZE);
  155769. if(ret<0)
  155770. /* this shouldn't be possible */
  155771. return(OV_EFAULT);
  155772. return(offset);
  155773. }
  155774. /* finds each bitstream link one at a time using a bisection search
  155775. (has to begin by knowing the offset of the lb's initial page).
  155776. Recurses for each link so it can alloc the link storage after
  155777. finding them all, then unroll and fill the cache at the same time */
  155778. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155779. ogg_int64_t begin,
  155780. ogg_int64_t searched,
  155781. ogg_int64_t end,
  155782. long currentno,
  155783. long m){
  155784. ogg_int64_t endsearched=end;
  155785. ogg_int64_t next=end;
  155786. ogg_page og;
  155787. ogg_int64_t ret;
  155788. /* the below guards against garbage seperating the last and
  155789. first pages of two links. */
  155790. while(searched<endsearched){
  155791. ogg_int64_t bisect;
  155792. if(endsearched-searched<CHUNKSIZE){
  155793. bisect=searched;
  155794. }else{
  155795. bisect=(searched+endsearched)/2;
  155796. }
  155797. _seek_helper(vf,bisect);
  155798. ret=_get_next_page(vf,&og,-1);
  155799. if(ret==OV_EREAD)return(OV_EREAD);
  155800. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155801. endsearched=bisect;
  155802. if(ret>=0)next=ret;
  155803. }else{
  155804. searched=ret+og.header_len+og.body_len;
  155805. }
  155806. }
  155807. _seek_helper(vf,next);
  155808. ret=_get_next_page(vf,&og,-1);
  155809. if(ret==OV_EREAD)return(OV_EREAD);
  155810. if(searched>=end || ret<0){
  155811. vf->links=m+1;
  155812. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155813. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155814. vf->offsets[m+1]=searched;
  155815. }else{
  155816. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155817. end,ogg_page_serialno(&og),m+1);
  155818. if(ret==OV_EREAD)return(OV_EREAD);
  155819. }
  155820. vf->offsets[m]=begin;
  155821. vf->serialnos[m]=currentno;
  155822. return(0);
  155823. }
  155824. /* uses the local ogg_stream storage in vf; this is important for
  155825. non-streaming input sources */
  155826. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155827. long *serialno,ogg_page *og_ptr){
  155828. ogg_page og;
  155829. ogg_packet op;
  155830. int i,ret;
  155831. if(!og_ptr){
  155832. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155833. if(llret==OV_EREAD)return(OV_EREAD);
  155834. if(llret<0)return OV_ENOTVORBIS;
  155835. og_ptr=&og;
  155836. }
  155837. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155838. if(serialno)*serialno=vf->os.serialno;
  155839. vf->ready_state=STREAMSET;
  155840. /* extract the initial header from the first page and verify that the
  155841. Ogg bitstream is in fact Vorbis data */
  155842. vorbis_info_init(vi);
  155843. vorbis_comment_init(vc);
  155844. i=0;
  155845. while(i<3){
  155846. ogg_stream_pagein(&vf->os,og_ptr);
  155847. while(i<3){
  155848. int result=ogg_stream_packetout(&vf->os,&op);
  155849. if(result==0)break;
  155850. if(result==-1){
  155851. ret=OV_EBADHEADER;
  155852. goto bail_header;
  155853. }
  155854. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155855. goto bail_header;
  155856. }
  155857. i++;
  155858. }
  155859. if(i<3)
  155860. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155861. ret=OV_EBADHEADER;
  155862. goto bail_header;
  155863. }
  155864. }
  155865. return 0;
  155866. bail_header:
  155867. vorbis_info_clear(vi);
  155868. vorbis_comment_clear(vc);
  155869. vf->ready_state=OPENED;
  155870. return ret;
  155871. }
  155872. /* last step of the OggVorbis_File initialization; get all the
  155873. vorbis_info structs and PCM positions. Only called by the seekable
  155874. initialization (local stream storage is hacked slightly; pay
  155875. attention to how that's done) */
  155876. /* this is void and does not propogate errors up because we want to be
  155877. able to open and use damaged bitstreams as well as we can. Just
  155878. watch out for missing information for links in the OggVorbis_File
  155879. struct */
  155880. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155881. ogg_page og;
  155882. int i;
  155883. ogg_int64_t ret;
  155884. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155885. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155886. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155887. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155888. for(i=0;i<vf->links;i++){
  155889. if(i==0){
  155890. /* we already grabbed the initial header earlier. Just set the offset */
  155891. vf->dataoffsets[i]=dataoffset;
  155892. _seek_helper(vf,dataoffset);
  155893. }else{
  155894. /* seek to the location of the initial header */
  155895. _seek_helper(vf,vf->offsets[i]);
  155896. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155897. vf->dataoffsets[i]=-1;
  155898. }else{
  155899. vf->dataoffsets[i]=vf->offset;
  155900. }
  155901. }
  155902. /* fetch beginning PCM offset */
  155903. if(vf->dataoffsets[i]!=-1){
  155904. ogg_int64_t accumulated=0;
  155905. long lastblock=-1;
  155906. int result;
  155907. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155908. while(1){
  155909. ogg_packet op;
  155910. ret=_get_next_page(vf,&og,-1);
  155911. if(ret<0)
  155912. /* this should not be possible unless the file is
  155913. truncated/mangled */
  155914. break;
  155915. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155916. break;
  155917. /* count blocksizes of all frames in the page */
  155918. ogg_stream_pagein(&vf->os,&og);
  155919. while((result=ogg_stream_packetout(&vf->os,&op))){
  155920. if(result>0){ /* ignore holes */
  155921. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155922. if(lastblock!=-1)
  155923. accumulated+=(lastblock+thisblock)>>2;
  155924. lastblock=thisblock;
  155925. }
  155926. }
  155927. if(ogg_page_granulepos(&og)!=-1){
  155928. /* pcm offset of last packet on the first audio page */
  155929. accumulated= ogg_page_granulepos(&og)-accumulated;
  155930. break;
  155931. }
  155932. }
  155933. /* less than zero? This is a stream with samples trimmed off
  155934. the beginning, a normal occurrence; set the offset to zero */
  155935. if(accumulated<0)accumulated=0;
  155936. vf->pcmlengths[i*2]=accumulated;
  155937. }
  155938. /* get the PCM length of this link. To do this,
  155939. get the last page of the stream */
  155940. {
  155941. ogg_int64_t end=vf->offsets[i+1];
  155942. _seek_helper(vf,end);
  155943. while(1){
  155944. ret=_get_prev_page(vf,&og);
  155945. if(ret<0){
  155946. /* this should not be possible */
  155947. vorbis_info_clear(vf->vi+i);
  155948. vorbis_comment_clear(vf->vc+i);
  155949. break;
  155950. }
  155951. if(ogg_page_granulepos(&og)!=-1){
  155952. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155953. break;
  155954. }
  155955. vf->offset=ret;
  155956. }
  155957. }
  155958. }
  155959. }
  155960. static int _make_decode_ready(OggVorbis_File *vf){
  155961. if(vf->ready_state>STREAMSET)return 0;
  155962. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155963. if(vf->seekable){
  155964. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155965. return OV_EBADLINK;
  155966. }else{
  155967. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155968. return OV_EBADLINK;
  155969. }
  155970. vorbis_block_init(&vf->vd,&vf->vb);
  155971. vf->ready_state=INITSET;
  155972. vf->bittrack=0.f;
  155973. vf->samptrack=0.f;
  155974. return 0;
  155975. }
  155976. static int _open_seekable2(OggVorbis_File *vf){
  155977. long serialno=vf->current_serialno;
  155978. ogg_int64_t dataoffset=vf->offset, end;
  155979. ogg_page og;
  155980. /* we're partially open and have a first link header state in
  155981. storage in vf */
  155982. /* we can seek, so set out learning all about this file */
  155983. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155984. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155985. /* We get the offset for the last page of the physical bitstream.
  155986. Most OggVorbis files will contain a single logical bitstream */
  155987. end=_get_prev_page(vf,&og);
  155988. if(end<0)return(end);
  155989. /* more than one logical bitstream? */
  155990. if(ogg_page_serialno(&og)!=serialno){
  155991. /* Chained bitstream. Bisect-search each logical bitstream
  155992. section. Do so based on serial number only */
  155993. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155994. }else{
  155995. /* Only one logical bitstream */
  155996. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155997. }
  155998. /* the initial header memory is referenced by vf after; don't free it */
  155999. _prefetch_all_headers(vf,dataoffset);
  156000. return(ov_raw_seek(vf,0));
  156001. }
  156002. /* clear out the current logical bitstream decoder */
  156003. static void _decode_clear(OggVorbis_File *vf){
  156004. vorbis_dsp_clear(&vf->vd);
  156005. vorbis_block_clear(&vf->vb);
  156006. vf->ready_state=OPENED;
  156007. }
  156008. /* fetch and process a packet. Handles the case where we're at a
  156009. bitstream boundary and dumps the decoding machine. If the decoding
  156010. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156011. date (seek and read both use this. seek uses a special hack with
  156012. readp).
  156013. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156014. 0) need more data (only if readp==0)
  156015. 1) got a packet
  156016. */
  156017. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156018. ogg_packet *op_in,
  156019. int readp,
  156020. int spanp){
  156021. ogg_page og;
  156022. /* handle one packet. Try to fetch it from current stream state */
  156023. /* extract packets from page */
  156024. while(1){
  156025. /* process a packet if we can. If the machine isn't loaded,
  156026. neither is a page */
  156027. if(vf->ready_state==INITSET){
  156028. while(1) {
  156029. ogg_packet op;
  156030. ogg_packet *op_ptr=(op_in?op_in:&op);
  156031. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156032. ogg_int64_t granulepos;
  156033. op_in=NULL;
  156034. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156035. if(result>0){
  156036. /* got a packet. process it */
  156037. granulepos=op_ptr->granulepos;
  156038. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156039. header handling. The
  156040. header packets aren't
  156041. audio, so if/when we
  156042. submit them,
  156043. vorbis_synthesis will
  156044. reject them */
  156045. /* suck in the synthesis data and track bitrate */
  156046. {
  156047. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156048. /* for proper use of libvorbis within libvorbisfile,
  156049. oldsamples will always be zero. */
  156050. if(oldsamples)return(OV_EFAULT);
  156051. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156052. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156053. vf->bittrack+=op_ptr->bytes*8;
  156054. }
  156055. /* update the pcm offset. */
  156056. if(granulepos!=-1 && !op_ptr->e_o_s){
  156057. int link=(vf->seekable?vf->current_link:0);
  156058. int i,samples;
  156059. /* this packet has a pcm_offset on it (the last packet
  156060. completed on a page carries the offset) After processing
  156061. (above), we know the pcm position of the *last* sample
  156062. ready to be returned. Find the offset of the *first*
  156063. As an aside, this trick is inaccurate if we begin
  156064. reading anew right at the last page; the end-of-stream
  156065. granulepos declares the last frame in the stream, and the
  156066. last packet of the last page may be a partial frame.
  156067. So, we need a previous granulepos from an in-sequence page
  156068. to have a reference point. Thus the !op_ptr->e_o_s clause
  156069. above */
  156070. if(vf->seekable && link>0)
  156071. granulepos-=vf->pcmlengths[link*2];
  156072. if(granulepos<0)granulepos=0; /* actually, this
  156073. shouldn't be possible
  156074. here unless the stream
  156075. is very broken */
  156076. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156077. granulepos-=samples;
  156078. for(i=0;i<link;i++)
  156079. granulepos+=vf->pcmlengths[i*2+1];
  156080. vf->pcm_offset=granulepos;
  156081. }
  156082. return(1);
  156083. }
  156084. }
  156085. else
  156086. break;
  156087. }
  156088. }
  156089. if(vf->ready_state>=OPENED){
  156090. ogg_int64_t ret;
  156091. if(!readp)return(0);
  156092. if((ret=_get_next_page(vf,&og,-1))<0){
  156093. return(OV_EOF); /* eof.
  156094. leave unitialized */
  156095. }
  156096. /* bitrate tracking; add the header's bytes here, the body bytes
  156097. are done by packet above */
  156098. vf->bittrack+=og.header_len*8;
  156099. /* has our decoding just traversed a bitstream boundary? */
  156100. if(vf->ready_state==INITSET){
  156101. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156102. if(!spanp)
  156103. return(OV_EOF);
  156104. _decode_clear(vf);
  156105. if(!vf->seekable){
  156106. vorbis_info_clear(vf->vi);
  156107. vorbis_comment_clear(vf->vc);
  156108. }
  156109. }
  156110. }
  156111. }
  156112. /* Do we need to load a new machine before submitting the page? */
  156113. /* This is different in the seekable and non-seekable cases.
  156114. In the seekable case, we already have all the header
  156115. information loaded and cached; we just initialize the machine
  156116. with it and continue on our merry way.
  156117. In the non-seekable (streaming) case, we'll only be at a
  156118. boundary if we just left the previous logical bitstream and
  156119. we're now nominally at the header of the next bitstream
  156120. */
  156121. if(vf->ready_state!=INITSET){
  156122. int link;
  156123. if(vf->ready_state<STREAMSET){
  156124. if(vf->seekable){
  156125. vf->current_serialno=ogg_page_serialno(&og);
  156126. /* match the serialno to bitstream section. We use this rather than
  156127. offset positions to avoid problems near logical bitstream
  156128. boundaries */
  156129. for(link=0;link<vf->links;link++)
  156130. if(vf->serialnos[link]==vf->current_serialno)break;
  156131. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156132. stream. error out,
  156133. leave machine
  156134. uninitialized */
  156135. vf->current_link=link;
  156136. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156137. vf->ready_state=STREAMSET;
  156138. }else{
  156139. /* we're streaming */
  156140. /* fetch the three header packets, build the info struct */
  156141. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156142. if(ret)return(ret);
  156143. vf->current_link++;
  156144. link=0;
  156145. }
  156146. }
  156147. {
  156148. int ret=_make_decode_ready(vf);
  156149. if(ret<0)return ret;
  156150. }
  156151. }
  156152. ogg_stream_pagein(&vf->os,&og);
  156153. }
  156154. }
  156155. /* if, eg, 64 bit stdio is configured by default, this will build with
  156156. fseek64 */
  156157. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156158. if(f==NULL)return(-1);
  156159. return fseek(f,off,whence);
  156160. }
  156161. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156162. long ibytes, ov_callbacks callbacks){
  156163. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156164. int ret;
  156165. memset(vf,0,sizeof(*vf));
  156166. vf->datasource=f;
  156167. vf->callbacks = callbacks;
  156168. /* init the framing state */
  156169. ogg_sync_init(&vf->oy);
  156170. /* perhaps some data was previously read into a buffer for testing
  156171. against other stream types. Allow initialization from this
  156172. previously read data (as we may be reading from a non-seekable
  156173. stream) */
  156174. if(initial){
  156175. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156176. memcpy(buffer,initial,ibytes);
  156177. ogg_sync_wrote(&vf->oy,ibytes);
  156178. }
  156179. /* can we seek? Stevens suggests the seek test was portable */
  156180. if(offsettest!=-1)vf->seekable=1;
  156181. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156182. entry for partial open */
  156183. vf->links=1;
  156184. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156185. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156186. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156187. /* Try to fetch the headers, maintaining all the storage */
  156188. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156189. vf->datasource=NULL;
  156190. ov_clear(vf);
  156191. }else
  156192. vf->ready_state=PARTOPEN;
  156193. return(ret);
  156194. }
  156195. static int _ov_open2(OggVorbis_File *vf){
  156196. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156197. vf->ready_state=OPENED;
  156198. if(vf->seekable){
  156199. int ret=_open_seekable2(vf);
  156200. if(ret){
  156201. vf->datasource=NULL;
  156202. ov_clear(vf);
  156203. }
  156204. return(ret);
  156205. }else
  156206. vf->ready_state=STREAMSET;
  156207. return 0;
  156208. }
  156209. /* clear out the OggVorbis_File struct */
  156210. int ov_clear(OggVorbis_File *vf){
  156211. if(vf){
  156212. vorbis_block_clear(&vf->vb);
  156213. vorbis_dsp_clear(&vf->vd);
  156214. ogg_stream_clear(&vf->os);
  156215. if(vf->vi && vf->links){
  156216. int i;
  156217. for(i=0;i<vf->links;i++){
  156218. vorbis_info_clear(vf->vi+i);
  156219. vorbis_comment_clear(vf->vc+i);
  156220. }
  156221. _ogg_free(vf->vi);
  156222. _ogg_free(vf->vc);
  156223. }
  156224. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156225. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156226. if(vf->serialnos)_ogg_free(vf->serialnos);
  156227. if(vf->offsets)_ogg_free(vf->offsets);
  156228. ogg_sync_clear(&vf->oy);
  156229. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156230. memset(vf,0,sizeof(*vf));
  156231. }
  156232. #ifdef DEBUG_LEAKS
  156233. _VDBG_dump();
  156234. #endif
  156235. return(0);
  156236. }
  156237. /* inspects the OggVorbis file and finds/documents all the logical
  156238. bitstreams contained in it. Tries to be tolerant of logical
  156239. bitstream sections that are truncated/woogie.
  156240. return: -1) error
  156241. 0) OK
  156242. */
  156243. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156244. ov_callbacks callbacks){
  156245. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156246. if(ret)return ret;
  156247. return _ov_open2(vf);
  156248. }
  156249. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156250. ov_callbacks callbacks = {
  156251. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156252. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156253. (int (*)(void *)) fclose,
  156254. (long (*)(void *)) ftell
  156255. };
  156256. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156257. }
  156258. /* cheap hack for game usage where downsampling is desirable; there's
  156259. no need for SRC as we can just do it cheaply in libvorbis. */
  156260. int ov_halfrate(OggVorbis_File *vf,int flag){
  156261. int i;
  156262. if(vf->vi==NULL)return OV_EINVAL;
  156263. if(!vf->seekable)return OV_EINVAL;
  156264. if(vf->ready_state>=STREAMSET)
  156265. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156266. will be able to swap this on the fly, but
  156267. for now dumping the decode machine is needed
  156268. to reinit the MDCT lookups. 1.1 libvorbis
  156269. is planned to be able to switch on the fly */
  156270. for(i=0;i<vf->links;i++){
  156271. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156272. ov_halfrate(vf,0);
  156273. return OV_EINVAL;
  156274. }
  156275. }
  156276. return 0;
  156277. }
  156278. int ov_halfrate_p(OggVorbis_File *vf){
  156279. if(vf->vi==NULL)return OV_EINVAL;
  156280. return vorbis_synthesis_halfrate_p(vf->vi);
  156281. }
  156282. /* Only partially open the vorbis file; test for Vorbisness, and load
  156283. the headers for the first chain. Do not seek (although test for
  156284. seekability). Use ov_test_open to finish opening the file, else
  156285. ov_clear to close/free it. Same return codes as open. */
  156286. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156287. ov_callbacks callbacks)
  156288. {
  156289. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156290. }
  156291. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156292. ov_callbacks callbacks = {
  156293. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156294. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156295. (int (*)(void *)) fclose,
  156296. (long (*)(void *)) ftell
  156297. };
  156298. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156299. }
  156300. int ov_test_open(OggVorbis_File *vf){
  156301. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156302. return _ov_open2(vf);
  156303. }
  156304. /* How many logical bitstreams in this physical bitstream? */
  156305. long ov_streams(OggVorbis_File *vf){
  156306. return vf->links;
  156307. }
  156308. /* Is the FILE * associated with vf seekable? */
  156309. long ov_seekable(OggVorbis_File *vf){
  156310. return vf->seekable;
  156311. }
  156312. /* returns the bitrate for a given logical bitstream or the entire
  156313. physical bitstream. If the file is open for random access, it will
  156314. find the *actual* average bitrate. If the file is streaming, it
  156315. returns the nominal bitrate (if set) else the average of the
  156316. upper/lower bounds (if set) else -1 (unset).
  156317. If you want the actual bitrate field settings, get them from the
  156318. vorbis_info structs */
  156319. long ov_bitrate(OggVorbis_File *vf,int i){
  156320. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156321. if(i>=vf->links)return(OV_EINVAL);
  156322. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156323. if(i<0){
  156324. ogg_int64_t bits=0;
  156325. int i;
  156326. float br;
  156327. for(i=0;i<vf->links;i++)
  156328. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156329. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156330. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156331. * so this is slightly transformed to make it work.
  156332. */
  156333. br = bits/ov_time_total(vf,-1);
  156334. return(rint(br));
  156335. }else{
  156336. if(vf->seekable){
  156337. /* return the actual bitrate */
  156338. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156339. }else{
  156340. /* return nominal if set */
  156341. if(vf->vi[i].bitrate_nominal>0){
  156342. return vf->vi[i].bitrate_nominal;
  156343. }else{
  156344. if(vf->vi[i].bitrate_upper>0){
  156345. if(vf->vi[i].bitrate_lower>0){
  156346. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156347. }else{
  156348. return vf->vi[i].bitrate_upper;
  156349. }
  156350. }
  156351. return(OV_FALSE);
  156352. }
  156353. }
  156354. }
  156355. }
  156356. /* returns the actual bitrate since last call. returns -1 if no
  156357. additional data to offer since last call (or at beginning of stream),
  156358. EINVAL if stream is only partially open
  156359. */
  156360. long ov_bitrate_instant(OggVorbis_File *vf){
  156361. int link=(vf->seekable?vf->current_link:0);
  156362. long ret;
  156363. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156364. if(vf->samptrack==0)return(OV_FALSE);
  156365. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156366. vf->bittrack=0.f;
  156367. vf->samptrack=0.f;
  156368. return(ret);
  156369. }
  156370. /* Guess */
  156371. long ov_serialnumber(OggVorbis_File *vf,int i){
  156372. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156373. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156374. if(i<0){
  156375. return(vf->current_serialno);
  156376. }else{
  156377. return(vf->serialnos[i]);
  156378. }
  156379. }
  156380. /* returns: total raw (compressed) length of content if i==-1
  156381. raw (compressed) length of that logical bitstream for i==0 to n
  156382. OV_EINVAL if the stream is not seekable (we can't know the length)
  156383. or if stream is only partially open
  156384. */
  156385. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156386. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156387. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156388. if(i<0){
  156389. ogg_int64_t acc=0;
  156390. int i;
  156391. for(i=0;i<vf->links;i++)
  156392. acc+=ov_raw_total(vf,i);
  156393. return(acc);
  156394. }else{
  156395. return(vf->offsets[i+1]-vf->offsets[i]);
  156396. }
  156397. }
  156398. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156399. (samples) of that logical bitstream for i==0 to n
  156400. OV_EINVAL if the stream is not seekable (we can't know the
  156401. length) or only partially open
  156402. */
  156403. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156404. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156405. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156406. if(i<0){
  156407. ogg_int64_t acc=0;
  156408. int i;
  156409. for(i=0;i<vf->links;i++)
  156410. acc+=ov_pcm_total(vf,i);
  156411. return(acc);
  156412. }else{
  156413. return(vf->pcmlengths[i*2+1]);
  156414. }
  156415. }
  156416. /* returns: total seconds of content if i==-1
  156417. seconds in that logical bitstream for i==0 to n
  156418. OV_EINVAL if the stream is not seekable (we can't know the
  156419. length) or only partially open
  156420. */
  156421. double ov_time_total(OggVorbis_File *vf,int i){
  156422. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156423. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156424. if(i<0){
  156425. double acc=0;
  156426. int i;
  156427. for(i=0;i<vf->links;i++)
  156428. acc+=ov_time_total(vf,i);
  156429. return(acc);
  156430. }else{
  156431. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156432. }
  156433. }
  156434. /* seek to an offset relative to the *compressed* data. This also
  156435. scans packets to update the PCM cursor. It will cross a logical
  156436. bitstream boundary, but only if it can't get any packets out of the
  156437. tail of the bitstream we seek to (so no surprises).
  156438. returns zero on success, nonzero on failure */
  156439. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156440. ogg_stream_state work_os;
  156441. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156442. if(!vf->seekable)
  156443. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156444. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156445. /* don't yet clear out decoding machine (if it's initialized), in
  156446. the case we're in the same link. Restart the decode lapping, and
  156447. let _fetch_and_process_packet deal with a potential bitstream
  156448. boundary */
  156449. vf->pcm_offset=-1;
  156450. ogg_stream_reset_serialno(&vf->os,
  156451. vf->current_serialno); /* must set serialno */
  156452. vorbis_synthesis_restart(&vf->vd);
  156453. _seek_helper(vf,pos);
  156454. /* we need to make sure the pcm_offset is set, but we don't want to
  156455. advance the raw cursor past good packets just to get to the first
  156456. with a granulepos. That's not equivalent behavior to beginning
  156457. decoding as immediately after the seek position as possible.
  156458. So, a hack. We use two stream states; a local scratch state and
  156459. the shared vf->os stream state. We use the local state to
  156460. scan, and the shared state as a buffer for later decode.
  156461. Unfortuantely, on the last page we still advance to last packet
  156462. because the granulepos on the last page is not necessarily on a
  156463. packet boundary, and we need to make sure the granpos is
  156464. correct.
  156465. */
  156466. {
  156467. ogg_page og;
  156468. ogg_packet op;
  156469. int lastblock=0;
  156470. int accblock=0;
  156471. int thisblock;
  156472. int eosflag;
  156473. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156474. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156475. return from not necessarily
  156476. starting from the beginning */
  156477. while(1){
  156478. if(vf->ready_state>=STREAMSET){
  156479. /* snarf/scan a packet if we can */
  156480. int result=ogg_stream_packetout(&work_os,&op);
  156481. if(result>0){
  156482. if(vf->vi[vf->current_link].codec_setup){
  156483. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156484. if(thisblock<0){
  156485. ogg_stream_packetout(&vf->os,NULL);
  156486. thisblock=0;
  156487. }else{
  156488. if(eosflag)
  156489. ogg_stream_packetout(&vf->os,NULL);
  156490. else
  156491. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156492. }
  156493. if(op.granulepos!=-1){
  156494. int i,link=vf->current_link;
  156495. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156496. if(granulepos<0)granulepos=0;
  156497. for(i=0;i<link;i++)
  156498. granulepos+=vf->pcmlengths[i*2+1];
  156499. vf->pcm_offset=granulepos-accblock;
  156500. break;
  156501. }
  156502. lastblock=thisblock;
  156503. continue;
  156504. }else
  156505. ogg_stream_packetout(&vf->os,NULL);
  156506. }
  156507. }
  156508. if(!lastblock){
  156509. if(_get_next_page(vf,&og,-1)<0){
  156510. vf->pcm_offset=ov_pcm_total(vf,-1);
  156511. break;
  156512. }
  156513. }else{
  156514. /* huh? Bogus stream with packets but no granulepos */
  156515. vf->pcm_offset=-1;
  156516. break;
  156517. }
  156518. /* has our decoding just traversed a bitstream boundary? */
  156519. if(vf->ready_state>=STREAMSET)
  156520. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156521. _decode_clear(vf); /* clear out stream state */
  156522. ogg_stream_clear(&work_os);
  156523. }
  156524. if(vf->ready_state<STREAMSET){
  156525. int link;
  156526. vf->current_serialno=ogg_page_serialno(&og);
  156527. for(link=0;link<vf->links;link++)
  156528. if(vf->serialnos[link]==vf->current_serialno)break;
  156529. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156530. error out, leave
  156531. machine uninitialized */
  156532. vf->current_link=link;
  156533. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156534. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156535. vf->ready_state=STREAMSET;
  156536. }
  156537. ogg_stream_pagein(&vf->os,&og);
  156538. ogg_stream_pagein(&work_os,&og);
  156539. eosflag=ogg_page_eos(&og);
  156540. }
  156541. }
  156542. ogg_stream_clear(&work_os);
  156543. vf->bittrack=0.f;
  156544. vf->samptrack=0.f;
  156545. return(0);
  156546. seek_error:
  156547. /* dump the machine so we're in a known state */
  156548. vf->pcm_offset=-1;
  156549. ogg_stream_clear(&work_os);
  156550. _decode_clear(vf);
  156551. return OV_EBADLINK;
  156552. }
  156553. /* Page granularity seek (faster than sample granularity because we
  156554. don't do the last bit of decode to find a specific sample).
  156555. Seek to the last [granule marked] page preceeding the specified pos
  156556. location, such that decoding past the returned point will quickly
  156557. arrive at the requested position. */
  156558. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156559. int link=-1;
  156560. ogg_int64_t result=0;
  156561. ogg_int64_t total=ov_pcm_total(vf,-1);
  156562. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156563. if(!vf->seekable)return(OV_ENOSEEK);
  156564. if(pos<0 || pos>total)return(OV_EINVAL);
  156565. /* which bitstream section does this pcm offset occur in? */
  156566. for(link=vf->links-1;link>=0;link--){
  156567. total-=vf->pcmlengths[link*2+1];
  156568. if(pos>=total)break;
  156569. }
  156570. /* search within the logical bitstream for the page with the highest
  156571. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156572. missing pages or incorrect frame number information in the
  156573. bitstream could make our task impossible. Account for that (it
  156574. would be an error condition) */
  156575. /* new search algorithm by HB (Nicholas Vinen) */
  156576. {
  156577. ogg_int64_t end=vf->offsets[link+1];
  156578. ogg_int64_t begin=vf->offsets[link];
  156579. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156580. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156581. ogg_int64_t target=pos-total+begintime;
  156582. ogg_int64_t best=begin;
  156583. ogg_page og;
  156584. while(begin<end){
  156585. ogg_int64_t bisect;
  156586. if(end-begin<CHUNKSIZE){
  156587. bisect=begin;
  156588. }else{
  156589. /* take a (pretty decent) guess. */
  156590. bisect=begin +
  156591. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156592. if(bisect<=begin)
  156593. bisect=begin+1;
  156594. }
  156595. _seek_helper(vf,bisect);
  156596. while(begin<end){
  156597. result=_get_next_page(vf,&og,end-vf->offset);
  156598. if(result==OV_EREAD) goto seek_error;
  156599. if(result<0){
  156600. if(bisect<=begin+1)
  156601. end=begin; /* found it */
  156602. else{
  156603. if(bisect==0) goto seek_error;
  156604. bisect-=CHUNKSIZE;
  156605. if(bisect<=begin)bisect=begin+1;
  156606. _seek_helper(vf,bisect);
  156607. }
  156608. }else{
  156609. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156610. if(granulepos==-1)continue;
  156611. if(granulepos<target){
  156612. best=result; /* raw offset of packet with granulepos */
  156613. begin=vf->offset; /* raw offset of next page */
  156614. begintime=granulepos;
  156615. if(target-begintime>44100)break;
  156616. bisect=begin; /* *not* begin + 1 */
  156617. }else{
  156618. if(bisect<=begin+1)
  156619. end=begin; /* found it */
  156620. else{
  156621. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156622. end=result;
  156623. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156624. if(bisect<=begin)bisect=begin+1;
  156625. _seek_helper(vf,bisect);
  156626. }else{
  156627. end=result;
  156628. endtime=granulepos;
  156629. break;
  156630. }
  156631. }
  156632. }
  156633. }
  156634. }
  156635. }
  156636. /* found our page. seek to it, update pcm offset. Easier case than
  156637. raw_seek, don't keep packets preceeding granulepos. */
  156638. {
  156639. ogg_page og;
  156640. ogg_packet op;
  156641. /* seek */
  156642. _seek_helper(vf,best);
  156643. vf->pcm_offset=-1;
  156644. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156645. if(link!=vf->current_link){
  156646. /* Different link; dump entire decode machine */
  156647. _decode_clear(vf);
  156648. vf->current_link=link;
  156649. vf->current_serialno=ogg_page_serialno(&og);
  156650. vf->ready_state=STREAMSET;
  156651. }else{
  156652. vorbis_synthesis_restart(&vf->vd);
  156653. }
  156654. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156655. ogg_stream_pagein(&vf->os,&og);
  156656. /* pull out all but last packet; the one with granulepos */
  156657. while(1){
  156658. result=ogg_stream_packetpeek(&vf->os,&op);
  156659. if(result==0){
  156660. /* !!! the packet finishing this page originated on a
  156661. preceeding page. Keep fetching previous pages until we
  156662. get one with a granulepos or without the 'continued' flag
  156663. set. Then just use raw_seek for simplicity. */
  156664. _seek_helper(vf,best);
  156665. while(1){
  156666. result=_get_prev_page(vf,&og);
  156667. if(result<0) goto seek_error;
  156668. if(ogg_page_granulepos(&og)>-1 ||
  156669. !ogg_page_continued(&og)){
  156670. return ov_raw_seek(vf,result);
  156671. }
  156672. vf->offset=result;
  156673. }
  156674. }
  156675. if(result<0){
  156676. result = OV_EBADPACKET;
  156677. goto seek_error;
  156678. }
  156679. if(op.granulepos!=-1){
  156680. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156681. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156682. vf->pcm_offset+=total;
  156683. break;
  156684. }else
  156685. result=ogg_stream_packetout(&vf->os,NULL);
  156686. }
  156687. }
  156688. }
  156689. /* verify result */
  156690. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156691. result=OV_EFAULT;
  156692. goto seek_error;
  156693. }
  156694. vf->bittrack=0.f;
  156695. vf->samptrack=0.f;
  156696. return(0);
  156697. seek_error:
  156698. /* dump machine so we're in a known state */
  156699. vf->pcm_offset=-1;
  156700. _decode_clear(vf);
  156701. return (int)result;
  156702. }
  156703. /* seek to a sample offset relative to the decompressed pcm stream
  156704. returns zero on success, nonzero on failure */
  156705. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156706. int thisblock,lastblock=0;
  156707. int ret=ov_pcm_seek_page(vf,pos);
  156708. if(ret<0)return(ret);
  156709. if((ret=_make_decode_ready(vf)))return ret;
  156710. /* discard leading packets we don't need for the lapping of the
  156711. position we want; don't decode them */
  156712. while(1){
  156713. ogg_packet op;
  156714. ogg_page og;
  156715. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156716. if(ret>0){
  156717. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156718. if(thisblock<0){
  156719. ogg_stream_packetout(&vf->os,NULL);
  156720. continue; /* non audio packet */
  156721. }
  156722. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156723. if(vf->pcm_offset+((thisblock+
  156724. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156725. /* remove the packet from packet queue and track its granulepos */
  156726. ogg_stream_packetout(&vf->os,NULL);
  156727. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156728. only tracking, no
  156729. pcm_decode */
  156730. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156731. /* end of logical stream case is hard, especially with exact
  156732. length positioning. */
  156733. if(op.granulepos>-1){
  156734. int i;
  156735. /* always believe the stream markers */
  156736. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156737. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156738. for(i=0;i<vf->current_link;i++)
  156739. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156740. }
  156741. lastblock=thisblock;
  156742. }else{
  156743. if(ret<0 && ret!=OV_HOLE)break;
  156744. /* suck in a new page */
  156745. if(_get_next_page(vf,&og,-1)<0)break;
  156746. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156747. if(vf->ready_state<STREAMSET){
  156748. int link;
  156749. vf->current_serialno=ogg_page_serialno(&og);
  156750. for(link=0;link<vf->links;link++)
  156751. if(vf->serialnos[link]==vf->current_serialno)break;
  156752. if(link==vf->links)return(OV_EBADLINK);
  156753. vf->current_link=link;
  156754. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156755. vf->ready_state=STREAMSET;
  156756. ret=_make_decode_ready(vf);
  156757. if(ret)return ret;
  156758. lastblock=0;
  156759. }
  156760. ogg_stream_pagein(&vf->os,&og);
  156761. }
  156762. }
  156763. vf->bittrack=0.f;
  156764. vf->samptrack=0.f;
  156765. /* discard samples until we reach the desired position. Crossing a
  156766. logical bitstream boundary with abandon is OK. */
  156767. while(vf->pcm_offset<pos){
  156768. ogg_int64_t target=pos-vf->pcm_offset;
  156769. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156770. if(samples>target)samples=target;
  156771. vorbis_synthesis_read(&vf->vd,samples);
  156772. vf->pcm_offset+=samples;
  156773. if(samples<target)
  156774. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156775. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156776. }
  156777. return 0;
  156778. }
  156779. /* seek to a playback time relative to the decompressed pcm stream
  156780. returns zero on success, nonzero on failure */
  156781. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156782. /* translate time to PCM position and call ov_pcm_seek */
  156783. int link=-1;
  156784. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156785. double time_total=ov_time_total(vf,-1);
  156786. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156787. if(!vf->seekable)return(OV_ENOSEEK);
  156788. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156789. /* which bitstream section does this time offset occur in? */
  156790. for(link=vf->links-1;link>=0;link--){
  156791. pcm_total-=vf->pcmlengths[link*2+1];
  156792. time_total-=ov_time_total(vf,link);
  156793. if(seconds>=time_total)break;
  156794. }
  156795. /* enough information to convert time offset to pcm offset */
  156796. {
  156797. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156798. return(ov_pcm_seek(vf,target));
  156799. }
  156800. }
  156801. /* page-granularity version of ov_time_seek
  156802. returns zero on success, nonzero on failure */
  156803. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156804. /* translate time to PCM position and call ov_pcm_seek */
  156805. int link=-1;
  156806. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156807. double time_total=ov_time_total(vf,-1);
  156808. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156809. if(!vf->seekable)return(OV_ENOSEEK);
  156810. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156811. /* which bitstream section does this time offset occur in? */
  156812. for(link=vf->links-1;link>=0;link--){
  156813. pcm_total-=vf->pcmlengths[link*2+1];
  156814. time_total-=ov_time_total(vf,link);
  156815. if(seconds>=time_total)break;
  156816. }
  156817. /* enough information to convert time offset to pcm offset */
  156818. {
  156819. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156820. return(ov_pcm_seek_page(vf,target));
  156821. }
  156822. }
  156823. /* tell the current stream offset cursor. Note that seek followed by
  156824. tell will likely not give the set offset due to caching */
  156825. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156826. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156827. return(vf->offset);
  156828. }
  156829. /* return PCM offset (sample) of next PCM sample to be read */
  156830. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156831. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156832. return(vf->pcm_offset);
  156833. }
  156834. /* return time offset (seconds) of next PCM sample to be read */
  156835. double ov_time_tell(OggVorbis_File *vf){
  156836. int link=0;
  156837. ogg_int64_t pcm_total=0;
  156838. double time_total=0.f;
  156839. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156840. if(vf->seekable){
  156841. pcm_total=ov_pcm_total(vf,-1);
  156842. time_total=ov_time_total(vf,-1);
  156843. /* which bitstream section does this time offset occur in? */
  156844. for(link=vf->links-1;link>=0;link--){
  156845. pcm_total-=vf->pcmlengths[link*2+1];
  156846. time_total-=ov_time_total(vf,link);
  156847. if(vf->pcm_offset>=pcm_total)break;
  156848. }
  156849. }
  156850. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156851. }
  156852. /* link: -1) return the vorbis_info struct for the bitstream section
  156853. currently being decoded
  156854. 0-n) to request information for a specific bitstream section
  156855. In the case of a non-seekable bitstream, any call returns the
  156856. current bitstream. NULL in the case that the machine is not
  156857. initialized */
  156858. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156859. if(vf->seekable){
  156860. if(link<0)
  156861. if(vf->ready_state>=STREAMSET)
  156862. return vf->vi+vf->current_link;
  156863. else
  156864. return vf->vi;
  156865. else
  156866. if(link>=vf->links)
  156867. return NULL;
  156868. else
  156869. return vf->vi+link;
  156870. }else{
  156871. return vf->vi;
  156872. }
  156873. }
  156874. /* grr, strong typing, grr, no templates/inheritence, grr */
  156875. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156876. if(vf->seekable){
  156877. if(link<0)
  156878. if(vf->ready_state>=STREAMSET)
  156879. return vf->vc+vf->current_link;
  156880. else
  156881. return vf->vc;
  156882. else
  156883. if(link>=vf->links)
  156884. return NULL;
  156885. else
  156886. return vf->vc+link;
  156887. }else{
  156888. return vf->vc;
  156889. }
  156890. }
  156891. static int host_is_big_endian() {
  156892. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156893. unsigned char *bytewise = (unsigned char *)&pattern;
  156894. if (bytewise[0] == 0xfe) return 1;
  156895. return 0;
  156896. }
  156897. /* up to this point, everything could more or less hide the multiple
  156898. logical bitstream nature of chaining from the toplevel application
  156899. if the toplevel application didn't particularly care. However, at
  156900. the point that we actually read audio back, the multiple-section
  156901. nature must surface: Multiple bitstream sections do not necessarily
  156902. have to have the same number of channels or sampling rate.
  156903. ov_read returns the sequential logical bitstream number currently
  156904. being decoded along with the PCM data in order that the toplevel
  156905. application can take action on channel/sample rate changes. This
  156906. number will be incremented even for streamed (non-seekable) streams
  156907. (for seekable streams, it represents the actual logical bitstream
  156908. index within the physical bitstream. Note that the accessor
  156909. functions above are aware of this dichotomy).
  156910. input values: buffer) a buffer to hold packed PCM data for return
  156911. length) the byte length requested to be placed into buffer
  156912. bigendianp) should the data be packed LSB first (0) or
  156913. MSB first (1)
  156914. word) word size for output. currently 1 (byte) or
  156915. 2 (16 bit short)
  156916. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156917. 0) EOF
  156918. n) number of bytes of PCM actually returned. The
  156919. below works on a packet-by-packet basis, so the
  156920. return length is not related to the 'length' passed
  156921. in, just guaranteed to fit.
  156922. *section) set to the logical bitstream number */
  156923. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156924. int bigendianp,int word,int sgned,int *bitstream){
  156925. int i,j;
  156926. int host_endian = host_is_big_endian();
  156927. float **pcm;
  156928. long samples;
  156929. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156930. while(1){
  156931. if(vf->ready_state==INITSET){
  156932. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156933. if(samples)break;
  156934. }
  156935. /* suck in another packet */
  156936. {
  156937. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156938. if(ret==OV_EOF)
  156939. return(0);
  156940. if(ret<=0)
  156941. return(ret);
  156942. }
  156943. }
  156944. if(samples>0){
  156945. /* yay! proceed to pack data into the byte buffer */
  156946. long channels=ov_info(vf,-1)->channels;
  156947. long bytespersample=word * channels;
  156948. vorbis_fpu_control fpu;
  156949. (void) fpu; // (to avoid a warning about it being unused)
  156950. if(samples>length/bytespersample)samples=length/bytespersample;
  156951. if(samples <= 0)
  156952. return OV_EINVAL;
  156953. /* a tight loop to pack each size */
  156954. {
  156955. int val;
  156956. if(word==1){
  156957. int off=(sgned?0:128);
  156958. vorbis_fpu_setround(&fpu);
  156959. for(j=0;j<samples;j++)
  156960. for(i=0;i<channels;i++){
  156961. val=vorbis_ftoi(pcm[i][j]*128.f);
  156962. if(val>127)val=127;
  156963. else if(val<-128)val=-128;
  156964. *buffer++=val+off;
  156965. }
  156966. vorbis_fpu_restore(fpu);
  156967. }else{
  156968. int off=(sgned?0:32768);
  156969. if(host_endian==bigendianp){
  156970. if(sgned){
  156971. vorbis_fpu_setround(&fpu);
  156972. for(i=0;i<channels;i++) { /* It's faster in this order */
  156973. float *src=pcm[i];
  156974. short *dest=((short *)buffer)+i;
  156975. for(j=0;j<samples;j++) {
  156976. val=vorbis_ftoi(src[j]*32768.f);
  156977. if(val>32767)val=32767;
  156978. else if(val<-32768)val=-32768;
  156979. *dest=val;
  156980. dest+=channels;
  156981. }
  156982. }
  156983. vorbis_fpu_restore(fpu);
  156984. }else{
  156985. vorbis_fpu_setround(&fpu);
  156986. for(i=0;i<channels;i++) {
  156987. float *src=pcm[i];
  156988. short *dest=((short *)buffer)+i;
  156989. for(j=0;j<samples;j++) {
  156990. val=vorbis_ftoi(src[j]*32768.f);
  156991. if(val>32767)val=32767;
  156992. else if(val<-32768)val=-32768;
  156993. *dest=val+off;
  156994. dest+=channels;
  156995. }
  156996. }
  156997. vorbis_fpu_restore(fpu);
  156998. }
  156999. }else if(bigendianp){
  157000. vorbis_fpu_setround(&fpu);
  157001. for(j=0;j<samples;j++)
  157002. for(i=0;i<channels;i++){
  157003. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157004. if(val>32767)val=32767;
  157005. else if(val<-32768)val=-32768;
  157006. val+=off;
  157007. *buffer++=(val>>8);
  157008. *buffer++=(val&0xff);
  157009. }
  157010. vorbis_fpu_restore(fpu);
  157011. }else{
  157012. int val;
  157013. vorbis_fpu_setround(&fpu);
  157014. for(j=0;j<samples;j++)
  157015. for(i=0;i<channels;i++){
  157016. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157017. if(val>32767)val=32767;
  157018. else if(val<-32768)val=-32768;
  157019. val+=off;
  157020. *buffer++=(val&0xff);
  157021. *buffer++=(val>>8);
  157022. }
  157023. vorbis_fpu_restore(fpu);
  157024. }
  157025. }
  157026. }
  157027. vorbis_synthesis_read(&vf->vd,samples);
  157028. vf->pcm_offset+=samples;
  157029. if(bitstream)*bitstream=vf->current_link;
  157030. return(samples*bytespersample);
  157031. }else{
  157032. return(samples);
  157033. }
  157034. }
  157035. /* input values: pcm_channels) a float vector per channel of output
  157036. length) the sample length being read by the app
  157037. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157038. 0) EOF
  157039. n) number of samples of PCM actually returned. The
  157040. below works on a packet-by-packet basis, so the
  157041. return length is not related to the 'length' passed
  157042. in, just guaranteed to fit.
  157043. *section) set to the logical bitstream number */
  157044. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157045. int *bitstream){
  157046. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157047. while(1){
  157048. if(vf->ready_state==INITSET){
  157049. float **pcm;
  157050. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157051. if(samples){
  157052. if(pcm_channels)*pcm_channels=pcm;
  157053. if(samples>length)samples=length;
  157054. vorbis_synthesis_read(&vf->vd,samples);
  157055. vf->pcm_offset+=samples;
  157056. if(bitstream)*bitstream=vf->current_link;
  157057. return samples;
  157058. }
  157059. }
  157060. /* suck in another packet */
  157061. {
  157062. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157063. if(ret==OV_EOF)return(0);
  157064. if(ret<=0)return(ret);
  157065. }
  157066. }
  157067. }
  157068. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157069. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157070. ogg_int64_t off);
  157071. static void _ov_splice(float **pcm,float **lappcm,
  157072. int n1, int n2,
  157073. int ch1, int ch2,
  157074. float *w1, float *w2){
  157075. int i,j;
  157076. float *w=w1;
  157077. int n=n1;
  157078. if(n1>n2){
  157079. n=n2;
  157080. w=w2;
  157081. }
  157082. /* splice */
  157083. for(j=0;j<ch1 && j<ch2;j++){
  157084. float *s=lappcm[j];
  157085. float *d=pcm[j];
  157086. for(i=0;i<n;i++){
  157087. float wd=w[i]*w[i];
  157088. float ws=1.-wd;
  157089. d[i]=d[i]*wd + s[i]*ws;
  157090. }
  157091. }
  157092. /* window from zero */
  157093. for(;j<ch2;j++){
  157094. float *d=pcm[j];
  157095. for(i=0;i<n;i++){
  157096. float wd=w[i]*w[i];
  157097. d[i]=d[i]*wd;
  157098. }
  157099. }
  157100. }
  157101. /* make sure vf is INITSET */
  157102. static int _ov_initset(OggVorbis_File *vf){
  157103. while(1){
  157104. if(vf->ready_state==INITSET)break;
  157105. /* suck in another packet */
  157106. {
  157107. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157108. if(ret<0 && ret!=OV_HOLE)return(ret);
  157109. }
  157110. }
  157111. return 0;
  157112. }
  157113. /* make sure vf is INITSET and that we have a primed buffer; if
  157114. we're crosslapping at a stream section boundary, this also makes
  157115. sure we're sanity checking against the right stream information */
  157116. static int _ov_initprime(OggVorbis_File *vf){
  157117. vorbis_dsp_state *vd=&vf->vd;
  157118. while(1){
  157119. if(vf->ready_state==INITSET)
  157120. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157121. /* suck in another packet */
  157122. {
  157123. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157124. if(ret<0 && ret!=OV_HOLE)return(ret);
  157125. }
  157126. }
  157127. return 0;
  157128. }
  157129. /* grab enough data for lapping from vf; this may be in the form of
  157130. unreturned, already-decoded pcm, remaining PCM we will need to
  157131. decode, or synthetic postextrapolation from last packets. */
  157132. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157133. float **lappcm,int lapsize){
  157134. int lapcount=0,i;
  157135. float **pcm;
  157136. /* try first to decode the lapping data */
  157137. while(lapcount<lapsize){
  157138. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157139. if(samples){
  157140. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157141. for(i=0;i<vi->channels;i++)
  157142. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157143. lapcount+=samples;
  157144. vorbis_synthesis_read(vd,samples);
  157145. }else{
  157146. /* suck in another packet */
  157147. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157148. if(ret==OV_EOF)break;
  157149. }
  157150. }
  157151. if(lapcount<lapsize){
  157152. /* failed to get lapping data from normal decode; pry it from the
  157153. postextrapolation buffering, or the second half of the MDCT
  157154. from the last packet */
  157155. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157156. if(samples==0){
  157157. for(i=0;i<vi->channels;i++)
  157158. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157159. lapcount=lapsize;
  157160. }else{
  157161. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157162. for(i=0;i<vi->channels;i++)
  157163. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157164. lapcount+=samples;
  157165. }
  157166. }
  157167. }
  157168. /* this sets up crosslapping of a sample by using trailing data from
  157169. sample 1 and lapping it into the windowing buffer of sample 2 */
  157170. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157171. vorbis_info *vi1,*vi2;
  157172. float **lappcm;
  157173. float **pcm;
  157174. float *w1,*w2;
  157175. int n1,n2,i,ret,hs1,hs2;
  157176. if(vf1==vf2)return(0); /* degenerate case */
  157177. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157178. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157179. /* the relevant overlap buffers must be pre-checked and pre-primed
  157180. before looking at settings in the event that priming would cross
  157181. a bitstream boundary. So, do it now */
  157182. ret=_ov_initset(vf1);
  157183. if(ret)return(ret);
  157184. ret=_ov_initprime(vf2);
  157185. if(ret)return(ret);
  157186. vi1=ov_info(vf1,-1);
  157187. vi2=ov_info(vf2,-1);
  157188. hs1=ov_halfrate_p(vf1);
  157189. hs2=ov_halfrate_p(vf2);
  157190. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157191. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157192. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157193. w1=vorbis_window(&vf1->vd,0);
  157194. w2=vorbis_window(&vf2->vd,0);
  157195. for(i=0;i<vi1->channels;i++)
  157196. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157197. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157198. /* have a lapping buffer from vf1; now to splice it into the lapping
  157199. buffer of vf2 */
  157200. /* consolidate and expose the buffer. */
  157201. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157202. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157203. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157204. /* splice */
  157205. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157206. /* done */
  157207. return(0);
  157208. }
  157209. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157210. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157211. vorbis_info *vi;
  157212. float **lappcm;
  157213. float **pcm;
  157214. float *w1,*w2;
  157215. int n1,n2,ch1,ch2,hs;
  157216. int i,ret;
  157217. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157218. ret=_ov_initset(vf);
  157219. if(ret)return(ret);
  157220. vi=ov_info(vf,-1);
  157221. hs=ov_halfrate_p(vf);
  157222. ch1=vi->channels;
  157223. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157224. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157225. persistent; even if the decode state
  157226. from this link gets dumped, this
  157227. window array continues to exist */
  157228. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157229. for(i=0;i<ch1;i++)
  157230. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157231. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157232. /* have lapping data; seek and prime the buffer */
  157233. ret=localseek(vf,pos);
  157234. if(ret)return ret;
  157235. ret=_ov_initprime(vf);
  157236. if(ret)return(ret);
  157237. /* Guard against cross-link changes; they're perfectly legal */
  157238. vi=ov_info(vf,-1);
  157239. ch2=vi->channels;
  157240. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157241. w2=vorbis_window(&vf->vd,0);
  157242. /* consolidate and expose the buffer. */
  157243. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157244. /* splice */
  157245. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157246. /* done */
  157247. return(0);
  157248. }
  157249. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157250. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157251. }
  157252. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157253. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157254. }
  157255. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157256. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157257. }
  157258. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157259. int (*localseek)(OggVorbis_File *,double)){
  157260. vorbis_info *vi;
  157261. float **lappcm;
  157262. float **pcm;
  157263. float *w1,*w2;
  157264. int n1,n2,ch1,ch2,hs;
  157265. int i,ret;
  157266. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157267. ret=_ov_initset(vf);
  157268. if(ret)return(ret);
  157269. vi=ov_info(vf,-1);
  157270. hs=ov_halfrate_p(vf);
  157271. ch1=vi->channels;
  157272. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157273. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157274. persistent; even if the decode state
  157275. from this link gets dumped, this
  157276. window array continues to exist */
  157277. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157278. for(i=0;i<ch1;i++)
  157279. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157280. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157281. /* have lapping data; seek and prime the buffer */
  157282. ret=localseek(vf,pos);
  157283. if(ret)return ret;
  157284. ret=_ov_initprime(vf);
  157285. if(ret)return(ret);
  157286. /* Guard against cross-link changes; they're perfectly legal */
  157287. vi=ov_info(vf,-1);
  157288. ch2=vi->channels;
  157289. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157290. w2=vorbis_window(&vf->vd,0);
  157291. /* consolidate and expose the buffer. */
  157292. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157293. /* splice */
  157294. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157295. /* done */
  157296. return(0);
  157297. }
  157298. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157299. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157300. }
  157301. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157302. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157303. }
  157304. #endif
  157305. /*** End of inlined file: vorbisfile.c ***/
  157306. /*** Start of inlined file: window.c ***/
  157307. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157308. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157309. // tasks..
  157310. #if JUCE_MSVC
  157311. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157312. #endif
  157313. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157314. #if JUCE_USE_OGGVORBIS
  157315. #include <stdlib.h>
  157316. #include <math.h>
  157317. static float vwin64[32] = {
  157318. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157319. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157320. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157321. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157322. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157323. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157324. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157325. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157326. };
  157327. static float vwin128[64] = {
  157328. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157329. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157330. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157331. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157332. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157333. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157334. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157335. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157336. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157337. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157338. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157339. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157340. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157341. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157342. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157343. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157344. };
  157345. static float vwin256[128] = {
  157346. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157347. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157348. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157349. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157350. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157351. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157352. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157353. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157354. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157355. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157356. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157357. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157358. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157359. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157360. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157361. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157362. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157363. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157364. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157365. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157366. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157367. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157368. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157369. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157370. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157371. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157372. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157373. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157374. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157375. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157376. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157377. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157378. };
  157379. static float vwin512[256] = {
  157380. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157381. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157382. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157383. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157384. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157385. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157386. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157387. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157388. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157389. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157390. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157391. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157392. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157393. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157394. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157395. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157396. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157397. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157398. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157399. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157400. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157401. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157402. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157403. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157404. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157405. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157406. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157407. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157408. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157409. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157410. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157411. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157412. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157413. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157414. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157415. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157416. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157417. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157418. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157419. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157420. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157421. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157422. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157423. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157424. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157425. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157426. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157427. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157428. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157429. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157430. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157431. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157432. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157433. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157434. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157435. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157436. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157437. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157438. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157439. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157440. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157441. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157442. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157443. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157444. };
  157445. static float vwin1024[512] = {
  157446. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157447. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157448. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157449. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157450. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157451. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157452. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157453. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157454. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157455. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157456. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157457. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157458. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157459. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157460. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157461. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157462. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157463. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157464. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157465. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157466. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157467. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157468. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157469. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157470. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157471. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157472. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157473. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157474. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157475. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157476. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157477. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157478. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157479. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157480. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157481. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157482. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157483. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157484. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157485. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157486. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157487. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157488. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157489. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157490. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157491. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157492. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157493. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157494. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157495. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157496. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157497. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157498. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157499. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157500. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157501. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157502. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157503. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157504. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157505. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157506. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157507. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157508. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157509. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157510. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157511. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157512. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157513. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157514. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157515. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157516. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157517. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157518. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157519. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157520. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157521. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157522. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157523. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157524. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157525. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157526. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157527. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157528. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157529. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157530. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157531. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157532. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157533. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157534. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157535. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157536. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157537. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157538. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157539. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157540. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157541. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157542. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157543. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157544. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157545. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157546. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157547. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157548. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157549. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157550. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157551. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157552. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157553. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157554. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157555. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157556. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157557. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157558. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157559. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157560. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157561. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157562. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157563. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157564. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157565. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157566. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157567. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157568. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157569. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157570. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157571. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157572. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157573. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157574. };
  157575. static float vwin2048[1024] = {
  157576. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157577. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157578. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157579. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157580. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157581. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157582. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157583. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157584. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157585. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157586. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157587. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157588. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157589. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157590. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157591. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157592. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157593. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157594. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157595. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157596. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157597. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157598. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157599. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157600. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157601. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157602. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157603. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157604. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157605. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157606. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157607. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157608. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157609. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157610. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157611. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157612. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157613. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157614. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157615. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157616. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157617. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157618. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157619. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157620. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157621. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157622. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157623. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157624. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157625. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157626. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157627. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157628. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157629. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157630. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157631. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157632. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157633. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157634. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157635. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157636. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157637. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157638. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157639. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157640. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157641. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157642. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157643. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157644. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157645. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157646. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157647. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157648. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157649. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157650. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157651. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157652. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157653. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157654. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157655. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157656. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157657. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157658. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157659. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157660. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157661. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157662. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157663. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157664. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157665. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157666. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157667. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157668. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157669. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157670. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157671. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157672. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157673. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157674. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157675. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157676. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157677. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157678. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157679. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157680. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157681. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157682. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157683. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157684. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157685. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157686. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157687. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157688. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157689. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157690. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157691. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157692. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157693. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157694. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157695. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157696. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157697. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157698. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157699. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157700. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157701. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157702. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157703. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157704. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157705. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157706. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157707. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157708. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157709. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157710. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157711. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157712. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157713. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157714. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157715. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157716. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157717. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157718. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157719. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157720. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157721. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157722. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157723. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157724. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157725. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157726. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157727. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157728. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157729. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157730. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157731. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157732. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157733. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157734. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157735. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157736. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157737. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157738. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157739. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157740. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157741. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157742. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157743. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157744. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157745. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157746. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157747. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157748. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157749. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157750. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157751. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157752. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157753. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157754. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157755. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157756. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157757. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157758. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157759. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157760. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157761. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157762. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157763. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157764. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157765. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157766. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157767. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157768. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157769. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157770. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157771. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157772. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157773. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157774. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157775. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157776. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157777. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157778. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157779. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157780. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157781. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157782. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157783. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157784. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157785. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157786. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157787. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157788. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157789. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157790. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157791. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157792. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157793. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157794. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157795. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157796. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157797. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157798. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157799. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157800. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157801. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157802. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157803. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157804. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157805. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157806. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157807. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157808. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157809. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157810. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157811. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157812. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157813. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157814. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157815. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157816. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157817. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157818. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157819. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157820. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157821. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157822. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157823. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157824. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157825. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157826. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157827. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157828. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157829. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157830. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157831. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157832. };
  157833. static float vwin4096[2048] = {
  157834. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157835. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157836. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157837. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157838. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157839. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157840. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157841. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157842. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157843. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157844. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157845. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157846. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157847. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157848. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157849. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157850. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157851. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157852. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157853. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157854. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157855. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157856. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157857. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157858. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157859. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157860. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157861. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157862. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157863. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157864. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157865. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157866. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157867. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157868. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157869. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157870. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157871. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157872. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157873. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157874. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157875. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157876. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157877. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157878. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157879. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157880. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157881. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157882. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157883. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157884. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157885. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157886. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157887. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157888. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157889. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157890. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157891. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157892. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157893. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157894. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157895. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157896. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157897. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157898. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157899. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157900. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157901. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157902. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157903. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157904. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157905. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157906. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157907. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157908. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157909. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157910. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157911. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157912. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157913. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157914. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157915. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157916. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157917. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157918. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157919. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157920. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157921. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157922. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157923. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157924. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157925. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157926. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157927. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157928. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157929. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157930. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157931. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157932. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157933. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157934. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157935. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157936. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157937. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157938. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157939. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157940. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157941. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157942. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157943. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157944. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157945. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157946. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157947. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157948. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157949. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157950. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157951. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157952. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157953. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157954. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157955. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157956. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157957. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157958. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157959. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157960. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157961. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157962. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157963. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157964. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157965. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157966. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157967. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157968. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157969. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157970. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157971. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157972. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157973. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157974. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157975. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157976. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157977. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157978. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157979. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157980. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157981. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157982. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157983. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157984. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157985. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157986. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157987. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157988. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157989. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157990. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157991. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157992. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157993. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157994. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157995. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157996. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157997. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157998. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157999. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  158000. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  158001. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  158002. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  158003. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  158004. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158005. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158006. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158007. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158008. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158009. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158010. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158011. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158012. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158013. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158014. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158015. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158016. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158017. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158018. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158019. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158020. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158021. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158022. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158023. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158024. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158025. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158026. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158027. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158028. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158029. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158030. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158031. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158032. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158033. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158034. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158035. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158036. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158037. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158038. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158039. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158040. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158041. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158042. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158043. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158044. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158045. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158046. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158047. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158048. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158049. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158050. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158051. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158052. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158053. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158054. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158055. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158056. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158057. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158058. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158059. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158060. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158061. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158062. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158063. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158064. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158065. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158066. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158067. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158068. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158069. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158070. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158071. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158072. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158073. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158074. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158075. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158076. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158077. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158078. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158079. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158080. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158081. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158082. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158083. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158084. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158085. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158086. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158087. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158088. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158089. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158090. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158091. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158092. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158093. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158094. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158095. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158096. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158097. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158098. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158099. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158100. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158101. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158102. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158103. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158104. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158105. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158106. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158107. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158108. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158109. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158110. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158111. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158112. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158113. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158114. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158115. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158116. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158117. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158118. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158119. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158120. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158121. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158122. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158123. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158124. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158125. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158126. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158127. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158128. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158129. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158130. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158131. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158132. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158133. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158134. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158135. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158136. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158137. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158138. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158139. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158140. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158141. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158142. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158143. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158144. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158145. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158146. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158147. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158148. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158149. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158150. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158151. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158152. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158153. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158154. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158155. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158156. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158157. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158158. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158159. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158160. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158161. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158162. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158163. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158164. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158165. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158166. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158167. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158168. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158169. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158170. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158171. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158172. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158173. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158174. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158175. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158176. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158177. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158178. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158179. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158180. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158181. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158182. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158183. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158184. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158185. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158186. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158187. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158188. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158189. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158190. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158191. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158192. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158193. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158194. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158195. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158196. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158197. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158198. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158199. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158200. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158201. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158202. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158203. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158204. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158205. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158206. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158207. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158208. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158209. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158210. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158211. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158212. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158213. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158214. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158215. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158216. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158217. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158218. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158219. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158220. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158221. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158222. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158223. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158224. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158225. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158226. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158227. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158228. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158229. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158230. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158231. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158232. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158233. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158234. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158235. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158236. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158237. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158238. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158239. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158240. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158241. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158242. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158243. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158244. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158245. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158246. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158247. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158248. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158249. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158250. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158251. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158252. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158253. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158254. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158255. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158256. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158257. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158258. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158259. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158260. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158261. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158262. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158263. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158264. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158265. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158266. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158267. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158268. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158269. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158270. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158271. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158272. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158273. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158274. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158275. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158276. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158277. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158278. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158279. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158280. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158281. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158282. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158283. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158284. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158285. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158286. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158287. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158288. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158289. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158290. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158291. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158292. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158293. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158294. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158295. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158296. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158297. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158298. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158299. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158300. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158301. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158302. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158303. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158304. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158305. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158306. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158307. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158308. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158309. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158310. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158311. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158312. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158313. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158314. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158315. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158316. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158317. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158318. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158319. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158320. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158321. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158322. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158323. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158324. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158325. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158326. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158327. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158328. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158329. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158330. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158331. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158332. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158333. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158334. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158335. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158336. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158337. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158338. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158339. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158340. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158341. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158342. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158343. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158344. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158345. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158346. };
  158347. static float vwin8192[4096] = {
  158348. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158349. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158350. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158351. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158352. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158353. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158354. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158355. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158356. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158357. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158358. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158359. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158360. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158361. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158362. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158363. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158364. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158365. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158366. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158367. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158368. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158369. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158370. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158371. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158372. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158373. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158374. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158375. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158376. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158377. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158378. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158379. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158380. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158381. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158382. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158383. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158384. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158385. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158386. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158387. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158388. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158389. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158390. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158391. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158392. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158393. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158394. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158395. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158396. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158397. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158398. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158399. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158400. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158401. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158402. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158403. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158404. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158405. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158406. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158407. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158408. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158409. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158410. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158411. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158412. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158413. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158414. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158415. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158416. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158417. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158418. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158419. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158420. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158421. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158422. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158423. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158424. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158425. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158426. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158427. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158428. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158429. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158430. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158431. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158432. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158433. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158434. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158435. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158436. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158437. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158438. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158439. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158440. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158441. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158442. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158443. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158444. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158445. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158446. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158447. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158448. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158449. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158450. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158451. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158452. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158453. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158454. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158455. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158456. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158457. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158458. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158459. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158460. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158461. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158462. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158463. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158464. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158465. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158466. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158467. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158468. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158469. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158470. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158471. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158472. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158473. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158474. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158475. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158476. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158477. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158478. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158479. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158480. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158481. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158482. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158483. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158484. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158485. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158486. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158487. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158488. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158489. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158490. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158491. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158492. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158493. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158494. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158495. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158496. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158497. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158498. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158499. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158500. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158501. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158502. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158503. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158504. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158505. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158506. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158507. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158508. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158509. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158510. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158511. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158512. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158513. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158514. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158515. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158516. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158517. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158518. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158519. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158520. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158521. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158522. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158523. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158524. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158525. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158526. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158527. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158528. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158529. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158530. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158531. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158532. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158533. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158534. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158535. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158536. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158537. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158538. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158539. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158540. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158541. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158542. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158543. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158544. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158545. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158546. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158547. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158548. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158549. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158550. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158551. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158552. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158553. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158554. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158555. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158556. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158557. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158558. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158559. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158560. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158561. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158562. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158563. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158564. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158565. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158566. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158567. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158568. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158569. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158570. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158571. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158572. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158573. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158574. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158575. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158576. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158577. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158578. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158579. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158580. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158581. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158582. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158583. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158584. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158585. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158586. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158587. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158588. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158589. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158590. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158591. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158592. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158593. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158594. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158595. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158596. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158597. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158598. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158599. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158600. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158601. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158602. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158603. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158604. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158605. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158606. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158607. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158608. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158609. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158610. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158611. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158612. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158613. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158614. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158615. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158616. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158617. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158618. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158619. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158620. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158621. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158622. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158623. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158624. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158625. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158626. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158627. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158628. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158629. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158630. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158631. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158632. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158633. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158634. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158635. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158636. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158637. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158638. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158639. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158640. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158641. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158642. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158643. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158644. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158645. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158646. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158647. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158648. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158649. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158650. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158651. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158652. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158653. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158654. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158655. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158656. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158657. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158658. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158659. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158660. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158661. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158662. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158663. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158664. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158665. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158666. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158667. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158668. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158669. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158670. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158671. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158672. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158673. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158674. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158675. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158676. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158677. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158678. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158679. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158680. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158681. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158682. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158683. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158684. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158685. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158686. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158687. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158688. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158689. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158690. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158691. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158692. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158693. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158694. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158695. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158696. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158697. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158698. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158699. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158700. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158701. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158702. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158703. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158704. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158705. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158706. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158707. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158708. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158709. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158710. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158711. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158712. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158713. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158714. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158715. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158716. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158717. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158718. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158719. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158720. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158721. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158722. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158723. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158724. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158725. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158726. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158727. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158728. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158729. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158730. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158731. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158732. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158733. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158734. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158735. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158736. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158737. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158738. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158739. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158740. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158741. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158742. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158743. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158744. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158745. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158746. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158747. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158748. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158749. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158750. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158751. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158752. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158753. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158754. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158755. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158756. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158757. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158758. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158759. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158760. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158761. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158762. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158763. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158764. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158765. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158766. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158767. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158768. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158769. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158770. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158771. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158772. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158773. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158774. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158775. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158776. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158777. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158778. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158779. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158780. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158781. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158782. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158783. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158784. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158785. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158786. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158787. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158788. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158789. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158790. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158791. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158792. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158793. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158794. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158795. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158796. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158797. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158798. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158799. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158800. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158801. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158802. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158803. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158804. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158805. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158806. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158807. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158808. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158809. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158810. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158811. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158812. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158813. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158814. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158815. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158816. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158817. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158818. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158819. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158820. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158821. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158822. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158823. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158824. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158825. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158826. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158827. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158828. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158829. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158830. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158831. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158832. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158833. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158834. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158835. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158836. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158837. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158838. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158839. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158840. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158841. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158842. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158843. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158844. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158845. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158846. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158847. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158848. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158849. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158850. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158851. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158852. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158853. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158854. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158855. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158856. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158857. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158858. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158859. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158860. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158861. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158862. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158863. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158864. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158865. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158866. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158867. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158868. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158869. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158870. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158871. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158872. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158873. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158874. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158875. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158876. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158877. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158878. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158879. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158880. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158881. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158882. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158883. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158884. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158885. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158886. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158887. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158888. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158889. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158890. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158891. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158892. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158893. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158894. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158895. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158896. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158897. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158898. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158899. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158900. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158901. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158902. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158903. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158904. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158905. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158906. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158907. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158908. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158909. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158910. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158911. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158912. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158913. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158914. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158915. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158916. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158917. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158918. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158919. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158920. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158921. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158922. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158923. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158924. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158925. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158926. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158927. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158928. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158929. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158930. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158931. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158932. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158933. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158934. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158935. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158936. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158937. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158938. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158939. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158940. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158941. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158942. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158943. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158944. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158945. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158946. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158947. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158948. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158949. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158950. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158951. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158952. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158953. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158954. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158955. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158956. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158957. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158958. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158959. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158960. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158961. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158962. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158963. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158964. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158965. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158966. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158967. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158968. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158969. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158970. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158971. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158972. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158973. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158974. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158975. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158976. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158977. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158978. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158979. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158980. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158981. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158982. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158983. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158984. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158985. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158986. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158987. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158988. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158989. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158990. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158991. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158992. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158993. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158994. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158995. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158996. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158997. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158998. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158999. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  159000. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  159001. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  159002. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  159003. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  159004. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159005. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159006. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159007. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159008. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159009. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159010. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159011. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159012. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159013. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159014. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159015. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159016. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159017. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159018. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159019. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159020. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159021. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159022. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159023. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159024. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159025. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159026. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159027. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159028. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159029. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159030. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159031. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159032. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159033. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159034. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159035. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159036. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159037. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159038. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159039. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159040. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159041. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159042. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159043. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159044. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159045. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159046. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159047. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159048. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159049. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159050. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159051. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159052. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159053. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159054. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159055. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159056. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159057. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159058. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159059. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159060. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159061. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159062. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159063. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159064. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159065. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159066. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159067. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159068. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159069. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159070. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159071. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159072. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159073. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159074. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159075. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159076. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159077. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159078. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159079. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159080. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159081. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159082. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159083. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159084. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159085. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159086. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159087. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159088. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159089. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159090. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159091. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159092. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159093. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159094. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159095. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159096. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159097. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159098. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159099. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159100. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159101. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159102. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159103. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159104. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159105. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159106. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159107. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159108. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159109. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159110. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159111. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159112. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159113. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159114. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159115. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159116. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159117. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159118. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159119. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159120. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159121. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159122. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159123. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159124. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159125. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159126. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159127. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159128. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159129. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159130. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159131. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159132. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159133. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159134. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159135. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159136. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159137. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159138. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159139. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159140. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159141. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159142. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159143. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159144. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159145. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159146. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159147. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159148. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159149. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159150. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159151. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159152. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159153. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159154. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159155. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159156. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159157. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159158. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159159. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159160. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159161. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159162. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159163. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159164. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159165. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159166. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159167. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159168. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159169. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159170. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159171. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159172. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159173. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159174. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159175. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159176. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159177. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159178. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159179. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159180. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159181. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159182. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159183. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159184. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159185. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159186. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159187. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159188. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159189. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159190. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159191. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159192. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159193. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159194. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159195. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159196. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159197. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159198. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159199. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159200. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159201. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159202. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159203. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159204. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159205. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159206. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159207. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159208. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159209. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159210. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159211. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159212. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159213. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159214. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159215. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159216. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159217. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159218. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159219. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159220. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159221. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159222. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159223. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159224. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159225. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159226. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159227. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159228. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159229. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159230. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159231. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159232. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159233. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159234. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159235. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159236. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159237. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159238. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159239. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159240. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159241. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159242. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159243. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159244. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159245. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159246. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159247. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159248. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159249. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159250. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159251. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159252. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159253. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159254. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159255. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159256. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159257. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159258. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159259. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159260. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159261. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159262. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159263. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159264. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159265. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159266. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159267. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159268. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159269. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159270. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159271. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159272. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159273. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159274. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159275. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159276. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159277. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159278. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159279. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159280. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159281. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159282. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159283. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159284. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159285. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159286. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159287. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159288. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159289. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159290. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159291. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159292. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159293. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159294. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159295. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159296. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159297. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159298. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159299. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159300. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159301. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159302. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159303. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159304. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159305. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159306. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159307. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159308. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159309. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159310. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159311. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159312. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159313. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159314. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159315. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159316. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159317. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159318. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159319. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159320. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159321. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159322. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159323. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159324. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159325. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159326. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159327. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159328. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159329. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159330. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159331. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159332. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159333. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159334. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159335. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159336. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159337. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159338. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159339. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159340. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159341. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159342. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159343. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159344. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159345. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159346. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159347. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159348. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159349. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159350. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159351. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159352. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159353. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159354. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159355. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159356. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159357. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159358. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159359. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159360. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159361. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159362. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159363. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159364. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159365. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159366. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159367. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159368. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159369. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159370. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159371. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159372. };
  159373. static float *vwin[8] = {
  159374. vwin64,
  159375. vwin128,
  159376. vwin256,
  159377. vwin512,
  159378. vwin1024,
  159379. vwin2048,
  159380. vwin4096,
  159381. vwin8192,
  159382. };
  159383. float *_vorbis_window_get(int n){
  159384. return vwin[n];
  159385. }
  159386. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159387. int lW,int W,int nW){
  159388. lW=(W?lW:0);
  159389. nW=(W?nW:0);
  159390. {
  159391. float *windowLW=vwin[winno[lW]];
  159392. float *windowNW=vwin[winno[nW]];
  159393. long n=blocksizes[W];
  159394. long ln=blocksizes[lW];
  159395. long rn=blocksizes[nW];
  159396. long leftbegin=n/4-ln/4;
  159397. long leftend=leftbegin+ln/2;
  159398. long rightbegin=n/2+n/4-rn/4;
  159399. long rightend=rightbegin+rn/2;
  159400. int i,p;
  159401. for(i=0;i<leftbegin;i++)
  159402. d[i]=0.f;
  159403. for(p=0;i<leftend;i++,p++)
  159404. d[i]*=windowLW[p];
  159405. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159406. d[i]*=windowNW[p];
  159407. for(;i<n;i++)
  159408. d[i]=0.f;
  159409. }
  159410. }
  159411. #endif
  159412. /*** End of inlined file: window.c ***/
  159413. #else
  159414. #include <vorbis/vorbisenc.h>
  159415. #include <vorbis/codec.h>
  159416. #include <vorbis/vorbisfile.h>
  159417. #endif
  159418. }
  159419. #undef max
  159420. #undef min
  159421. BEGIN_JUCE_NAMESPACE
  159422. static const char* const oggFormatName = "Ogg-Vorbis file";
  159423. static const char* const oggExtensions[] = { ".ogg", 0 };
  159424. class OggReader : public AudioFormatReader
  159425. {
  159426. OggVorbisNamespace::OggVorbis_File ovFile;
  159427. OggVorbisNamespace::ov_callbacks callbacks;
  159428. AudioSampleBuffer reservoir;
  159429. int reservoirStart, samplesInReservoir;
  159430. public:
  159431. OggReader (InputStream* const inp)
  159432. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159433. reservoir (2, 4096),
  159434. reservoirStart (0),
  159435. samplesInReservoir (0)
  159436. {
  159437. using namespace OggVorbisNamespace;
  159438. sampleRate = 0;
  159439. usesFloatingPointData = true;
  159440. callbacks.read_func = &oggReadCallback;
  159441. callbacks.seek_func = &oggSeekCallback;
  159442. callbacks.close_func = &oggCloseCallback;
  159443. callbacks.tell_func = &oggTellCallback;
  159444. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159445. if (err == 0)
  159446. {
  159447. vorbis_info* info = ov_info (&ovFile, -1);
  159448. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159449. numChannels = info->channels;
  159450. bitsPerSample = 16;
  159451. sampleRate = info->rate;
  159452. reservoir.setSize (numChannels,
  159453. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159454. }
  159455. }
  159456. ~OggReader()
  159457. {
  159458. OggVorbisNamespace::ov_clear (&ovFile);
  159459. }
  159460. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159461. int64 startSampleInFile, int numSamples)
  159462. {
  159463. while (numSamples > 0)
  159464. {
  159465. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159466. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159467. {
  159468. // got a few samples overlapping, so use them before seeking..
  159469. const int numToUse = jmin (numSamples, numAvailable);
  159470. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159471. if (destSamples[i] != 0)
  159472. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159473. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159474. sizeof (float) * numToUse);
  159475. startSampleInFile += numToUse;
  159476. numSamples -= numToUse;
  159477. startOffsetInDestBuffer += numToUse;
  159478. if (numSamples == 0)
  159479. break;
  159480. }
  159481. if (startSampleInFile < reservoirStart
  159482. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159483. {
  159484. // buffer miss, so refill the reservoir
  159485. int bitStream = 0;
  159486. reservoirStart = jmax (0, (int) startSampleInFile);
  159487. samplesInReservoir = reservoir.getNumSamples();
  159488. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159489. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159490. int offset = 0;
  159491. int numToRead = samplesInReservoir;
  159492. while (numToRead > 0)
  159493. {
  159494. float** dataIn = 0;
  159495. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159496. if (samps <= 0)
  159497. break;
  159498. jassert (samps <= numToRead);
  159499. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159500. {
  159501. memcpy (reservoir.getSampleData (i, offset),
  159502. dataIn[i],
  159503. sizeof (float) * samps);
  159504. }
  159505. numToRead -= samps;
  159506. offset += samps;
  159507. }
  159508. if (numToRead > 0)
  159509. reservoir.clear (offset, numToRead);
  159510. }
  159511. }
  159512. if (numSamples > 0)
  159513. {
  159514. for (int i = numDestChannels; --i >= 0;)
  159515. if (destSamples[i] != 0)
  159516. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159517. sizeof (int) * numSamples);
  159518. }
  159519. return true;
  159520. }
  159521. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159522. {
  159523. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159524. }
  159525. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159526. {
  159527. InputStream* const in = static_cast <InputStream*> (datasource);
  159528. if (whence == SEEK_CUR)
  159529. offset += in->getPosition();
  159530. else if (whence == SEEK_END)
  159531. offset += in->getTotalLength();
  159532. in->setPosition (offset);
  159533. return 0;
  159534. }
  159535. static int oggCloseCallback (void*)
  159536. {
  159537. return 0;
  159538. }
  159539. static long oggTellCallback (void* datasource)
  159540. {
  159541. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159542. }
  159543. private:
  159544. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159545. };
  159546. class OggWriter : public AudioFormatWriter
  159547. {
  159548. OggVorbisNamespace::ogg_stream_state os;
  159549. OggVorbisNamespace::ogg_page og;
  159550. OggVorbisNamespace::ogg_packet op;
  159551. OggVorbisNamespace::vorbis_info vi;
  159552. OggVorbisNamespace::vorbis_comment vc;
  159553. OggVorbisNamespace::vorbis_dsp_state vd;
  159554. OggVorbisNamespace::vorbis_block vb;
  159555. public:
  159556. bool ok;
  159557. OggWriter (OutputStream* const out,
  159558. const double sampleRate,
  159559. const int numChannels,
  159560. const int bitsPerSample,
  159561. const int qualityIndex)
  159562. : AudioFormatWriter (out, TRANS (oggFormatName),
  159563. sampleRate,
  159564. numChannels,
  159565. bitsPerSample)
  159566. {
  159567. using namespace OggVorbisNamespace;
  159568. ok = false;
  159569. vorbis_info_init (&vi);
  159570. if (vorbis_encode_init_vbr (&vi,
  159571. numChannels,
  159572. (int) sampleRate,
  159573. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159574. {
  159575. vorbis_comment_init (&vc);
  159576. if (JUCEApplication::getInstance() != 0)
  159577. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159578. vorbis_analysis_init (&vd, &vi);
  159579. vorbis_block_init (&vd, &vb);
  159580. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159581. ogg_packet header;
  159582. ogg_packet header_comm;
  159583. ogg_packet header_code;
  159584. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159585. ogg_stream_packetin (&os, &header);
  159586. ogg_stream_packetin (&os, &header_comm);
  159587. ogg_stream_packetin (&os, &header_code);
  159588. for (;;)
  159589. {
  159590. if (ogg_stream_flush (&os, &og) == 0)
  159591. break;
  159592. output->write (og.header, og.header_len);
  159593. output->write (og.body, og.body_len);
  159594. }
  159595. ok = true;
  159596. }
  159597. }
  159598. ~OggWriter()
  159599. {
  159600. using namespace OggVorbisNamespace;
  159601. if (ok)
  159602. {
  159603. // write a zero-length packet to show ogg that we're finished..
  159604. write (0, 0);
  159605. ogg_stream_clear (&os);
  159606. vorbis_block_clear (&vb);
  159607. vorbis_dsp_clear (&vd);
  159608. vorbis_comment_clear (&vc);
  159609. vorbis_info_clear (&vi);
  159610. output->flush();
  159611. }
  159612. else
  159613. {
  159614. vorbis_info_clear (&vi);
  159615. output = 0; // to stop the base class deleting this, as it needs to be returned
  159616. // to the caller of createWriter()
  159617. }
  159618. }
  159619. bool write (const int** samplesToWrite, int numSamples)
  159620. {
  159621. using namespace OggVorbisNamespace;
  159622. if (! ok)
  159623. return false;
  159624. if (numSamples > 0)
  159625. {
  159626. const double gain = 1.0 / 0x80000000u;
  159627. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159628. for (int i = numChannels; --i >= 0;)
  159629. {
  159630. float* const dst = vorbisBuffer[i];
  159631. const int* const src = samplesToWrite [i];
  159632. if (src != 0 && dst != 0)
  159633. {
  159634. for (int j = 0; j < numSamples; ++j)
  159635. dst[j] = (float) (src[j] * gain);
  159636. }
  159637. }
  159638. }
  159639. vorbis_analysis_wrote (&vd, numSamples);
  159640. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159641. {
  159642. vorbis_analysis (&vb, 0);
  159643. vorbis_bitrate_addblock (&vb);
  159644. while (vorbis_bitrate_flushpacket (&vd, &op))
  159645. {
  159646. ogg_stream_packetin (&os, &op);
  159647. for (;;)
  159648. {
  159649. if (ogg_stream_pageout (&os, &og) == 0)
  159650. break;
  159651. output->write (og.header, og.header_len);
  159652. output->write (og.body, og.body_len);
  159653. if (ogg_page_eos (&og))
  159654. break;
  159655. }
  159656. }
  159657. }
  159658. return true;
  159659. }
  159660. private:
  159661. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159662. };
  159663. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159664. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159665. {
  159666. }
  159667. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159668. {
  159669. }
  159670. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159671. {
  159672. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159673. return Array <int> (rates);
  159674. }
  159675. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159676. {
  159677. const int depths[] = { 32, 0 };
  159678. return Array <int> (depths);
  159679. }
  159680. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159681. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159682. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159683. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159684. const bool deleteStreamIfOpeningFails)
  159685. {
  159686. ScopedPointer <OggReader> r (new OggReader (in));
  159687. if (r->sampleRate != 0)
  159688. return r.release();
  159689. if (! deleteStreamIfOpeningFails)
  159690. r->input = 0;
  159691. return 0;
  159692. }
  159693. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159694. double sampleRate,
  159695. unsigned int numChannels,
  159696. int bitsPerSample,
  159697. const StringPairArray& /*metadataValues*/,
  159698. int qualityOptionIndex)
  159699. {
  159700. ScopedPointer <OggWriter> w (new OggWriter (out,
  159701. sampleRate,
  159702. numChannels,
  159703. bitsPerSample,
  159704. qualityOptionIndex));
  159705. return w->ok ? w.release() : 0;
  159706. }
  159707. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159708. {
  159709. StringArray s;
  159710. s.add ("Low Quality");
  159711. s.add ("Medium Quality");
  159712. s.add ("High Quality");
  159713. return s;
  159714. }
  159715. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159716. {
  159717. FileInputStream* const in = source.createInputStream();
  159718. if (in != 0)
  159719. {
  159720. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159721. if (r != 0)
  159722. {
  159723. const int64 numSamps = r->lengthInSamples;
  159724. r = 0;
  159725. const int64 fileNumSamps = source.getSize() / 4;
  159726. const double ratio = numSamps / (double) fileNumSamps;
  159727. if (ratio > 12.0)
  159728. return 0;
  159729. else if (ratio > 6.0)
  159730. return 1;
  159731. else
  159732. return 2;
  159733. }
  159734. }
  159735. return 1;
  159736. }
  159737. END_JUCE_NAMESPACE
  159738. #endif
  159739. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159740. #endif
  159741. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159742. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159743. #if JUCE_MSVC
  159744. #pragma warning (push)
  159745. #endif
  159746. namespace jpeglibNamespace
  159747. {
  159748. #if JUCE_INCLUDE_JPEGLIB_CODE
  159749. #if JUCE_MINGW
  159750. typedef unsigned char boolean;
  159751. #endif
  159752. #define JPEG_INTERNALS
  159753. #undef FAR
  159754. /*** Start of inlined file: jpeglib.h ***/
  159755. #ifndef JPEGLIB_H
  159756. #define JPEGLIB_H
  159757. /*
  159758. * First we include the configuration files that record how this
  159759. * installation of the JPEG library is set up. jconfig.h can be
  159760. * generated automatically for many systems. jmorecfg.h contains
  159761. * manual configuration options that most people need not worry about.
  159762. */
  159763. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159764. /*** Start of inlined file: jconfig.h ***/
  159765. /* see jconfig.doc for explanations */
  159766. // disable all the warnings under MSVC
  159767. #ifdef _MSC_VER
  159768. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159769. #endif
  159770. #ifdef __BORLANDC__
  159771. #pragma warn -8057
  159772. #pragma warn -8019
  159773. #pragma warn -8004
  159774. #pragma warn -8008
  159775. #endif
  159776. #define HAVE_PROTOTYPES
  159777. #define HAVE_UNSIGNED_CHAR
  159778. #define HAVE_UNSIGNED_SHORT
  159779. /* #define void char */
  159780. /* #define const */
  159781. #undef CHAR_IS_UNSIGNED
  159782. #define HAVE_STDDEF_H
  159783. #define HAVE_STDLIB_H
  159784. #undef NEED_BSD_STRINGS
  159785. #undef NEED_SYS_TYPES_H
  159786. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159787. #undef NEED_SHORT_EXTERNAL_NAMES
  159788. #undef INCOMPLETE_TYPES_BROKEN
  159789. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159790. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159791. typedef unsigned char boolean;
  159792. #endif
  159793. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159794. #ifdef JPEG_INTERNALS
  159795. #undef RIGHT_SHIFT_IS_UNSIGNED
  159796. #endif /* JPEG_INTERNALS */
  159797. #ifdef JPEG_CJPEG_DJPEG
  159798. #define BMP_SUPPORTED /* BMP image file format */
  159799. #define GIF_SUPPORTED /* GIF image file format */
  159800. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159801. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159802. #define TARGA_SUPPORTED /* Targa image file format */
  159803. #define TWO_FILE_COMMANDLINE /* optional */
  159804. #define USE_SETMODE /* Microsoft has setmode() */
  159805. #undef NEED_SIGNAL_CATCHER
  159806. #undef DONT_USE_B_MODE
  159807. #undef PROGRESS_REPORT /* optional */
  159808. #endif /* JPEG_CJPEG_DJPEG */
  159809. /*** End of inlined file: jconfig.h ***/
  159810. /* widely used configuration options */
  159811. #endif
  159812. /*** Start of inlined file: jmorecfg.h ***/
  159813. /*
  159814. * Define BITS_IN_JSAMPLE as either
  159815. * 8 for 8-bit sample values (the usual setting)
  159816. * 12 for 12-bit sample values
  159817. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159818. * JPEG standard, and the IJG code does not support anything else!
  159819. * We do not support run-time selection of data precision, sorry.
  159820. */
  159821. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159822. /*
  159823. * Maximum number of components (color channels) allowed in JPEG image.
  159824. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159825. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159826. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159827. * really short on memory. (Each allowed component costs a hundred or so
  159828. * bytes of storage, whether actually used in an image or not.)
  159829. */
  159830. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159831. /*
  159832. * Basic data types.
  159833. * You may need to change these if you have a machine with unusual data
  159834. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159835. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159836. * but it had better be at least 16.
  159837. */
  159838. /* Representation of a single sample (pixel element value).
  159839. * We frequently allocate large arrays of these, so it's important to keep
  159840. * them small. But if you have memory to burn and access to char or short
  159841. * arrays is very slow on your hardware, you might want to change these.
  159842. */
  159843. #if BITS_IN_JSAMPLE == 8
  159844. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159845. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159846. */
  159847. #ifdef HAVE_UNSIGNED_CHAR
  159848. typedef unsigned char JSAMPLE;
  159849. #define GETJSAMPLE(value) ((int) (value))
  159850. #else /* not HAVE_UNSIGNED_CHAR */
  159851. typedef char JSAMPLE;
  159852. #ifdef CHAR_IS_UNSIGNED
  159853. #define GETJSAMPLE(value) ((int) (value))
  159854. #else
  159855. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159856. #endif /* CHAR_IS_UNSIGNED */
  159857. #endif /* HAVE_UNSIGNED_CHAR */
  159858. #define MAXJSAMPLE 255
  159859. #define CENTERJSAMPLE 128
  159860. #endif /* BITS_IN_JSAMPLE == 8 */
  159861. #if BITS_IN_JSAMPLE == 12
  159862. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159863. * On nearly all machines "short" will do nicely.
  159864. */
  159865. typedef short JSAMPLE;
  159866. #define GETJSAMPLE(value) ((int) (value))
  159867. #define MAXJSAMPLE 4095
  159868. #define CENTERJSAMPLE 2048
  159869. #endif /* BITS_IN_JSAMPLE == 12 */
  159870. /* Representation of a DCT frequency coefficient.
  159871. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159872. * Again, we allocate large arrays of these, but you can change to int
  159873. * if you have memory to burn and "short" is really slow.
  159874. */
  159875. typedef short JCOEF;
  159876. /* Compressed datastreams are represented as arrays of JOCTET.
  159877. * These must be EXACTLY 8 bits wide, at least once they are written to
  159878. * external storage. Note that when using the stdio data source/destination
  159879. * managers, this is also the data type passed to fread/fwrite.
  159880. */
  159881. #ifdef HAVE_UNSIGNED_CHAR
  159882. typedef unsigned char JOCTET;
  159883. #define GETJOCTET(value) (value)
  159884. #else /* not HAVE_UNSIGNED_CHAR */
  159885. typedef char JOCTET;
  159886. #ifdef CHAR_IS_UNSIGNED
  159887. #define GETJOCTET(value) (value)
  159888. #else
  159889. #define GETJOCTET(value) ((value) & 0xFF)
  159890. #endif /* CHAR_IS_UNSIGNED */
  159891. #endif /* HAVE_UNSIGNED_CHAR */
  159892. /* These typedefs are used for various table entries and so forth.
  159893. * They must be at least as wide as specified; but making them too big
  159894. * won't cost a huge amount of memory, so we don't provide special
  159895. * extraction code like we did for JSAMPLE. (In other words, these
  159896. * typedefs live at a different point on the speed/space tradeoff curve.)
  159897. */
  159898. /* UINT8 must hold at least the values 0..255. */
  159899. #ifdef HAVE_UNSIGNED_CHAR
  159900. typedef unsigned char UINT8;
  159901. #else /* not HAVE_UNSIGNED_CHAR */
  159902. #ifdef CHAR_IS_UNSIGNED
  159903. typedef char UINT8;
  159904. #else /* not CHAR_IS_UNSIGNED */
  159905. typedef short UINT8;
  159906. #endif /* CHAR_IS_UNSIGNED */
  159907. #endif /* HAVE_UNSIGNED_CHAR */
  159908. /* UINT16 must hold at least the values 0..65535. */
  159909. #ifdef HAVE_UNSIGNED_SHORT
  159910. typedef unsigned short UINT16;
  159911. #else /* not HAVE_UNSIGNED_SHORT */
  159912. typedef unsigned int UINT16;
  159913. #endif /* HAVE_UNSIGNED_SHORT */
  159914. /* INT16 must hold at least the values -32768..32767. */
  159915. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159916. typedef short INT16;
  159917. #endif
  159918. /* INT32 must hold at least signed 32-bit values. */
  159919. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159920. typedef long INT32;
  159921. #endif
  159922. /* Datatype used for image dimensions. The JPEG standard only supports
  159923. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159924. * "unsigned int" is sufficient on all machines. However, if you need to
  159925. * handle larger images and you don't mind deviating from the spec, you
  159926. * can change this datatype.
  159927. */
  159928. typedef unsigned int JDIMENSION;
  159929. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159930. /* These macros are used in all function definitions and extern declarations.
  159931. * You could modify them if you need to change function linkage conventions;
  159932. * in particular, you'll need to do that to make the library a Windows DLL.
  159933. * Another application is to make all functions global for use with debuggers
  159934. * or code profilers that require it.
  159935. */
  159936. /* a function called through method pointers: */
  159937. #define METHODDEF(type) static type
  159938. /* a function used only in its module: */
  159939. #define LOCAL(type) static type
  159940. /* a function referenced thru EXTERNs: */
  159941. #define GLOBAL(type) type
  159942. /* a reference to a GLOBAL function: */
  159943. #define EXTERN(type) extern type
  159944. /* This macro is used to declare a "method", that is, a function pointer.
  159945. * We want to supply prototype parameters if the compiler can cope.
  159946. * Note that the arglist parameter must be parenthesized!
  159947. * Again, you can customize this if you need special linkage keywords.
  159948. */
  159949. #ifdef HAVE_PROTOTYPES
  159950. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159951. #else
  159952. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159953. #endif
  159954. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159955. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159956. * by just saying "FAR *" where such a pointer is needed. In a few places
  159957. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159958. */
  159959. #ifdef NEED_FAR_POINTERS
  159960. #define FAR far
  159961. #else
  159962. #define FAR
  159963. #endif
  159964. /*
  159965. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159966. * in standard header files. Or you may have conflicts with application-
  159967. * specific header files that you want to include together with these files.
  159968. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159969. */
  159970. #ifndef HAVE_BOOLEAN
  159971. typedef int boolean;
  159972. #endif
  159973. #ifndef FALSE /* in case these macros already exist */
  159974. #define FALSE 0 /* values of boolean */
  159975. #endif
  159976. #ifndef TRUE
  159977. #define TRUE 1
  159978. #endif
  159979. /*
  159980. * The remaining options affect code selection within the JPEG library,
  159981. * but they don't need to be visible to most applications using the library.
  159982. * To minimize application namespace pollution, the symbols won't be
  159983. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159984. */
  159985. #ifdef JPEG_INTERNALS
  159986. #define JPEG_INTERNAL_OPTIONS
  159987. #endif
  159988. #ifdef JPEG_INTERNAL_OPTIONS
  159989. /*
  159990. * These defines indicate whether to include various optional functions.
  159991. * Undefining some of these symbols will produce a smaller but less capable
  159992. * library. Note that you can leave certain source files out of the
  159993. * compilation/linking process if you've #undef'd the corresponding symbols.
  159994. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159995. */
  159996. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159997. /* Capability options common to encoder and decoder: */
  159998. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159999. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160000. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160001. /* Encoder capability options: */
  160002. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160003. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160004. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160005. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160006. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160007. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160008. * precision, so jchuff.c normally uses entropy optimization to compute
  160009. * usable tables for higher precision. If you don't want to do optimization,
  160010. * you'll have to supply different default Huffman tables.
  160011. * The exact same statements apply for progressive JPEG: the default tables
  160012. * don't work for progressive mode. (This may get fixed, however.)
  160013. */
  160014. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160015. /* Decoder capability options: */
  160016. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160017. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160018. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160019. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160020. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160021. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160022. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160023. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160024. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160025. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160026. /* more capability options later, no doubt */
  160027. /*
  160028. * Ordering of RGB data in scanlines passed to or from the application.
  160029. * If your application wants to deal with data in the order B,G,R, just
  160030. * change these macros. You can also deal with formats such as R,G,B,X
  160031. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160032. * the offsets will also change the order in which colormap data is organized.
  160033. * RESTRICTIONS:
  160034. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160035. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160036. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160037. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160038. * is not 3 (they don't understand about dummy color components!). So you
  160039. * can't use color quantization if you change that value.
  160040. */
  160041. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160042. #define RGB_GREEN 1 /* Offset of Green */
  160043. #define RGB_BLUE 2 /* Offset of Blue */
  160044. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160045. /* Definitions for speed-related optimizations. */
  160046. /* If your compiler supports inline functions, define INLINE
  160047. * as the inline keyword; otherwise define it as empty.
  160048. */
  160049. #ifndef INLINE
  160050. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160051. #define INLINE __inline__
  160052. #endif
  160053. #ifndef INLINE
  160054. #define INLINE /* default is to define it as empty */
  160055. #endif
  160056. #endif
  160057. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160058. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160059. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160060. */
  160061. #ifndef MULTIPLIER
  160062. #define MULTIPLIER int /* type for fastest integer multiply */
  160063. #endif
  160064. /* FAST_FLOAT should be either float or double, whichever is done faster
  160065. * by your compiler. (Note that this type is only used in the floating point
  160066. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160067. * Typically, float is faster in ANSI C compilers, while double is faster in
  160068. * pre-ANSI compilers (because they insist on converting to double anyway).
  160069. * The code below therefore chooses float if we have ANSI-style prototypes.
  160070. */
  160071. #ifndef FAST_FLOAT
  160072. #ifdef HAVE_PROTOTYPES
  160073. #define FAST_FLOAT float
  160074. #else
  160075. #define FAST_FLOAT double
  160076. #endif
  160077. #endif
  160078. #endif /* JPEG_INTERNAL_OPTIONS */
  160079. /*** End of inlined file: jmorecfg.h ***/
  160080. /* seldom changed options */
  160081. /* Version ID for the JPEG library.
  160082. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160083. */
  160084. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160085. /* Various constants determining the sizes of things.
  160086. * All of these are specified by the JPEG standard, so don't change them
  160087. * if you want to be compatible.
  160088. */
  160089. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160090. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160091. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160092. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160093. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160094. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160095. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160096. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160097. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160098. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160099. * to handle it. We even let you do this from the jconfig.h file. However,
  160100. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160101. * sometimes emits noncompliant files doesn't mean you should too.
  160102. */
  160103. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160104. #ifndef D_MAX_BLOCKS_IN_MCU
  160105. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160106. #endif
  160107. /* Data structures for images (arrays of samples and of DCT coefficients).
  160108. * On 80x86 machines, the image arrays are too big for near pointers,
  160109. * but the pointer arrays can fit in near memory.
  160110. */
  160111. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160112. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160113. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160114. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160115. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160116. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160117. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160118. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160119. /* Types for JPEG compression parameters and working tables. */
  160120. /* DCT coefficient quantization tables. */
  160121. typedef struct {
  160122. /* This array gives the coefficient quantizers in natural array order
  160123. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160124. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160125. */
  160126. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160127. /* This field is used only during compression. It's initialized FALSE when
  160128. * the table is created, and set TRUE when it's been output to the file.
  160129. * You could suppress output of a table by setting this to TRUE.
  160130. * (See jpeg_suppress_tables for an example.)
  160131. */
  160132. boolean sent_table; /* TRUE when table has been output */
  160133. } JQUANT_TBL;
  160134. /* Huffman coding tables. */
  160135. typedef struct {
  160136. /* These two fields directly represent the contents of a JPEG DHT marker */
  160137. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160138. /* length k bits; bits[0] is unused */
  160139. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160140. /* This field is used only during compression. It's initialized FALSE when
  160141. * the table is created, and set TRUE when it's been output to the file.
  160142. * You could suppress output of a table by setting this to TRUE.
  160143. * (See jpeg_suppress_tables for an example.)
  160144. */
  160145. boolean sent_table; /* TRUE when table has been output */
  160146. } JHUFF_TBL;
  160147. /* Basic info about one component (color channel). */
  160148. typedef struct {
  160149. /* These values are fixed over the whole image. */
  160150. /* For compression, they must be supplied by parameter setup; */
  160151. /* for decompression, they are read from the SOF marker. */
  160152. int component_id; /* identifier for this component (0..255) */
  160153. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160154. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160155. int v_samp_factor; /* vertical sampling factor (1..4) */
  160156. int quant_tbl_no; /* quantization table selector (0..3) */
  160157. /* These values may vary between scans. */
  160158. /* For compression, they must be supplied by parameter setup; */
  160159. /* for decompression, they are read from the SOS marker. */
  160160. /* The decompressor output side may not use these variables. */
  160161. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160162. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160163. /* Remaining fields should be treated as private by applications. */
  160164. /* These values are computed during compression or decompression startup: */
  160165. /* Component's size in DCT blocks.
  160166. * Any dummy blocks added to complete an MCU are not counted; therefore
  160167. * these values do not depend on whether a scan is interleaved or not.
  160168. */
  160169. JDIMENSION width_in_blocks;
  160170. JDIMENSION height_in_blocks;
  160171. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160172. * For decompression this is the size of the output from one DCT block,
  160173. * reflecting any scaling we choose to apply during the IDCT step.
  160174. * Values of 1,2,4,8 are likely to be supported. Note that different
  160175. * components may receive different IDCT scalings.
  160176. */
  160177. int DCT_scaled_size;
  160178. /* The downsampled dimensions are the component's actual, unpadded number
  160179. * of samples at the main buffer (preprocessing/compression interface), thus
  160180. * downsampled_width = ceil(image_width * Hi/Hmax)
  160181. * and similarly for height. For decompression, IDCT scaling is included, so
  160182. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160183. */
  160184. JDIMENSION downsampled_width; /* actual width in samples */
  160185. JDIMENSION downsampled_height; /* actual height in samples */
  160186. /* This flag is used only for decompression. In cases where some of the
  160187. * components will be ignored (eg grayscale output from YCbCr image),
  160188. * we can skip most computations for the unused components.
  160189. */
  160190. boolean component_needed; /* do we need the value of this component? */
  160191. /* These values are computed before starting a scan of the component. */
  160192. /* The decompressor output side may not use these variables. */
  160193. int MCU_width; /* number of blocks per MCU, horizontally */
  160194. int MCU_height; /* number of blocks per MCU, vertically */
  160195. int MCU_blocks; /* MCU_width * MCU_height */
  160196. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160197. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160198. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160199. /* Saved quantization table for component; NULL if none yet saved.
  160200. * See jdinput.c comments about the need for this information.
  160201. * This field is currently used only for decompression.
  160202. */
  160203. JQUANT_TBL * quant_table;
  160204. /* Private per-component storage for DCT or IDCT subsystem. */
  160205. void * dct_table;
  160206. } jpeg_component_info;
  160207. /* The script for encoding a multiple-scan file is an array of these: */
  160208. typedef struct {
  160209. int comps_in_scan; /* number of components encoded in this scan */
  160210. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160211. int Ss, Se; /* progressive JPEG spectral selection parms */
  160212. int Ah, Al; /* progressive JPEG successive approx. parms */
  160213. } jpeg_scan_info;
  160214. /* The decompressor can save APPn and COM markers in a list of these: */
  160215. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160216. struct jpeg_marker_struct {
  160217. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160218. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160219. unsigned int original_length; /* # bytes of data in the file */
  160220. unsigned int data_length; /* # bytes of data saved at data[] */
  160221. JOCTET FAR * data; /* the data contained in the marker */
  160222. /* the marker length word is not counted in data_length or original_length */
  160223. };
  160224. /* Known color spaces. */
  160225. typedef enum {
  160226. JCS_UNKNOWN, /* error/unspecified */
  160227. JCS_GRAYSCALE, /* monochrome */
  160228. JCS_RGB, /* red/green/blue */
  160229. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160230. JCS_CMYK, /* C/M/Y/K */
  160231. JCS_YCCK /* Y/Cb/Cr/K */
  160232. } J_COLOR_SPACE;
  160233. /* DCT/IDCT algorithm options. */
  160234. typedef enum {
  160235. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160236. JDCT_IFAST, /* faster, less accurate integer method */
  160237. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160238. } J_DCT_METHOD;
  160239. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160240. #define JDCT_DEFAULT JDCT_ISLOW
  160241. #endif
  160242. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160243. #define JDCT_FASTEST JDCT_IFAST
  160244. #endif
  160245. /* Dithering options for decompression. */
  160246. typedef enum {
  160247. JDITHER_NONE, /* no dithering */
  160248. JDITHER_ORDERED, /* simple ordered dither */
  160249. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160250. } J_DITHER_MODE;
  160251. /* Common fields between JPEG compression and decompression master structs. */
  160252. #define jpeg_common_fields \
  160253. struct jpeg_error_mgr * err; /* Error handler module */\
  160254. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160255. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160256. void * client_data; /* Available for use by application */\
  160257. boolean is_decompressor; /* So common code can tell which is which */\
  160258. int global_state /* For checking call sequence validity */
  160259. /* Routines that are to be used by both halves of the library are declared
  160260. * to receive a pointer to this structure. There are no actual instances of
  160261. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160262. */
  160263. struct jpeg_common_struct {
  160264. jpeg_common_fields; /* Fields common to both master struct types */
  160265. /* Additional fields follow in an actual jpeg_compress_struct or
  160266. * jpeg_decompress_struct. All three structs must agree on these
  160267. * initial fields! (This would be a lot cleaner in C++.)
  160268. */
  160269. };
  160270. typedef struct jpeg_common_struct * j_common_ptr;
  160271. typedef struct jpeg_compress_struct * j_compress_ptr;
  160272. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160273. /* Master record for a compression instance */
  160274. struct jpeg_compress_struct {
  160275. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160276. /* Destination for compressed data */
  160277. struct jpeg_destination_mgr * dest;
  160278. /* Description of source image --- these fields must be filled in by
  160279. * outer application before starting compression. in_color_space must
  160280. * be correct before you can even call jpeg_set_defaults().
  160281. */
  160282. JDIMENSION image_width; /* input image width */
  160283. JDIMENSION image_height; /* input image height */
  160284. int input_components; /* # of color components in input image */
  160285. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160286. double input_gamma; /* image gamma of input image */
  160287. /* Compression parameters --- these fields must be set before calling
  160288. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160289. * initialize everything to reasonable defaults, then changing anything
  160290. * the application specifically wants to change. That way you won't get
  160291. * burnt when new parameters are added. Also note that there are several
  160292. * helper routines to simplify changing parameters.
  160293. */
  160294. int data_precision; /* bits of precision in image data */
  160295. int num_components; /* # of color components in JPEG image */
  160296. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160297. jpeg_component_info * comp_info;
  160298. /* comp_info[i] describes component that appears i'th in SOF */
  160299. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160300. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160301. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160302. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160303. /* ptrs to Huffman coding tables, or NULL if not defined */
  160304. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160305. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160306. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160307. int num_scans; /* # of entries in scan_info array */
  160308. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160309. /* The default value of scan_info is NULL, which causes a single-scan
  160310. * sequential JPEG file to be emitted. To create a multi-scan file,
  160311. * set num_scans and scan_info to point to an array of scan definitions.
  160312. */
  160313. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160314. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160315. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160316. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160317. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160318. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160319. /* The restart interval can be specified in absolute MCUs by setting
  160320. * restart_interval, or in MCU rows by setting restart_in_rows
  160321. * (in which case the correct restart_interval will be figured
  160322. * for each scan).
  160323. */
  160324. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160325. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160326. /* Parameters controlling emission of special markers. */
  160327. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160328. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160329. UINT8 JFIF_minor_version;
  160330. /* These three values are not used by the JPEG code, merely copied */
  160331. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160332. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160333. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160334. UINT8 density_unit; /* JFIF code for pixel size units */
  160335. UINT16 X_density; /* Horizontal pixel density */
  160336. UINT16 Y_density; /* Vertical pixel density */
  160337. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160338. /* State variable: index of next scanline to be written to
  160339. * jpeg_write_scanlines(). Application may use this to control its
  160340. * processing loop, e.g., "while (next_scanline < image_height)".
  160341. */
  160342. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160343. /* Remaining fields are known throughout compressor, but generally
  160344. * should not be touched by a surrounding application.
  160345. */
  160346. /*
  160347. * These fields are computed during compression startup
  160348. */
  160349. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160350. int max_h_samp_factor; /* largest h_samp_factor */
  160351. int max_v_samp_factor; /* largest v_samp_factor */
  160352. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160353. /* The coefficient controller receives data in units of MCU rows as defined
  160354. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160355. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160356. * "iMCU" (interleaved MCU) row.
  160357. */
  160358. /*
  160359. * These fields are valid during any one scan.
  160360. * They describe the components and MCUs actually appearing in the scan.
  160361. */
  160362. int comps_in_scan; /* # of JPEG components in this scan */
  160363. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160364. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160365. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160366. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160367. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160368. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160369. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160370. /* i'th block in an MCU */
  160371. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160372. /*
  160373. * Links to compression subobjects (methods and private variables of modules)
  160374. */
  160375. struct jpeg_comp_master * master;
  160376. struct jpeg_c_main_controller * main;
  160377. struct jpeg_c_prep_controller * prep;
  160378. struct jpeg_c_coef_controller * coef;
  160379. struct jpeg_marker_writer * marker;
  160380. struct jpeg_color_converter * cconvert;
  160381. struct jpeg_downsampler * downsample;
  160382. struct jpeg_forward_dct * fdct;
  160383. struct jpeg_entropy_encoder * entropy;
  160384. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160385. int script_space_size;
  160386. };
  160387. /* Master record for a decompression instance */
  160388. struct jpeg_decompress_struct {
  160389. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160390. /* Source of compressed data */
  160391. struct jpeg_source_mgr * src;
  160392. /* Basic description of image --- filled in by jpeg_read_header(). */
  160393. /* Application may inspect these values to decide how to process image. */
  160394. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160395. JDIMENSION image_height; /* nominal image height */
  160396. int num_components; /* # of color components in JPEG image */
  160397. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160398. /* Decompression processing parameters --- these fields must be set before
  160399. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160400. * them to default values.
  160401. */
  160402. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160403. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160404. double output_gamma; /* image gamma wanted in output */
  160405. boolean buffered_image; /* TRUE=multiple output passes */
  160406. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160407. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160408. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160409. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160410. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160411. /* the following are ignored if not quantize_colors: */
  160412. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160413. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160414. int desired_number_of_colors; /* max # colors to use in created colormap */
  160415. /* these are significant only in buffered-image mode: */
  160416. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160417. boolean enable_external_quant;/* enable future use of external colormap */
  160418. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160419. /* Description of actual output image that will be returned to application.
  160420. * These fields are computed by jpeg_start_decompress().
  160421. * You can also use jpeg_calc_output_dimensions() to determine these values
  160422. * in advance of calling jpeg_start_decompress().
  160423. */
  160424. JDIMENSION output_width; /* scaled image width */
  160425. JDIMENSION output_height; /* scaled image height */
  160426. int out_color_components; /* # of color components in out_color_space */
  160427. int output_components; /* # of color components returned */
  160428. /* output_components is 1 (a colormap index) when quantizing colors;
  160429. * otherwise it equals out_color_components.
  160430. */
  160431. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160432. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160433. * high, space and time will be wasted due to unnecessary data copying.
  160434. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160435. */
  160436. /* When quantizing colors, the output colormap is described by these fields.
  160437. * The application can supply a colormap by setting colormap non-NULL before
  160438. * calling jpeg_start_decompress; otherwise a colormap is created during
  160439. * jpeg_start_decompress or jpeg_start_output.
  160440. * The map has out_color_components rows and actual_number_of_colors columns.
  160441. */
  160442. int actual_number_of_colors; /* number of entries in use */
  160443. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160444. /* State variables: these variables indicate the progress of decompression.
  160445. * The application may examine these but must not modify them.
  160446. */
  160447. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160448. * Application may use this to control its processing loop, e.g.,
  160449. * "while (output_scanline < output_height)".
  160450. */
  160451. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160452. /* Current input scan number and number of iMCU rows completed in scan.
  160453. * These indicate the progress of the decompressor input side.
  160454. */
  160455. int input_scan_number; /* Number of SOS markers seen so far */
  160456. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160457. /* The "output scan number" is the notional scan being displayed by the
  160458. * output side. The decompressor will not allow output scan/row number
  160459. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160460. */
  160461. int output_scan_number; /* Nominal scan number being displayed */
  160462. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160463. /* Current progression status. coef_bits[c][i] indicates the precision
  160464. * with which component c's DCT coefficient i (in zigzag order) is known.
  160465. * It is -1 when no data has yet been received, otherwise it is the point
  160466. * transform (shift) value for the most recent scan of the coefficient
  160467. * (thus, 0 at completion of the progression).
  160468. * This pointer is NULL when reading a non-progressive file.
  160469. */
  160470. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160471. /* Internal JPEG parameters --- the application usually need not look at
  160472. * these fields. Note that the decompressor output side may not use
  160473. * any parameters that can change between scans.
  160474. */
  160475. /* Quantization and Huffman tables are carried forward across input
  160476. * datastreams when processing abbreviated JPEG datastreams.
  160477. */
  160478. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160479. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160480. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160481. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160482. /* ptrs to Huffman coding tables, or NULL if not defined */
  160483. /* These parameters are never carried across datastreams, since they
  160484. * are given in SOF/SOS markers or defined to be reset by SOI.
  160485. */
  160486. int data_precision; /* bits of precision in image data */
  160487. jpeg_component_info * comp_info;
  160488. /* comp_info[i] describes component that appears i'th in SOF */
  160489. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160490. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160491. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160492. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160493. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160494. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160495. /* These fields record data obtained from optional markers recognized by
  160496. * the JPEG library.
  160497. */
  160498. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160499. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160500. UINT8 JFIF_major_version; /* JFIF version number */
  160501. UINT8 JFIF_minor_version;
  160502. UINT8 density_unit; /* JFIF code for pixel size units */
  160503. UINT16 X_density; /* Horizontal pixel density */
  160504. UINT16 Y_density; /* Vertical pixel density */
  160505. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160506. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160507. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160508. /* Aside from the specific data retained from APPn markers known to the
  160509. * library, the uninterpreted contents of any or all APPn and COM markers
  160510. * can be saved in a list for examination by the application.
  160511. */
  160512. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160513. /* Remaining fields are known throughout decompressor, but generally
  160514. * should not be touched by a surrounding application.
  160515. */
  160516. /*
  160517. * These fields are computed during decompression startup
  160518. */
  160519. int max_h_samp_factor; /* largest h_samp_factor */
  160520. int max_v_samp_factor; /* largest v_samp_factor */
  160521. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160522. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160523. /* The coefficient controller's input and output progress is measured in
  160524. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160525. * in fully interleaved JPEG scans, but are used whether the scan is
  160526. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160527. * rows of each component. Therefore, the IDCT output contains
  160528. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160529. */
  160530. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160531. /*
  160532. * These fields are valid during any one scan.
  160533. * They describe the components and MCUs actually appearing in the scan.
  160534. * Note that the decompressor output side must not use these fields.
  160535. */
  160536. int comps_in_scan; /* # of JPEG components in this scan */
  160537. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160538. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160539. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160540. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160541. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160542. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160543. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160544. /* i'th block in an MCU */
  160545. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160546. /* This field is shared between entropy decoder and marker parser.
  160547. * It is either zero or the code of a JPEG marker that has been
  160548. * read from the data source, but has not yet been processed.
  160549. */
  160550. int unread_marker;
  160551. /*
  160552. * Links to decompression subobjects (methods, private variables of modules)
  160553. */
  160554. struct jpeg_decomp_master * master;
  160555. struct jpeg_d_main_controller * main;
  160556. struct jpeg_d_coef_controller * coef;
  160557. struct jpeg_d_post_controller * post;
  160558. struct jpeg_input_controller * inputctl;
  160559. struct jpeg_marker_reader * marker;
  160560. struct jpeg_entropy_decoder * entropy;
  160561. struct jpeg_inverse_dct * idct;
  160562. struct jpeg_upsampler * upsample;
  160563. struct jpeg_color_deconverter * cconvert;
  160564. struct jpeg_color_quantizer * cquantize;
  160565. };
  160566. /* "Object" declarations for JPEG modules that may be supplied or called
  160567. * directly by the surrounding application.
  160568. * As with all objects in the JPEG library, these structs only define the
  160569. * publicly visible methods and state variables of a module. Additional
  160570. * private fields may exist after the public ones.
  160571. */
  160572. /* Error handler object */
  160573. struct jpeg_error_mgr {
  160574. /* Error exit handler: does not return to caller */
  160575. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160576. /* Conditionally emit a trace or warning message */
  160577. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160578. /* Routine that actually outputs a trace or error message */
  160579. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160580. /* Format a message string for the most recent JPEG error or message */
  160581. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160582. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160583. /* Reset error state variables at start of a new image */
  160584. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160585. /* The message ID code and any parameters are saved here.
  160586. * A message can have one string parameter or up to 8 int parameters.
  160587. */
  160588. int msg_code;
  160589. #define JMSG_STR_PARM_MAX 80
  160590. union {
  160591. int i[8];
  160592. char s[JMSG_STR_PARM_MAX];
  160593. } msg_parm;
  160594. /* Standard state variables for error facility */
  160595. int trace_level; /* max msg_level that will be displayed */
  160596. /* For recoverable corrupt-data errors, we emit a warning message,
  160597. * but keep going unless emit_message chooses to abort. emit_message
  160598. * should count warnings in num_warnings. The surrounding application
  160599. * can check for bad data by seeing if num_warnings is nonzero at the
  160600. * end of processing.
  160601. */
  160602. long num_warnings; /* number of corrupt-data warnings */
  160603. /* These fields point to the table(s) of error message strings.
  160604. * An application can change the table pointer to switch to a different
  160605. * message list (typically, to change the language in which errors are
  160606. * reported). Some applications may wish to add additional error codes
  160607. * that will be handled by the JPEG library error mechanism; the second
  160608. * table pointer is used for this purpose.
  160609. *
  160610. * First table includes all errors generated by JPEG library itself.
  160611. * Error code 0 is reserved for a "no such error string" message.
  160612. */
  160613. const char * const * jpeg_message_table; /* Library errors */
  160614. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160615. /* Second table can be added by application (see cjpeg/djpeg for example).
  160616. * It contains strings numbered first_addon_message..last_addon_message.
  160617. */
  160618. const char * const * addon_message_table; /* Non-library errors */
  160619. int first_addon_message; /* code for first string in addon table */
  160620. int last_addon_message; /* code for last string in addon table */
  160621. };
  160622. /* Progress monitor object */
  160623. struct jpeg_progress_mgr {
  160624. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160625. long pass_counter; /* work units completed in this pass */
  160626. long pass_limit; /* total number of work units in this pass */
  160627. int completed_passes; /* passes completed so far */
  160628. int total_passes; /* total number of passes expected */
  160629. };
  160630. /* Data destination object for compression */
  160631. struct jpeg_destination_mgr {
  160632. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160633. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160634. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160635. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160636. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160637. };
  160638. /* Data source object for decompression */
  160639. struct jpeg_source_mgr {
  160640. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160641. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160642. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160643. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160644. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160645. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160646. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160647. };
  160648. /* Memory manager object.
  160649. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160650. * and "really big" objects (virtual arrays with backing store if needed).
  160651. * The memory manager does not allow individual objects to be freed; rather,
  160652. * each created object is assigned to a pool, and whole pools can be freed
  160653. * at once. This is faster and more convenient than remembering exactly what
  160654. * to free, especially where malloc()/free() are not too speedy.
  160655. * NB: alloc routines never return NULL. They exit to error_exit if not
  160656. * successful.
  160657. */
  160658. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160659. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160660. #define JPOOL_NUMPOOLS 2
  160661. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160662. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160663. struct jpeg_memory_mgr {
  160664. /* Method pointers */
  160665. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160666. size_t sizeofobject));
  160667. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160668. size_t sizeofobject));
  160669. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160670. JDIMENSION samplesperrow,
  160671. JDIMENSION numrows));
  160672. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160673. JDIMENSION blocksperrow,
  160674. JDIMENSION numrows));
  160675. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160676. int pool_id,
  160677. boolean pre_zero,
  160678. JDIMENSION samplesperrow,
  160679. JDIMENSION numrows,
  160680. JDIMENSION maxaccess));
  160681. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160682. int pool_id,
  160683. boolean pre_zero,
  160684. JDIMENSION blocksperrow,
  160685. JDIMENSION numrows,
  160686. JDIMENSION maxaccess));
  160687. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160688. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160689. jvirt_sarray_ptr ptr,
  160690. JDIMENSION start_row,
  160691. JDIMENSION num_rows,
  160692. boolean writable));
  160693. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160694. jvirt_barray_ptr ptr,
  160695. JDIMENSION start_row,
  160696. JDIMENSION num_rows,
  160697. boolean writable));
  160698. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160699. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160700. /* Limit on memory allocation for this JPEG object. (Note that this is
  160701. * merely advisory, not a guaranteed maximum; it only affects the space
  160702. * used for virtual-array buffers.) May be changed by outer application
  160703. * after creating the JPEG object.
  160704. */
  160705. long max_memory_to_use;
  160706. /* Maximum allocation request accepted by alloc_large. */
  160707. long max_alloc_chunk;
  160708. };
  160709. /* Routine signature for application-supplied marker processing methods.
  160710. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160711. */
  160712. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160713. /* Declarations for routines called by application.
  160714. * The JPP macro hides prototype parameters from compilers that can't cope.
  160715. * Note JPP requires double parentheses.
  160716. */
  160717. #ifdef HAVE_PROTOTYPES
  160718. #define JPP(arglist) arglist
  160719. #else
  160720. #define JPP(arglist) ()
  160721. #endif
  160722. /* Short forms of external names for systems with brain-damaged linkers.
  160723. * We shorten external names to be unique in the first six letters, which
  160724. * is good enough for all known systems.
  160725. * (If your compiler itself needs names to be unique in less than 15
  160726. * characters, you are out of luck. Get a better compiler.)
  160727. */
  160728. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160729. #define jpeg_std_error jStdError
  160730. #define jpeg_CreateCompress jCreaCompress
  160731. #define jpeg_CreateDecompress jCreaDecompress
  160732. #define jpeg_destroy_compress jDestCompress
  160733. #define jpeg_destroy_decompress jDestDecompress
  160734. #define jpeg_stdio_dest jStdDest
  160735. #define jpeg_stdio_src jStdSrc
  160736. #define jpeg_set_defaults jSetDefaults
  160737. #define jpeg_set_colorspace jSetColorspace
  160738. #define jpeg_default_colorspace jDefColorspace
  160739. #define jpeg_set_quality jSetQuality
  160740. #define jpeg_set_linear_quality jSetLQuality
  160741. #define jpeg_add_quant_table jAddQuantTable
  160742. #define jpeg_quality_scaling jQualityScaling
  160743. #define jpeg_simple_progression jSimProgress
  160744. #define jpeg_suppress_tables jSuppressTables
  160745. #define jpeg_alloc_quant_table jAlcQTable
  160746. #define jpeg_alloc_huff_table jAlcHTable
  160747. #define jpeg_start_compress jStrtCompress
  160748. #define jpeg_write_scanlines jWrtScanlines
  160749. #define jpeg_finish_compress jFinCompress
  160750. #define jpeg_write_raw_data jWrtRawData
  160751. #define jpeg_write_marker jWrtMarker
  160752. #define jpeg_write_m_header jWrtMHeader
  160753. #define jpeg_write_m_byte jWrtMByte
  160754. #define jpeg_write_tables jWrtTables
  160755. #define jpeg_read_header jReadHeader
  160756. #define jpeg_start_decompress jStrtDecompress
  160757. #define jpeg_read_scanlines jReadScanlines
  160758. #define jpeg_finish_decompress jFinDecompress
  160759. #define jpeg_read_raw_data jReadRawData
  160760. #define jpeg_has_multiple_scans jHasMultScn
  160761. #define jpeg_start_output jStrtOutput
  160762. #define jpeg_finish_output jFinOutput
  160763. #define jpeg_input_complete jInComplete
  160764. #define jpeg_new_colormap jNewCMap
  160765. #define jpeg_consume_input jConsumeInput
  160766. #define jpeg_calc_output_dimensions jCalcDimensions
  160767. #define jpeg_save_markers jSaveMarkers
  160768. #define jpeg_set_marker_processor jSetMarker
  160769. #define jpeg_read_coefficients jReadCoefs
  160770. #define jpeg_write_coefficients jWrtCoefs
  160771. #define jpeg_copy_critical_parameters jCopyCrit
  160772. #define jpeg_abort_compress jAbrtCompress
  160773. #define jpeg_abort_decompress jAbrtDecompress
  160774. #define jpeg_abort jAbort
  160775. #define jpeg_destroy jDestroy
  160776. #define jpeg_resync_to_restart jResyncRestart
  160777. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160778. /* Default error-management setup */
  160779. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160780. JPP((struct jpeg_error_mgr * err));
  160781. /* Initialization of JPEG compression objects.
  160782. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160783. * names that applications should call. These expand to calls on
  160784. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160785. * passed for version mismatch checking.
  160786. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160787. */
  160788. #define jpeg_create_compress(cinfo) \
  160789. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160790. (size_t) sizeof(struct jpeg_compress_struct))
  160791. #define jpeg_create_decompress(cinfo) \
  160792. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160793. (size_t) sizeof(struct jpeg_decompress_struct))
  160794. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160795. int version, size_t structsize));
  160796. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160797. int version, size_t structsize));
  160798. /* Destruction of JPEG compression objects */
  160799. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160800. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160801. /* Standard data source and destination managers: stdio streams. */
  160802. /* Caller is responsible for opening the file before and closing after. */
  160803. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160804. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160805. /* Default parameter setup for compression */
  160806. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160807. /* Compression parameter setup aids */
  160808. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160809. J_COLOR_SPACE colorspace));
  160810. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160811. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160812. boolean force_baseline));
  160813. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160814. int scale_factor,
  160815. boolean force_baseline));
  160816. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160817. const unsigned int *basic_table,
  160818. int scale_factor,
  160819. boolean force_baseline));
  160820. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160821. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160822. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160823. boolean suppress));
  160824. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160825. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160826. /* Main entry points for compression */
  160827. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160828. boolean write_all_tables));
  160829. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160830. JSAMPARRAY scanlines,
  160831. JDIMENSION num_lines));
  160832. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160833. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160834. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160835. JSAMPIMAGE data,
  160836. JDIMENSION num_lines));
  160837. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160838. EXTERN(void) jpeg_write_marker
  160839. JPP((j_compress_ptr cinfo, int marker,
  160840. const JOCTET * dataptr, unsigned int datalen));
  160841. /* Same, but piecemeal. */
  160842. EXTERN(void) jpeg_write_m_header
  160843. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160844. EXTERN(void) jpeg_write_m_byte
  160845. JPP((j_compress_ptr cinfo, int val));
  160846. /* Alternate compression function: just write an abbreviated table file */
  160847. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160848. /* Decompression startup: read start of JPEG datastream to see what's there */
  160849. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160850. boolean require_image));
  160851. /* Return value is one of: */
  160852. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160853. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160854. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160855. /* If you pass require_image = TRUE (normal case), you need not check for
  160856. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160857. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160858. * give a suspension return (the stdio source module doesn't).
  160859. */
  160860. /* Main entry points for decompression */
  160861. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160862. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160863. JSAMPARRAY scanlines,
  160864. JDIMENSION max_lines));
  160865. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160866. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160867. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160868. JSAMPIMAGE data,
  160869. JDIMENSION max_lines));
  160870. /* Additional entry points for buffered-image mode. */
  160871. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160872. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160873. int scan_number));
  160874. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160875. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160876. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160877. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160878. /* Return value is one of: */
  160879. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160880. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160881. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160882. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160883. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160884. /* Precalculate output dimensions for current decompression parameters. */
  160885. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160886. /* Control saving of COM and APPn markers into marker_list. */
  160887. EXTERN(void) jpeg_save_markers
  160888. JPP((j_decompress_ptr cinfo, int marker_code,
  160889. unsigned int length_limit));
  160890. /* Install a special processing method for COM or APPn markers. */
  160891. EXTERN(void) jpeg_set_marker_processor
  160892. JPP((j_decompress_ptr cinfo, int marker_code,
  160893. jpeg_marker_parser_method routine));
  160894. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160895. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160896. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160897. jvirt_barray_ptr * coef_arrays));
  160898. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160899. j_compress_ptr dstinfo));
  160900. /* If you choose to abort compression or decompression before completing
  160901. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160902. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160903. * if you're done with the JPEG object, but if you want to clean it up and
  160904. * reuse it, call this:
  160905. */
  160906. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160907. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160908. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160909. * flavor of JPEG object. These may be more convenient in some places.
  160910. */
  160911. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160912. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160913. /* Default restart-marker-resync procedure for use by data source modules */
  160914. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160915. int desired));
  160916. /* These marker codes are exported since applications and data source modules
  160917. * are likely to want to use them.
  160918. */
  160919. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160920. #define JPEG_EOI 0xD9 /* EOI marker code */
  160921. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160922. #define JPEG_COM 0xFE /* COM marker code */
  160923. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160924. * for structure definitions that are never filled in, keep it quiet by
  160925. * supplying dummy definitions for the various substructures.
  160926. */
  160927. #ifdef INCOMPLETE_TYPES_BROKEN
  160928. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160929. struct jvirt_sarray_control { long dummy; };
  160930. struct jvirt_barray_control { long dummy; };
  160931. struct jpeg_comp_master { long dummy; };
  160932. struct jpeg_c_main_controller { long dummy; };
  160933. struct jpeg_c_prep_controller { long dummy; };
  160934. struct jpeg_c_coef_controller { long dummy; };
  160935. struct jpeg_marker_writer { long dummy; };
  160936. struct jpeg_color_converter { long dummy; };
  160937. struct jpeg_downsampler { long dummy; };
  160938. struct jpeg_forward_dct { long dummy; };
  160939. struct jpeg_entropy_encoder { long dummy; };
  160940. struct jpeg_decomp_master { long dummy; };
  160941. struct jpeg_d_main_controller { long dummy; };
  160942. struct jpeg_d_coef_controller { long dummy; };
  160943. struct jpeg_d_post_controller { long dummy; };
  160944. struct jpeg_input_controller { long dummy; };
  160945. struct jpeg_marker_reader { long dummy; };
  160946. struct jpeg_entropy_decoder { long dummy; };
  160947. struct jpeg_inverse_dct { long dummy; };
  160948. struct jpeg_upsampler { long dummy; };
  160949. struct jpeg_color_deconverter { long dummy; };
  160950. struct jpeg_color_quantizer { long dummy; };
  160951. #endif /* JPEG_INTERNALS */
  160952. #endif /* INCOMPLETE_TYPES_BROKEN */
  160953. /*
  160954. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160955. * The internal structure declarations are read only when that is true.
  160956. * Applications using the library should not include jpegint.h, but may wish
  160957. * to include jerror.h.
  160958. */
  160959. #ifdef JPEG_INTERNALS
  160960. /*** Start of inlined file: jpegint.h ***/
  160961. /* Declarations for both compression & decompression */
  160962. typedef enum { /* Operating modes for buffer controllers */
  160963. JBUF_PASS_THRU, /* Plain stripwise operation */
  160964. /* Remaining modes require a full-image buffer to have been created */
  160965. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160966. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160967. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160968. } J_BUF_MODE;
  160969. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160970. #define CSTATE_START 100 /* after create_compress */
  160971. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160972. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160973. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160974. #define DSTATE_START 200 /* after create_decompress */
  160975. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160976. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160977. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160978. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160979. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160980. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160981. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160982. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160983. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160984. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160985. /* Declarations for compression modules */
  160986. /* Master control module */
  160987. struct jpeg_comp_master {
  160988. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160989. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160990. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160991. /* State variables made visible to other modules */
  160992. boolean call_pass_startup; /* True if pass_startup must be called */
  160993. boolean is_last_pass; /* True during last pass */
  160994. };
  160995. /* Main buffer control (downsampled-data buffer) */
  160996. struct jpeg_c_main_controller {
  160997. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160998. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160999. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161000. JDIMENSION in_rows_avail));
  161001. };
  161002. /* Compression preprocessing (downsampling input buffer control) */
  161003. struct jpeg_c_prep_controller {
  161004. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161005. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161006. JSAMPARRAY input_buf,
  161007. JDIMENSION *in_row_ctr,
  161008. JDIMENSION in_rows_avail,
  161009. JSAMPIMAGE output_buf,
  161010. JDIMENSION *out_row_group_ctr,
  161011. JDIMENSION out_row_groups_avail));
  161012. };
  161013. /* Coefficient buffer control */
  161014. struct jpeg_c_coef_controller {
  161015. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161016. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161017. JSAMPIMAGE input_buf));
  161018. };
  161019. /* Colorspace conversion */
  161020. struct jpeg_color_converter {
  161021. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161022. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161023. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161024. JDIMENSION output_row, int num_rows));
  161025. };
  161026. /* Downsampling */
  161027. struct jpeg_downsampler {
  161028. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161029. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161030. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161031. JSAMPIMAGE output_buf,
  161032. JDIMENSION out_row_group_index));
  161033. boolean need_context_rows; /* TRUE if need rows above & below */
  161034. };
  161035. /* Forward DCT (also controls coefficient quantization) */
  161036. struct jpeg_forward_dct {
  161037. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161038. /* perhaps this should be an array??? */
  161039. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161040. jpeg_component_info * compptr,
  161041. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161042. JDIMENSION start_row, JDIMENSION start_col,
  161043. JDIMENSION num_blocks));
  161044. };
  161045. /* Entropy encoding */
  161046. struct jpeg_entropy_encoder {
  161047. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161048. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161049. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161050. };
  161051. /* Marker writing */
  161052. struct jpeg_marker_writer {
  161053. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161054. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161055. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161056. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161057. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161058. /* These routines are exported to allow insertion of extra markers */
  161059. /* Probably only COM and APPn markers should be written this way */
  161060. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161061. unsigned int datalen));
  161062. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161063. };
  161064. /* Declarations for decompression modules */
  161065. /* Master control module */
  161066. struct jpeg_decomp_master {
  161067. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161068. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161069. /* State variables made visible to other modules */
  161070. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161071. };
  161072. /* Input control module */
  161073. struct jpeg_input_controller {
  161074. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161075. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161076. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161077. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161078. /* State variables made visible to other modules */
  161079. boolean has_multiple_scans; /* True if file has multiple scans */
  161080. boolean eoi_reached; /* True when EOI has been consumed */
  161081. };
  161082. /* Main buffer control (downsampled-data buffer) */
  161083. struct jpeg_d_main_controller {
  161084. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161085. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161086. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161087. JDIMENSION out_rows_avail));
  161088. };
  161089. /* Coefficient buffer control */
  161090. struct jpeg_d_coef_controller {
  161091. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161092. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161093. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161094. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161095. JSAMPIMAGE output_buf));
  161096. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161097. jvirt_barray_ptr *coef_arrays;
  161098. };
  161099. /* Decompression postprocessing (color quantization buffer control) */
  161100. struct jpeg_d_post_controller {
  161101. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161102. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161103. JSAMPIMAGE input_buf,
  161104. JDIMENSION *in_row_group_ctr,
  161105. JDIMENSION in_row_groups_avail,
  161106. JSAMPARRAY output_buf,
  161107. JDIMENSION *out_row_ctr,
  161108. JDIMENSION out_rows_avail));
  161109. };
  161110. /* Marker reading & parsing */
  161111. struct jpeg_marker_reader {
  161112. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161113. /* Read markers until SOS or EOI.
  161114. * Returns same codes as are defined for jpeg_consume_input:
  161115. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161116. */
  161117. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161118. /* Read a restart marker --- exported for use by entropy decoder only */
  161119. jpeg_marker_parser_method read_restart_marker;
  161120. /* State of marker reader --- nominally internal, but applications
  161121. * supplying COM or APPn handlers might like to know the state.
  161122. */
  161123. boolean saw_SOI; /* found SOI? */
  161124. boolean saw_SOF; /* found SOF? */
  161125. int next_restart_num; /* next restart number expected (0-7) */
  161126. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161127. };
  161128. /* Entropy decoding */
  161129. struct jpeg_entropy_decoder {
  161130. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161131. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161132. JBLOCKROW *MCU_data));
  161133. /* This is here to share code between baseline and progressive decoders; */
  161134. /* other modules probably should not use it */
  161135. boolean insufficient_data; /* set TRUE after emitting warning */
  161136. };
  161137. /* Inverse DCT (also performs dequantization) */
  161138. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161139. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161140. JCOEFPTR coef_block,
  161141. JSAMPARRAY output_buf, JDIMENSION output_col));
  161142. struct jpeg_inverse_dct {
  161143. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161144. /* It is useful to allow each component to have a separate IDCT method. */
  161145. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161146. };
  161147. /* Upsampling (note that upsampler must also call color converter) */
  161148. struct jpeg_upsampler {
  161149. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161150. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161151. JSAMPIMAGE input_buf,
  161152. JDIMENSION *in_row_group_ctr,
  161153. JDIMENSION in_row_groups_avail,
  161154. JSAMPARRAY output_buf,
  161155. JDIMENSION *out_row_ctr,
  161156. JDIMENSION out_rows_avail));
  161157. boolean need_context_rows; /* TRUE if need rows above & below */
  161158. };
  161159. /* Colorspace conversion */
  161160. struct jpeg_color_deconverter {
  161161. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161162. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161163. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161164. JSAMPARRAY output_buf, int num_rows));
  161165. };
  161166. /* Color quantization or color precision reduction */
  161167. struct jpeg_color_quantizer {
  161168. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161169. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161170. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161171. int num_rows));
  161172. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161173. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161174. };
  161175. /* Miscellaneous useful macros */
  161176. #undef MAX
  161177. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161178. #undef MIN
  161179. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161180. /* We assume that right shift corresponds to signed division by 2 with
  161181. * rounding towards minus infinity. This is correct for typical "arithmetic
  161182. * shift" instructions that shift in copies of the sign bit. But some
  161183. * C compilers implement >> with an unsigned shift. For these machines you
  161184. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161185. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161186. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161187. * included in the variables of any routine using RIGHT_SHIFT.
  161188. */
  161189. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161190. #define SHIFT_TEMPS INT32 shift_temp;
  161191. #define RIGHT_SHIFT(x,shft) \
  161192. ((shift_temp = (x)) < 0 ? \
  161193. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161194. (shift_temp >> (shft)))
  161195. #else
  161196. #define SHIFT_TEMPS
  161197. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161198. #endif
  161199. /* Short forms of external names for systems with brain-damaged linkers. */
  161200. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161201. #define jinit_compress_master jICompress
  161202. #define jinit_c_master_control jICMaster
  161203. #define jinit_c_main_controller jICMainC
  161204. #define jinit_c_prep_controller jICPrepC
  161205. #define jinit_c_coef_controller jICCoefC
  161206. #define jinit_color_converter jICColor
  161207. #define jinit_downsampler jIDownsampler
  161208. #define jinit_forward_dct jIFDCT
  161209. #define jinit_huff_encoder jIHEncoder
  161210. #define jinit_phuff_encoder jIPHEncoder
  161211. #define jinit_marker_writer jIMWriter
  161212. #define jinit_master_decompress jIDMaster
  161213. #define jinit_d_main_controller jIDMainC
  161214. #define jinit_d_coef_controller jIDCoefC
  161215. #define jinit_d_post_controller jIDPostC
  161216. #define jinit_input_controller jIInCtlr
  161217. #define jinit_marker_reader jIMReader
  161218. #define jinit_huff_decoder jIHDecoder
  161219. #define jinit_phuff_decoder jIPHDecoder
  161220. #define jinit_inverse_dct jIIDCT
  161221. #define jinit_upsampler jIUpsampler
  161222. #define jinit_color_deconverter jIDColor
  161223. #define jinit_1pass_quantizer jI1Quant
  161224. #define jinit_2pass_quantizer jI2Quant
  161225. #define jinit_merged_upsampler jIMUpsampler
  161226. #define jinit_memory_mgr jIMemMgr
  161227. #define jdiv_round_up jDivRound
  161228. #define jround_up jRound
  161229. #define jcopy_sample_rows jCopySamples
  161230. #define jcopy_block_row jCopyBlocks
  161231. #define jzero_far jZeroFar
  161232. #define jpeg_zigzag_order jZIGTable
  161233. #define jpeg_natural_order jZAGTable
  161234. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161235. /* Compression module initialization routines */
  161236. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161237. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161238. boolean transcode_only));
  161239. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161240. boolean need_full_buffer));
  161241. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161242. boolean need_full_buffer));
  161243. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161244. boolean need_full_buffer));
  161245. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161246. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161247. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161248. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161249. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161250. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161251. /* Decompression module initialization routines */
  161252. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161253. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161254. boolean need_full_buffer));
  161255. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161256. boolean need_full_buffer));
  161257. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161258. boolean need_full_buffer));
  161259. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161260. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161261. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161262. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161263. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161264. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161265. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161266. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161267. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161268. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161269. /* Memory manager initialization */
  161270. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161271. /* Utility routines in jutils.c */
  161272. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161273. EXTERN(long) jround_up JPP((long a, long b));
  161274. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161275. JSAMPARRAY output_array, int dest_row,
  161276. int num_rows, JDIMENSION num_cols));
  161277. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161278. JDIMENSION num_blocks));
  161279. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161280. /* Constant tables in jutils.c */
  161281. #if 0 /* This table is not actually needed in v6a */
  161282. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161283. #endif
  161284. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161285. /* Suppress undefined-structure complaints if necessary. */
  161286. #ifdef INCOMPLETE_TYPES_BROKEN
  161287. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161288. struct jvirt_sarray_control { long dummy; };
  161289. struct jvirt_barray_control { long dummy; };
  161290. #endif
  161291. #endif /* INCOMPLETE_TYPES_BROKEN */
  161292. /*** End of inlined file: jpegint.h ***/
  161293. /* fetch private declarations */
  161294. /*** Start of inlined file: jerror.h ***/
  161295. /*
  161296. * To define the enum list of message codes, include this file without
  161297. * defining macro JMESSAGE. To create a message string table, include it
  161298. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161299. */
  161300. #ifndef JMESSAGE
  161301. #ifndef JERROR_H
  161302. /* First time through, define the enum list */
  161303. #define JMAKE_ENUM_LIST
  161304. #else
  161305. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161306. #define JMESSAGE(code,string)
  161307. #endif /* JERROR_H */
  161308. #endif /* JMESSAGE */
  161309. #ifdef JMAKE_ENUM_LIST
  161310. typedef enum {
  161311. #define JMESSAGE(code,string) code ,
  161312. #endif /* JMAKE_ENUM_LIST */
  161313. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161314. /* For maintenance convenience, list is alphabetical by message code name */
  161315. JMESSAGE(JERR_ARITH_NOTIMPL,
  161316. "Sorry, there are legal restrictions on arithmetic coding")
  161317. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161318. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161319. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161320. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161321. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161322. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161323. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161324. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161325. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161326. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161327. JMESSAGE(JERR_BAD_LIB_VERSION,
  161328. "Wrong JPEG library version: library is %d, caller expects %d")
  161329. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161330. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161331. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161332. JMESSAGE(JERR_BAD_PROGRESSION,
  161333. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161334. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161335. "Invalid progressive parameters at scan script entry %d")
  161336. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161337. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161338. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161339. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161340. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161341. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161342. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161343. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161344. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161345. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161346. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161347. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161348. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161349. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161350. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161351. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161352. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161353. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161354. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161355. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161356. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161357. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161358. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161359. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161360. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161361. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161362. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161363. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161364. "Cannot transcode due to multiple use of quantization table %d")
  161365. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161366. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161367. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161368. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161369. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161370. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161371. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161372. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161373. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161374. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161375. JMESSAGE(JERR_QUANT_COMPONENTS,
  161376. "Cannot quantize more than %d color components")
  161377. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161378. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161379. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161380. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161381. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161382. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161383. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161384. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161385. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161386. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161387. JMESSAGE(JERR_TFILE_WRITE,
  161388. "Write failed on temporary file --- out of disk space?")
  161389. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161390. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161391. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161392. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161393. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161394. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161395. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161396. JMESSAGE(JMSG_VERSION, JVERSION)
  161397. JMESSAGE(JTRC_16BIT_TABLES,
  161398. "Caution: quantization tables are too coarse for baseline JPEG")
  161399. JMESSAGE(JTRC_ADOBE,
  161400. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161401. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161402. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161403. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161404. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161405. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161406. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161407. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161408. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161409. JMESSAGE(JTRC_EOI, "End Of Image")
  161410. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161411. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161412. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161413. "Warning: thumbnail image size does not match data length %u")
  161414. JMESSAGE(JTRC_JFIF_EXTENSION,
  161415. "JFIF extension marker: type 0x%02x, length %u")
  161416. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161417. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161418. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161419. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161420. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161421. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161422. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161423. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161424. JMESSAGE(JTRC_RST, "RST%d")
  161425. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161426. "Smoothing not supported with nonstandard sampling ratios")
  161427. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161428. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161429. JMESSAGE(JTRC_SOI, "Start of Image")
  161430. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161431. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161432. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161433. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161434. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161435. JMESSAGE(JTRC_THUMB_JPEG,
  161436. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161437. JMESSAGE(JTRC_THUMB_PALETTE,
  161438. "JFIF extension marker: palette thumbnail image, length %u")
  161439. JMESSAGE(JTRC_THUMB_RGB,
  161440. "JFIF extension marker: RGB thumbnail image, length %u")
  161441. JMESSAGE(JTRC_UNKNOWN_IDS,
  161442. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161443. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161444. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161445. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161446. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161447. "Inconsistent progression sequence for component %d coefficient %d")
  161448. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161449. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161450. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161451. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161452. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161453. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161454. JMESSAGE(JWRN_MUST_RESYNC,
  161455. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161456. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161457. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161458. #ifdef JMAKE_ENUM_LIST
  161459. JMSG_LASTMSGCODE
  161460. } J_MESSAGE_CODE;
  161461. #undef JMAKE_ENUM_LIST
  161462. #endif /* JMAKE_ENUM_LIST */
  161463. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161464. #undef JMESSAGE
  161465. #ifndef JERROR_H
  161466. #define JERROR_H
  161467. /* Macros to simplify using the error and trace message stuff */
  161468. /* The first parameter is either type of cinfo pointer */
  161469. /* Fatal errors (print message and exit) */
  161470. #define ERREXIT(cinfo,code) \
  161471. ((cinfo)->err->msg_code = (code), \
  161472. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161473. #define ERREXIT1(cinfo,code,p1) \
  161474. ((cinfo)->err->msg_code = (code), \
  161475. (cinfo)->err->msg_parm.i[0] = (p1), \
  161476. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161477. #define ERREXIT2(cinfo,code,p1,p2) \
  161478. ((cinfo)->err->msg_code = (code), \
  161479. (cinfo)->err->msg_parm.i[0] = (p1), \
  161480. (cinfo)->err->msg_parm.i[1] = (p2), \
  161481. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161482. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161483. ((cinfo)->err->msg_code = (code), \
  161484. (cinfo)->err->msg_parm.i[0] = (p1), \
  161485. (cinfo)->err->msg_parm.i[1] = (p2), \
  161486. (cinfo)->err->msg_parm.i[2] = (p3), \
  161487. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161488. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161489. ((cinfo)->err->msg_code = (code), \
  161490. (cinfo)->err->msg_parm.i[0] = (p1), \
  161491. (cinfo)->err->msg_parm.i[1] = (p2), \
  161492. (cinfo)->err->msg_parm.i[2] = (p3), \
  161493. (cinfo)->err->msg_parm.i[3] = (p4), \
  161494. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161495. #define ERREXITS(cinfo,code,str) \
  161496. ((cinfo)->err->msg_code = (code), \
  161497. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161498. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161499. #define MAKESTMT(stuff) do { stuff } while (0)
  161500. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161501. #define WARNMS(cinfo,code) \
  161502. ((cinfo)->err->msg_code = (code), \
  161503. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161504. #define WARNMS1(cinfo,code,p1) \
  161505. ((cinfo)->err->msg_code = (code), \
  161506. (cinfo)->err->msg_parm.i[0] = (p1), \
  161507. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161508. #define WARNMS2(cinfo,code,p1,p2) \
  161509. ((cinfo)->err->msg_code = (code), \
  161510. (cinfo)->err->msg_parm.i[0] = (p1), \
  161511. (cinfo)->err->msg_parm.i[1] = (p2), \
  161512. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161513. /* Informational/debugging messages */
  161514. #define TRACEMS(cinfo,lvl,code) \
  161515. ((cinfo)->err->msg_code = (code), \
  161516. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161517. #define TRACEMS1(cinfo,lvl,code,p1) \
  161518. ((cinfo)->err->msg_code = (code), \
  161519. (cinfo)->err->msg_parm.i[0] = (p1), \
  161520. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161521. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161522. ((cinfo)->err->msg_code = (code), \
  161523. (cinfo)->err->msg_parm.i[0] = (p1), \
  161524. (cinfo)->err->msg_parm.i[1] = (p2), \
  161525. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161526. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161527. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161528. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161529. (cinfo)->err->msg_code = (code); \
  161530. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161531. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161532. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161533. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161534. (cinfo)->err->msg_code = (code); \
  161535. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161536. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161537. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161538. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161539. _mp[4] = (p5); \
  161540. (cinfo)->err->msg_code = (code); \
  161541. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161542. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161543. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161544. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161545. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161546. (cinfo)->err->msg_code = (code); \
  161547. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161548. #define TRACEMSS(cinfo,lvl,code,str) \
  161549. ((cinfo)->err->msg_code = (code), \
  161550. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161551. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161552. #endif /* JERROR_H */
  161553. /*** End of inlined file: jerror.h ***/
  161554. /* fetch error codes too */
  161555. #endif
  161556. #endif /* JPEGLIB_H */
  161557. /*** End of inlined file: jpeglib.h ***/
  161558. /*** Start of inlined file: jcapimin.c ***/
  161559. #define JPEG_INTERNALS
  161560. /*** Start of inlined file: jinclude.h ***/
  161561. /* Include auto-config file to find out which system include files we need. */
  161562. #ifndef __jinclude_h__
  161563. #define __jinclude_h__
  161564. /*** Start of inlined file: jconfig.h ***/
  161565. /* see jconfig.doc for explanations */
  161566. // disable all the warnings under MSVC
  161567. #ifdef _MSC_VER
  161568. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161569. #endif
  161570. #ifdef __BORLANDC__
  161571. #pragma warn -8057
  161572. #pragma warn -8019
  161573. #pragma warn -8004
  161574. #pragma warn -8008
  161575. #endif
  161576. #define HAVE_PROTOTYPES
  161577. #define HAVE_UNSIGNED_CHAR
  161578. #define HAVE_UNSIGNED_SHORT
  161579. /* #define void char */
  161580. /* #define const */
  161581. #undef CHAR_IS_UNSIGNED
  161582. #define HAVE_STDDEF_H
  161583. #define HAVE_STDLIB_H
  161584. #undef NEED_BSD_STRINGS
  161585. #undef NEED_SYS_TYPES_H
  161586. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161587. #undef NEED_SHORT_EXTERNAL_NAMES
  161588. #undef INCOMPLETE_TYPES_BROKEN
  161589. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161590. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161591. typedef unsigned char boolean;
  161592. #endif
  161593. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161594. #ifdef JPEG_INTERNALS
  161595. #undef RIGHT_SHIFT_IS_UNSIGNED
  161596. #endif /* JPEG_INTERNALS */
  161597. #ifdef JPEG_CJPEG_DJPEG
  161598. #define BMP_SUPPORTED /* BMP image file format */
  161599. #define GIF_SUPPORTED /* GIF image file format */
  161600. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161601. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161602. #define TARGA_SUPPORTED /* Targa image file format */
  161603. #define TWO_FILE_COMMANDLINE /* optional */
  161604. #define USE_SETMODE /* Microsoft has setmode() */
  161605. #undef NEED_SIGNAL_CATCHER
  161606. #undef DONT_USE_B_MODE
  161607. #undef PROGRESS_REPORT /* optional */
  161608. #endif /* JPEG_CJPEG_DJPEG */
  161609. /*** End of inlined file: jconfig.h ***/
  161610. /* auto configuration options */
  161611. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161612. /*
  161613. * We need the NULL macro and size_t typedef.
  161614. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161615. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161616. * pull in <sys/types.h> as well.
  161617. * Note that the core JPEG library does not require <stdio.h>;
  161618. * only the default error handler and data source/destination modules do.
  161619. * But we must pull it in because of the references to FILE in jpeglib.h.
  161620. * You can remove those references if you want to compile without <stdio.h>.
  161621. */
  161622. #ifdef HAVE_STDDEF_H
  161623. #include <stddef.h>
  161624. #endif
  161625. #ifdef HAVE_STDLIB_H
  161626. #include <stdlib.h>
  161627. #endif
  161628. #ifdef NEED_SYS_TYPES_H
  161629. #include <sys/types.h>
  161630. #endif
  161631. #include <stdio.h>
  161632. /*
  161633. * We need memory copying and zeroing functions, plus strncpy().
  161634. * ANSI and System V implementations declare these in <string.h>.
  161635. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161636. * Some systems may declare memset and memcpy in <memory.h>.
  161637. *
  161638. * NOTE: we assume the size parameters to these functions are of type size_t.
  161639. * Change the casts in these macros if not!
  161640. */
  161641. #ifdef NEED_BSD_STRINGS
  161642. #include <strings.h>
  161643. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161644. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161645. #else /* not BSD, assume ANSI/SysV string lib */
  161646. #include <string.h>
  161647. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161648. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161649. #endif
  161650. /*
  161651. * In ANSI C, and indeed any rational implementation, size_t is also the
  161652. * type returned by sizeof(). However, it seems there are some irrational
  161653. * implementations out there, in which sizeof() returns an int even though
  161654. * size_t is defined as long or unsigned long. To ensure consistent results
  161655. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161656. */
  161657. #define SIZEOF(object) ((size_t) sizeof(object))
  161658. /*
  161659. * The modules that use fread() and fwrite() always invoke them through
  161660. * these macros. On some systems you may need to twiddle the argument casts.
  161661. * CAUTION: argument order is different from underlying functions!
  161662. */
  161663. #define JFREAD(file,buf,sizeofbuf) \
  161664. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161665. #define JFWRITE(file,buf,sizeofbuf) \
  161666. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161667. typedef enum { /* JPEG marker codes */
  161668. M_SOF0 = 0xc0,
  161669. M_SOF1 = 0xc1,
  161670. M_SOF2 = 0xc2,
  161671. M_SOF3 = 0xc3,
  161672. M_SOF5 = 0xc5,
  161673. M_SOF6 = 0xc6,
  161674. M_SOF7 = 0xc7,
  161675. M_JPG = 0xc8,
  161676. M_SOF9 = 0xc9,
  161677. M_SOF10 = 0xca,
  161678. M_SOF11 = 0xcb,
  161679. M_SOF13 = 0xcd,
  161680. M_SOF14 = 0xce,
  161681. M_SOF15 = 0xcf,
  161682. M_DHT = 0xc4,
  161683. M_DAC = 0xcc,
  161684. M_RST0 = 0xd0,
  161685. M_RST1 = 0xd1,
  161686. M_RST2 = 0xd2,
  161687. M_RST3 = 0xd3,
  161688. M_RST4 = 0xd4,
  161689. M_RST5 = 0xd5,
  161690. M_RST6 = 0xd6,
  161691. M_RST7 = 0xd7,
  161692. M_SOI = 0xd8,
  161693. M_EOI = 0xd9,
  161694. M_SOS = 0xda,
  161695. M_DQT = 0xdb,
  161696. M_DNL = 0xdc,
  161697. M_DRI = 0xdd,
  161698. M_DHP = 0xde,
  161699. M_EXP = 0xdf,
  161700. M_APP0 = 0xe0,
  161701. M_APP1 = 0xe1,
  161702. M_APP2 = 0xe2,
  161703. M_APP3 = 0xe3,
  161704. M_APP4 = 0xe4,
  161705. M_APP5 = 0xe5,
  161706. M_APP6 = 0xe6,
  161707. M_APP7 = 0xe7,
  161708. M_APP8 = 0xe8,
  161709. M_APP9 = 0xe9,
  161710. M_APP10 = 0xea,
  161711. M_APP11 = 0xeb,
  161712. M_APP12 = 0xec,
  161713. M_APP13 = 0xed,
  161714. M_APP14 = 0xee,
  161715. M_APP15 = 0xef,
  161716. M_JPG0 = 0xf0,
  161717. M_JPG13 = 0xfd,
  161718. M_COM = 0xfe,
  161719. M_TEM = 0x01,
  161720. M_ERROR = 0x100
  161721. } JPEG_MARKER;
  161722. /*
  161723. * Figure F.12: extend sign bit.
  161724. * On some machines, a shift and add will be faster than a table lookup.
  161725. */
  161726. #ifdef AVOID_TABLES
  161727. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161728. #else
  161729. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161730. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161731. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161732. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161733. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161734. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161735. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161736. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161737. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161738. #endif /* AVOID_TABLES */
  161739. #endif
  161740. /*** End of inlined file: jinclude.h ***/
  161741. /*
  161742. * Initialization of a JPEG compression object.
  161743. * The error manager must already be set up (in case memory manager fails).
  161744. */
  161745. GLOBAL(void)
  161746. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161747. {
  161748. int i;
  161749. /* Guard against version mismatches between library and caller. */
  161750. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161751. if (version != JPEG_LIB_VERSION)
  161752. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161753. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161754. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161755. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161756. /* For debugging purposes, we zero the whole master structure.
  161757. * But the application has already set the err pointer, and may have set
  161758. * client_data, so we have to save and restore those fields.
  161759. * Note: if application hasn't set client_data, tools like Purify may
  161760. * complain here.
  161761. */
  161762. {
  161763. struct jpeg_error_mgr * err = cinfo->err;
  161764. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161765. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161766. cinfo->err = err;
  161767. cinfo->client_data = client_data;
  161768. }
  161769. cinfo->is_decompressor = FALSE;
  161770. /* Initialize a memory manager instance for this object */
  161771. jinit_memory_mgr((j_common_ptr) cinfo);
  161772. /* Zero out pointers to permanent structures. */
  161773. cinfo->progress = NULL;
  161774. cinfo->dest = NULL;
  161775. cinfo->comp_info = NULL;
  161776. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161777. cinfo->quant_tbl_ptrs[i] = NULL;
  161778. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161779. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161780. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161781. }
  161782. cinfo->script_space = NULL;
  161783. cinfo->input_gamma = 1.0; /* in case application forgets */
  161784. /* OK, I'm ready */
  161785. cinfo->global_state = CSTATE_START;
  161786. }
  161787. /*
  161788. * Destruction of a JPEG compression object
  161789. */
  161790. GLOBAL(void)
  161791. jpeg_destroy_compress (j_compress_ptr cinfo)
  161792. {
  161793. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161794. }
  161795. /*
  161796. * Abort processing of a JPEG compression operation,
  161797. * but don't destroy the object itself.
  161798. */
  161799. GLOBAL(void)
  161800. jpeg_abort_compress (j_compress_ptr cinfo)
  161801. {
  161802. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161803. }
  161804. /*
  161805. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161806. * Marks all currently defined tables as already written (if suppress)
  161807. * or not written (if !suppress). This will control whether they get emitted
  161808. * by a subsequent jpeg_start_compress call.
  161809. *
  161810. * This routine is exported for use by applications that want to produce
  161811. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161812. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161813. * jcparam.o would be linked whether the application used it or not.
  161814. */
  161815. GLOBAL(void)
  161816. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161817. {
  161818. int i;
  161819. JQUANT_TBL * qtbl;
  161820. JHUFF_TBL * htbl;
  161821. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161822. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161823. qtbl->sent_table = suppress;
  161824. }
  161825. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161826. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161827. htbl->sent_table = suppress;
  161828. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161829. htbl->sent_table = suppress;
  161830. }
  161831. }
  161832. /*
  161833. * Finish JPEG compression.
  161834. *
  161835. * If a multipass operating mode was selected, this may do a great deal of
  161836. * work including most of the actual output.
  161837. */
  161838. GLOBAL(void)
  161839. jpeg_finish_compress (j_compress_ptr cinfo)
  161840. {
  161841. JDIMENSION iMCU_row;
  161842. if (cinfo->global_state == CSTATE_SCANNING ||
  161843. cinfo->global_state == CSTATE_RAW_OK) {
  161844. /* Terminate first pass */
  161845. if (cinfo->next_scanline < cinfo->image_height)
  161846. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161847. (*cinfo->master->finish_pass) (cinfo);
  161848. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161849. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161850. /* Perform any remaining passes */
  161851. while (! cinfo->master->is_last_pass) {
  161852. (*cinfo->master->prepare_for_pass) (cinfo);
  161853. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161854. if (cinfo->progress != NULL) {
  161855. cinfo->progress->pass_counter = (long) iMCU_row;
  161856. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161857. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161858. }
  161859. /* We bypass the main controller and invoke coef controller directly;
  161860. * all work is being done from the coefficient buffer.
  161861. */
  161862. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161863. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161864. }
  161865. (*cinfo->master->finish_pass) (cinfo);
  161866. }
  161867. /* Write EOI, do final cleanup */
  161868. (*cinfo->marker->write_file_trailer) (cinfo);
  161869. (*cinfo->dest->term_destination) (cinfo);
  161870. /* We can use jpeg_abort to release memory and reset global_state */
  161871. jpeg_abort((j_common_ptr) cinfo);
  161872. }
  161873. /*
  161874. * Write a special marker.
  161875. * This is only recommended for writing COM or APPn markers.
  161876. * Must be called after jpeg_start_compress() and before
  161877. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161878. */
  161879. GLOBAL(void)
  161880. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161881. const JOCTET *dataptr, unsigned int datalen)
  161882. {
  161883. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161884. if (cinfo->next_scanline != 0 ||
  161885. (cinfo->global_state != CSTATE_SCANNING &&
  161886. cinfo->global_state != CSTATE_RAW_OK &&
  161887. cinfo->global_state != CSTATE_WRCOEFS))
  161888. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161889. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161890. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161891. while (datalen--) {
  161892. (*write_marker_byte) (cinfo, *dataptr);
  161893. dataptr++;
  161894. }
  161895. }
  161896. /* Same, but piecemeal. */
  161897. GLOBAL(void)
  161898. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161899. {
  161900. if (cinfo->next_scanline != 0 ||
  161901. (cinfo->global_state != CSTATE_SCANNING &&
  161902. cinfo->global_state != CSTATE_RAW_OK &&
  161903. cinfo->global_state != CSTATE_WRCOEFS))
  161904. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161905. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161906. }
  161907. GLOBAL(void)
  161908. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161909. {
  161910. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161911. }
  161912. /*
  161913. * Alternate compression function: just write an abbreviated table file.
  161914. * Before calling this, all parameters and a data destination must be set up.
  161915. *
  161916. * To produce a pair of files containing abbreviated tables and abbreviated
  161917. * image data, one would proceed as follows:
  161918. *
  161919. * initialize JPEG object
  161920. * set JPEG parameters
  161921. * set destination to table file
  161922. * jpeg_write_tables(cinfo);
  161923. * set destination to image file
  161924. * jpeg_start_compress(cinfo, FALSE);
  161925. * write data...
  161926. * jpeg_finish_compress(cinfo);
  161927. *
  161928. * jpeg_write_tables has the side effect of marking all tables written
  161929. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161930. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161931. */
  161932. GLOBAL(void)
  161933. jpeg_write_tables (j_compress_ptr cinfo)
  161934. {
  161935. if (cinfo->global_state != CSTATE_START)
  161936. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161937. /* (Re)initialize error mgr and destination modules */
  161938. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161939. (*cinfo->dest->init_destination) (cinfo);
  161940. /* Initialize the marker writer ... bit of a crock to do it here. */
  161941. jinit_marker_writer(cinfo);
  161942. /* Write them tables! */
  161943. (*cinfo->marker->write_tables_only) (cinfo);
  161944. /* And clean up. */
  161945. (*cinfo->dest->term_destination) (cinfo);
  161946. /*
  161947. * In library releases up through v6a, we called jpeg_abort() here to free
  161948. * any working memory allocated by the destination manager and marker
  161949. * writer. Some applications had a problem with that: they allocated space
  161950. * of their own from the library memory manager, and didn't want it to go
  161951. * away during write_tables. So now we do nothing. This will cause a
  161952. * memory leak if an app calls write_tables repeatedly without doing a full
  161953. * compression cycle or otherwise resetting the JPEG object. However, that
  161954. * seems less bad than unexpectedly freeing memory in the normal case.
  161955. * An app that prefers the old behavior can call jpeg_abort for itself after
  161956. * each call to jpeg_write_tables().
  161957. */
  161958. }
  161959. /*** End of inlined file: jcapimin.c ***/
  161960. /*** Start of inlined file: jcapistd.c ***/
  161961. #define JPEG_INTERNALS
  161962. /*
  161963. * Compression initialization.
  161964. * Before calling this, all parameters and a data destination must be set up.
  161965. *
  161966. * We require a write_all_tables parameter as a failsafe check when writing
  161967. * multiple datastreams from the same compression object. Since prior runs
  161968. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161969. * would emit an abbreviated stream (no tables) by default. This may be what
  161970. * is wanted, but for safety's sake it should not be the default behavior:
  161971. * programmers should have to make a deliberate choice to emit abbreviated
  161972. * images. Therefore the documentation and examples should encourage people
  161973. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161974. * wrong thing.
  161975. */
  161976. GLOBAL(void)
  161977. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161978. {
  161979. if (cinfo->global_state != CSTATE_START)
  161980. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161981. if (write_all_tables)
  161982. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161983. /* (Re)initialize error mgr and destination modules */
  161984. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161985. (*cinfo->dest->init_destination) (cinfo);
  161986. /* Perform master selection of active modules */
  161987. jinit_compress_master(cinfo);
  161988. /* Set up for the first pass */
  161989. (*cinfo->master->prepare_for_pass) (cinfo);
  161990. /* Ready for application to drive first pass through jpeg_write_scanlines
  161991. * or jpeg_write_raw_data.
  161992. */
  161993. cinfo->next_scanline = 0;
  161994. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161995. }
  161996. /*
  161997. * Write some scanlines of data to the JPEG compressor.
  161998. *
  161999. * The return value will be the number of lines actually written.
  162000. * This should be less than the supplied num_lines only in case that
  162001. * the data destination module has requested suspension of the compressor,
  162002. * or if more than image_height scanlines are passed in.
  162003. *
  162004. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162005. * this likely signals an application programmer error. However,
  162006. * excess scanlines passed in the last valid call are *silently* ignored,
  162007. * so that the application need not adjust num_lines for end-of-image
  162008. * when using a multiple-scanline buffer.
  162009. */
  162010. GLOBAL(JDIMENSION)
  162011. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162012. JDIMENSION num_lines)
  162013. {
  162014. JDIMENSION row_ctr, rows_left;
  162015. if (cinfo->global_state != CSTATE_SCANNING)
  162016. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162017. if (cinfo->next_scanline >= cinfo->image_height)
  162018. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162019. /* Call progress monitor hook if present */
  162020. if (cinfo->progress != NULL) {
  162021. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162022. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162023. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162024. }
  162025. /* Give master control module another chance if this is first call to
  162026. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162027. * delayed so that application can write COM, etc, markers between
  162028. * jpeg_start_compress and jpeg_write_scanlines.
  162029. */
  162030. if (cinfo->master->call_pass_startup)
  162031. (*cinfo->master->pass_startup) (cinfo);
  162032. /* Ignore any extra scanlines at bottom of image. */
  162033. rows_left = cinfo->image_height - cinfo->next_scanline;
  162034. if (num_lines > rows_left)
  162035. num_lines = rows_left;
  162036. row_ctr = 0;
  162037. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162038. cinfo->next_scanline += row_ctr;
  162039. return row_ctr;
  162040. }
  162041. /*
  162042. * Alternate entry point to write raw data.
  162043. * Processes exactly one iMCU row per call, unless suspended.
  162044. */
  162045. GLOBAL(JDIMENSION)
  162046. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162047. JDIMENSION num_lines)
  162048. {
  162049. JDIMENSION lines_per_iMCU_row;
  162050. if (cinfo->global_state != CSTATE_RAW_OK)
  162051. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162052. if (cinfo->next_scanline >= cinfo->image_height) {
  162053. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162054. return 0;
  162055. }
  162056. /* Call progress monitor hook if present */
  162057. if (cinfo->progress != NULL) {
  162058. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162059. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162060. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162061. }
  162062. /* Give master control module another chance if this is first call to
  162063. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162064. * delayed so that application can write COM, etc, markers between
  162065. * jpeg_start_compress and jpeg_write_raw_data.
  162066. */
  162067. if (cinfo->master->call_pass_startup)
  162068. (*cinfo->master->pass_startup) (cinfo);
  162069. /* Verify that at least one iMCU row has been passed. */
  162070. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162071. if (num_lines < lines_per_iMCU_row)
  162072. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162073. /* Directly compress the row. */
  162074. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162075. /* If compressor did not consume the whole row, suspend processing. */
  162076. return 0;
  162077. }
  162078. /* OK, we processed one iMCU row. */
  162079. cinfo->next_scanline += lines_per_iMCU_row;
  162080. return lines_per_iMCU_row;
  162081. }
  162082. /*** End of inlined file: jcapistd.c ***/
  162083. /*** Start of inlined file: jccoefct.c ***/
  162084. #define JPEG_INTERNALS
  162085. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162086. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162087. * step is run during the first pass, and subsequent passes need only read
  162088. * the buffered coefficients.
  162089. */
  162090. #ifdef ENTROPY_OPT_SUPPORTED
  162091. #define FULL_COEF_BUFFER_SUPPORTED
  162092. #else
  162093. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162094. #define FULL_COEF_BUFFER_SUPPORTED
  162095. #endif
  162096. #endif
  162097. /* Private buffer controller object */
  162098. typedef struct {
  162099. struct jpeg_c_coef_controller pub; /* public fields */
  162100. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162101. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162102. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162103. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162104. /* For single-pass compression, it's sufficient to buffer just one MCU
  162105. * (although this may prove a bit slow in practice). We allocate a
  162106. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162107. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162108. * it's not really very big; this is to keep the module interfaces unchanged
  162109. * when a large coefficient buffer is necessary.)
  162110. * In multi-pass modes, this array points to the current MCU's blocks
  162111. * within the virtual arrays.
  162112. */
  162113. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162114. /* In multi-pass modes, we need a virtual block array for each component. */
  162115. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162116. } my_coef_controller;
  162117. typedef my_coef_controller * my_coef_ptr;
  162118. /* Forward declarations */
  162119. METHODDEF(boolean) compress_data
  162120. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162121. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162122. METHODDEF(boolean) compress_first_pass
  162123. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162124. METHODDEF(boolean) compress_output
  162125. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162126. #endif
  162127. LOCAL(void)
  162128. start_iMCU_row (j_compress_ptr cinfo)
  162129. /* Reset within-iMCU-row counters for a new row */
  162130. {
  162131. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162132. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162133. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162134. * But at the bottom of the image, process only what's left.
  162135. */
  162136. if (cinfo->comps_in_scan > 1) {
  162137. coef->MCU_rows_per_iMCU_row = 1;
  162138. } else {
  162139. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162140. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162141. else
  162142. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162143. }
  162144. coef->mcu_ctr = 0;
  162145. coef->MCU_vert_offset = 0;
  162146. }
  162147. /*
  162148. * Initialize for a processing pass.
  162149. */
  162150. METHODDEF(void)
  162151. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162152. {
  162153. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162154. coef->iMCU_row_num = 0;
  162155. start_iMCU_row(cinfo);
  162156. switch (pass_mode) {
  162157. case JBUF_PASS_THRU:
  162158. if (coef->whole_image[0] != NULL)
  162159. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162160. coef->pub.compress_data = compress_data;
  162161. break;
  162162. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162163. case JBUF_SAVE_AND_PASS:
  162164. if (coef->whole_image[0] == NULL)
  162165. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162166. coef->pub.compress_data = compress_first_pass;
  162167. break;
  162168. case JBUF_CRANK_DEST:
  162169. if (coef->whole_image[0] == NULL)
  162170. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162171. coef->pub.compress_data = compress_output;
  162172. break;
  162173. #endif
  162174. default:
  162175. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162176. break;
  162177. }
  162178. }
  162179. /*
  162180. * Process some data in the single-pass case.
  162181. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162182. * per call, ie, v_samp_factor block rows for each component in the image.
  162183. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162184. *
  162185. * NB: input_buf contains a plane for each component in image,
  162186. * which we index according to the component's SOF position.
  162187. */
  162188. METHODDEF(boolean)
  162189. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162190. {
  162191. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162192. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162193. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162194. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162195. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162196. JDIMENSION ypos, xpos;
  162197. jpeg_component_info *compptr;
  162198. /* Loop to write as much as one whole iMCU row */
  162199. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162200. yoffset++) {
  162201. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162202. MCU_col_num++) {
  162203. /* Determine where data comes from in input_buf and do the DCT thing.
  162204. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162205. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162206. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162207. * specially. The data in them does not matter for image reconstruction,
  162208. * so we fill them with values that will encode to the smallest amount of
  162209. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162210. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162211. */
  162212. blkn = 0;
  162213. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162214. compptr = cinfo->cur_comp_info[ci];
  162215. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162216. : compptr->last_col_width;
  162217. xpos = MCU_col_num * compptr->MCU_sample_width;
  162218. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162219. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162220. if (coef->iMCU_row_num < last_iMCU_row ||
  162221. yoffset+yindex < compptr->last_row_height) {
  162222. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162223. input_buf[compptr->component_index],
  162224. coef->MCU_buffer[blkn],
  162225. ypos, xpos, (JDIMENSION) blockcnt);
  162226. if (blockcnt < compptr->MCU_width) {
  162227. /* Create some dummy blocks at the right edge of the image. */
  162228. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162229. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162230. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162231. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162232. }
  162233. }
  162234. } else {
  162235. /* Create a row of dummy blocks at the bottom of the image. */
  162236. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162237. compptr->MCU_width * SIZEOF(JBLOCK));
  162238. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162239. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162240. }
  162241. }
  162242. blkn += compptr->MCU_width;
  162243. ypos += DCTSIZE;
  162244. }
  162245. }
  162246. /* Try to write the MCU. In event of a suspension failure, we will
  162247. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162248. */
  162249. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162250. /* Suspension forced; update state counters and exit */
  162251. coef->MCU_vert_offset = yoffset;
  162252. coef->mcu_ctr = MCU_col_num;
  162253. return FALSE;
  162254. }
  162255. }
  162256. /* Completed an MCU row, but perhaps not an iMCU row */
  162257. coef->mcu_ctr = 0;
  162258. }
  162259. /* Completed the iMCU row, advance counters for next one */
  162260. coef->iMCU_row_num++;
  162261. start_iMCU_row(cinfo);
  162262. return TRUE;
  162263. }
  162264. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162265. /*
  162266. * Process some data in the first pass of a multi-pass case.
  162267. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162268. * per call, ie, v_samp_factor block rows for each component in the image.
  162269. * This amount of data is read from the source buffer, DCT'd and quantized,
  162270. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162271. * as needed at the right and lower edges. (The dummy blocks are constructed
  162272. * in the virtual arrays, which have been padded appropriately.) This makes
  162273. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162274. *
  162275. * We must also emit the data to the entropy encoder. This is conveniently
  162276. * done by calling compress_output() after we've loaded the current strip
  162277. * of the virtual arrays.
  162278. *
  162279. * NB: input_buf contains a plane for each component in image. All
  162280. * components are DCT'd and loaded into the virtual arrays in this pass.
  162281. * However, it may be that only a subset of the components are emitted to
  162282. * the entropy encoder during this first pass; be careful about looking
  162283. * at the scan-dependent variables (MCU dimensions, etc).
  162284. */
  162285. METHODDEF(boolean)
  162286. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162287. {
  162288. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162289. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162290. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162291. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162292. JCOEF lastDC;
  162293. jpeg_component_info *compptr;
  162294. JBLOCKARRAY buffer;
  162295. JBLOCKROW thisblockrow, lastblockrow;
  162296. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162297. ci++, compptr++) {
  162298. /* Align the virtual buffer for this component. */
  162299. buffer = (*cinfo->mem->access_virt_barray)
  162300. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162301. coef->iMCU_row_num * compptr->v_samp_factor,
  162302. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162303. /* Count non-dummy DCT block rows in this iMCU row. */
  162304. if (coef->iMCU_row_num < last_iMCU_row)
  162305. block_rows = compptr->v_samp_factor;
  162306. else {
  162307. /* NB: can't use last_row_height here, since may not be set! */
  162308. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162309. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162310. }
  162311. blocks_across = compptr->width_in_blocks;
  162312. h_samp_factor = compptr->h_samp_factor;
  162313. /* Count number of dummy blocks to be added at the right margin. */
  162314. ndummy = (int) (blocks_across % h_samp_factor);
  162315. if (ndummy > 0)
  162316. ndummy = h_samp_factor - ndummy;
  162317. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162318. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162319. */
  162320. for (block_row = 0; block_row < block_rows; block_row++) {
  162321. thisblockrow = buffer[block_row];
  162322. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162323. input_buf[ci], thisblockrow,
  162324. (JDIMENSION) (block_row * DCTSIZE),
  162325. (JDIMENSION) 0, blocks_across);
  162326. if (ndummy > 0) {
  162327. /* Create dummy blocks at the right edge of the image. */
  162328. thisblockrow += blocks_across; /* => first dummy block */
  162329. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162330. lastDC = thisblockrow[-1][0];
  162331. for (bi = 0; bi < ndummy; bi++) {
  162332. thisblockrow[bi][0] = lastDC;
  162333. }
  162334. }
  162335. }
  162336. /* If at end of image, create dummy block rows as needed.
  162337. * The tricky part here is that within each MCU, we want the DC values
  162338. * of the dummy blocks to match the last real block's DC value.
  162339. * This squeezes a few more bytes out of the resulting file...
  162340. */
  162341. if (coef->iMCU_row_num == last_iMCU_row) {
  162342. blocks_across += ndummy; /* include lower right corner */
  162343. MCUs_across = blocks_across / h_samp_factor;
  162344. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162345. block_row++) {
  162346. thisblockrow = buffer[block_row];
  162347. lastblockrow = buffer[block_row-1];
  162348. jzero_far((void FAR *) thisblockrow,
  162349. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162350. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162351. lastDC = lastblockrow[h_samp_factor-1][0];
  162352. for (bi = 0; bi < h_samp_factor; bi++) {
  162353. thisblockrow[bi][0] = lastDC;
  162354. }
  162355. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162356. lastblockrow += h_samp_factor;
  162357. }
  162358. }
  162359. }
  162360. }
  162361. /* NB: compress_output will increment iMCU_row_num if successful.
  162362. * A suspension return will result in redoing all the work above next time.
  162363. */
  162364. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162365. return compress_output(cinfo, input_buf);
  162366. }
  162367. /*
  162368. * Process some data in subsequent passes of a multi-pass case.
  162369. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162370. * per call, ie, v_samp_factor block rows for each component in the scan.
  162371. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162372. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162373. *
  162374. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162375. */
  162376. METHODDEF(boolean)
  162377. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162378. {
  162379. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162380. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162381. int blkn, ci, xindex, yindex, yoffset;
  162382. JDIMENSION start_col;
  162383. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162384. JBLOCKROW buffer_ptr;
  162385. jpeg_component_info *compptr;
  162386. /* Align the virtual buffers for the components used in this scan.
  162387. * NB: during first pass, this is safe only because the buffers will
  162388. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162389. */
  162390. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162391. compptr = cinfo->cur_comp_info[ci];
  162392. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162393. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162394. coef->iMCU_row_num * compptr->v_samp_factor,
  162395. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162396. }
  162397. /* Loop to process one whole iMCU row */
  162398. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162399. yoffset++) {
  162400. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162401. MCU_col_num++) {
  162402. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162403. blkn = 0; /* index of current DCT block within MCU */
  162404. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162405. compptr = cinfo->cur_comp_info[ci];
  162406. start_col = MCU_col_num * compptr->MCU_width;
  162407. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162408. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162409. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162410. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162411. }
  162412. }
  162413. }
  162414. /* Try to write the MCU. */
  162415. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162416. /* Suspension forced; update state counters and exit */
  162417. coef->MCU_vert_offset = yoffset;
  162418. coef->mcu_ctr = MCU_col_num;
  162419. return FALSE;
  162420. }
  162421. }
  162422. /* Completed an MCU row, but perhaps not an iMCU row */
  162423. coef->mcu_ctr = 0;
  162424. }
  162425. /* Completed the iMCU row, advance counters for next one */
  162426. coef->iMCU_row_num++;
  162427. start_iMCU_row(cinfo);
  162428. return TRUE;
  162429. }
  162430. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162431. /*
  162432. * Initialize coefficient buffer controller.
  162433. */
  162434. GLOBAL(void)
  162435. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162436. {
  162437. my_coef_ptr coef;
  162438. coef = (my_coef_ptr)
  162439. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162440. SIZEOF(my_coef_controller));
  162441. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162442. coef->pub.start_pass = start_pass_coef;
  162443. /* Create the coefficient buffer. */
  162444. if (need_full_buffer) {
  162445. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162446. /* Allocate a full-image virtual array for each component, */
  162447. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162448. int ci;
  162449. jpeg_component_info *compptr;
  162450. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162451. ci++, compptr++) {
  162452. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162453. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162454. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162455. (long) compptr->h_samp_factor),
  162456. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162457. (long) compptr->v_samp_factor),
  162458. (JDIMENSION) compptr->v_samp_factor);
  162459. }
  162460. #else
  162461. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162462. #endif
  162463. } else {
  162464. /* We only need a single-MCU buffer. */
  162465. JBLOCKROW buffer;
  162466. int i;
  162467. buffer = (JBLOCKROW)
  162468. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162469. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162470. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162471. coef->MCU_buffer[i] = buffer + i;
  162472. }
  162473. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162474. }
  162475. }
  162476. /*** End of inlined file: jccoefct.c ***/
  162477. /*** Start of inlined file: jccolor.c ***/
  162478. #define JPEG_INTERNALS
  162479. /* Private subobject */
  162480. typedef struct {
  162481. struct jpeg_color_converter pub; /* public fields */
  162482. /* Private state for RGB->YCC conversion */
  162483. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162484. } my_color_converter;
  162485. typedef my_color_converter * my_cconvert_ptr;
  162486. /**************** RGB -> YCbCr conversion: most common case **************/
  162487. /*
  162488. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162489. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162490. * The conversion equations to be implemented are therefore
  162491. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162492. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162493. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162494. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162495. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162496. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162497. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162498. * were not represented exactly. Now we sacrifice exact representation of
  162499. * maximum red and maximum blue in order to get exact grayscales.
  162500. *
  162501. * To avoid floating-point arithmetic, we represent the fractional constants
  162502. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162503. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162504. *
  162505. * For even more speed, we avoid doing any multiplications in the inner loop
  162506. * by precalculating the constants times R,G,B for all possible values.
  162507. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162508. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162509. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162510. * colorspace anyway.
  162511. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162512. * in the tables to save adding them separately in the inner loop.
  162513. */
  162514. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162515. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162516. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162517. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162518. /* We allocate one big table and divide it up into eight parts, instead of
  162519. * doing eight alloc_small requests. This lets us use a single table base
  162520. * address, which can be held in a register in the inner loops on many
  162521. * machines (more than can hold all eight addresses, anyway).
  162522. */
  162523. #define R_Y_OFF 0 /* offset to R => Y section */
  162524. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162525. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162526. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162527. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162528. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162529. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162530. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162531. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162532. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162533. /*
  162534. * Initialize for RGB->YCC colorspace conversion.
  162535. */
  162536. METHODDEF(void)
  162537. rgb_ycc_start (j_compress_ptr cinfo)
  162538. {
  162539. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162540. INT32 * rgb_ycc_tab;
  162541. INT32 i;
  162542. /* Allocate and fill in the conversion tables. */
  162543. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162544. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162545. (TABLE_SIZE * SIZEOF(INT32)));
  162546. for (i = 0; i <= MAXJSAMPLE; i++) {
  162547. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162548. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162549. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162550. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162551. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162552. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162553. * This ensures that the maximum output will round to MAXJSAMPLE
  162554. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162555. */
  162556. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162557. /* B=>Cb and R=>Cr tables are the same
  162558. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162559. */
  162560. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162561. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162562. }
  162563. }
  162564. /*
  162565. * Convert some rows of samples to the JPEG colorspace.
  162566. *
  162567. * Note that we change from the application's interleaved-pixel format
  162568. * to our internal noninterleaved, one-plane-per-component format.
  162569. * The input buffer is therefore three times as wide as the output buffer.
  162570. *
  162571. * A starting row offset is provided only for the output buffer. The caller
  162572. * can easily adjust the passed input_buf value to accommodate any row
  162573. * offset required on that side.
  162574. */
  162575. METHODDEF(void)
  162576. rgb_ycc_convert (j_compress_ptr cinfo,
  162577. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162578. JDIMENSION output_row, int num_rows)
  162579. {
  162580. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162581. register int r, g, b;
  162582. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162583. register JSAMPROW inptr;
  162584. register JSAMPROW outptr0, outptr1, outptr2;
  162585. register JDIMENSION col;
  162586. JDIMENSION num_cols = cinfo->image_width;
  162587. while (--num_rows >= 0) {
  162588. inptr = *input_buf++;
  162589. outptr0 = output_buf[0][output_row];
  162590. outptr1 = output_buf[1][output_row];
  162591. outptr2 = output_buf[2][output_row];
  162592. output_row++;
  162593. for (col = 0; col < num_cols; col++) {
  162594. r = GETJSAMPLE(inptr[RGB_RED]);
  162595. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162596. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162597. inptr += RGB_PIXELSIZE;
  162598. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162599. * must be too; we do not need an explicit range-limiting operation.
  162600. * Hence the value being shifted is never negative, and we don't
  162601. * need the general RIGHT_SHIFT macro.
  162602. */
  162603. /* Y */
  162604. outptr0[col] = (JSAMPLE)
  162605. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162606. >> SCALEBITS);
  162607. /* Cb */
  162608. outptr1[col] = (JSAMPLE)
  162609. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162610. >> SCALEBITS);
  162611. /* Cr */
  162612. outptr2[col] = (JSAMPLE)
  162613. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162614. >> SCALEBITS);
  162615. }
  162616. }
  162617. }
  162618. /**************** Cases other than RGB -> YCbCr **************/
  162619. /*
  162620. * Convert some rows of samples to the JPEG colorspace.
  162621. * This version handles RGB->grayscale conversion, which is the same
  162622. * as the RGB->Y portion of RGB->YCbCr.
  162623. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162624. */
  162625. METHODDEF(void)
  162626. rgb_gray_convert (j_compress_ptr cinfo,
  162627. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162628. JDIMENSION output_row, int num_rows)
  162629. {
  162630. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162631. register int r, g, b;
  162632. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162633. register JSAMPROW inptr;
  162634. register JSAMPROW outptr;
  162635. register JDIMENSION col;
  162636. JDIMENSION num_cols = cinfo->image_width;
  162637. while (--num_rows >= 0) {
  162638. inptr = *input_buf++;
  162639. outptr = output_buf[0][output_row];
  162640. output_row++;
  162641. for (col = 0; col < num_cols; col++) {
  162642. r = GETJSAMPLE(inptr[RGB_RED]);
  162643. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162644. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162645. inptr += RGB_PIXELSIZE;
  162646. /* Y */
  162647. outptr[col] = (JSAMPLE)
  162648. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162649. >> SCALEBITS);
  162650. }
  162651. }
  162652. }
  162653. /*
  162654. * Convert some rows of samples to the JPEG colorspace.
  162655. * This version handles Adobe-style CMYK->YCCK conversion,
  162656. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162657. * conversion as above, while passing K (black) unchanged.
  162658. * We assume rgb_ycc_start has been called.
  162659. */
  162660. METHODDEF(void)
  162661. cmyk_ycck_convert (j_compress_ptr cinfo,
  162662. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162663. JDIMENSION output_row, int num_rows)
  162664. {
  162665. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162666. register int r, g, b;
  162667. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162668. register JSAMPROW inptr;
  162669. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162670. register JDIMENSION col;
  162671. JDIMENSION num_cols = cinfo->image_width;
  162672. while (--num_rows >= 0) {
  162673. inptr = *input_buf++;
  162674. outptr0 = output_buf[0][output_row];
  162675. outptr1 = output_buf[1][output_row];
  162676. outptr2 = output_buf[2][output_row];
  162677. outptr3 = output_buf[3][output_row];
  162678. output_row++;
  162679. for (col = 0; col < num_cols; col++) {
  162680. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162681. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162682. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162683. /* K passes through as-is */
  162684. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162685. inptr += 4;
  162686. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162687. * must be too; we do not need an explicit range-limiting operation.
  162688. * Hence the value being shifted is never negative, and we don't
  162689. * need the general RIGHT_SHIFT macro.
  162690. */
  162691. /* Y */
  162692. outptr0[col] = (JSAMPLE)
  162693. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162694. >> SCALEBITS);
  162695. /* Cb */
  162696. outptr1[col] = (JSAMPLE)
  162697. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162698. >> SCALEBITS);
  162699. /* Cr */
  162700. outptr2[col] = (JSAMPLE)
  162701. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162702. >> SCALEBITS);
  162703. }
  162704. }
  162705. }
  162706. /*
  162707. * Convert some rows of samples to the JPEG colorspace.
  162708. * This version handles grayscale output with no conversion.
  162709. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162710. */
  162711. METHODDEF(void)
  162712. grayscale_convert (j_compress_ptr cinfo,
  162713. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162714. JDIMENSION output_row, int num_rows)
  162715. {
  162716. register JSAMPROW inptr;
  162717. register JSAMPROW outptr;
  162718. register JDIMENSION col;
  162719. JDIMENSION num_cols = cinfo->image_width;
  162720. int instride = cinfo->input_components;
  162721. while (--num_rows >= 0) {
  162722. inptr = *input_buf++;
  162723. outptr = output_buf[0][output_row];
  162724. output_row++;
  162725. for (col = 0; col < num_cols; col++) {
  162726. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162727. inptr += instride;
  162728. }
  162729. }
  162730. }
  162731. /*
  162732. * Convert some rows of samples to the JPEG colorspace.
  162733. * This version handles multi-component colorspaces without conversion.
  162734. * We assume input_components == num_components.
  162735. */
  162736. METHODDEF(void)
  162737. null_convert (j_compress_ptr cinfo,
  162738. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162739. JDIMENSION output_row, int num_rows)
  162740. {
  162741. register JSAMPROW inptr;
  162742. register JSAMPROW outptr;
  162743. register JDIMENSION col;
  162744. register int ci;
  162745. int nc = cinfo->num_components;
  162746. JDIMENSION num_cols = cinfo->image_width;
  162747. while (--num_rows >= 0) {
  162748. /* It seems fastest to make a separate pass for each component. */
  162749. for (ci = 0; ci < nc; ci++) {
  162750. inptr = *input_buf;
  162751. outptr = output_buf[ci][output_row];
  162752. for (col = 0; col < num_cols; col++) {
  162753. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162754. inptr += nc;
  162755. }
  162756. }
  162757. input_buf++;
  162758. output_row++;
  162759. }
  162760. }
  162761. /*
  162762. * Empty method for start_pass.
  162763. */
  162764. METHODDEF(void)
  162765. null_method (j_compress_ptr)
  162766. {
  162767. /* no work needed */
  162768. }
  162769. /*
  162770. * Module initialization routine for input colorspace conversion.
  162771. */
  162772. GLOBAL(void)
  162773. jinit_color_converter (j_compress_ptr cinfo)
  162774. {
  162775. my_cconvert_ptr cconvert;
  162776. cconvert = (my_cconvert_ptr)
  162777. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162778. SIZEOF(my_color_converter));
  162779. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162780. /* set start_pass to null method until we find out differently */
  162781. cconvert->pub.start_pass = null_method;
  162782. /* Make sure input_components agrees with in_color_space */
  162783. switch (cinfo->in_color_space) {
  162784. case JCS_GRAYSCALE:
  162785. if (cinfo->input_components != 1)
  162786. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162787. break;
  162788. case JCS_RGB:
  162789. #if RGB_PIXELSIZE != 3
  162790. if (cinfo->input_components != RGB_PIXELSIZE)
  162791. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162792. break;
  162793. #endif /* else share code with YCbCr */
  162794. case JCS_YCbCr:
  162795. if (cinfo->input_components != 3)
  162796. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162797. break;
  162798. case JCS_CMYK:
  162799. case JCS_YCCK:
  162800. if (cinfo->input_components != 4)
  162801. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162802. break;
  162803. default: /* JCS_UNKNOWN can be anything */
  162804. if (cinfo->input_components < 1)
  162805. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162806. break;
  162807. }
  162808. /* Check num_components, set conversion method based on requested space */
  162809. switch (cinfo->jpeg_color_space) {
  162810. case JCS_GRAYSCALE:
  162811. if (cinfo->num_components != 1)
  162812. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162813. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162814. cconvert->pub.color_convert = grayscale_convert;
  162815. else if (cinfo->in_color_space == JCS_RGB) {
  162816. cconvert->pub.start_pass = rgb_ycc_start;
  162817. cconvert->pub.color_convert = rgb_gray_convert;
  162818. } else if (cinfo->in_color_space == JCS_YCbCr)
  162819. cconvert->pub.color_convert = grayscale_convert;
  162820. else
  162821. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162822. break;
  162823. case JCS_RGB:
  162824. if (cinfo->num_components != 3)
  162825. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162826. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162827. cconvert->pub.color_convert = null_convert;
  162828. else
  162829. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162830. break;
  162831. case JCS_YCbCr:
  162832. if (cinfo->num_components != 3)
  162833. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162834. if (cinfo->in_color_space == JCS_RGB) {
  162835. cconvert->pub.start_pass = rgb_ycc_start;
  162836. cconvert->pub.color_convert = rgb_ycc_convert;
  162837. } else if (cinfo->in_color_space == JCS_YCbCr)
  162838. cconvert->pub.color_convert = null_convert;
  162839. else
  162840. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162841. break;
  162842. case JCS_CMYK:
  162843. if (cinfo->num_components != 4)
  162844. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162845. if (cinfo->in_color_space == JCS_CMYK)
  162846. cconvert->pub.color_convert = null_convert;
  162847. else
  162848. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162849. break;
  162850. case JCS_YCCK:
  162851. if (cinfo->num_components != 4)
  162852. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162853. if (cinfo->in_color_space == JCS_CMYK) {
  162854. cconvert->pub.start_pass = rgb_ycc_start;
  162855. cconvert->pub.color_convert = cmyk_ycck_convert;
  162856. } else if (cinfo->in_color_space == JCS_YCCK)
  162857. cconvert->pub.color_convert = null_convert;
  162858. else
  162859. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162860. break;
  162861. default: /* allow null conversion of JCS_UNKNOWN */
  162862. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162863. cinfo->num_components != cinfo->input_components)
  162864. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162865. cconvert->pub.color_convert = null_convert;
  162866. break;
  162867. }
  162868. }
  162869. /*** End of inlined file: jccolor.c ***/
  162870. #undef FIX
  162871. /*** Start of inlined file: jcdctmgr.c ***/
  162872. #define JPEG_INTERNALS
  162873. /*** Start of inlined file: jdct.h ***/
  162874. /*
  162875. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162876. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162877. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162878. * implementations use an array of type FAST_FLOAT, instead.)
  162879. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162880. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162881. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162882. * convention improves accuracy in integer implementations and saves some
  162883. * work in floating-point ones.
  162884. * Quantization of the output coefficients is done by jcdctmgr.c.
  162885. */
  162886. #ifndef __jdct_h__
  162887. #define __jdct_h__
  162888. #if BITS_IN_JSAMPLE == 8
  162889. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162890. #else
  162891. typedef INT32 DCTELEM; /* must have 32 bits */
  162892. #endif
  162893. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162894. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162895. /*
  162896. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162897. * to an output sample array. The routine must dequantize the input data as
  162898. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162899. * pointed to by compptr->dct_table. The output data is to be placed into the
  162900. * sample array starting at a specified column. (Any row offset needed will
  162901. * be applied to the array pointer before it is passed to the IDCT code.)
  162902. * Note that the number of samples emitted by the IDCT routine is
  162903. * DCT_scaled_size * DCT_scaled_size.
  162904. */
  162905. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162906. /*
  162907. * Each IDCT routine has its own ideas about the best dct_table element type.
  162908. */
  162909. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162910. #if BITS_IN_JSAMPLE == 8
  162911. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162912. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162913. #else
  162914. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162915. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162916. #endif
  162917. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162918. /*
  162919. * Each IDCT routine is responsible for range-limiting its results and
  162920. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162921. * be quite far out of range if the input data is corrupt, so a bulletproof
  162922. * range-limiting step is required. We use a mask-and-table-lookup method
  162923. * to do the combined operations quickly. See the comments with
  162924. * prepare_range_limit_table (in jdmaster.c) for more info.
  162925. */
  162926. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162927. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162928. /* Short forms of external names for systems with brain-damaged linkers. */
  162929. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162930. #define jpeg_fdct_islow jFDislow
  162931. #define jpeg_fdct_ifast jFDifast
  162932. #define jpeg_fdct_float jFDfloat
  162933. #define jpeg_idct_islow jRDislow
  162934. #define jpeg_idct_ifast jRDifast
  162935. #define jpeg_idct_float jRDfloat
  162936. #define jpeg_idct_4x4 jRD4x4
  162937. #define jpeg_idct_2x2 jRD2x2
  162938. #define jpeg_idct_1x1 jRD1x1
  162939. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162940. /* Extern declarations for the forward and inverse DCT routines. */
  162941. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162942. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162943. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162944. EXTERN(void) jpeg_idct_islow
  162945. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162946. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162947. EXTERN(void) jpeg_idct_ifast
  162948. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162949. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162950. EXTERN(void) jpeg_idct_float
  162951. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162952. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162953. EXTERN(void) jpeg_idct_4x4
  162954. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162955. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162956. EXTERN(void) jpeg_idct_2x2
  162957. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162958. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162959. EXTERN(void) jpeg_idct_1x1
  162960. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162961. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162962. /*
  162963. * Macros for handling fixed-point arithmetic; these are used by many
  162964. * but not all of the DCT/IDCT modules.
  162965. *
  162966. * All values are expected to be of type INT32.
  162967. * Fractional constants are scaled left by CONST_BITS bits.
  162968. * CONST_BITS is defined within each module using these macros,
  162969. * and may differ from one module to the next.
  162970. */
  162971. #define ONE ((INT32) 1)
  162972. #define CONST_SCALE (ONE << CONST_BITS)
  162973. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162974. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162975. * thus causing a lot of useless floating-point operations at run time.
  162976. */
  162977. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162978. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162979. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162980. * the fudge factor is correct for either sign of X.
  162981. */
  162982. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162983. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162984. * This macro is used only when the two inputs will actually be no more than
  162985. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162986. * full 32x32 multiply. This provides a useful speedup on many machines.
  162987. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162988. * in C, but some C compilers will do the right thing if you provide the
  162989. * correct combination of casts.
  162990. */
  162991. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162992. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162993. #endif
  162994. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162995. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162996. #endif
  162997. #ifndef MULTIPLY16C16 /* default definition */
  162998. #define MULTIPLY16C16(var,const) ((var) * (const))
  162999. #endif
  163000. /* Same except both inputs are variables. */
  163001. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163002. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163003. #endif
  163004. #ifndef MULTIPLY16V16 /* default definition */
  163005. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163006. #endif
  163007. #endif
  163008. /*** End of inlined file: jdct.h ***/
  163009. /* Private declarations for DCT subsystem */
  163010. /* Private subobject for this module */
  163011. typedef struct {
  163012. struct jpeg_forward_dct pub; /* public fields */
  163013. /* Pointer to the DCT routine actually in use */
  163014. forward_DCT_method_ptr do_dct;
  163015. /* The actual post-DCT divisors --- not identical to the quant table
  163016. * entries, because of scaling (especially for an unnormalized DCT).
  163017. * Each table is given in normal array order.
  163018. */
  163019. DCTELEM * divisors[NUM_QUANT_TBLS];
  163020. #ifdef DCT_FLOAT_SUPPORTED
  163021. /* Same as above for the floating-point case. */
  163022. float_DCT_method_ptr do_float_dct;
  163023. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163024. #endif
  163025. } my_fdct_controller;
  163026. typedef my_fdct_controller * my_fdct_ptr;
  163027. /*
  163028. * Initialize for a processing pass.
  163029. * Verify that all referenced Q-tables are present, and set up
  163030. * the divisor table for each one.
  163031. * In the current implementation, DCT of all components is done during
  163032. * the first pass, even if only some components will be output in the
  163033. * first scan. Hence all components should be examined here.
  163034. */
  163035. METHODDEF(void)
  163036. start_pass_fdctmgr (j_compress_ptr cinfo)
  163037. {
  163038. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163039. int ci, qtblno, i;
  163040. jpeg_component_info *compptr;
  163041. JQUANT_TBL * qtbl;
  163042. DCTELEM * dtbl;
  163043. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163044. ci++, compptr++) {
  163045. qtblno = compptr->quant_tbl_no;
  163046. /* Make sure specified quantization table is present */
  163047. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163048. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163049. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163050. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163051. /* Compute divisors for this quant table */
  163052. /* We may do this more than once for same table, but it's not a big deal */
  163053. switch (cinfo->dct_method) {
  163054. #ifdef DCT_ISLOW_SUPPORTED
  163055. case JDCT_ISLOW:
  163056. /* For LL&M IDCT method, divisors are equal to raw quantization
  163057. * coefficients multiplied by 8 (to counteract scaling).
  163058. */
  163059. if (fdct->divisors[qtblno] == NULL) {
  163060. fdct->divisors[qtblno] = (DCTELEM *)
  163061. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163062. DCTSIZE2 * SIZEOF(DCTELEM));
  163063. }
  163064. dtbl = fdct->divisors[qtblno];
  163065. for (i = 0; i < DCTSIZE2; i++) {
  163066. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163067. }
  163068. break;
  163069. #endif
  163070. #ifdef DCT_IFAST_SUPPORTED
  163071. case JDCT_IFAST:
  163072. {
  163073. /* For AA&N IDCT method, divisors are equal to quantization
  163074. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163075. * scalefactor[0] = 1
  163076. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163077. * We apply a further scale factor of 8.
  163078. */
  163079. #define CONST_BITS 14
  163080. static const INT16 aanscales[DCTSIZE2] = {
  163081. /* precomputed values scaled up by 14 bits */
  163082. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163083. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163084. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163085. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163086. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163087. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163088. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163089. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163090. };
  163091. SHIFT_TEMPS
  163092. if (fdct->divisors[qtblno] == NULL) {
  163093. fdct->divisors[qtblno] = (DCTELEM *)
  163094. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163095. DCTSIZE2 * SIZEOF(DCTELEM));
  163096. }
  163097. dtbl = fdct->divisors[qtblno];
  163098. for (i = 0; i < DCTSIZE2; i++) {
  163099. dtbl[i] = (DCTELEM)
  163100. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163101. (INT32) aanscales[i]),
  163102. CONST_BITS-3);
  163103. }
  163104. }
  163105. break;
  163106. #endif
  163107. #ifdef DCT_FLOAT_SUPPORTED
  163108. case JDCT_FLOAT:
  163109. {
  163110. /* For float AA&N IDCT method, divisors are equal to quantization
  163111. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163112. * scalefactor[0] = 1
  163113. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163114. * We apply a further scale factor of 8.
  163115. * What's actually stored is 1/divisor so that the inner loop can
  163116. * use a multiplication rather than a division.
  163117. */
  163118. FAST_FLOAT * fdtbl;
  163119. int row, col;
  163120. static const double aanscalefactor[DCTSIZE] = {
  163121. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163122. 1.0, 0.785694958, 0.541196100, 0.275899379
  163123. };
  163124. if (fdct->float_divisors[qtblno] == NULL) {
  163125. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163126. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163127. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163128. }
  163129. fdtbl = fdct->float_divisors[qtblno];
  163130. i = 0;
  163131. for (row = 0; row < DCTSIZE; row++) {
  163132. for (col = 0; col < DCTSIZE; col++) {
  163133. fdtbl[i] = (FAST_FLOAT)
  163134. (1.0 / (((double) qtbl->quantval[i] *
  163135. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163136. i++;
  163137. }
  163138. }
  163139. }
  163140. break;
  163141. #endif
  163142. default:
  163143. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163144. break;
  163145. }
  163146. }
  163147. }
  163148. /*
  163149. * Perform forward DCT on one or more blocks of a component.
  163150. *
  163151. * The input samples are taken from the sample_data[] array starting at
  163152. * position start_row/start_col, and moving to the right for any additional
  163153. * blocks. The quantized coefficients are returned in coef_blocks[].
  163154. */
  163155. METHODDEF(void)
  163156. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163157. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163158. JDIMENSION start_row, JDIMENSION start_col,
  163159. JDIMENSION num_blocks)
  163160. /* This version is used for integer DCT implementations. */
  163161. {
  163162. /* This routine is heavily used, so it's worth coding it tightly. */
  163163. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163164. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163165. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163166. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163167. JDIMENSION bi;
  163168. sample_data += start_row; /* fold in the vertical offset once */
  163169. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163170. /* Load data into workspace, applying unsigned->signed conversion */
  163171. { register DCTELEM *workspaceptr;
  163172. register JSAMPROW elemptr;
  163173. register int elemr;
  163174. workspaceptr = workspace;
  163175. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163176. elemptr = sample_data[elemr] + start_col;
  163177. #if DCTSIZE == 8 /* unroll the inner loop */
  163178. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163179. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163180. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163181. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163182. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163183. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163184. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163185. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163186. #else
  163187. { register int elemc;
  163188. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163189. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163190. }
  163191. }
  163192. #endif
  163193. }
  163194. }
  163195. /* Perform the DCT */
  163196. (*do_dct) (workspace);
  163197. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163198. { register DCTELEM temp, qval;
  163199. register int i;
  163200. register JCOEFPTR output_ptr = coef_blocks[bi];
  163201. for (i = 0; i < DCTSIZE2; i++) {
  163202. qval = divisors[i];
  163203. temp = workspace[i];
  163204. /* Divide the coefficient value by qval, ensuring proper rounding.
  163205. * Since C does not specify the direction of rounding for negative
  163206. * quotients, we have to force the dividend positive for portability.
  163207. *
  163208. * In most files, at least half of the output values will be zero
  163209. * (at default quantization settings, more like three-quarters...)
  163210. * so we should ensure that this case is fast. On many machines,
  163211. * a comparison is enough cheaper than a divide to make a special test
  163212. * a win. Since both inputs will be nonnegative, we need only test
  163213. * for a < b to discover whether a/b is 0.
  163214. * If your machine's division is fast enough, define FAST_DIVIDE.
  163215. */
  163216. #ifdef FAST_DIVIDE
  163217. #define DIVIDE_BY(a,b) a /= b
  163218. #else
  163219. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163220. #endif
  163221. if (temp < 0) {
  163222. temp = -temp;
  163223. temp += qval>>1; /* for rounding */
  163224. DIVIDE_BY(temp, qval);
  163225. temp = -temp;
  163226. } else {
  163227. temp += qval>>1; /* for rounding */
  163228. DIVIDE_BY(temp, qval);
  163229. }
  163230. output_ptr[i] = (JCOEF) temp;
  163231. }
  163232. }
  163233. }
  163234. }
  163235. #ifdef DCT_FLOAT_SUPPORTED
  163236. METHODDEF(void)
  163237. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163238. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163239. JDIMENSION start_row, JDIMENSION start_col,
  163240. JDIMENSION num_blocks)
  163241. /* This version is used for floating-point DCT implementations. */
  163242. {
  163243. /* This routine is heavily used, so it's worth coding it tightly. */
  163244. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163245. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163246. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163247. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163248. JDIMENSION bi;
  163249. sample_data += start_row; /* fold in the vertical offset once */
  163250. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163251. /* Load data into workspace, applying unsigned->signed conversion */
  163252. { register FAST_FLOAT *workspaceptr;
  163253. register JSAMPROW elemptr;
  163254. register int elemr;
  163255. workspaceptr = workspace;
  163256. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163257. elemptr = sample_data[elemr] + start_col;
  163258. #if DCTSIZE == 8 /* unroll the inner loop */
  163259. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163260. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163261. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163262. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163263. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163264. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163265. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163266. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163267. #else
  163268. { register int elemc;
  163269. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163270. *workspaceptr++ = (FAST_FLOAT)
  163271. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163272. }
  163273. }
  163274. #endif
  163275. }
  163276. }
  163277. /* Perform the DCT */
  163278. (*do_dct) (workspace);
  163279. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163280. { register FAST_FLOAT temp;
  163281. register int i;
  163282. register JCOEFPTR output_ptr = coef_blocks[bi];
  163283. for (i = 0; i < DCTSIZE2; i++) {
  163284. /* Apply the quantization and scaling factor */
  163285. temp = workspace[i] * divisors[i];
  163286. /* Round to nearest integer.
  163287. * Since C does not specify the direction of rounding for negative
  163288. * quotients, we have to force the dividend positive for portability.
  163289. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163290. * code should work for either 16-bit or 32-bit ints.
  163291. */
  163292. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163293. }
  163294. }
  163295. }
  163296. }
  163297. #endif /* DCT_FLOAT_SUPPORTED */
  163298. /*
  163299. * Initialize FDCT manager.
  163300. */
  163301. GLOBAL(void)
  163302. jinit_forward_dct (j_compress_ptr cinfo)
  163303. {
  163304. my_fdct_ptr fdct;
  163305. int i;
  163306. fdct = (my_fdct_ptr)
  163307. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163308. SIZEOF(my_fdct_controller));
  163309. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163310. fdct->pub.start_pass = start_pass_fdctmgr;
  163311. switch (cinfo->dct_method) {
  163312. #ifdef DCT_ISLOW_SUPPORTED
  163313. case JDCT_ISLOW:
  163314. fdct->pub.forward_DCT = forward_DCT;
  163315. fdct->do_dct = jpeg_fdct_islow;
  163316. break;
  163317. #endif
  163318. #ifdef DCT_IFAST_SUPPORTED
  163319. case JDCT_IFAST:
  163320. fdct->pub.forward_DCT = forward_DCT;
  163321. fdct->do_dct = jpeg_fdct_ifast;
  163322. break;
  163323. #endif
  163324. #ifdef DCT_FLOAT_SUPPORTED
  163325. case JDCT_FLOAT:
  163326. fdct->pub.forward_DCT = forward_DCT_float;
  163327. fdct->do_float_dct = jpeg_fdct_float;
  163328. break;
  163329. #endif
  163330. default:
  163331. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163332. break;
  163333. }
  163334. /* Mark divisor tables unallocated */
  163335. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163336. fdct->divisors[i] = NULL;
  163337. #ifdef DCT_FLOAT_SUPPORTED
  163338. fdct->float_divisors[i] = NULL;
  163339. #endif
  163340. }
  163341. }
  163342. /*** End of inlined file: jcdctmgr.c ***/
  163343. #undef CONST_BITS
  163344. /*** Start of inlined file: jchuff.c ***/
  163345. #define JPEG_INTERNALS
  163346. /*** Start of inlined file: jchuff.h ***/
  163347. /* The legal range of a DCT coefficient is
  163348. * -1024 .. +1023 for 8-bit data;
  163349. * -16384 .. +16383 for 12-bit data.
  163350. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163351. */
  163352. #ifndef _jchuff_h_
  163353. #define _jchuff_h_
  163354. #if BITS_IN_JSAMPLE == 8
  163355. #define MAX_COEF_BITS 10
  163356. #else
  163357. #define MAX_COEF_BITS 14
  163358. #endif
  163359. /* Derived data constructed for each Huffman table */
  163360. typedef struct {
  163361. unsigned int ehufco[256]; /* code for each symbol */
  163362. char ehufsi[256]; /* length of code for each symbol */
  163363. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163364. } c_derived_tbl;
  163365. /* Short forms of external names for systems with brain-damaged linkers. */
  163366. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163367. #define jpeg_make_c_derived_tbl jMkCDerived
  163368. #define jpeg_gen_optimal_table jGenOptTbl
  163369. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163370. /* Expand a Huffman table definition into the derived format */
  163371. EXTERN(void) jpeg_make_c_derived_tbl
  163372. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163373. c_derived_tbl ** pdtbl));
  163374. /* Generate an optimal table definition given the specified counts */
  163375. EXTERN(void) jpeg_gen_optimal_table
  163376. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163377. #endif
  163378. /*** End of inlined file: jchuff.h ***/
  163379. /* Declarations shared with jcphuff.c */
  163380. /* Expanded entropy encoder object for Huffman encoding.
  163381. *
  163382. * The savable_state subrecord contains fields that change within an MCU,
  163383. * but must not be updated permanently until we complete the MCU.
  163384. */
  163385. typedef struct {
  163386. INT32 put_buffer; /* current bit-accumulation buffer */
  163387. int put_bits; /* # of bits now in it */
  163388. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163389. } savable_state;
  163390. /* This macro is to work around compilers with missing or broken
  163391. * structure assignment. You'll need to fix this code if you have
  163392. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163393. */
  163394. #ifndef NO_STRUCT_ASSIGN
  163395. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163396. #else
  163397. #if MAX_COMPS_IN_SCAN == 4
  163398. #define ASSIGN_STATE(dest,src) \
  163399. ((dest).put_buffer = (src).put_buffer, \
  163400. (dest).put_bits = (src).put_bits, \
  163401. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163402. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163403. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163404. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163405. #endif
  163406. #endif
  163407. typedef struct {
  163408. struct jpeg_entropy_encoder pub; /* public fields */
  163409. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163410. /* These fields are NOT loaded into local working state. */
  163411. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163412. int next_restart_num; /* next restart number to write (0-7) */
  163413. /* Pointers to derived tables (these workspaces have image lifespan) */
  163414. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163415. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163416. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163417. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163418. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163419. #endif
  163420. } huff_entropy_encoder;
  163421. typedef huff_entropy_encoder * huff_entropy_ptr;
  163422. /* Working state while writing an MCU.
  163423. * This struct contains all the fields that are needed by subroutines.
  163424. */
  163425. typedef struct {
  163426. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163427. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163428. savable_state cur; /* Current bit buffer & DC state */
  163429. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163430. } working_state;
  163431. /* Forward declarations */
  163432. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163433. JBLOCKROW *MCU_data));
  163434. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163435. #ifdef ENTROPY_OPT_SUPPORTED
  163436. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163437. JBLOCKROW *MCU_data));
  163438. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163439. #endif
  163440. /*
  163441. * Initialize for a Huffman-compressed scan.
  163442. * If gather_statistics is TRUE, we do not output anything during the scan,
  163443. * just count the Huffman symbols used and generate Huffman code tables.
  163444. */
  163445. METHODDEF(void)
  163446. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163447. {
  163448. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163449. int ci, dctbl, actbl;
  163450. jpeg_component_info * compptr;
  163451. if (gather_statistics) {
  163452. #ifdef ENTROPY_OPT_SUPPORTED
  163453. entropy->pub.encode_mcu = encode_mcu_gather;
  163454. entropy->pub.finish_pass = finish_pass_gather;
  163455. #else
  163456. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163457. #endif
  163458. } else {
  163459. entropy->pub.encode_mcu = encode_mcu_huff;
  163460. entropy->pub.finish_pass = finish_pass_huff;
  163461. }
  163462. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163463. compptr = cinfo->cur_comp_info[ci];
  163464. dctbl = compptr->dc_tbl_no;
  163465. actbl = compptr->ac_tbl_no;
  163466. if (gather_statistics) {
  163467. #ifdef ENTROPY_OPT_SUPPORTED
  163468. /* Check for invalid table indexes */
  163469. /* (make_c_derived_tbl does this in the other path) */
  163470. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163471. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163472. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163473. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163474. /* Allocate and zero the statistics tables */
  163475. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163476. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163477. entropy->dc_count_ptrs[dctbl] = (long *)
  163478. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163479. 257 * SIZEOF(long));
  163480. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163481. if (entropy->ac_count_ptrs[actbl] == NULL)
  163482. entropy->ac_count_ptrs[actbl] = (long *)
  163483. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163484. 257 * SIZEOF(long));
  163485. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163486. #endif
  163487. } else {
  163488. /* Compute derived values for Huffman tables */
  163489. /* We may do this more than once for a table, but it's not expensive */
  163490. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163491. & entropy->dc_derived_tbls[dctbl]);
  163492. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163493. & entropy->ac_derived_tbls[actbl]);
  163494. }
  163495. /* Initialize DC predictions to 0 */
  163496. entropy->saved.last_dc_val[ci] = 0;
  163497. }
  163498. /* Initialize bit buffer to empty */
  163499. entropy->saved.put_buffer = 0;
  163500. entropy->saved.put_bits = 0;
  163501. /* Initialize restart stuff */
  163502. entropy->restarts_to_go = cinfo->restart_interval;
  163503. entropy->next_restart_num = 0;
  163504. }
  163505. /*
  163506. * Compute the derived values for a Huffman table.
  163507. * This routine also performs some validation checks on the table.
  163508. *
  163509. * Note this is also used by jcphuff.c.
  163510. */
  163511. GLOBAL(void)
  163512. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163513. c_derived_tbl ** pdtbl)
  163514. {
  163515. JHUFF_TBL *htbl;
  163516. c_derived_tbl *dtbl;
  163517. int p, i, l, lastp, si, maxsymbol;
  163518. char huffsize[257];
  163519. unsigned int huffcode[257];
  163520. unsigned int code;
  163521. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163522. * paralleling the order of the symbols themselves in htbl->huffval[].
  163523. */
  163524. /* Find the input Huffman table */
  163525. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163526. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163527. htbl =
  163528. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163529. if (htbl == NULL)
  163530. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163531. /* Allocate a workspace if we haven't already done so. */
  163532. if (*pdtbl == NULL)
  163533. *pdtbl = (c_derived_tbl *)
  163534. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163535. SIZEOF(c_derived_tbl));
  163536. dtbl = *pdtbl;
  163537. /* Figure C.1: make table of Huffman code length for each symbol */
  163538. p = 0;
  163539. for (l = 1; l <= 16; l++) {
  163540. i = (int) htbl->bits[l];
  163541. if (i < 0 || p + i > 256) /* protect against table overrun */
  163542. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163543. while (i--)
  163544. huffsize[p++] = (char) l;
  163545. }
  163546. huffsize[p] = 0;
  163547. lastp = p;
  163548. /* Figure C.2: generate the codes themselves */
  163549. /* We also validate that the counts represent a legal Huffman code tree. */
  163550. code = 0;
  163551. si = huffsize[0];
  163552. p = 0;
  163553. while (huffsize[p]) {
  163554. while (((int) huffsize[p]) == si) {
  163555. huffcode[p++] = code;
  163556. code++;
  163557. }
  163558. /* code is now 1 more than the last code used for codelength si; but
  163559. * it must still fit in si bits, since no code is allowed to be all ones.
  163560. */
  163561. if (((INT32) code) >= (((INT32) 1) << si))
  163562. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163563. code <<= 1;
  163564. si++;
  163565. }
  163566. /* Figure C.3: generate encoding tables */
  163567. /* These are code and size indexed by symbol value */
  163568. /* Set all codeless symbols to have code length 0;
  163569. * this lets us detect duplicate VAL entries here, and later
  163570. * allows emit_bits to detect any attempt to emit such symbols.
  163571. */
  163572. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163573. /* This is also a convenient place to check for out-of-range
  163574. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163575. * but only 0..15 for DC. (We could constrain them further
  163576. * based on data depth and mode, but this seems enough.)
  163577. */
  163578. maxsymbol = isDC ? 15 : 255;
  163579. for (p = 0; p < lastp; p++) {
  163580. i = htbl->huffval[p];
  163581. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163582. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163583. dtbl->ehufco[i] = huffcode[p];
  163584. dtbl->ehufsi[i] = huffsize[p];
  163585. }
  163586. }
  163587. /* Outputting bytes to the file */
  163588. /* Emit a byte, taking 'action' if must suspend. */
  163589. #define emit_byte(state,val,action) \
  163590. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163591. if (--(state)->free_in_buffer == 0) \
  163592. if (! dump_buffer(state)) \
  163593. { action; } }
  163594. LOCAL(boolean)
  163595. dump_buffer (working_state * state)
  163596. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163597. {
  163598. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163599. if (! (*dest->empty_output_buffer) (state->cinfo))
  163600. return FALSE;
  163601. /* After a successful buffer dump, must reset buffer pointers */
  163602. state->next_output_byte = dest->next_output_byte;
  163603. state->free_in_buffer = dest->free_in_buffer;
  163604. return TRUE;
  163605. }
  163606. /* Outputting bits to the file */
  163607. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163608. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163609. * in one call, and we never retain more than 7 bits in put_buffer
  163610. * between calls, so 24 bits are sufficient.
  163611. */
  163612. INLINE
  163613. LOCAL(boolean)
  163614. emit_bits (working_state * state, unsigned int code, int size)
  163615. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163616. {
  163617. /* This routine is heavily used, so it's worth coding tightly. */
  163618. register INT32 put_buffer = (INT32) code;
  163619. register int put_bits = state->cur.put_bits;
  163620. /* if size is 0, caller used an invalid Huffman table entry */
  163621. if (size == 0)
  163622. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163623. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163624. put_bits += size; /* new number of bits in buffer */
  163625. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163626. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163627. while (put_bits >= 8) {
  163628. int c = (int) ((put_buffer >> 16) & 0xFF);
  163629. emit_byte(state, c, return FALSE);
  163630. if (c == 0xFF) { /* need to stuff a zero byte? */
  163631. emit_byte(state, 0, return FALSE);
  163632. }
  163633. put_buffer <<= 8;
  163634. put_bits -= 8;
  163635. }
  163636. state->cur.put_buffer = put_buffer; /* update state variables */
  163637. state->cur.put_bits = put_bits;
  163638. return TRUE;
  163639. }
  163640. LOCAL(boolean)
  163641. flush_bits (working_state * state)
  163642. {
  163643. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163644. return FALSE;
  163645. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163646. state->cur.put_bits = 0;
  163647. return TRUE;
  163648. }
  163649. /* Encode a single block's worth of coefficients */
  163650. LOCAL(boolean)
  163651. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163652. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163653. {
  163654. register int temp, temp2;
  163655. register int nbits;
  163656. register int k, r, i;
  163657. /* Encode the DC coefficient difference per section F.1.2.1 */
  163658. temp = temp2 = block[0] - last_dc_val;
  163659. if (temp < 0) {
  163660. temp = -temp; /* temp is abs value of input */
  163661. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163662. /* This code assumes we are on a two's complement machine */
  163663. temp2--;
  163664. }
  163665. /* Find the number of bits needed for the magnitude of the coefficient */
  163666. nbits = 0;
  163667. while (temp) {
  163668. nbits++;
  163669. temp >>= 1;
  163670. }
  163671. /* Check for out-of-range coefficient values.
  163672. * Since we're encoding a difference, the range limit is twice as much.
  163673. */
  163674. if (nbits > MAX_COEF_BITS+1)
  163675. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163676. /* Emit the Huffman-coded symbol for the number of bits */
  163677. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163678. return FALSE;
  163679. /* Emit that number of bits of the value, if positive, */
  163680. /* or the complement of its magnitude, if negative. */
  163681. if (nbits) /* emit_bits rejects calls with size 0 */
  163682. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163683. return FALSE;
  163684. /* Encode the AC coefficients per section F.1.2.2 */
  163685. r = 0; /* r = run length of zeros */
  163686. for (k = 1; k < DCTSIZE2; k++) {
  163687. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163688. r++;
  163689. } else {
  163690. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163691. while (r > 15) {
  163692. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163693. return FALSE;
  163694. r -= 16;
  163695. }
  163696. temp2 = temp;
  163697. if (temp < 0) {
  163698. temp = -temp; /* temp is abs value of input */
  163699. /* This code assumes we are on a two's complement machine */
  163700. temp2--;
  163701. }
  163702. /* Find the number of bits needed for the magnitude of the coefficient */
  163703. nbits = 1; /* there must be at least one 1 bit */
  163704. while ((temp >>= 1))
  163705. nbits++;
  163706. /* Check for out-of-range coefficient values */
  163707. if (nbits > MAX_COEF_BITS)
  163708. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163709. /* Emit Huffman symbol for run length / number of bits */
  163710. i = (r << 4) + nbits;
  163711. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163712. return FALSE;
  163713. /* Emit that number of bits of the value, if positive, */
  163714. /* or the complement of its magnitude, if negative. */
  163715. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163716. return FALSE;
  163717. r = 0;
  163718. }
  163719. }
  163720. /* If the last coef(s) were zero, emit an end-of-block code */
  163721. if (r > 0)
  163722. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163723. return FALSE;
  163724. return TRUE;
  163725. }
  163726. /*
  163727. * Emit a restart marker & resynchronize predictions.
  163728. */
  163729. LOCAL(boolean)
  163730. emit_restart (working_state * state, int restart_num)
  163731. {
  163732. int ci;
  163733. if (! flush_bits(state))
  163734. return FALSE;
  163735. emit_byte(state, 0xFF, return FALSE);
  163736. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163737. /* Re-initialize DC predictions to 0 */
  163738. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163739. state->cur.last_dc_val[ci] = 0;
  163740. /* The restart counter is not updated until we successfully write the MCU. */
  163741. return TRUE;
  163742. }
  163743. /*
  163744. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163745. */
  163746. METHODDEF(boolean)
  163747. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163748. {
  163749. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163750. working_state state;
  163751. int blkn, ci;
  163752. jpeg_component_info * compptr;
  163753. /* Load up working state */
  163754. state.next_output_byte = cinfo->dest->next_output_byte;
  163755. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163756. ASSIGN_STATE(state.cur, entropy->saved);
  163757. state.cinfo = cinfo;
  163758. /* Emit restart marker if needed */
  163759. if (cinfo->restart_interval) {
  163760. if (entropy->restarts_to_go == 0)
  163761. if (! emit_restart(&state, entropy->next_restart_num))
  163762. return FALSE;
  163763. }
  163764. /* Encode the MCU data blocks */
  163765. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163766. ci = cinfo->MCU_membership[blkn];
  163767. compptr = cinfo->cur_comp_info[ci];
  163768. if (! encode_one_block(&state,
  163769. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163770. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163771. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163772. return FALSE;
  163773. /* Update last_dc_val */
  163774. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163775. }
  163776. /* Completed MCU, so update state */
  163777. cinfo->dest->next_output_byte = state.next_output_byte;
  163778. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163779. ASSIGN_STATE(entropy->saved, state.cur);
  163780. /* Update restart-interval state too */
  163781. if (cinfo->restart_interval) {
  163782. if (entropy->restarts_to_go == 0) {
  163783. entropy->restarts_to_go = cinfo->restart_interval;
  163784. entropy->next_restart_num++;
  163785. entropy->next_restart_num &= 7;
  163786. }
  163787. entropy->restarts_to_go--;
  163788. }
  163789. return TRUE;
  163790. }
  163791. /*
  163792. * Finish up at the end of a Huffman-compressed scan.
  163793. */
  163794. METHODDEF(void)
  163795. finish_pass_huff (j_compress_ptr cinfo)
  163796. {
  163797. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163798. working_state state;
  163799. /* Load up working state ... flush_bits needs it */
  163800. state.next_output_byte = cinfo->dest->next_output_byte;
  163801. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163802. ASSIGN_STATE(state.cur, entropy->saved);
  163803. state.cinfo = cinfo;
  163804. /* Flush out the last data */
  163805. if (! flush_bits(&state))
  163806. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163807. /* Update state */
  163808. cinfo->dest->next_output_byte = state.next_output_byte;
  163809. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163810. ASSIGN_STATE(entropy->saved, state.cur);
  163811. }
  163812. /*
  163813. * Huffman coding optimization.
  163814. *
  163815. * We first scan the supplied data and count the number of uses of each symbol
  163816. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163817. * Then we build a Huffman coding tree for the observed counts.
  163818. * Symbols which are not needed at all for the particular image are not
  163819. * assigned any code, which saves space in the DHT marker as well as in
  163820. * the compressed data.
  163821. */
  163822. #ifdef ENTROPY_OPT_SUPPORTED
  163823. /* Process a single block's worth of coefficients */
  163824. LOCAL(void)
  163825. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163826. long dc_counts[], long ac_counts[])
  163827. {
  163828. register int temp;
  163829. register int nbits;
  163830. register int k, r;
  163831. /* Encode the DC coefficient difference per section F.1.2.1 */
  163832. temp = block[0] - last_dc_val;
  163833. if (temp < 0)
  163834. temp = -temp;
  163835. /* Find the number of bits needed for the magnitude of the coefficient */
  163836. nbits = 0;
  163837. while (temp) {
  163838. nbits++;
  163839. temp >>= 1;
  163840. }
  163841. /* Check for out-of-range coefficient values.
  163842. * Since we're encoding a difference, the range limit is twice as much.
  163843. */
  163844. if (nbits > MAX_COEF_BITS+1)
  163845. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163846. /* Count the Huffman symbol for the number of bits */
  163847. dc_counts[nbits]++;
  163848. /* Encode the AC coefficients per section F.1.2.2 */
  163849. r = 0; /* r = run length of zeros */
  163850. for (k = 1; k < DCTSIZE2; k++) {
  163851. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163852. r++;
  163853. } else {
  163854. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163855. while (r > 15) {
  163856. ac_counts[0xF0]++;
  163857. r -= 16;
  163858. }
  163859. /* Find the number of bits needed for the magnitude of the coefficient */
  163860. if (temp < 0)
  163861. temp = -temp;
  163862. /* Find the number of bits needed for the magnitude of the coefficient */
  163863. nbits = 1; /* there must be at least one 1 bit */
  163864. while ((temp >>= 1))
  163865. nbits++;
  163866. /* Check for out-of-range coefficient values */
  163867. if (nbits > MAX_COEF_BITS)
  163868. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163869. /* Count Huffman symbol for run length / number of bits */
  163870. ac_counts[(r << 4) + nbits]++;
  163871. r = 0;
  163872. }
  163873. }
  163874. /* If the last coef(s) were zero, emit an end-of-block code */
  163875. if (r > 0)
  163876. ac_counts[0]++;
  163877. }
  163878. /*
  163879. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163880. * No data is actually output, so no suspension return is possible.
  163881. */
  163882. METHODDEF(boolean)
  163883. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163884. {
  163885. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163886. int blkn, ci;
  163887. jpeg_component_info * compptr;
  163888. /* Take care of restart intervals if needed */
  163889. if (cinfo->restart_interval) {
  163890. if (entropy->restarts_to_go == 0) {
  163891. /* Re-initialize DC predictions to 0 */
  163892. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163893. entropy->saved.last_dc_val[ci] = 0;
  163894. /* Update restart state */
  163895. entropy->restarts_to_go = cinfo->restart_interval;
  163896. }
  163897. entropy->restarts_to_go--;
  163898. }
  163899. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163900. ci = cinfo->MCU_membership[blkn];
  163901. compptr = cinfo->cur_comp_info[ci];
  163902. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163903. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163904. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163905. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163906. }
  163907. return TRUE;
  163908. }
  163909. /*
  163910. * Generate the best Huffman code table for the given counts, fill htbl.
  163911. * Note this is also used by jcphuff.c.
  163912. *
  163913. * The JPEG standard requires that no symbol be assigned a codeword of all
  163914. * one bits (so that padding bits added at the end of a compressed segment
  163915. * can't look like a valid code). Because of the canonical ordering of
  163916. * codewords, this just means that there must be an unused slot in the
  163917. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163918. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163919. * with count 1. In theory that's not optimal; giving it count zero but
  163920. * including it in the symbol set anyway should give a better Huffman code.
  163921. * But the theoretically better code actually seems to come out worse in
  163922. * practice, because it produces more all-ones bytes (which incur stuffed
  163923. * zero bytes in the final file). In any case the difference is tiny.
  163924. *
  163925. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163926. * If some symbols have a very small but nonzero probability, the Huffman tree
  163927. * must be adjusted to meet the code length restriction. We currently use
  163928. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163929. * optimal; it may not choose the best possible limited-length code. But
  163930. * typically only very-low-frequency symbols will be given less-than-optimal
  163931. * lengths, so the code is almost optimal. Experimental comparisons against
  163932. * an optimal limited-length-code algorithm indicate that the difference is
  163933. * microscopic --- usually less than a hundredth of a percent of total size.
  163934. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163935. */
  163936. GLOBAL(void)
  163937. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163938. {
  163939. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163940. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163941. int codesize[257]; /* codesize[k] = code length of symbol k */
  163942. int others[257]; /* next symbol in current branch of tree */
  163943. int c1, c2;
  163944. int p, i, j;
  163945. long v;
  163946. /* This algorithm is explained in section K.2 of the JPEG standard */
  163947. MEMZERO(bits, SIZEOF(bits));
  163948. MEMZERO(codesize, SIZEOF(codesize));
  163949. for (i = 0; i < 257; i++)
  163950. others[i] = -1; /* init links to empty */
  163951. freq[256] = 1; /* make sure 256 has a nonzero count */
  163952. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163953. * that no real symbol is given code-value of all ones, because 256
  163954. * will be placed last in the largest codeword category.
  163955. */
  163956. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163957. for (;;) {
  163958. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163959. /* In case of ties, take the larger symbol number */
  163960. c1 = -1;
  163961. v = 1000000000L;
  163962. for (i = 0; i <= 256; i++) {
  163963. if (freq[i] && freq[i] <= v) {
  163964. v = freq[i];
  163965. c1 = i;
  163966. }
  163967. }
  163968. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163969. /* In case of ties, take the larger symbol number */
  163970. c2 = -1;
  163971. v = 1000000000L;
  163972. for (i = 0; i <= 256; i++) {
  163973. if (freq[i] && freq[i] <= v && i != c1) {
  163974. v = freq[i];
  163975. c2 = i;
  163976. }
  163977. }
  163978. /* Done if we've merged everything into one frequency */
  163979. if (c2 < 0)
  163980. break;
  163981. /* Else merge the two counts/trees */
  163982. freq[c1] += freq[c2];
  163983. freq[c2] = 0;
  163984. /* Increment the codesize of everything in c1's tree branch */
  163985. codesize[c1]++;
  163986. while (others[c1] >= 0) {
  163987. c1 = others[c1];
  163988. codesize[c1]++;
  163989. }
  163990. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163991. /* Increment the codesize of everything in c2's tree branch */
  163992. codesize[c2]++;
  163993. while (others[c2] >= 0) {
  163994. c2 = others[c2];
  163995. codesize[c2]++;
  163996. }
  163997. }
  163998. /* Now count the number of symbols of each code length */
  163999. for (i = 0; i <= 256; i++) {
  164000. if (codesize[i]) {
  164001. /* The JPEG standard seems to think that this can't happen, */
  164002. /* but I'm paranoid... */
  164003. if (codesize[i] > MAX_CLEN)
  164004. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164005. bits[codesize[i]]++;
  164006. }
  164007. }
  164008. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164009. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164010. * Here is what the JPEG spec says about how this next bit works:
  164011. * Since symbols are paired for the longest Huffman code, the symbols are
  164012. * removed from this length category two at a time. The prefix for the pair
  164013. * (which is one bit shorter) is allocated to one of the pair; then,
  164014. * skipping the BITS entry for that prefix length, a code word from the next
  164015. * shortest nonzero BITS entry is converted into a prefix for two code words
  164016. * one bit longer.
  164017. */
  164018. for (i = MAX_CLEN; i > 16; i--) {
  164019. while (bits[i] > 0) {
  164020. j = i - 2; /* find length of new prefix to be used */
  164021. while (bits[j] == 0)
  164022. j--;
  164023. bits[i] -= 2; /* remove two symbols */
  164024. bits[i-1]++; /* one goes in this length */
  164025. bits[j+1] += 2; /* two new symbols in this length */
  164026. bits[j]--; /* symbol of this length is now a prefix */
  164027. }
  164028. }
  164029. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164030. while (bits[i] == 0) /* find largest codelength still in use */
  164031. i--;
  164032. bits[i]--;
  164033. /* Return final symbol counts (only for lengths 0..16) */
  164034. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164035. /* Return a list of the symbols sorted by code length */
  164036. /* It's not real clear to me why we don't need to consider the codelength
  164037. * changes made above, but the JPEG spec seems to think this works.
  164038. */
  164039. p = 0;
  164040. for (i = 1; i <= MAX_CLEN; i++) {
  164041. for (j = 0; j <= 255; j++) {
  164042. if (codesize[j] == i) {
  164043. htbl->huffval[p] = (UINT8) j;
  164044. p++;
  164045. }
  164046. }
  164047. }
  164048. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164049. htbl->sent_table = FALSE;
  164050. }
  164051. /*
  164052. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164053. */
  164054. METHODDEF(void)
  164055. finish_pass_gather (j_compress_ptr cinfo)
  164056. {
  164057. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164058. int ci, dctbl, actbl;
  164059. jpeg_component_info * compptr;
  164060. JHUFF_TBL **htblptr;
  164061. boolean did_dc[NUM_HUFF_TBLS];
  164062. boolean did_ac[NUM_HUFF_TBLS];
  164063. /* It's important not to apply jpeg_gen_optimal_table more than once
  164064. * per table, because it clobbers the input frequency counts!
  164065. */
  164066. MEMZERO(did_dc, SIZEOF(did_dc));
  164067. MEMZERO(did_ac, SIZEOF(did_ac));
  164068. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164069. compptr = cinfo->cur_comp_info[ci];
  164070. dctbl = compptr->dc_tbl_no;
  164071. actbl = compptr->ac_tbl_no;
  164072. if (! did_dc[dctbl]) {
  164073. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164074. if (*htblptr == NULL)
  164075. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164076. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164077. did_dc[dctbl] = TRUE;
  164078. }
  164079. if (! did_ac[actbl]) {
  164080. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164081. if (*htblptr == NULL)
  164082. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164083. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164084. did_ac[actbl] = TRUE;
  164085. }
  164086. }
  164087. }
  164088. #endif /* ENTROPY_OPT_SUPPORTED */
  164089. /*
  164090. * Module initialization routine for Huffman entropy encoding.
  164091. */
  164092. GLOBAL(void)
  164093. jinit_huff_encoder (j_compress_ptr cinfo)
  164094. {
  164095. huff_entropy_ptr entropy;
  164096. int i;
  164097. entropy = (huff_entropy_ptr)
  164098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164099. SIZEOF(huff_entropy_encoder));
  164100. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164101. entropy->pub.start_pass = start_pass_huff;
  164102. /* Mark tables unallocated */
  164103. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164104. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164105. #ifdef ENTROPY_OPT_SUPPORTED
  164106. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164107. #endif
  164108. }
  164109. }
  164110. /*** End of inlined file: jchuff.c ***/
  164111. #undef emit_byte
  164112. /*** Start of inlined file: jcinit.c ***/
  164113. #define JPEG_INTERNALS
  164114. /*
  164115. * Master selection of compression modules.
  164116. * This is done once at the start of processing an image. We determine
  164117. * which modules will be used and give them appropriate initialization calls.
  164118. */
  164119. GLOBAL(void)
  164120. jinit_compress_master (j_compress_ptr cinfo)
  164121. {
  164122. /* Initialize master control (includes parameter checking/processing) */
  164123. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164124. /* Preprocessing */
  164125. if (! cinfo->raw_data_in) {
  164126. jinit_color_converter(cinfo);
  164127. jinit_downsampler(cinfo);
  164128. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164129. }
  164130. /* Forward DCT */
  164131. jinit_forward_dct(cinfo);
  164132. /* Entropy encoding: either Huffman or arithmetic coding. */
  164133. if (cinfo->arith_code) {
  164134. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164135. } else {
  164136. if (cinfo->progressive_mode) {
  164137. #ifdef C_PROGRESSIVE_SUPPORTED
  164138. jinit_phuff_encoder(cinfo);
  164139. #else
  164140. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164141. #endif
  164142. } else
  164143. jinit_huff_encoder(cinfo);
  164144. }
  164145. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164146. jinit_c_coef_controller(cinfo,
  164147. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164148. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164149. jinit_marker_writer(cinfo);
  164150. /* We can now tell the memory manager to allocate virtual arrays. */
  164151. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164152. /* Write the datastream header (SOI) immediately.
  164153. * Frame and scan headers are postponed till later.
  164154. * This lets application insert special markers after the SOI.
  164155. */
  164156. (*cinfo->marker->write_file_header) (cinfo);
  164157. }
  164158. /*** End of inlined file: jcinit.c ***/
  164159. /*** Start of inlined file: jcmainct.c ***/
  164160. #define JPEG_INTERNALS
  164161. /* Note: currently, there is no operating mode in which a full-image buffer
  164162. * is needed at this step. If there were, that mode could not be used with
  164163. * "raw data" input, since this module is bypassed in that case. However,
  164164. * we've left the code here for possible use in special applications.
  164165. */
  164166. #undef FULL_MAIN_BUFFER_SUPPORTED
  164167. /* Private buffer controller object */
  164168. typedef struct {
  164169. struct jpeg_c_main_controller pub; /* public fields */
  164170. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164171. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164172. boolean suspended; /* remember if we suspended output */
  164173. J_BUF_MODE pass_mode; /* current operating mode */
  164174. /* If using just a strip buffer, this points to the entire set of buffers
  164175. * (we allocate one for each component). In the full-image case, this
  164176. * points to the currently accessible strips of the virtual arrays.
  164177. */
  164178. JSAMPARRAY buffer[MAX_COMPONENTS];
  164179. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164180. /* If using full-image storage, this array holds pointers to virtual-array
  164181. * control blocks for each component. Unused if not full-image storage.
  164182. */
  164183. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164184. #endif
  164185. } my_main_controller;
  164186. typedef my_main_controller * my_main_ptr;
  164187. /* Forward declarations */
  164188. METHODDEF(void) process_data_simple_main
  164189. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164190. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164191. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164192. METHODDEF(void) process_data_buffer_main
  164193. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164194. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164195. #endif
  164196. /*
  164197. * Initialize for a processing pass.
  164198. */
  164199. METHODDEF(void)
  164200. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164201. {
  164202. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164203. /* Do nothing in raw-data mode. */
  164204. if (cinfo->raw_data_in)
  164205. return;
  164206. main_->cur_iMCU_row = 0; /* initialize counters */
  164207. main_->rowgroup_ctr = 0;
  164208. main_->suspended = FALSE;
  164209. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164210. switch (pass_mode) {
  164211. case JBUF_PASS_THRU:
  164212. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164213. if (main_->whole_image[0] != NULL)
  164214. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164215. #endif
  164216. main_->pub.process_data = process_data_simple_main;
  164217. break;
  164218. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164219. case JBUF_SAVE_SOURCE:
  164220. case JBUF_CRANK_DEST:
  164221. case JBUF_SAVE_AND_PASS:
  164222. if (main_->whole_image[0] == NULL)
  164223. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164224. main_->pub.process_data = process_data_buffer_main;
  164225. break;
  164226. #endif
  164227. default:
  164228. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164229. break;
  164230. }
  164231. }
  164232. /*
  164233. * Process some data.
  164234. * This routine handles the simple pass-through mode,
  164235. * where we have only a strip buffer.
  164236. */
  164237. METHODDEF(void)
  164238. process_data_simple_main (j_compress_ptr cinfo,
  164239. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164240. JDIMENSION in_rows_avail)
  164241. {
  164242. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164243. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164244. /* Read input data if we haven't filled the main buffer yet */
  164245. if (main_->rowgroup_ctr < DCTSIZE)
  164246. (*cinfo->prep->pre_process_data) (cinfo,
  164247. input_buf, in_row_ctr, in_rows_avail,
  164248. main_->buffer, &main_->rowgroup_ctr,
  164249. (JDIMENSION) DCTSIZE);
  164250. /* If we don't have a full iMCU row buffered, return to application for
  164251. * more data. Note that preprocessor will always pad to fill the iMCU row
  164252. * at the bottom of the image.
  164253. */
  164254. if (main_->rowgroup_ctr != DCTSIZE)
  164255. return;
  164256. /* Send the completed row to the compressor */
  164257. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164258. /* If compressor did not consume the whole row, then we must need to
  164259. * suspend processing and return to the application. In this situation
  164260. * we pretend we didn't yet consume the last input row; otherwise, if
  164261. * it happened to be the last row of the image, the application would
  164262. * think we were done.
  164263. */
  164264. if (! main_->suspended) {
  164265. (*in_row_ctr)--;
  164266. main_->suspended = TRUE;
  164267. }
  164268. return;
  164269. }
  164270. /* We did finish the row. Undo our little suspension hack if a previous
  164271. * call suspended; then mark the main buffer empty.
  164272. */
  164273. if (main_->suspended) {
  164274. (*in_row_ctr)++;
  164275. main_->suspended = FALSE;
  164276. }
  164277. main_->rowgroup_ctr = 0;
  164278. main_->cur_iMCU_row++;
  164279. }
  164280. }
  164281. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164282. /*
  164283. * Process some data.
  164284. * This routine handles all of the modes that use a full-size buffer.
  164285. */
  164286. METHODDEF(void)
  164287. process_data_buffer_main (j_compress_ptr cinfo,
  164288. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164289. JDIMENSION in_rows_avail)
  164290. {
  164291. my_main_ptr main = (my_main_ptr) cinfo->main;
  164292. int ci;
  164293. jpeg_component_info *compptr;
  164294. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164295. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164296. /* Realign the virtual buffers if at the start of an iMCU row. */
  164297. if (main->rowgroup_ctr == 0) {
  164298. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164299. ci++, compptr++) {
  164300. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164301. ((j_common_ptr) cinfo, main->whole_image[ci],
  164302. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164303. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164304. }
  164305. /* In a read pass, pretend we just read some source data. */
  164306. if (! writing) {
  164307. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164308. main->rowgroup_ctr = DCTSIZE;
  164309. }
  164310. }
  164311. /* If a write pass, read input data until the current iMCU row is full. */
  164312. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164313. if (writing) {
  164314. (*cinfo->prep->pre_process_data) (cinfo,
  164315. input_buf, in_row_ctr, in_rows_avail,
  164316. main->buffer, &main->rowgroup_ctr,
  164317. (JDIMENSION) DCTSIZE);
  164318. /* Return to application if we need more data to fill the iMCU row. */
  164319. if (main->rowgroup_ctr < DCTSIZE)
  164320. return;
  164321. }
  164322. /* Emit data, unless this is a sink-only pass. */
  164323. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164324. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164325. /* If compressor did not consume the whole row, then we must need to
  164326. * suspend processing and return to the application. In this situation
  164327. * we pretend we didn't yet consume the last input row; otherwise, if
  164328. * it happened to be the last row of the image, the application would
  164329. * think we were done.
  164330. */
  164331. if (! main->suspended) {
  164332. (*in_row_ctr)--;
  164333. main->suspended = TRUE;
  164334. }
  164335. return;
  164336. }
  164337. /* We did finish the row. Undo our little suspension hack if a previous
  164338. * call suspended; then mark the main buffer empty.
  164339. */
  164340. if (main->suspended) {
  164341. (*in_row_ctr)++;
  164342. main->suspended = FALSE;
  164343. }
  164344. }
  164345. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164346. main->rowgroup_ctr = 0;
  164347. main->cur_iMCU_row++;
  164348. }
  164349. }
  164350. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164351. /*
  164352. * Initialize main buffer controller.
  164353. */
  164354. GLOBAL(void)
  164355. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164356. {
  164357. my_main_ptr main_;
  164358. int ci;
  164359. jpeg_component_info *compptr;
  164360. main_ = (my_main_ptr)
  164361. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164362. SIZEOF(my_main_controller));
  164363. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164364. main_->pub.start_pass = start_pass_main;
  164365. /* We don't need to create a buffer in raw-data mode. */
  164366. if (cinfo->raw_data_in)
  164367. return;
  164368. /* Create the buffer. It holds downsampled data, so each component
  164369. * may be of a different size.
  164370. */
  164371. if (need_full_buffer) {
  164372. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164373. /* Allocate a full-image virtual array for each component */
  164374. /* Note we pad the bottom to a multiple of the iMCU height */
  164375. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164376. ci++, compptr++) {
  164377. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164378. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164379. compptr->width_in_blocks * DCTSIZE,
  164380. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164381. (long) compptr->v_samp_factor) * DCTSIZE,
  164382. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164383. }
  164384. #else
  164385. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164386. #endif
  164387. } else {
  164388. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164389. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164390. #endif
  164391. /* Allocate a strip buffer for each component */
  164392. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164393. ci++, compptr++) {
  164394. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164395. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164396. compptr->width_in_blocks * DCTSIZE,
  164397. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164398. }
  164399. }
  164400. }
  164401. /*** End of inlined file: jcmainct.c ***/
  164402. /*** Start of inlined file: jcmarker.c ***/
  164403. #define JPEG_INTERNALS
  164404. /* Private state */
  164405. typedef struct {
  164406. struct jpeg_marker_writer pub; /* public fields */
  164407. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164408. } my_marker_writer;
  164409. typedef my_marker_writer * my_marker_ptr;
  164410. /*
  164411. * Basic output routines.
  164412. *
  164413. * Note that we do not support suspension while writing a marker.
  164414. * Therefore, an application using suspension must ensure that there is
  164415. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164416. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164417. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164418. * modes are not supported at all with suspension, so those two are the only
  164419. * points where markers will be written.
  164420. */
  164421. LOCAL(void)
  164422. emit_byte (j_compress_ptr cinfo, int val)
  164423. /* Emit a byte */
  164424. {
  164425. struct jpeg_destination_mgr * dest = cinfo->dest;
  164426. *(dest->next_output_byte)++ = (JOCTET) val;
  164427. if (--dest->free_in_buffer == 0) {
  164428. if (! (*dest->empty_output_buffer) (cinfo))
  164429. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164430. }
  164431. }
  164432. LOCAL(void)
  164433. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164434. /* Emit a marker code */
  164435. {
  164436. emit_byte(cinfo, 0xFF);
  164437. emit_byte(cinfo, (int) mark);
  164438. }
  164439. LOCAL(void)
  164440. emit_2bytes (j_compress_ptr cinfo, int value)
  164441. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164442. {
  164443. emit_byte(cinfo, (value >> 8) & 0xFF);
  164444. emit_byte(cinfo, value & 0xFF);
  164445. }
  164446. /*
  164447. * Routines to write specific marker types.
  164448. */
  164449. LOCAL(int)
  164450. emit_dqt (j_compress_ptr cinfo, int index)
  164451. /* Emit a DQT marker */
  164452. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164453. {
  164454. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164455. int prec;
  164456. int i;
  164457. if (qtbl == NULL)
  164458. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164459. prec = 0;
  164460. for (i = 0; i < DCTSIZE2; i++) {
  164461. if (qtbl->quantval[i] > 255)
  164462. prec = 1;
  164463. }
  164464. if (! qtbl->sent_table) {
  164465. emit_marker(cinfo, M_DQT);
  164466. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164467. emit_byte(cinfo, index + (prec<<4));
  164468. for (i = 0; i < DCTSIZE2; i++) {
  164469. /* The table entries must be emitted in zigzag order. */
  164470. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164471. if (prec)
  164472. emit_byte(cinfo, (int) (qval >> 8));
  164473. emit_byte(cinfo, (int) (qval & 0xFF));
  164474. }
  164475. qtbl->sent_table = TRUE;
  164476. }
  164477. return prec;
  164478. }
  164479. LOCAL(void)
  164480. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164481. /* Emit a DHT marker */
  164482. {
  164483. JHUFF_TBL * htbl;
  164484. int length, i;
  164485. if (is_ac) {
  164486. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164487. index += 0x10; /* output index has AC bit set */
  164488. } else {
  164489. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164490. }
  164491. if (htbl == NULL)
  164492. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164493. if (! htbl->sent_table) {
  164494. emit_marker(cinfo, M_DHT);
  164495. length = 0;
  164496. for (i = 1; i <= 16; i++)
  164497. length += htbl->bits[i];
  164498. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164499. emit_byte(cinfo, index);
  164500. for (i = 1; i <= 16; i++)
  164501. emit_byte(cinfo, htbl->bits[i]);
  164502. for (i = 0; i < length; i++)
  164503. emit_byte(cinfo, htbl->huffval[i]);
  164504. htbl->sent_table = TRUE;
  164505. }
  164506. }
  164507. LOCAL(void)
  164508. emit_dac (j_compress_ptr)
  164509. /* Emit a DAC marker */
  164510. /* Since the useful info is so small, we want to emit all the tables in */
  164511. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164512. {
  164513. #ifdef C_ARITH_CODING_SUPPORTED
  164514. char dc_in_use[NUM_ARITH_TBLS];
  164515. char ac_in_use[NUM_ARITH_TBLS];
  164516. int length, i;
  164517. jpeg_component_info *compptr;
  164518. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164519. dc_in_use[i] = ac_in_use[i] = 0;
  164520. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164521. compptr = cinfo->cur_comp_info[i];
  164522. dc_in_use[compptr->dc_tbl_no] = 1;
  164523. ac_in_use[compptr->ac_tbl_no] = 1;
  164524. }
  164525. length = 0;
  164526. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164527. length += dc_in_use[i] + ac_in_use[i];
  164528. emit_marker(cinfo, M_DAC);
  164529. emit_2bytes(cinfo, length*2 + 2);
  164530. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164531. if (dc_in_use[i]) {
  164532. emit_byte(cinfo, i);
  164533. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164534. }
  164535. if (ac_in_use[i]) {
  164536. emit_byte(cinfo, i + 0x10);
  164537. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164538. }
  164539. }
  164540. #endif /* C_ARITH_CODING_SUPPORTED */
  164541. }
  164542. LOCAL(void)
  164543. emit_dri (j_compress_ptr cinfo)
  164544. /* Emit a DRI marker */
  164545. {
  164546. emit_marker(cinfo, M_DRI);
  164547. emit_2bytes(cinfo, 4); /* fixed length */
  164548. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164549. }
  164550. LOCAL(void)
  164551. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164552. /* Emit a SOF marker */
  164553. {
  164554. int ci;
  164555. jpeg_component_info *compptr;
  164556. emit_marker(cinfo, code);
  164557. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164558. /* Make sure image isn't bigger than SOF field can handle */
  164559. if ((long) cinfo->image_height > 65535L ||
  164560. (long) cinfo->image_width > 65535L)
  164561. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164562. emit_byte(cinfo, cinfo->data_precision);
  164563. emit_2bytes(cinfo, (int) cinfo->image_height);
  164564. emit_2bytes(cinfo, (int) cinfo->image_width);
  164565. emit_byte(cinfo, cinfo->num_components);
  164566. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164567. ci++, compptr++) {
  164568. emit_byte(cinfo, compptr->component_id);
  164569. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164570. emit_byte(cinfo, compptr->quant_tbl_no);
  164571. }
  164572. }
  164573. LOCAL(void)
  164574. emit_sos (j_compress_ptr cinfo)
  164575. /* Emit a SOS marker */
  164576. {
  164577. int i, td, ta;
  164578. jpeg_component_info *compptr;
  164579. emit_marker(cinfo, M_SOS);
  164580. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164581. emit_byte(cinfo, cinfo->comps_in_scan);
  164582. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164583. compptr = cinfo->cur_comp_info[i];
  164584. emit_byte(cinfo, compptr->component_id);
  164585. td = compptr->dc_tbl_no;
  164586. ta = compptr->ac_tbl_no;
  164587. if (cinfo->progressive_mode) {
  164588. /* Progressive mode: only DC or only AC tables are used in one scan;
  164589. * furthermore, Huffman coding of DC refinement uses no table at all.
  164590. * We emit 0 for unused field(s); this is recommended by the P&M text
  164591. * but does not seem to be specified in the standard.
  164592. */
  164593. if (cinfo->Ss == 0) {
  164594. ta = 0; /* DC scan */
  164595. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164596. td = 0; /* no DC table either */
  164597. } else {
  164598. td = 0; /* AC scan */
  164599. }
  164600. }
  164601. emit_byte(cinfo, (td << 4) + ta);
  164602. }
  164603. emit_byte(cinfo, cinfo->Ss);
  164604. emit_byte(cinfo, cinfo->Se);
  164605. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164606. }
  164607. LOCAL(void)
  164608. emit_jfif_app0 (j_compress_ptr cinfo)
  164609. /* Emit a JFIF-compliant APP0 marker */
  164610. {
  164611. /*
  164612. * Length of APP0 block (2 bytes)
  164613. * Block ID (4 bytes - ASCII "JFIF")
  164614. * Zero byte (1 byte to terminate the ID string)
  164615. * Version Major, Minor (2 bytes - major first)
  164616. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164617. * Xdpu (2 bytes - dots per unit horizontal)
  164618. * Ydpu (2 bytes - dots per unit vertical)
  164619. * Thumbnail X size (1 byte)
  164620. * Thumbnail Y size (1 byte)
  164621. */
  164622. emit_marker(cinfo, M_APP0);
  164623. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164624. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164625. emit_byte(cinfo, 0x46);
  164626. emit_byte(cinfo, 0x49);
  164627. emit_byte(cinfo, 0x46);
  164628. emit_byte(cinfo, 0);
  164629. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164630. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164631. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164632. emit_2bytes(cinfo, (int) cinfo->X_density);
  164633. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164634. emit_byte(cinfo, 0); /* No thumbnail image */
  164635. emit_byte(cinfo, 0);
  164636. }
  164637. LOCAL(void)
  164638. emit_adobe_app14 (j_compress_ptr cinfo)
  164639. /* Emit an Adobe APP14 marker */
  164640. {
  164641. /*
  164642. * Length of APP14 block (2 bytes)
  164643. * Block ID (5 bytes - ASCII "Adobe")
  164644. * Version Number (2 bytes - currently 100)
  164645. * Flags0 (2 bytes - currently 0)
  164646. * Flags1 (2 bytes - currently 0)
  164647. * Color transform (1 byte)
  164648. *
  164649. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164650. * now in circulation seem to use Version = 100, so that's what we write.
  164651. *
  164652. * We write the color transform byte as 1 if the JPEG color space is
  164653. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164654. * whether the encoder performed a transformation, which is pretty useless.
  164655. */
  164656. emit_marker(cinfo, M_APP14);
  164657. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164658. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164659. emit_byte(cinfo, 0x64);
  164660. emit_byte(cinfo, 0x6F);
  164661. emit_byte(cinfo, 0x62);
  164662. emit_byte(cinfo, 0x65);
  164663. emit_2bytes(cinfo, 100); /* Version */
  164664. emit_2bytes(cinfo, 0); /* Flags0 */
  164665. emit_2bytes(cinfo, 0); /* Flags1 */
  164666. switch (cinfo->jpeg_color_space) {
  164667. case JCS_YCbCr:
  164668. emit_byte(cinfo, 1); /* Color transform = 1 */
  164669. break;
  164670. case JCS_YCCK:
  164671. emit_byte(cinfo, 2); /* Color transform = 2 */
  164672. break;
  164673. default:
  164674. emit_byte(cinfo, 0); /* Color transform = 0 */
  164675. break;
  164676. }
  164677. }
  164678. /*
  164679. * These routines allow writing an arbitrary marker with parameters.
  164680. * The only intended use is to emit COM or APPn markers after calling
  164681. * write_file_header and before calling write_frame_header.
  164682. * Other uses are not guaranteed to produce desirable results.
  164683. * Counting the parameter bytes properly is the caller's responsibility.
  164684. */
  164685. METHODDEF(void)
  164686. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164687. /* Emit an arbitrary marker header */
  164688. {
  164689. if (datalen > (unsigned int) 65533) /* safety check */
  164690. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164691. emit_marker(cinfo, (JPEG_MARKER) marker);
  164692. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164693. }
  164694. METHODDEF(void)
  164695. write_marker_byte (j_compress_ptr cinfo, int val)
  164696. /* Emit one byte of marker parameters following write_marker_header */
  164697. {
  164698. emit_byte(cinfo, val);
  164699. }
  164700. /*
  164701. * Write datastream header.
  164702. * This consists of an SOI and optional APPn markers.
  164703. * We recommend use of the JFIF marker, but not the Adobe marker,
  164704. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164705. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164706. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164707. * Note that an application can write additional header markers after
  164708. * jpeg_start_compress returns.
  164709. */
  164710. METHODDEF(void)
  164711. write_file_header (j_compress_ptr cinfo)
  164712. {
  164713. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164714. emit_marker(cinfo, M_SOI); /* first the SOI */
  164715. /* SOI is defined to reset restart interval to 0 */
  164716. marker->last_restart_interval = 0;
  164717. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164718. emit_jfif_app0(cinfo);
  164719. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164720. emit_adobe_app14(cinfo);
  164721. }
  164722. /*
  164723. * Write frame header.
  164724. * This consists of DQT and SOFn markers.
  164725. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164726. * This avoids compatibility problems with incorrect implementations that
  164727. * try to error-check the quant table numbers as soon as they see the SOF.
  164728. */
  164729. METHODDEF(void)
  164730. write_frame_header (j_compress_ptr cinfo)
  164731. {
  164732. int ci, prec;
  164733. boolean is_baseline;
  164734. jpeg_component_info *compptr;
  164735. /* Emit DQT for each quantization table.
  164736. * Note that emit_dqt() suppresses any duplicate tables.
  164737. */
  164738. prec = 0;
  164739. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164740. ci++, compptr++) {
  164741. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164742. }
  164743. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164744. /* Check for a non-baseline specification.
  164745. * Note we assume that Huffman table numbers won't be changed later.
  164746. */
  164747. if (cinfo->arith_code || cinfo->progressive_mode ||
  164748. cinfo->data_precision != 8) {
  164749. is_baseline = FALSE;
  164750. } else {
  164751. is_baseline = TRUE;
  164752. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164753. ci++, compptr++) {
  164754. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164755. is_baseline = FALSE;
  164756. }
  164757. if (prec && is_baseline) {
  164758. is_baseline = FALSE;
  164759. /* If it's baseline except for quantizer size, warn the user */
  164760. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164761. }
  164762. }
  164763. /* Emit the proper SOF marker */
  164764. if (cinfo->arith_code) {
  164765. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164766. } else {
  164767. if (cinfo->progressive_mode)
  164768. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164769. else if (is_baseline)
  164770. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164771. else
  164772. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164773. }
  164774. }
  164775. /*
  164776. * Write scan header.
  164777. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164778. * Compressed data will be written following the SOS.
  164779. */
  164780. METHODDEF(void)
  164781. write_scan_header (j_compress_ptr cinfo)
  164782. {
  164783. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164784. int i;
  164785. jpeg_component_info *compptr;
  164786. if (cinfo->arith_code) {
  164787. /* Emit arith conditioning info. We may have some duplication
  164788. * if the file has multiple scans, but it's so small it's hardly
  164789. * worth worrying about.
  164790. */
  164791. emit_dac(cinfo);
  164792. } else {
  164793. /* Emit Huffman tables.
  164794. * Note that emit_dht() suppresses any duplicate tables.
  164795. */
  164796. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164797. compptr = cinfo->cur_comp_info[i];
  164798. if (cinfo->progressive_mode) {
  164799. /* Progressive mode: only DC or only AC tables are used in one scan */
  164800. if (cinfo->Ss == 0) {
  164801. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164802. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164803. } else {
  164804. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164805. }
  164806. } else {
  164807. /* Sequential mode: need both DC and AC tables */
  164808. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164809. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164810. }
  164811. }
  164812. }
  164813. /* Emit DRI if required --- note that DRI value could change for each scan.
  164814. * We avoid wasting space with unnecessary DRIs, however.
  164815. */
  164816. if (cinfo->restart_interval != marker->last_restart_interval) {
  164817. emit_dri(cinfo);
  164818. marker->last_restart_interval = cinfo->restart_interval;
  164819. }
  164820. emit_sos(cinfo);
  164821. }
  164822. /*
  164823. * Write datastream trailer.
  164824. */
  164825. METHODDEF(void)
  164826. write_file_trailer (j_compress_ptr cinfo)
  164827. {
  164828. emit_marker(cinfo, M_EOI);
  164829. }
  164830. /*
  164831. * Write an abbreviated table-specification datastream.
  164832. * This consists of SOI, DQT and DHT tables, and EOI.
  164833. * Any table that is defined and not marked sent_table = TRUE will be
  164834. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164835. */
  164836. METHODDEF(void)
  164837. write_tables_only (j_compress_ptr cinfo)
  164838. {
  164839. int i;
  164840. emit_marker(cinfo, M_SOI);
  164841. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164842. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164843. (void) emit_dqt(cinfo, i);
  164844. }
  164845. if (! cinfo->arith_code) {
  164846. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164847. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164848. emit_dht(cinfo, i, FALSE);
  164849. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164850. emit_dht(cinfo, i, TRUE);
  164851. }
  164852. }
  164853. emit_marker(cinfo, M_EOI);
  164854. }
  164855. /*
  164856. * Initialize the marker writer module.
  164857. */
  164858. GLOBAL(void)
  164859. jinit_marker_writer (j_compress_ptr cinfo)
  164860. {
  164861. my_marker_ptr marker;
  164862. /* Create the subobject */
  164863. marker = (my_marker_ptr)
  164864. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164865. SIZEOF(my_marker_writer));
  164866. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164867. /* Initialize method pointers */
  164868. marker->pub.write_file_header = write_file_header;
  164869. marker->pub.write_frame_header = write_frame_header;
  164870. marker->pub.write_scan_header = write_scan_header;
  164871. marker->pub.write_file_trailer = write_file_trailer;
  164872. marker->pub.write_tables_only = write_tables_only;
  164873. marker->pub.write_marker_header = write_marker_header;
  164874. marker->pub.write_marker_byte = write_marker_byte;
  164875. /* Initialize private state */
  164876. marker->last_restart_interval = 0;
  164877. }
  164878. /*** End of inlined file: jcmarker.c ***/
  164879. /*** Start of inlined file: jcmaster.c ***/
  164880. #define JPEG_INTERNALS
  164881. /* Private state */
  164882. typedef enum {
  164883. main_pass, /* input data, also do first output step */
  164884. huff_opt_pass, /* Huffman code optimization pass */
  164885. output_pass /* data output pass */
  164886. } c_pass_type;
  164887. typedef struct {
  164888. struct jpeg_comp_master pub; /* public fields */
  164889. c_pass_type pass_type; /* the type of the current pass */
  164890. int pass_number; /* # of passes completed */
  164891. int total_passes; /* total # of passes needed */
  164892. int scan_number; /* current index in scan_info[] */
  164893. } my_comp_master;
  164894. typedef my_comp_master * my_master_ptr;
  164895. /*
  164896. * Support routines that do various essential calculations.
  164897. */
  164898. LOCAL(void)
  164899. initial_setup (j_compress_ptr cinfo)
  164900. /* Do computations that are needed before master selection phase */
  164901. {
  164902. int ci;
  164903. jpeg_component_info *compptr;
  164904. long samplesperrow;
  164905. JDIMENSION jd_samplesperrow;
  164906. /* Sanity check on image dimensions */
  164907. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164908. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164909. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164910. /* Make sure image isn't bigger than I can handle */
  164911. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164912. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164913. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164914. /* Width of an input scanline must be representable as JDIMENSION. */
  164915. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164916. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164917. if ((long) jd_samplesperrow != samplesperrow)
  164918. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164919. /* For now, precision must match compiled-in value... */
  164920. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164921. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164922. /* Check that number of components won't exceed internal array sizes */
  164923. if (cinfo->num_components > MAX_COMPONENTS)
  164924. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164925. MAX_COMPONENTS);
  164926. /* Compute maximum sampling factors; check factor validity */
  164927. cinfo->max_h_samp_factor = 1;
  164928. cinfo->max_v_samp_factor = 1;
  164929. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164930. ci++, compptr++) {
  164931. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164932. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164933. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164934. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164935. compptr->h_samp_factor);
  164936. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164937. compptr->v_samp_factor);
  164938. }
  164939. /* Compute dimensions of components */
  164940. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164941. ci++, compptr++) {
  164942. /* Fill in the correct component_index value; don't rely on application */
  164943. compptr->component_index = ci;
  164944. /* For compression, we never do DCT scaling. */
  164945. compptr->DCT_scaled_size = DCTSIZE;
  164946. /* Size in DCT blocks */
  164947. compptr->width_in_blocks = (JDIMENSION)
  164948. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164949. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164950. compptr->height_in_blocks = (JDIMENSION)
  164951. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164952. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164953. /* Size in samples */
  164954. compptr->downsampled_width = (JDIMENSION)
  164955. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164956. (long) cinfo->max_h_samp_factor);
  164957. compptr->downsampled_height = (JDIMENSION)
  164958. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164959. (long) cinfo->max_v_samp_factor);
  164960. /* Mark component needed (this flag isn't actually used for compression) */
  164961. compptr->component_needed = TRUE;
  164962. }
  164963. /* Compute number of fully interleaved MCU rows (number of times that
  164964. * main controller will call coefficient controller).
  164965. */
  164966. cinfo->total_iMCU_rows = (JDIMENSION)
  164967. jdiv_round_up((long) cinfo->image_height,
  164968. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164969. }
  164970. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164971. LOCAL(void)
  164972. validate_script (j_compress_ptr cinfo)
  164973. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164974. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164975. */
  164976. {
  164977. const jpeg_scan_info * scanptr;
  164978. int scanno, ncomps, ci, coefi, thisi;
  164979. int Ss, Se, Ah, Al;
  164980. boolean component_sent[MAX_COMPONENTS];
  164981. #ifdef C_PROGRESSIVE_SUPPORTED
  164982. int * last_bitpos_ptr;
  164983. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164984. /* -1 until that coefficient has been seen; then last Al for it */
  164985. #endif
  164986. if (cinfo->num_scans <= 0)
  164987. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164988. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164989. * for progressive JPEG, no scan can have this.
  164990. */
  164991. scanptr = cinfo->scan_info;
  164992. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164993. #ifdef C_PROGRESSIVE_SUPPORTED
  164994. cinfo->progressive_mode = TRUE;
  164995. last_bitpos_ptr = & last_bitpos[0][0];
  164996. for (ci = 0; ci < cinfo->num_components; ci++)
  164997. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164998. *last_bitpos_ptr++ = -1;
  164999. #else
  165000. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165001. #endif
  165002. } else {
  165003. cinfo->progressive_mode = FALSE;
  165004. for (ci = 0; ci < cinfo->num_components; ci++)
  165005. component_sent[ci] = FALSE;
  165006. }
  165007. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165008. /* Validate component indexes */
  165009. ncomps = scanptr->comps_in_scan;
  165010. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165011. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165012. for (ci = 0; ci < ncomps; ci++) {
  165013. thisi = scanptr->component_index[ci];
  165014. if (thisi < 0 || thisi >= cinfo->num_components)
  165015. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165016. /* Components must appear in SOF order within each scan */
  165017. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165018. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165019. }
  165020. /* Validate progression parameters */
  165021. Ss = scanptr->Ss;
  165022. Se = scanptr->Se;
  165023. Ah = scanptr->Ah;
  165024. Al = scanptr->Al;
  165025. if (cinfo->progressive_mode) {
  165026. #ifdef C_PROGRESSIVE_SUPPORTED
  165027. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165028. * seems wrong: the upper bound ought to depend on data precision.
  165029. * Perhaps they really meant 0..N+1 for N-bit precision.
  165030. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165031. * out-of-range reconstructed DC values during the first DC scan,
  165032. * which might cause problems for some decoders.
  165033. */
  165034. #if BITS_IN_JSAMPLE == 8
  165035. #define MAX_AH_AL 10
  165036. #else
  165037. #define MAX_AH_AL 13
  165038. #endif
  165039. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165040. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165041. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165042. if (Ss == 0) {
  165043. if (Se != 0) /* DC and AC together not OK */
  165044. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165045. } else {
  165046. if (ncomps != 1) /* AC scans must be for only one component */
  165047. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165048. }
  165049. for (ci = 0; ci < ncomps; ci++) {
  165050. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165051. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165052. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165053. for (coefi = Ss; coefi <= Se; coefi++) {
  165054. if (last_bitpos_ptr[coefi] < 0) {
  165055. /* first scan of this coefficient */
  165056. if (Ah != 0)
  165057. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165058. } else {
  165059. /* not first scan */
  165060. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165061. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165062. }
  165063. last_bitpos_ptr[coefi] = Al;
  165064. }
  165065. }
  165066. #endif
  165067. } else {
  165068. /* For sequential JPEG, all progression parameters must be these: */
  165069. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165070. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165071. /* Make sure components are not sent twice */
  165072. for (ci = 0; ci < ncomps; ci++) {
  165073. thisi = scanptr->component_index[ci];
  165074. if (component_sent[thisi])
  165075. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165076. component_sent[thisi] = TRUE;
  165077. }
  165078. }
  165079. }
  165080. /* Now verify that everything got sent. */
  165081. if (cinfo->progressive_mode) {
  165082. #ifdef C_PROGRESSIVE_SUPPORTED
  165083. /* For progressive mode, we only check that at least some DC data
  165084. * got sent for each component; the spec does not require that all bits
  165085. * of all coefficients be transmitted. Would it be wiser to enforce
  165086. * transmission of all coefficient bits??
  165087. */
  165088. for (ci = 0; ci < cinfo->num_components; ci++) {
  165089. if (last_bitpos[ci][0] < 0)
  165090. ERREXIT(cinfo, JERR_MISSING_DATA);
  165091. }
  165092. #endif
  165093. } else {
  165094. for (ci = 0; ci < cinfo->num_components; ci++) {
  165095. if (! component_sent[ci])
  165096. ERREXIT(cinfo, JERR_MISSING_DATA);
  165097. }
  165098. }
  165099. }
  165100. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165101. LOCAL(void)
  165102. select_scan_parameters (j_compress_ptr cinfo)
  165103. /* Set up the scan parameters for the current scan */
  165104. {
  165105. int ci;
  165106. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165107. if (cinfo->scan_info != NULL) {
  165108. /* Prepare for current scan --- the script is already validated */
  165109. my_master_ptr master = (my_master_ptr) cinfo->master;
  165110. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165111. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165112. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165113. cinfo->cur_comp_info[ci] =
  165114. &cinfo->comp_info[scanptr->component_index[ci]];
  165115. }
  165116. cinfo->Ss = scanptr->Ss;
  165117. cinfo->Se = scanptr->Se;
  165118. cinfo->Ah = scanptr->Ah;
  165119. cinfo->Al = scanptr->Al;
  165120. }
  165121. else
  165122. #endif
  165123. {
  165124. /* Prepare for single sequential-JPEG scan containing all components */
  165125. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165126. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165127. MAX_COMPS_IN_SCAN);
  165128. cinfo->comps_in_scan = cinfo->num_components;
  165129. for (ci = 0; ci < cinfo->num_components; ci++) {
  165130. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165131. }
  165132. cinfo->Ss = 0;
  165133. cinfo->Se = DCTSIZE2-1;
  165134. cinfo->Ah = 0;
  165135. cinfo->Al = 0;
  165136. }
  165137. }
  165138. LOCAL(void)
  165139. per_scan_setup (j_compress_ptr cinfo)
  165140. /* Do computations that are needed before processing a JPEG scan */
  165141. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165142. {
  165143. int ci, mcublks, tmp;
  165144. jpeg_component_info *compptr;
  165145. if (cinfo->comps_in_scan == 1) {
  165146. /* Noninterleaved (single-component) scan */
  165147. compptr = cinfo->cur_comp_info[0];
  165148. /* Overall image size in MCUs */
  165149. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165150. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165151. /* For noninterleaved scan, always one block per MCU */
  165152. compptr->MCU_width = 1;
  165153. compptr->MCU_height = 1;
  165154. compptr->MCU_blocks = 1;
  165155. compptr->MCU_sample_width = DCTSIZE;
  165156. compptr->last_col_width = 1;
  165157. /* For noninterleaved scans, it is convenient to define last_row_height
  165158. * as the number of block rows present in the last iMCU row.
  165159. */
  165160. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165161. if (tmp == 0) tmp = compptr->v_samp_factor;
  165162. compptr->last_row_height = tmp;
  165163. /* Prepare array describing MCU composition */
  165164. cinfo->blocks_in_MCU = 1;
  165165. cinfo->MCU_membership[0] = 0;
  165166. } else {
  165167. /* Interleaved (multi-component) scan */
  165168. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165169. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165170. MAX_COMPS_IN_SCAN);
  165171. /* Overall image size in MCUs */
  165172. cinfo->MCUs_per_row = (JDIMENSION)
  165173. jdiv_round_up((long) cinfo->image_width,
  165174. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165175. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165176. jdiv_round_up((long) cinfo->image_height,
  165177. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165178. cinfo->blocks_in_MCU = 0;
  165179. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165180. compptr = cinfo->cur_comp_info[ci];
  165181. /* Sampling factors give # of blocks of component in each MCU */
  165182. compptr->MCU_width = compptr->h_samp_factor;
  165183. compptr->MCU_height = compptr->v_samp_factor;
  165184. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165185. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165186. /* Figure number of non-dummy blocks in last MCU column & row */
  165187. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165188. if (tmp == 0) tmp = compptr->MCU_width;
  165189. compptr->last_col_width = tmp;
  165190. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165191. if (tmp == 0) tmp = compptr->MCU_height;
  165192. compptr->last_row_height = tmp;
  165193. /* Prepare array describing MCU composition */
  165194. mcublks = compptr->MCU_blocks;
  165195. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165196. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165197. while (mcublks-- > 0) {
  165198. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165199. }
  165200. }
  165201. }
  165202. /* Convert restart specified in rows to actual MCU count. */
  165203. /* Note that count must fit in 16 bits, so we provide limiting. */
  165204. if (cinfo->restart_in_rows > 0) {
  165205. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165206. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165207. }
  165208. }
  165209. /*
  165210. * Per-pass setup.
  165211. * This is called at the beginning of each pass. We determine which modules
  165212. * will be active during this pass and give them appropriate start_pass calls.
  165213. * We also set is_last_pass to indicate whether any more passes will be
  165214. * required.
  165215. */
  165216. METHODDEF(void)
  165217. prepare_for_pass (j_compress_ptr cinfo)
  165218. {
  165219. my_master_ptr master = (my_master_ptr) cinfo->master;
  165220. switch (master->pass_type) {
  165221. case main_pass:
  165222. /* Initial pass: will collect input data, and do either Huffman
  165223. * optimization or data output for the first scan.
  165224. */
  165225. select_scan_parameters(cinfo);
  165226. per_scan_setup(cinfo);
  165227. if (! cinfo->raw_data_in) {
  165228. (*cinfo->cconvert->start_pass) (cinfo);
  165229. (*cinfo->downsample->start_pass) (cinfo);
  165230. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165231. }
  165232. (*cinfo->fdct->start_pass) (cinfo);
  165233. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165234. (*cinfo->coef->start_pass) (cinfo,
  165235. (master->total_passes > 1 ?
  165236. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165237. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165238. if (cinfo->optimize_coding) {
  165239. /* No immediate data output; postpone writing frame/scan headers */
  165240. master->pub.call_pass_startup = FALSE;
  165241. } else {
  165242. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165243. master->pub.call_pass_startup = TRUE;
  165244. }
  165245. break;
  165246. #ifdef ENTROPY_OPT_SUPPORTED
  165247. case huff_opt_pass:
  165248. /* Do Huffman optimization for a scan after the first one. */
  165249. select_scan_parameters(cinfo);
  165250. per_scan_setup(cinfo);
  165251. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165252. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165253. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165254. master->pub.call_pass_startup = FALSE;
  165255. break;
  165256. }
  165257. /* Special case: Huffman DC refinement scans need no Huffman table
  165258. * and therefore we can skip the optimization pass for them.
  165259. */
  165260. master->pass_type = output_pass;
  165261. master->pass_number++;
  165262. /*FALLTHROUGH*/
  165263. #endif
  165264. case output_pass:
  165265. /* Do a data-output pass. */
  165266. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165267. if (! cinfo->optimize_coding) {
  165268. select_scan_parameters(cinfo);
  165269. per_scan_setup(cinfo);
  165270. }
  165271. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165272. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165273. /* We emit frame/scan headers now */
  165274. if (master->scan_number == 0)
  165275. (*cinfo->marker->write_frame_header) (cinfo);
  165276. (*cinfo->marker->write_scan_header) (cinfo);
  165277. master->pub.call_pass_startup = FALSE;
  165278. break;
  165279. default:
  165280. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165281. }
  165282. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165283. /* Set up progress monitor's pass info if present */
  165284. if (cinfo->progress != NULL) {
  165285. cinfo->progress->completed_passes = master->pass_number;
  165286. cinfo->progress->total_passes = master->total_passes;
  165287. }
  165288. }
  165289. /*
  165290. * Special start-of-pass hook.
  165291. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165292. * In single-pass processing, we need this hook because we don't want to
  165293. * write frame/scan headers during jpeg_start_compress; we want to let the
  165294. * application write COM markers etc. between jpeg_start_compress and the
  165295. * jpeg_write_scanlines loop.
  165296. * In multi-pass processing, this routine is not used.
  165297. */
  165298. METHODDEF(void)
  165299. pass_startup (j_compress_ptr cinfo)
  165300. {
  165301. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165302. (*cinfo->marker->write_frame_header) (cinfo);
  165303. (*cinfo->marker->write_scan_header) (cinfo);
  165304. }
  165305. /*
  165306. * Finish up at end of pass.
  165307. */
  165308. METHODDEF(void)
  165309. finish_pass_master (j_compress_ptr cinfo)
  165310. {
  165311. my_master_ptr master = (my_master_ptr) cinfo->master;
  165312. /* The entropy coder always needs an end-of-pass call,
  165313. * either to analyze statistics or to flush its output buffer.
  165314. */
  165315. (*cinfo->entropy->finish_pass) (cinfo);
  165316. /* Update state for next pass */
  165317. switch (master->pass_type) {
  165318. case main_pass:
  165319. /* next pass is either output of scan 0 (after optimization)
  165320. * or output of scan 1 (if no optimization).
  165321. */
  165322. master->pass_type = output_pass;
  165323. if (! cinfo->optimize_coding)
  165324. master->scan_number++;
  165325. break;
  165326. case huff_opt_pass:
  165327. /* next pass is always output of current scan */
  165328. master->pass_type = output_pass;
  165329. break;
  165330. case output_pass:
  165331. /* next pass is either optimization or output of next scan */
  165332. if (cinfo->optimize_coding)
  165333. master->pass_type = huff_opt_pass;
  165334. master->scan_number++;
  165335. break;
  165336. }
  165337. master->pass_number++;
  165338. }
  165339. /*
  165340. * Initialize master compression control.
  165341. */
  165342. GLOBAL(void)
  165343. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165344. {
  165345. my_master_ptr master;
  165346. master = (my_master_ptr)
  165347. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165348. SIZEOF(my_comp_master));
  165349. cinfo->master = (struct jpeg_comp_master *) master;
  165350. master->pub.prepare_for_pass = prepare_for_pass;
  165351. master->pub.pass_startup = pass_startup;
  165352. master->pub.finish_pass = finish_pass_master;
  165353. master->pub.is_last_pass = FALSE;
  165354. /* Validate parameters, determine derived values */
  165355. initial_setup(cinfo);
  165356. if (cinfo->scan_info != NULL) {
  165357. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165358. validate_script(cinfo);
  165359. #else
  165360. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165361. #endif
  165362. } else {
  165363. cinfo->progressive_mode = FALSE;
  165364. cinfo->num_scans = 1;
  165365. }
  165366. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165367. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165368. /* Initialize my private state */
  165369. if (transcode_only) {
  165370. /* no main pass in transcoding */
  165371. if (cinfo->optimize_coding)
  165372. master->pass_type = huff_opt_pass;
  165373. else
  165374. master->pass_type = output_pass;
  165375. } else {
  165376. /* for normal compression, first pass is always this type: */
  165377. master->pass_type = main_pass;
  165378. }
  165379. master->scan_number = 0;
  165380. master->pass_number = 0;
  165381. if (cinfo->optimize_coding)
  165382. master->total_passes = cinfo->num_scans * 2;
  165383. else
  165384. master->total_passes = cinfo->num_scans;
  165385. }
  165386. /*** End of inlined file: jcmaster.c ***/
  165387. /*** Start of inlined file: jcomapi.c ***/
  165388. #define JPEG_INTERNALS
  165389. /*
  165390. * Abort processing of a JPEG compression or decompression operation,
  165391. * but don't destroy the object itself.
  165392. *
  165393. * For this, we merely clean up all the nonpermanent memory pools.
  165394. * Note that temp files (virtual arrays) are not allowed to belong to
  165395. * the permanent pool, so we will be able to close all temp files here.
  165396. * Closing a data source or destination, if necessary, is the application's
  165397. * responsibility.
  165398. */
  165399. GLOBAL(void)
  165400. jpeg_abort (j_common_ptr cinfo)
  165401. {
  165402. int pool;
  165403. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165404. if (cinfo->mem == NULL)
  165405. return;
  165406. /* Releasing pools in reverse order might help avoid fragmentation
  165407. * with some (brain-damaged) malloc libraries.
  165408. */
  165409. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165410. (*cinfo->mem->free_pool) (cinfo, pool);
  165411. }
  165412. /* Reset overall state for possible reuse of object */
  165413. if (cinfo->is_decompressor) {
  165414. cinfo->global_state = DSTATE_START;
  165415. /* Try to keep application from accessing now-deleted marker list.
  165416. * A bit kludgy to do it here, but this is the most central place.
  165417. */
  165418. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165419. } else {
  165420. cinfo->global_state = CSTATE_START;
  165421. }
  165422. }
  165423. /*
  165424. * Destruction of a JPEG object.
  165425. *
  165426. * Everything gets deallocated except the master jpeg_compress_struct itself
  165427. * and the error manager struct. Both of these are supplied by the application
  165428. * and must be freed, if necessary, by the application. (Often they are on
  165429. * the stack and so don't need to be freed anyway.)
  165430. * Closing a data source or destination, if necessary, is the application's
  165431. * responsibility.
  165432. */
  165433. GLOBAL(void)
  165434. jpeg_destroy (j_common_ptr cinfo)
  165435. {
  165436. /* We need only tell the memory manager to release everything. */
  165437. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165438. if (cinfo->mem != NULL)
  165439. (*cinfo->mem->self_destruct) (cinfo);
  165440. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165441. cinfo->global_state = 0; /* mark it destroyed */
  165442. }
  165443. /*
  165444. * Convenience routines for allocating quantization and Huffman tables.
  165445. * (Would jutils.c be a more reasonable place to put these?)
  165446. */
  165447. GLOBAL(JQUANT_TBL *)
  165448. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165449. {
  165450. JQUANT_TBL *tbl;
  165451. tbl = (JQUANT_TBL *)
  165452. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165453. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165454. return tbl;
  165455. }
  165456. GLOBAL(JHUFF_TBL *)
  165457. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165458. {
  165459. JHUFF_TBL *tbl;
  165460. tbl = (JHUFF_TBL *)
  165461. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165462. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165463. return tbl;
  165464. }
  165465. /*** End of inlined file: jcomapi.c ***/
  165466. /*** Start of inlined file: jcparam.c ***/
  165467. #define JPEG_INTERNALS
  165468. /*
  165469. * Quantization table setup routines
  165470. */
  165471. GLOBAL(void)
  165472. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165473. const unsigned int *basic_table,
  165474. int scale_factor, boolean force_baseline)
  165475. /* Define a quantization table equal to the basic_table times
  165476. * a scale factor (given as a percentage).
  165477. * If force_baseline is TRUE, the computed quantization table entries
  165478. * are limited to 1..255 for JPEG baseline compatibility.
  165479. */
  165480. {
  165481. JQUANT_TBL ** qtblptr;
  165482. int i;
  165483. long temp;
  165484. /* Safety check to ensure start_compress not called yet. */
  165485. if (cinfo->global_state != CSTATE_START)
  165486. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165487. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165488. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165489. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165490. if (*qtblptr == NULL)
  165491. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165492. for (i = 0; i < DCTSIZE2; i++) {
  165493. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165494. /* limit the values to the valid range */
  165495. if (temp <= 0L) temp = 1L;
  165496. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165497. if (force_baseline && temp > 255L)
  165498. temp = 255L; /* limit to baseline range if requested */
  165499. (*qtblptr)->quantval[i] = (UINT16) temp;
  165500. }
  165501. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165502. (*qtblptr)->sent_table = FALSE;
  165503. }
  165504. GLOBAL(void)
  165505. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165506. boolean force_baseline)
  165507. /* Set or change the 'quality' (quantization) setting, using default tables
  165508. * and a straight percentage-scaling quality scale. In most cases it's better
  165509. * to use jpeg_set_quality (below); this entry point is provided for
  165510. * applications that insist on a linear percentage scaling.
  165511. */
  165512. {
  165513. /* These are the sample quantization tables given in JPEG spec section K.1.
  165514. * The spec says that the values given produce "good" quality, and
  165515. * when divided by 2, "very good" quality.
  165516. */
  165517. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165518. 16, 11, 10, 16, 24, 40, 51, 61,
  165519. 12, 12, 14, 19, 26, 58, 60, 55,
  165520. 14, 13, 16, 24, 40, 57, 69, 56,
  165521. 14, 17, 22, 29, 51, 87, 80, 62,
  165522. 18, 22, 37, 56, 68, 109, 103, 77,
  165523. 24, 35, 55, 64, 81, 104, 113, 92,
  165524. 49, 64, 78, 87, 103, 121, 120, 101,
  165525. 72, 92, 95, 98, 112, 100, 103, 99
  165526. };
  165527. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165528. 17, 18, 24, 47, 99, 99, 99, 99,
  165529. 18, 21, 26, 66, 99, 99, 99, 99,
  165530. 24, 26, 56, 99, 99, 99, 99, 99,
  165531. 47, 66, 99, 99, 99, 99, 99, 99,
  165532. 99, 99, 99, 99, 99, 99, 99, 99,
  165533. 99, 99, 99, 99, 99, 99, 99, 99,
  165534. 99, 99, 99, 99, 99, 99, 99, 99,
  165535. 99, 99, 99, 99, 99, 99, 99, 99
  165536. };
  165537. /* Set up two quantization tables using the specified scaling */
  165538. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165539. scale_factor, force_baseline);
  165540. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165541. scale_factor, force_baseline);
  165542. }
  165543. GLOBAL(int)
  165544. jpeg_quality_scaling (int quality)
  165545. /* Convert a user-specified quality rating to a percentage scaling factor
  165546. * for an underlying quantization table, using our recommended scaling curve.
  165547. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165548. */
  165549. {
  165550. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165551. if (quality <= 0) quality = 1;
  165552. if (quality > 100) quality = 100;
  165553. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165554. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165555. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165556. * to make all the table entries 1 (hence, minimum quantization loss).
  165557. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165558. */
  165559. if (quality < 50)
  165560. quality = 5000 / quality;
  165561. else
  165562. quality = 200 - quality*2;
  165563. return quality;
  165564. }
  165565. GLOBAL(void)
  165566. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165567. /* Set or change the 'quality' (quantization) setting, using default tables.
  165568. * This is the standard quality-adjusting entry point for typical user
  165569. * interfaces; only those who want detailed control over quantization tables
  165570. * would use the preceding three routines directly.
  165571. */
  165572. {
  165573. /* Convert user 0-100 rating to percentage scaling */
  165574. quality = jpeg_quality_scaling(quality);
  165575. /* Set up standard quality tables */
  165576. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165577. }
  165578. /*
  165579. * Huffman table setup routines
  165580. */
  165581. LOCAL(void)
  165582. add_huff_table (j_compress_ptr cinfo,
  165583. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165584. /* Define a Huffman table */
  165585. {
  165586. int nsymbols, len;
  165587. if (*htblptr == NULL)
  165588. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165589. /* Copy the number-of-symbols-of-each-code-length counts */
  165590. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165591. /* Validate the counts. We do this here mainly so we can copy the right
  165592. * number of symbols from the val[] array, without risking marching off
  165593. * the end of memory. jchuff.c will do a more thorough test later.
  165594. */
  165595. nsymbols = 0;
  165596. for (len = 1; len <= 16; len++)
  165597. nsymbols += bits[len];
  165598. if (nsymbols < 1 || nsymbols > 256)
  165599. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165600. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165601. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165602. (*htblptr)->sent_table = FALSE;
  165603. }
  165604. LOCAL(void)
  165605. std_huff_tables (j_compress_ptr cinfo)
  165606. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165607. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165608. {
  165609. static const UINT8 bits_dc_luminance[17] =
  165610. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165611. static const UINT8 val_dc_luminance[] =
  165612. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165613. static const UINT8 bits_dc_chrominance[17] =
  165614. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165615. static const UINT8 val_dc_chrominance[] =
  165616. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165617. static const UINT8 bits_ac_luminance[17] =
  165618. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165619. static const UINT8 val_ac_luminance[] =
  165620. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165621. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165622. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165623. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165624. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165625. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165626. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165627. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165628. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165629. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165630. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165631. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165632. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165633. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165634. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165635. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165636. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165637. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165638. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165639. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165640. 0xf9, 0xfa };
  165641. static const UINT8 bits_ac_chrominance[17] =
  165642. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165643. static const UINT8 val_ac_chrominance[] =
  165644. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165645. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165646. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165647. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165648. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165649. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165650. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165651. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165652. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165653. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165654. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165655. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165656. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165657. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165658. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165659. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165660. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165661. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165662. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165663. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165664. 0xf9, 0xfa };
  165665. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165666. bits_dc_luminance, val_dc_luminance);
  165667. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165668. bits_ac_luminance, val_ac_luminance);
  165669. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165670. bits_dc_chrominance, val_dc_chrominance);
  165671. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165672. bits_ac_chrominance, val_ac_chrominance);
  165673. }
  165674. /*
  165675. * Default parameter setup for compression.
  165676. *
  165677. * Applications that don't choose to use this routine must do their
  165678. * own setup of all these parameters. Alternately, you can call this
  165679. * to establish defaults and then alter parameters selectively. This
  165680. * is the recommended approach since, if we add any new parameters,
  165681. * your code will still work (they'll be set to reasonable defaults).
  165682. */
  165683. GLOBAL(void)
  165684. jpeg_set_defaults (j_compress_ptr cinfo)
  165685. {
  165686. int i;
  165687. /* Safety check to ensure start_compress not called yet. */
  165688. if (cinfo->global_state != CSTATE_START)
  165689. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165690. /* Allocate comp_info array large enough for maximum component count.
  165691. * Array is made permanent in case application wants to compress
  165692. * multiple images at same param settings.
  165693. */
  165694. if (cinfo->comp_info == NULL)
  165695. cinfo->comp_info = (jpeg_component_info *)
  165696. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165697. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165698. /* Initialize everything not dependent on the color space */
  165699. cinfo->data_precision = BITS_IN_JSAMPLE;
  165700. /* Set up two quantization tables using default quality of 75 */
  165701. jpeg_set_quality(cinfo, 75, TRUE);
  165702. /* Set up two Huffman tables */
  165703. std_huff_tables(cinfo);
  165704. /* Initialize default arithmetic coding conditioning */
  165705. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165706. cinfo->arith_dc_L[i] = 0;
  165707. cinfo->arith_dc_U[i] = 1;
  165708. cinfo->arith_ac_K[i] = 5;
  165709. }
  165710. /* Default is no multiple-scan output */
  165711. cinfo->scan_info = NULL;
  165712. cinfo->num_scans = 0;
  165713. /* Expect normal source image, not raw downsampled data */
  165714. cinfo->raw_data_in = FALSE;
  165715. /* Use Huffman coding, not arithmetic coding, by default */
  165716. cinfo->arith_code = FALSE;
  165717. /* By default, don't do extra passes to optimize entropy coding */
  165718. cinfo->optimize_coding = FALSE;
  165719. /* The standard Huffman tables are only valid for 8-bit data precision.
  165720. * If the precision is higher, force optimization on so that usable
  165721. * tables will be computed. This test can be removed if default tables
  165722. * are supplied that are valid for the desired precision.
  165723. */
  165724. if (cinfo->data_precision > 8)
  165725. cinfo->optimize_coding = TRUE;
  165726. /* By default, use the simpler non-cosited sampling alignment */
  165727. cinfo->CCIR601_sampling = FALSE;
  165728. /* No input smoothing */
  165729. cinfo->smoothing_factor = 0;
  165730. /* DCT algorithm preference */
  165731. cinfo->dct_method = JDCT_DEFAULT;
  165732. /* No restart markers */
  165733. cinfo->restart_interval = 0;
  165734. cinfo->restart_in_rows = 0;
  165735. /* Fill in default JFIF marker parameters. Note that whether the marker
  165736. * will actually be written is determined by jpeg_set_colorspace.
  165737. *
  165738. * By default, the library emits JFIF version code 1.01.
  165739. * An application that wants to emit JFIF 1.02 extension markers should set
  165740. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165741. * to 1.02, but there may still be some decoders in use that will complain
  165742. * about that; saying 1.01 should minimize compatibility problems.
  165743. */
  165744. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165745. cinfo->JFIF_minor_version = 1;
  165746. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165747. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165748. cinfo->Y_density = 1;
  165749. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165750. jpeg_default_colorspace(cinfo);
  165751. }
  165752. /*
  165753. * Select an appropriate JPEG colorspace for in_color_space.
  165754. */
  165755. GLOBAL(void)
  165756. jpeg_default_colorspace (j_compress_ptr cinfo)
  165757. {
  165758. switch (cinfo->in_color_space) {
  165759. case JCS_GRAYSCALE:
  165760. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165761. break;
  165762. case JCS_RGB:
  165763. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165764. break;
  165765. case JCS_YCbCr:
  165766. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165767. break;
  165768. case JCS_CMYK:
  165769. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165770. break;
  165771. case JCS_YCCK:
  165772. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165773. break;
  165774. case JCS_UNKNOWN:
  165775. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165776. break;
  165777. default:
  165778. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165779. }
  165780. }
  165781. /*
  165782. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165783. */
  165784. GLOBAL(void)
  165785. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165786. {
  165787. jpeg_component_info * compptr;
  165788. int ci;
  165789. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165790. (compptr = &cinfo->comp_info[index], \
  165791. compptr->component_id = (id), \
  165792. compptr->h_samp_factor = (hsamp), \
  165793. compptr->v_samp_factor = (vsamp), \
  165794. compptr->quant_tbl_no = (quant), \
  165795. compptr->dc_tbl_no = (dctbl), \
  165796. compptr->ac_tbl_no = (actbl) )
  165797. /* Safety check to ensure start_compress not called yet. */
  165798. if (cinfo->global_state != CSTATE_START)
  165799. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165800. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165801. * tables 1 for chrominance components.
  165802. */
  165803. cinfo->jpeg_color_space = colorspace;
  165804. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165805. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165806. switch (colorspace) {
  165807. case JCS_GRAYSCALE:
  165808. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165809. cinfo->num_components = 1;
  165810. /* JFIF specifies component ID 1 */
  165811. SET_COMP(0, 1, 1,1, 0, 0,0);
  165812. break;
  165813. case JCS_RGB:
  165814. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165815. cinfo->num_components = 3;
  165816. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165817. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165818. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165819. break;
  165820. case JCS_YCbCr:
  165821. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165822. cinfo->num_components = 3;
  165823. /* JFIF specifies component IDs 1,2,3 */
  165824. /* We default to 2x2 subsamples of chrominance */
  165825. SET_COMP(0, 1, 2,2, 0, 0,0);
  165826. SET_COMP(1, 2, 1,1, 1, 1,1);
  165827. SET_COMP(2, 3, 1,1, 1, 1,1);
  165828. break;
  165829. case JCS_CMYK:
  165830. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165831. cinfo->num_components = 4;
  165832. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165833. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165834. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165835. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165836. break;
  165837. case JCS_YCCK:
  165838. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165839. cinfo->num_components = 4;
  165840. SET_COMP(0, 1, 2,2, 0, 0,0);
  165841. SET_COMP(1, 2, 1,1, 1, 1,1);
  165842. SET_COMP(2, 3, 1,1, 1, 1,1);
  165843. SET_COMP(3, 4, 2,2, 0, 0,0);
  165844. break;
  165845. case JCS_UNKNOWN:
  165846. cinfo->num_components = cinfo->input_components;
  165847. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165848. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165849. MAX_COMPONENTS);
  165850. for (ci = 0; ci < cinfo->num_components; ci++) {
  165851. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165852. }
  165853. break;
  165854. default:
  165855. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165856. }
  165857. }
  165858. #ifdef C_PROGRESSIVE_SUPPORTED
  165859. LOCAL(jpeg_scan_info *)
  165860. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165861. int Ss, int Se, int Ah, int Al)
  165862. /* Support routine: generate one scan for specified component */
  165863. {
  165864. scanptr->comps_in_scan = 1;
  165865. scanptr->component_index[0] = ci;
  165866. scanptr->Ss = Ss;
  165867. scanptr->Se = Se;
  165868. scanptr->Ah = Ah;
  165869. scanptr->Al = Al;
  165870. scanptr++;
  165871. return scanptr;
  165872. }
  165873. LOCAL(jpeg_scan_info *)
  165874. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165875. int Ss, int Se, int Ah, int Al)
  165876. /* Support routine: generate one scan for each component */
  165877. {
  165878. int ci;
  165879. for (ci = 0; ci < ncomps; ci++) {
  165880. scanptr->comps_in_scan = 1;
  165881. scanptr->component_index[0] = ci;
  165882. scanptr->Ss = Ss;
  165883. scanptr->Se = Se;
  165884. scanptr->Ah = Ah;
  165885. scanptr->Al = Al;
  165886. scanptr++;
  165887. }
  165888. return scanptr;
  165889. }
  165890. LOCAL(jpeg_scan_info *)
  165891. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165892. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165893. {
  165894. int ci;
  165895. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165896. /* Single interleaved DC scan */
  165897. scanptr->comps_in_scan = ncomps;
  165898. for (ci = 0; ci < ncomps; ci++)
  165899. scanptr->component_index[ci] = ci;
  165900. scanptr->Ss = scanptr->Se = 0;
  165901. scanptr->Ah = Ah;
  165902. scanptr->Al = Al;
  165903. scanptr++;
  165904. } else {
  165905. /* Noninterleaved DC scan for each component */
  165906. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165907. }
  165908. return scanptr;
  165909. }
  165910. /*
  165911. * Create a recommended progressive-JPEG script.
  165912. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165913. */
  165914. GLOBAL(void)
  165915. jpeg_simple_progression (j_compress_ptr cinfo)
  165916. {
  165917. int ncomps = cinfo->num_components;
  165918. int nscans;
  165919. jpeg_scan_info * scanptr;
  165920. /* Safety check to ensure start_compress not called yet. */
  165921. if (cinfo->global_state != CSTATE_START)
  165922. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165923. /* Figure space needed for script. Calculation must match code below! */
  165924. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165925. /* Custom script for YCbCr color images. */
  165926. nscans = 10;
  165927. } else {
  165928. /* All-purpose script for other color spaces. */
  165929. if (ncomps > MAX_COMPS_IN_SCAN)
  165930. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165931. else
  165932. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165933. }
  165934. /* Allocate space for script.
  165935. * We need to put it in the permanent pool in case the application performs
  165936. * multiple compressions without changing the settings. To avoid a memory
  165937. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165938. * object, we try to re-use previously allocated space, and we allocate
  165939. * enough space to handle YCbCr even if initially asked for grayscale.
  165940. */
  165941. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165942. cinfo->script_space_size = MAX(nscans, 10);
  165943. cinfo->script_space = (jpeg_scan_info *)
  165944. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165945. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165946. }
  165947. scanptr = cinfo->script_space;
  165948. cinfo->scan_info = scanptr;
  165949. cinfo->num_scans = nscans;
  165950. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165951. /* Custom script for YCbCr color images. */
  165952. /* Initial DC scan */
  165953. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165954. /* Initial AC scan: get some luma data out in a hurry */
  165955. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165956. /* Chroma data is too small to be worth expending many scans on */
  165957. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165958. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165959. /* Complete spectral selection for luma AC */
  165960. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165961. /* Refine next bit of luma AC */
  165962. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165963. /* Finish DC successive approximation */
  165964. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165965. /* Finish AC successive approximation */
  165966. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165967. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165968. /* Luma bottom bit comes last since it's usually largest scan */
  165969. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165970. } else {
  165971. /* All-purpose script for other color spaces. */
  165972. /* Successive approximation first pass */
  165973. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165974. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165975. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165976. /* Successive approximation second pass */
  165977. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165978. /* Successive approximation final pass */
  165979. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165980. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165981. }
  165982. }
  165983. #endif /* C_PROGRESSIVE_SUPPORTED */
  165984. /*** End of inlined file: jcparam.c ***/
  165985. /*** Start of inlined file: jcphuff.c ***/
  165986. #define JPEG_INTERNALS
  165987. #ifdef C_PROGRESSIVE_SUPPORTED
  165988. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165989. typedef struct {
  165990. struct jpeg_entropy_encoder pub; /* public fields */
  165991. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165992. boolean gather_statistics;
  165993. /* Bit-level coding status.
  165994. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165995. */
  165996. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165997. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165998. INT32 put_buffer; /* current bit-accumulation buffer */
  165999. int put_bits; /* # of bits now in it */
  166000. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166001. /* Coding status for DC components */
  166002. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166003. /* Coding status for AC components */
  166004. int ac_tbl_no; /* the table number of the single component */
  166005. unsigned int EOBRUN; /* run length of EOBs */
  166006. unsigned int BE; /* # of buffered correction bits before MCU */
  166007. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166008. /* packing correction bits tightly would save some space but cost time... */
  166009. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166010. int next_restart_num; /* next restart number to write (0-7) */
  166011. /* Pointers to derived tables (these workspaces have image lifespan).
  166012. * Since any one scan codes only DC or only AC, we only need one set
  166013. * of tables, not one for DC and one for AC.
  166014. */
  166015. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166016. /* Statistics tables for optimization; again, one set is enough */
  166017. long * count_ptrs[NUM_HUFF_TBLS];
  166018. } phuff_entropy_encoder;
  166019. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166020. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166021. * buffer can hold. Larger sizes may slightly improve compression, but
  166022. * 1000 is already well into the realm of overkill.
  166023. * The minimum safe size is 64 bits.
  166024. */
  166025. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166026. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166027. * We assume that int right shift is unsigned if INT32 right shift is,
  166028. * which should be safe.
  166029. */
  166030. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166031. #define ISHIFT_TEMPS int ishift_temp;
  166032. #define IRIGHT_SHIFT(x,shft) \
  166033. ((ishift_temp = (x)) < 0 ? \
  166034. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166035. (ishift_temp >> (shft)))
  166036. #else
  166037. #define ISHIFT_TEMPS
  166038. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166039. #endif
  166040. /* Forward declarations */
  166041. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166042. JBLOCKROW *MCU_data));
  166043. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166044. JBLOCKROW *MCU_data));
  166045. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166046. JBLOCKROW *MCU_data));
  166047. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166048. JBLOCKROW *MCU_data));
  166049. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166050. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166051. /*
  166052. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166053. */
  166054. METHODDEF(void)
  166055. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166056. {
  166057. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166058. boolean is_DC_band;
  166059. int ci, tbl;
  166060. jpeg_component_info * compptr;
  166061. entropy->cinfo = cinfo;
  166062. entropy->gather_statistics = gather_statistics;
  166063. is_DC_band = (cinfo->Ss == 0);
  166064. /* We assume jcmaster.c already validated the scan parameters. */
  166065. /* Select execution routines */
  166066. if (cinfo->Ah == 0) {
  166067. if (is_DC_band)
  166068. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166069. else
  166070. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166071. } else {
  166072. if (is_DC_band)
  166073. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166074. else {
  166075. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166076. /* AC refinement needs a correction bit buffer */
  166077. if (entropy->bit_buffer == NULL)
  166078. entropy->bit_buffer = (char *)
  166079. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166080. MAX_CORR_BITS * SIZEOF(char));
  166081. }
  166082. }
  166083. if (gather_statistics)
  166084. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166085. else
  166086. entropy->pub.finish_pass = finish_pass_phuff;
  166087. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166088. * for AC coefficients.
  166089. */
  166090. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166091. compptr = cinfo->cur_comp_info[ci];
  166092. /* Initialize DC predictions to 0 */
  166093. entropy->last_dc_val[ci] = 0;
  166094. /* Get table index */
  166095. if (is_DC_band) {
  166096. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166097. continue;
  166098. tbl = compptr->dc_tbl_no;
  166099. } else {
  166100. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166101. }
  166102. if (gather_statistics) {
  166103. /* Check for invalid table index */
  166104. /* (make_c_derived_tbl does this in the other path) */
  166105. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166106. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166107. /* Allocate and zero the statistics tables */
  166108. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166109. if (entropy->count_ptrs[tbl] == NULL)
  166110. entropy->count_ptrs[tbl] = (long *)
  166111. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166112. 257 * SIZEOF(long));
  166113. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166114. } else {
  166115. /* Compute derived values for Huffman table */
  166116. /* We may do this more than once for a table, but it's not expensive */
  166117. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166118. & entropy->derived_tbls[tbl]);
  166119. }
  166120. }
  166121. /* Initialize AC stuff */
  166122. entropy->EOBRUN = 0;
  166123. entropy->BE = 0;
  166124. /* Initialize bit buffer to empty */
  166125. entropy->put_buffer = 0;
  166126. entropy->put_bits = 0;
  166127. /* Initialize restart stuff */
  166128. entropy->restarts_to_go = cinfo->restart_interval;
  166129. entropy->next_restart_num = 0;
  166130. }
  166131. /* Outputting bytes to the file.
  166132. * NB: these must be called only when actually outputting,
  166133. * that is, entropy->gather_statistics == FALSE.
  166134. */
  166135. /* Emit a byte */
  166136. #define emit_byte(entropy,val) \
  166137. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166138. if (--(entropy)->free_in_buffer == 0) \
  166139. dump_buffer_p(entropy); }
  166140. LOCAL(void)
  166141. dump_buffer_p (phuff_entropy_ptr entropy)
  166142. /* Empty the output buffer; we do not support suspension in this module. */
  166143. {
  166144. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166145. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166146. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166147. /* After a successful buffer dump, must reset buffer pointers */
  166148. entropy->next_output_byte = dest->next_output_byte;
  166149. entropy->free_in_buffer = dest->free_in_buffer;
  166150. }
  166151. /* Outputting bits to the file */
  166152. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166153. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166154. * in one call, and we never retain more than 7 bits in put_buffer
  166155. * between calls, so 24 bits are sufficient.
  166156. */
  166157. INLINE
  166158. LOCAL(void)
  166159. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166160. /* Emit some bits, unless we are in gather mode */
  166161. {
  166162. /* This routine is heavily used, so it's worth coding tightly. */
  166163. register INT32 put_buffer = (INT32) code;
  166164. register int put_bits = entropy->put_bits;
  166165. /* if size is 0, caller used an invalid Huffman table entry */
  166166. if (size == 0)
  166167. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166168. if (entropy->gather_statistics)
  166169. return; /* do nothing if we're only getting stats */
  166170. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166171. put_bits += size; /* new number of bits in buffer */
  166172. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166173. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166174. while (put_bits >= 8) {
  166175. int c = (int) ((put_buffer >> 16) & 0xFF);
  166176. emit_byte(entropy, c);
  166177. if (c == 0xFF) { /* need to stuff a zero byte? */
  166178. emit_byte(entropy, 0);
  166179. }
  166180. put_buffer <<= 8;
  166181. put_bits -= 8;
  166182. }
  166183. entropy->put_buffer = put_buffer; /* update variables */
  166184. entropy->put_bits = put_bits;
  166185. }
  166186. LOCAL(void)
  166187. flush_bits_p (phuff_entropy_ptr entropy)
  166188. {
  166189. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166190. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166191. entropy->put_bits = 0;
  166192. }
  166193. /*
  166194. * Emit (or just count) a Huffman symbol.
  166195. */
  166196. INLINE
  166197. LOCAL(void)
  166198. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166199. {
  166200. if (entropy->gather_statistics)
  166201. entropy->count_ptrs[tbl_no][symbol]++;
  166202. else {
  166203. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166204. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166205. }
  166206. }
  166207. /*
  166208. * Emit bits from a correction bit buffer.
  166209. */
  166210. LOCAL(void)
  166211. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166212. unsigned int nbits)
  166213. {
  166214. if (entropy->gather_statistics)
  166215. return; /* no real work */
  166216. while (nbits > 0) {
  166217. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166218. bufstart++;
  166219. nbits--;
  166220. }
  166221. }
  166222. /*
  166223. * Emit any pending EOBRUN symbol.
  166224. */
  166225. LOCAL(void)
  166226. emit_eobrun (phuff_entropy_ptr entropy)
  166227. {
  166228. register int temp, nbits;
  166229. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166230. temp = entropy->EOBRUN;
  166231. nbits = 0;
  166232. while ((temp >>= 1))
  166233. nbits++;
  166234. /* safety check: shouldn't happen given limited correction-bit buffer */
  166235. if (nbits > 14)
  166236. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166237. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166238. if (nbits)
  166239. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166240. entropy->EOBRUN = 0;
  166241. /* Emit any buffered correction bits */
  166242. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166243. entropy->BE = 0;
  166244. }
  166245. }
  166246. /*
  166247. * Emit a restart marker & resynchronize predictions.
  166248. */
  166249. LOCAL(void)
  166250. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166251. {
  166252. int ci;
  166253. emit_eobrun(entropy);
  166254. if (! entropy->gather_statistics) {
  166255. flush_bits_p(entropy);
  166256. emit_byte(entropy, 0xFF);
  166257. emit_byte(entropy, JPEG_RST0 + restart_num);
  166258. }
  166259. if (entropy->cinfo->Ss == 0) {
  166260. /* Re-initialize DC predictions to 0 */
  166261. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166262. entropy->last_dc_val[ci] = 0;
  166263. } else {
  166264. /* Re-initialize all AC-related fields to 0 */
  166265. entropy->EOBRUN = 0;
  166266. entropy->BE = 0;
  166267. }
  166268. }
  166269. /*
  166270. * MCU encoding for DC initial scan (either spectral selection,
  166271. * or first pass of successive approximation).
  166272. */
  166273. METHODDEF(boolean)
  166274. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166275. {
  166276. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166277. register int temp, temp2;
  166278. register int nbits;
  166279. int blkn, ci;
  166280. int Al = cinfo->Al;
  166281. JBLOCKROW block;
  166282. jpeg_component_info * compptr;
  166283. ISHIFT_TEMPS
  166284. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166285. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166286. /* Emit restart marker if needed */
  166287. if (cinfo->restart_interval)
  166288. if (entropy->restarts_to_go == 0)
  166289. emit_restart_p(entropy, entropy->next_restart_num);
  166290. /* Encode the MCU data blocks */
  166291. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166292. block = MCU_data[blkn];
  166293. ci = cinfo->MCU_membership[blkn];
  166294. compptr = cinfo->cur_comp_info[ci];
  166295. /* Compute the DC value after the required point transform by Al.
  166296. * This is simply an arithmetic right shift.
  166297. */
  166298. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166299. /* DC differences are figured on the point-transformed values. */
  166300. temp = temp2 - entropy->last_dc_val[ci];
  166301. entropy->last_dc_val[ci] = temp2;
  166302. /* Encode the DC coefficient difference per section G.1.2.1 */
  166303. temp2 = temp;
  166304. if (temp < 0) {
  166305. temp = -temp; /* temp is abs value of input */
  166306. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166307. /* This code assumes we are on a two's complement machine */
  166308. temp2--;
  166309. }
  166310. /* Find the number of bits needed for the magnitude of the coefficient */
  166311. nbits = 0;
  166312. while (temp) {
  166313. nbits++;
  166314. temp >>= 1;
  166315. }
  166316. /* Check for out-of-range coefficient values.
  166317. * Since we're encoding a difference, the range limit is twice as much.
  166318. */
  166319. if (nbits > MAX_COEF_BITS+1)
  166320. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166321. /* Count/emit the Huffman-coded symbol for the number of bits */
  166322. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166323. /* Emit that number of bits of the value, if positive, */
  166324. /* or the complement of its magnitude, if negative. */
  166325. if (nbits) /* emit_bits rejects calls with size 0 */
  166326. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166327. }
  166328. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166329. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166330. /* Update restart-interval state too */
  166331. if (cinfo->restart_interval) {
  166332. if (entropy->restarts_to_go == 0) {
  166333. entropy->restarts_to_go = cinfo->restart_interval;
  166334. entropy->next_restart_num++;
  166335. entropy->next_restart_num &= 7;
  166336. }
  166337. entropy->restarts_to_go--;
  166338. }
  166339. return TRUE;
  166340. }
  166341. /*
  166342. * MCU encoding for AC initial scan (either spectral selection,
  166343. * or first pass of successive approximation).
  166344. */
  166345. METHODDEF(boolean)
  166346. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166347. {
  166348. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166349. register int temp, temp2;
  166350. register int nbits;
  166351. register int r, k;
  166352. int Se = cinfo->Se;
  166353. int Al = cinfo->Al;
  166354. JBLOCKROW block;
  166355. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166356. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166357. /* Emit restart marker if needed */
  166358. if (cinfo->restart_interval)
  166359. if (entropy->restarts_to_go == 0)
  166360. emit_restart_p(entropy, entropy->next_restart_num);
  166361. /* Encode the MCU data block */
  166362. block = MCU_data[0];
  166363. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166364. r = 0; /* r = run length of zeros */
  166365. for (k = cinfo->Ss; k <= Se; k++) {
  166366. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166367. r++;
  166368. continue;
  166369. }
  166370. /* We must apply the point transform by Al. For AC coefficients this
  166371. * is an integer division with rounding towards 0. To do this portably
  166372. * in C, we shift after obtaining the absolute value; so the code is
  166373. * interwoven with finding the abs value (temp) and output bits (temp2).
  166374. */
  166375. if (temp < 0) {
  166376. temp = -temp; /* temp is abs value of input */
  166377. temp >>= Al; /* apply the point transform */
  166378. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166379. temp2 = ~temp;
  166380. } else {
  166381. temp >>= Al; /* apply the point transform */
  166382. temp2 = temp;
  166383. }
  166384. /* Watch out for case that nonzero coef is zero after point transform */
  166385. if (temp == 0) {
  166386. r++;
  166387. continue;
  166388. }
  166389. /* Emit any pending EOBRUN */
  166390. if (entropy->EOBRUN > 0)
  166391. emit_eobrun(entropy);
  166392. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166393. while (r > 15) {
  166394. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166395. r -= 16;
  166396. }
  166397. /* Find the number of bits needed for the magnitude of the coefficient */
  166398. nbits = 1; /* there must be at least one 1 bit */
  166399. while ((temp >>= 1))
  166400. nbits++;
  166401. /* Check for out-of-range coefficient values */
  166402. if (nbits > MAX_COEF_BITS)
  166403. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166404. /* Count/emit Huffman symbol for run length / number of bits */
  166405. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166406. /* Emit that number of bits of the value, if positive, */
  166407. /* or the complement of its magnitude, if negative. */
  166408. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166409. r = 0; /* reset zero run length */
  166410. }
  166411. if (r > 0) { /* If there are trailing zeroes, */
  166412. entropy->EOBRUN++; /* count an EOB */
  166413. if (entropy->EOBRUN == 0x7FFF)
  166414. emit_eobrun(entropy); /* force it out to avoid overflow */
  166415. }
  166416. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166417. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166418. /* Update restart-interval state too */
  166419. if (cinfo->restart_interval) {
  166420. if (entropy->restarts_to_go == 0) {
  166421. entropy->restarts_to_go = cinfo->restart_interval;
  166422. entropy->next_restart_num++;
  166423. entropy->next_restart_num &= 7;
  166424. }
  166425. entropy->restarts_to_go--;
  166426. }
  166427. return TRUE;
  166428. }
  166429. /*
  166430. * MCU encoding for DC successive approximation refinement scan.
  166431. * Note: we assume such scans can be multi-component, although the spec
  166432. * is not very clear on the point.
  166433. */
  166434. METHODDEF(boolean)
  166435. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166436. {
  166437. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166438. register int temp;
  166439. int blkn;
  166440. int Al = cinfo->Al;
  166441. JBLOCKROW block;
  166442. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166443. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166444. /* Emit restart marker if needed */
  166445. if (cinfo->restart_interval)
  166446. if (entropy->restarts_to_go == 0)
  166447. emit_restart_p(entropy, entropy->next_restart_num);
  166448. /* Encode the MCU data blocks */
  166449. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166450. block = MCU_data[blkn];
  166451. /* We simply emit the Al'th bit of the DC coefficient value. */
  166452. temp = (*block)[0];
  166453. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166454. }
  166455. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166456. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166457. /* Update restart-interval state too */
  166458. if (cinfo->restart_interval) {
  166459. if (entropy->restarts_to_go == 0) {
  166460. entropy->restarts_to_go = cinfo->restart_interval;
  166461. entropy->next_restart_num++;
  166462. entropy->next_restart_num &= 7;
  166463. }
  166464. entropy->restarts_to_go--;
  166465. }
  166466. return TRUE;
  166467. }
  166468. /*
  166469. * MCU encoding for AC successive approximation refinement scan.
  166470. */
  166471. METHODDEF(boolean)
  166472. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166473. {
  166474. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166475. register int temp;
  166476. register int r, k;
  166477. int EOB;
  166478. char *BR_buffer;
  166479. unsigned int BR;
  166480. int Se = cinfo->Se;
  166481. int Al = cinfo->Al;
  166482. JBLOCKROW block;
  166483. int absvalues[DCTSIZE2];
  166484. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166485. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166486. /* Emit restart marker if needed */
  166487. if (cinfo->restart_interval)
  166488. if (entropy->restarts_to_go == 0)
  166489. emit_restart_p(entropy, entropy->next_restart_num);
  166490. /* Encode the MCU data block */
  166491. block = MCU_data[0];
  166492. /* It is convenient to make a pre-pass to determine the transformed
  166493. * coefficients' absolute values and the EOB position.
  166494. */
  166495. EOB = 0;
  166496. for (k = cinfo->Ss; k <= Se; k++) {
  166497. temp = (*block)[jpeg_natural_order[k]];
  166498. /* We must apply the point transform by Al. For AC coefficients this
  166499. * is an integer division with rounding towards 0. To do this portably
  166500. * in C, we shift after obtaining the absolute value.
  166501. */
  166502. if (temp < 0)
  166503. temp = -temp; /* temp is abs value of input */
  166504. temp >>= Al; /* apply the point transform */
  166505. absvalues[k] = temp; /* save abs value for main pass */
  166506. if (temp == 1)
  166507. EOB = k; /* EOB = index of last newly-nonzero coef */
  166508. }
  166509. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166510. r = 0; /* r = run length of zeros */
  166511. BR = 0; /* BR = count of buffered bits added now */
  166512. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166513. for (k = cinfo->Ss; k <= Se; k++) {
  166514. if ((temp = absvalues[k]) == 0) {
  166515. r++;
  166516. continue;
  166517. }
  166518. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166519. while (r > 15 && k <= EOB) {
  166520. /* emit any pending EOBRUN and the BE correction bits */
  166521. emit_eobrun(entropy);
  166522. /* Emit ZRL */
  166523. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166524. r -= 16;
  166525. /* Emit buffered correction bits that must be associated with ZRL */
  166526. emit_buffered_bits(entropy, BR_buffer, BR);
  166527. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166528. BR = 0;
  166529. }
  166530. /* If the coef was previously nonzero, it only needs a correction bit.
  166531. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166532. * that we also need to test r > 15. But if r > 15, we can only get here
  166533. * if k > EOB, which implies that this coefficient is not 1.
  166534. */
  166535. if (temp > 1) {
  166536. /* The correction bit is the next bit of the absolute value. */
  166537. BR_buffer[BR++] = (char) (temp & 1);
  166538. continue;
  166539. }
  166540. /* Emit any pending EOBRUN and the BE correction bits */
  166541. emit_eobrun(entropy);
  166542. /* Count/emit Huffman symbol for run length / number of bits */
  166543. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166544. /* Emit output bit for newly-nonzero coef */
  166545. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166546. emit_bits_p(entropy, (unsigned int) temp, 1);
  166547. /* Emit buffered correction bits that must be associated with this code */
  166548. emit_buffered_bits(entropy, BR_buffer, BR);
  166549. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166550. BR = 0;
  166551. r = 0; /* reset zero run length */
  166552. }
  166553. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166554. entropy->EOBRUN++; /* count an EOB */
  166555. entropy->BE += BR; /* concat my correction bits to older ones */
  166556. /* We force out the EOB if we risk either:
  166557. * 1. overflow of the EOB counter;
  166558. * 2. overflow of the correction bit buffer during the next MCU.
  166559. */
  166560. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166561. emit_eobrun(entropy);
  166562. }
  166563. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166564. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166565. /* Update restart-interval state too */
  166566. if (cinfo->restart_interval) {
  166567. if (entropy->restarts_to_go == 0) {
  166568. entropy->restarts_to_go = cinfo->restart_interval;
  166569. entropy->next_restart_num++;
  166570. entropy->next_restart_num &= 7;
  166571. }
  166572. entropy->restarts_to_go--;
  166573. }
  166574. return TRUE;
  166575. }
  166576. /*
  166577. * Finish up at the end of a Huffman-compressed progressive scan.
  166578. */
  166579. METHODDEF(void)
  166580. finish_pass_phuff (j_compress_ptr cinfo)
  166581. {
  166582. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166583. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166584. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166585. /* Flush out any buffered data */
  166586. emit_eobrun(entropy);
  166587. flush_bits_p(entropy);
  166588. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166589. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166590. }
  166591. /*
  166592. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166593. */
  166594. METHODDEF(void)
  166595. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166596. {
  166597. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166598. boolean is_DC_band;
  166599. int ci, tbl;
  166600. jpeg_component_info * compptr;
  166601. JHUFF_TBL **htblptr;
  166602. boolean did[NUM_HUFF_TBLS];
  166603. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166604. emit_eobrun(entropy);
  166605. is_DC_band = (cinfo->Ss == 0);
  166606. /* It's important not to apply jpeg_gen_optimal_table more than once
  166607. * per table, because it clobbers the input frequency counts!
  166608. */
  166609. MEMZERO(did, SIZEOF(did));
  166610. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166611. compptr = cinfo->cur_comp_info[ci];
  166612. if (is_DC_band) {
  166613. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166614. continue;
  166615. tbl = compptr->dc_tbl_no;
  166616. } else {
  166617. tbl = compptr->ac_tbl_no;
  166618. }
  166619. if (! did[tbl]) {
  166620. if (is_DC_band)
  166621. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166622. else
  166623. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166624. if (*htblptr == NULL)
  166625. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166626. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166627. did[tbl] = TRUE;
  166628. }
  166629. }
  166630. }
  166631. /*
  166632. * Module initialization routine for progressive Huffman entropy encoding.
  166633. */
  166634. GLOBAL(void)
  166635. jinit_phuff_encoder (j_compress_ptr cinfo)
  166636. {
  166637. phuff_entropy_ptr entropy;
  166638. int i;
  166639. entropy = (phuff_entropy_ptr)
  166640. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166641. SIZEOF(phuff_entropy_encoder));
  166642. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166643. entropy->pub.start_pass = start_pass_phuff;
  166644. /* Mark tables unallocated */
  166645. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166646. entropy->derived_tbls[i] = NULL;
  166647. entropy->count_ptrs[i] = NULL;
  166648. }
  166649. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166650. }
  166651. #endif /* C_PROGRESSIVE_SUPPORTED */
  166652. /*** End of inlined file: jcphuff.c ***/
  166653. /*** Start of inlined file: jcprepct.c ***/
  166654. #define JPEG_INTERNALS
  166655. /* At present, jcsample.c can request context rows only for smoothing.
  166656. * In the future, we might also need context rows for CCIR601 sampling
  166657. * or other more-complex downsampling procedures. The code to support
  166658. * context rows should be compiled only if needed.
  166659. */
  166660. #ifdef INPUT_SMOOTHING_SUPPORTED
  166661. #define CONTEXT_ROWS_SUPPORTED
  166662. #endif
  166663. /*
  166664. * For the simple (no-context-row) case, we just need to buffer one
  166665. * row group's worth of pixels for the downsampling step. At the bottom of
  166666. * the image, we pad to a full row group by replicating the last pixel row.
  166667. * The downsampler's last output row is then replicated if needed to pad
  166668. * out to a full iMCU row.
  166669. *
  166670. * When providing context rows, we must buffer three row groups' worth of
  166671. * pixels. Three row groups are physically allocated, but the row pointer
  166672. * arrays are made five row groups high, with the extra pointers above and
  166673. * below "wrapping around" to point to the last and first real row groups.
  166674. * This allows the downsampler to access the proper context rows.
  166675. * At the top and bottom of the image, we create dummy context rows by
  166676. * copying the first or last real pixel row. This copying could be avoided
  166677. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166678. * trouble on the compression side.
  166679. */
  166680. /* Private buffer controller object */
  166681. typedef struct {
  166682. struct jpeg_c_prep_controller pub; /* public fields */
  166683. /* Downsampling input buffer. This buffer holds color-converted data
  166684. * until we have enough to do a downsample step.
  166685. */
  166686. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166687. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166688. int next_buf_row; /* index of next row to store in color_buf */
  166689. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166690. int this_row_group; /* starting row index of group to process */
  166691. int next_buf_stop; /* downsample when we reach this index */
  166692. #endif
  166693. } my_prep_controller;
  166694. typedef my_prep_controller * my_prep_ptr;
  166695. /*
  166696. * Initialize for a processing pass.
  166697. */
  166698. METHODDEF(void)
  166699. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166700. {
  166701. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166702. if (pass_mode != JBUF_PASS_THRU)
  166703. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166704. /* Initialize total-height counter for detecting bottom of image */
  166705. prep->rows_to_go = cinfo->image_height;
  166706. /* Mark the conversion buffer empty */
  166707. prep->next_buf_row = 0;
  166708. #ifdef CONTEXT_ROWS_SUPPORTED
  166709. /* Preset additional state variables for context mode.
  166710. * These aren't used in non-context mode, so we needn't test which mode.
  166711. */
  166712. prep->this_row_group = 0;
  166713. /* Set next_buf_stop to stop after two row groups have been read in. */
  166714. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166715. #endif
  166716. }
  166717. /*
  166718. * Expand an image vertically from height input_rows to height output_rows,
  166719. * by duplicating the bottom row.
  166720. */
  166721. LOCAL(void)
  166722. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166723. int input_rows, int output_rows)
  166724. {
  166725. register int row;
  166726. for (row = input_rows; row < output_rows; row++) {
  166727. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166728. 1, num_cols);
  166729. }
  166730. }
  166731. /*
  166732. * Process some data in the simple no-context case.
  166733. *
  166734. * Preprocessor output data is counted in "row groups". A row group
  166735. * is defined to be v_samp_factor sample rows of each component.
  166736. * Downsampling will produce this much data from each max_v_samp_factor
  166737. * input rows.
  166738. */
  166739. METHODDEF(void)
  166740. pre_process_data (j_compress_ptr cinfo,
  166741. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166742. JDIMENSION in_rows_avail,
  166743. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166744. JDIMENSION out_row_groups_avail)
  166745. {
  166746. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166747. int numrows, ci;
  166748. JDIMENSION inrows;
  166749. jpeg_component_info * compptr;
  166750. while (*in_row_ctr < in_rows_avail &&
  166751. *out_row_group_ctr < out_row_groups_avail) {
  166752. /* Do color conversion to fill the conversion buffer. */
  166753. inrows = in_rows_avail - *in_row_ctr;
  166754. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166755. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166756. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166757. prep->color_buf,
  166758. (JDIMENSION) prep->next_buf_row,
  166759. numrows);
  166760. *in_row_ctr += numrows;
  166761. prep->next_buf_row += numrows;
  166762. prep->rows_to_go -= numrows;
  166763. /* If at bottom of image, pad to fill the conversion buffer. */
  166764. if (prep->rows_to_go == 0 &&
  166765. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166766. for (ci = 0; ci < cinfo->num_components; ci++) {
  166767. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166768. prep->next_buf_row, cinfo->max_v_samp_factor);
  166769. }
  166770. prep->next_buf_row = cinfo->max_v_samp_factor;
  166771. }
  166772. /* If we've filled the conversion buffer, empty it. */
  166773. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166774. (*cinfo->downsample->downsample) (cinfo,
  166775. prep->color_buf, (JDIMENSION) 0,
  166776. output_buf, *out_row_group_ctr);
  166777. prep->next_buf_row = 0;
  166778. (*out_row_group_ctr)++;
  166779. }
  166780. /* If at bottom of image, pad the output to a full iMCU height.
  166781. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166782. */
  166783. if (prep->rows_to_go == 0 &&
  166784. *out_row_group_ctr < out_row_groups_avail) {
  166785. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166786. ci++, compptr++) {
  166787. expand_bottom_edge(output_buf[ci],
  166788. compptr->width_in_blocks * DCTSIZE,
  166789. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166790. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166791. }
  166792. *out_row_group_ctr = out_row_groups_avail;
  166793. break; /* can exit outer loop without test */
  166794. }
  166795. }
  166796. }
  166797. #ifdef CONTEXT_ROWS_SUPPORTED
  166798. /*
  166799. * Process some data in the context case.
  166800. */
  166801. METHODDEF(void)
  166802. pre_process_context (j_compress_ptr cinfo,
  166803. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166804. JDIMENSION in_rows_avail,
  166805. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166806. JDIMENSION out_row_groups_avail)
  166807. {
  166808. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166809. int numrows, ci;
  166810. int buf_height = cinfo->max_v_samp_factor * 3;
  166811. JDIMENSION inrows;
  166812. while (*out_row_group_ctr < out_row_groups_avail) {
  166813. if (*in_row_ctr < in_rows_avail) {
  166814. /* Do color conversion to fill the conversion buffer. */
  166815. inrows = in_rows_avail - *in_row_ctr;
  166816. numrows = prep->next_buf_stop - prep->next_buf_row;
  166817. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166818. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166819. prep->color_buf,
  166820. (JDIMENSION) prep->next_buf_row,
  166821. numrows);
  166822. /* Pad at top of image, if first time through */
  166823. if (prep->rows_to_go == cinfo->image_height) {
  166824. for (ci = 0; ci < cinfo->num_components; ci++) {
  166825. int row;
  166826. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166827. jcopy_sample_rows(prep->color_buf[ci], 0,
  166828. prep->color_buf[ci], -row,
  166829. 1, cinfo->image_width);
  166830. }
  166831. }
  166832. }
  166833. *in_row_ctr += numrows;
  166834. prep->next_buf_row += numrows;
  166835. prep->rows_to_go -= numrows;
  166836. } else {
  166837. /* Return for more data, unless we are at the bottom of the image. */
  166838. if (prep->rows_to_go != 0)
  166839. break;
  166840. /* When at bottom of image, pad to fill the conversion buffer. */
  166841. if (prep->next_buf_row < prep->next_buf_stop) {
  166842. for (ci = 0; ci < cinfo->num_components; ci++) {
  166843. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166844. prep->next_buf_row, prep->next_buf_stop);
  166845. }
  166846. prep->next_buf_row = prep->next_buf_stop;
  166847. }
  166848. }
  166849. /* If we've gotten enough data, downsample a row group. */
  166850. if (prep->next_buf_row == prep->next_buf_stop) {
  166851. (*cinfo->downsample->downsample) (cinfo,
  166852. prep->color_buf,
  166853. (JDIMENSION) prep->this_row_group,
  166854. output_buf, *out_row_group_ctr);
  166855. (*out_row_group_ctr)++;
  166856. /* Advance pointers with wraparound as necessary. */
  166857. prep->this_row_group += cinfo->max_v_samp_factor;
  166858. if (prep->this_row_group >= buf_height)
  166859. prep->this_row_group = 0;
  166860. if (prep->next_buf_row >= buf_height)
  166861. prep->next_buf_row = 0;
  166862. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166863. }
  166864. }
  166865. }
  166866. /*
  166867. * Create the wrapped-around downsampling input buffer needed for context mode.
  166868. */
  166869. LOCAL(void)
  166870. create_context_buffer (j_compress_ptr cinfo)
  166871. {
  166872. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166873. int rgroup_height = cinfo->max_v_samp_factor;
  166874. int ci, i;
  166875. jpeg_component_info * compptr;
  166876. JSAMPARRAY true_buffer, fake_buffer;
  166877. /* Grab enough space for fake row pointers for all the components;
  166878. * we need five row groups' worth of pointers for each component.
  166879. */
  166880. fake_buffer = (JSAMPARRAY)
  166881. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166882. (cinfo->num_components * 5 * rgroup_height) *
  166883. SIZEOF(JSAMPROW));
  166884. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166885. ci++, compptr++) {
  166886. /* Allocate the actual buffer space (3 row groups) for this component.
  166887. * We make the buffer wide enough to allow the downsampler to edge-expand
  166888. * horizontally within the buffer, if it so chooses.
  166889. */
  166890. true_buffer = (*cinfo->mem->alloc_sarray)
  166891. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166892. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166893. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166894. (JDIMENSION) (3 * rgroup_height));
  166895. /* Copy true buffer row pointers into the middle of the fake row array */
  166896. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166897. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166898. /* Fill in the above and below wraparound pointers */
  166899. for (i = 0; i < rgroup_height; i++) {
  166900. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166901. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166902. }
  166903. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166904. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166905. }
  166906. }
  166907. #endif /* CONTEXT_ROWS_SUPPORTED */
  166908. /*
  166909. * Initialize preprocessing controller.
  166910. */
  166911. GLOBAL(void)
  166912. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166913. {
  166914. my_prep_ptr prep;
  166915. int ci;
  166916. jpeg_component_info * compptr;
  166917. if (need_full_buffer) /* safety check */
  166918. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166919. prep = (my_prep_ptr)
  166920. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166921. SIZEOF(my_prep_controller));
  166922. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166923. prep->pub.start_pass = start_pass_prep;
  166924. /* Allocate the color conversion buffer.
  166925. * We make the buffer wide enough to allow the downsampler to edge-expand
  166926. * horizontally within the buffer, if it so chooses.
  166927. */
  166928. if (cinfo->downsample->need_context_rows) {
  166929. /* Set up to provide context rows */
  166930. #ifdef CONTEXT_ROWS_SUPPORTED
  166931. prep->pub.pre_process_data = pre_process_context;
  166932. create_context_buffer(cinfo);
  166933. #else
  166934. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166935. #endif
  166936. } else {
  166937. /* No context, just make it tall enough for one row group */
  166938. prep->pub.pre_process_data = pre_process_data;
  166939. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166940. ci++, compptr++) {
  166941. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166942. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166943. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166944. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166945. (JDIMENSION) cinfo->max_v_samp_factor);
  166946. }
  166947. }
  166948. }
  166949. /*** End of inlined file: jcprepct.c ***/
  166950. /*** Start of inlined file: jcsample.c ***/
  166951. #define JPEG_INTERNALS
  166952. /* Pointer to routine to downsample a single component */
  166953. typedef JMETHOD(void, downsample1_ptr,
  166954. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166955. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166956. /* Private subobject */
  166957. typedef struct {
  166958. struct jpeg_downsampler pub; /* public fields */
  166959. /* Downsampling method pointers, one per component */
  166960. downsample1_ptr methods[MAX_COMPONENTS];
  166961. } my_downsampler;
  166962. typedef my_downsampler * my_downsample_ptr;
  166963. /*
  166964. * Initialize for a downsampling pass.
  166965. */
  166966. METHODDEF(void)
  166967. start_pass_downsample (j_compress_ptr)
  166968. {
  166969. /* no work for now */
  166970. }
  166971. /*
  166972. * Expand a component horizontally from width input_cols to width output_cols,
  166973. * by duplicating the rightmost samples.
  166974. */
  166975. LOCAL(void)
  166976. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166977. JDIMENSION input_cols, JDIMENSION output_cols)
  166978. {
  166979. register JSAMPROW ptr;
  166980. register JSAMPLE pixval;
  166981. register int count;
  166982. int row;
  166983. int numcols = (int) (output_cols - input_cols);
  166984. if (numcols > 0) {
  166985. for (row = 0; row < num_rows; row++) {
  166986. ptr = image_data[row] + input_cols;
  166987. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166988. for (count = numcols; count > 0; count--)
  166989. *ptr++ = pixval;
  166990. }
  166991. }
  166992. }
  166993. /*
  166994. * Do downsampling for a whole row group (all components).
  166995. *
  166996. * In this version we simply downsample each component independently.
  166997. */
  166998. METHODDEF(void)
  166999. sep_downsample (j_compress_ptr cinfo,
  167000. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167001. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167002. {
  167003. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167004. int ci;
  167005. jpeg_component_info * compptr;
  167006. JSAMPARRAY in_ptr, out_ptr;
  167007. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167008. ci++, compptr++) {
  167009. in_ptr = input_buf[ci] + in_row_index;
  167010. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167011. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167012. }
  167013. }
  167014. /*
  167015. * Downsample pixel values of a single component.
  167016. * One row group is processed per call.
  167017. * This version handles arbitrary integral sampling ratios, without smoothing.
  167018. * Note that this version is not actually used for customary sampling ratios.
  167019. */
  167020. METHODDEF(void)
  167021. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167022. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167023. {
  167024. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167025. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167026. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167027. JSAMPROW inptr, outptr;
  167028. INT32 outvalue;
  167029. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167030. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167031. numpix = h_expand * v_expand;
  167032. numpix2 = numpix/2;
  167033. /* Expand input data enough to let all the output samples be generated
  167034. * by the standard loop. Special-casing padded output would be more
  167035. * efficient.
  167036. */
  167037. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167038. cinfo->image_width, output_cols * h_expand);
  167039. inrow = 0;
  167040. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167041. outptr = output_data[outrow];
  167042. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167043. outcol++, outcol_h += h_expand) {
  167044. outvalue = 0;
  167045. for (v = 0; v < v_expand; v++) {
  167046. inptr = input_data[inrow+v] + outcol_h;
  167047. for (h = 0; h < h_expand; h++) {
  167048. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167049. }
  167050. }
  167051. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167052. }
  167053. inrow += v_expand;
  167054. }
  167055. }
  167056. /*
  167057. * Downsample pixel values of a single component.
  167058. * This version handles the special case of a full-size component,
  167059. * without smoothing.
  167060. */
  167061. METHODDEF(void)
  167062. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167063. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167064. {
  167065. /* Copy the data */
  167066. jcopy_sample_rows(input_data, 0, output_data, 0,
  167067. cinfo->max_v_samp_factor, cinfo->image_width);
  167068. /* Edge-expand */
  167069. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167070. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167071. }
  167072. /*
  167073. * Downsample pixel values of a single component.
  167074. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167075. * without smoothing.
  167076. *
  167077. * A note about the "bias" calculations: when rounding fractional values to
  167078. * integer, we do not want to always round 0.5 up to the next integer.
  167079. * If we did that, we'd introduce a noticeable bias towards larger values.
  167080. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167081. * alternate pixel locations (a simple ordered dither pattern).
  167082. */
  167083. METHODDEF(void)
  167084. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167085. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167086. {
  167087. int outrow;
  167088. JDIMENSION outcol;
  167089. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167090. register JSAMPROW inptr, outptr;
  167091. register int bias;
  167092. /* Expand input data enough to let all the output samples be generated
  167093. * by the standard loop. Special-casing padded output would be more
  167094. * efficient.
  167095. */
  167096. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167097. cinfo->image_width, output_cols * 2);
  167098. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167099. outptr = output_data[outrow];
  167100. inptr = input_data[outrow];
  167101. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167102. for (outcol = 0; outcol < output_cols; outcol++) {
  167103. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167104. + bias) >> 1);
  167105. bias ^= 1; /* 0=>1, 1=>0 */
  167106. inptr += 2;
  167107. }
  167108. }
  167109. }
  167110. /*
  167111. * Downsample pixel values of a single component.
  167112. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167113. * without smoothing.
  167114. */
  167115. METHODDEF(void)
  167116. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167117. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167118. {
  167119. int inrow, outrow;
  167120. JDIMENSION outcol;
  167121. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167122. register JSAMPROW inptr0, inptr1, outptr;
  167123. register int bias;
  167124. /* Expand input data enough to let all the output samples be generated
  167125. * by the standard loop. Special-casing padded output would be more
  167126. * efficient.
  167127. */
  167128. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167129. cinfo->image_width, output_cols * 2);
  167130. inrow = 0;
  167131. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167132. outptr = output_data[outrow];
  167133. inptr0 = input_data[inrow];
  167134. inptr1 = input_data[inrow+1];
  167135. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167136. for (outcol = 0; outcol < output_cols; outcol++) {
  167137. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167138. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167139. + bias) >> 2);
  167140. bias ^= 3; /* 1=>2, 2=>1 */
  167141. inptr0 += 2; inptr1 += 2;
  167142. }
  167143. inrow += 2;
  167144. }
  167145. }
  167146. #ifdef INPUT_SMOOTHING_SUPPORTED
  167147. /*
  167148. * Downsample pixel values of a single component.
  167149. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167150. * with smoothing. One row of context is required.
  167151. */
  167152. METHODDEF(void)
  167153. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167154. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167155. {
  167156. int inrow, outrow;
  167157. JDIMENSION colctr;
  167158. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167159. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167160. INT32 membersum, neighsum, memberscale, neighscale;
  167161. /* Expand input data enough to let all the output samples be generated
  167162. * by the standard loop. Special-casing padded output would be more
  167163. * efficient.
  167164. */
  167165. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167166. cinfo->image_width, output_cols * 2);
  167167. /* We don't bother to form the individual "smoothed" input pixel values;
  167168. * we can directly compute the output which is the average of the four
  167169. * smoothed values. Each of the four member pixels contributes a fraction
  167170. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167171. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167172. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167173. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167174. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167175. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167176. * factors are scaled by 2^16 = 65536.
  167177. * Also recall that SF = smoothing_factor / 1024.
  167178. */
  167179. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167180. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167181. inrow = 0;
  167182. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167183. outptr = output_data[outrow];
  167184. inptr0 = input_data[inrow];
  167185. inptr1 = input_data[inrow+1];
  167186. above_ptr = input_data[inrow-1];
  167187. below_ptr = input_data[inrow+2];
  167188. /* Special case for first column: pretend column -1 is same as column 0 */
  167189. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167190. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167191. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167192. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167193. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167194. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167195. neighsum += neighsum;
  167196. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167197. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167198. membersum = membersum * memberscale + neighsum * neighscale;
  167199. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167200. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167201. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167202. /* sum of pixels directly mapped to this output element */
  167203. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167204. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167205. /* sum of edge-neighbor pixels */
  167206. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167207. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167208. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167209. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167210. /* The edge-neighbors count twice as much as corner-neighbors */
  167211. neighsum += neighsum;
  167212. /* Add in the corner-neighbors */
  167213. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167214. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167215. /* form final output scaled up by 2^16 */
  167216. membersum = membersum * memberscale + neighsum * neighscale;
  167217. /* round, descale and output it */
  167218. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167219. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167220. }
  167221. /* Special case for last column */
  167222. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167223. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167224. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167225. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167226. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167227. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167228. neighsum += neighsum;
  167229. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167230. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167231. membersum = membersum * memberscale + neighsum * neighscale;
  167232. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167233. inrow += 2;
  167234. }
  167235. }
  167236. /*
  167237. * Downsample pixel values of a single component.
  167238. * This version handles the special case of a full-size component,
  167239. * with smoothing. One row of context is required.
  167240. */
  167241. METHODDEF(void)
  167242. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167243. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167244. {
  167245. int outrow;
  167246. JDIMENSION colctr;
  167247. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167248. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167249. INT32 membersum, neighsum, memberscale, neighscale;
  167250. int colsum, lastcolsum, nextcolsum;
  167251. /* Expand input data enough to let all the output samples be generated
  167252. * by the standard loop. Special-casing padded output would be more
  167253. * efficient.
  167254. */
  167255. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167256. cinfo->image_width, output_cols);
  167257. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167258. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167259. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167260. * Also recall that SF = smoothing_factor / 1024.
  167261. */
  167262. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167263. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167264. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167265. outptr = output_data[outrow];
  167266. inptr = input_data[outrow];
  167267. above_ptr = input_data[outrow-1];
  167268. below_ptr = input_data[outrow+1];
  167269. /* Special case for first column */
  167270. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167271. GETJSAMPLE(*inptr);
  167272. membersum = GETJSAMPLE(*inptr++);
  167273. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167274. GETJSAMPLE(*inptr);
  167275. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167276. membersum = membersum * memberscale + neighsum * neighscale;
  167277. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167278. lastcolsum = colsum; colsum = nextcolsum;
  167279. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167280. membersum = GETJSAMPLE(*inptr++);
  167281. above_ptr++; below_ptr++;
  167282. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167283. GETJSAMPLE(*inptr);
  167284. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167285. membersum = membersum * memberscale + neighsum * neighscale;
  167286. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167287. lastcolsum = colsum; colsum = nextcolsum;
  167288. }
  167289. /* Special case for last column */
  167290. membersum = GETJSAMPLE(*inptr);
  167291. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167292. membersum = membersum * memberscale + neighsum * neighscale;
  167293. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167294. }
  167295. }
  167296. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167297. /*
  167298. * Module initialization routine for downsampling.
  167299. * Note that we must select a routine for each component.
  167300. */
  167301. GLOBAL(void)
  167302. jinit_downsampler (j_compress_ptr cinfo)
  167303. {
  167304. my_downsample_ptr downsample;
  167305. int ci;
  167306. jpeg_component_info * compptr;
  167307. boolean smoothok = TRUE;
  167308. downsample = (my_downsample_ptr)
  167309. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167310. SIZEOF(my_downsampler));
  167311. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167312. downsample->pub.start_pass = start_pass_downsample;
  167313. downsample->pub.downsample = sep_downsample;
  167314. downsample->pub.need_context_rows = FALSE;
  167315. if (cinfo->CCIR601_sampling)
  167316. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167317. /* Verify we can handle the sampling factors, and set up method pointers */
  167318. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167319. ci++, compptr++) {
  167320. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167321. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167322. #ifdef INPUT_SMOOTHING_SUPPORTED
  167323. if (cinfo->smoothing_factor) {
  167324. downsample->methods[ci] = fullsize_smooth_downsample;
  167325. downsample->pub.need_context_rows = TRUE;
  167326. } else
  167327. #endif
  167328. downsample->methods[ci] = fullsize_downsample;
  167329. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167330. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167331. smoothok = FALSE;
  167332. downsample->methods[ci] = h2v1_downsample;
  167333. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167334. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167335. #ifdef INPUT_SMOOTHING_SUPPORTED
  167336. if (cinfo->smoothing_factor) {
  167337. downsample->methods[ci] = h2v2_smooth_downsample;
  167338. downsample->pub.need_context_rows = TRUE;
  167339. } else
  167340. #endif
  167341. downsample->methods[ci] = h2v2_downsample;
  167342. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167343. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167344. smoothok = FALSE;
  167345. downsample->methods[ci] = int_downsample;
  167346. } else
  167347. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167348. }
  167349. #ifdef INPUT_SMOOTHING_SUPPORTED
  167350. if (cinfo->smoothing_factor && !smoothok)
  167351. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167352. #endif
  167353. }
  167354. /*** End of inlined file: jcsample.c ***/
  167355. /*** Start of inlined file: jctrans.c ***/
  167356. #define JPEG_INTERNALS
  167357. /* Forward declarations */
  167358. LOCAL(void) transencode_master_selection
  167359. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167360. LOCAL(void) transencode_coef_controller
  167361. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167362. /*
  167363. * Compression initialization for writing raw-coefficient data.
  167364. * Before calling this, all parameters and a data destination must be set up.
  167365. * Call jpeg_finish_compress() to actually write the data.
  167366. *
  167367. * The number of passed virtual arrays must match cinfo->num_components.
  167368. * Note that the virtual arrays need not be filled or even realized at
  167369. * the time write_coefficients is called; indeed, if the virtual arrays
  167370. * were requested from this compression object's memory manager, they
  167371. * typically will be realized during this routine and filled afterwards.
  167372. */
  167373. GLOBAL(void)
  167374. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167375. {
  167376. if (cinfo->global_state != CSTATE_START)
  167377. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167378. /* Mark all tables to be written */
  167379. jpeg_suppress_tables(cinfo, FALSE);
  167380. /* (Re)initialize error mgr and destination modules */
  167381. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167382. (*cinfo->dest->init_destination) (cinfo);
  167383. /* Perform master selection of active modules */
  167384. transencode_master_selection(cinfo, coef_arrays);
  167385. /* Wait for jpeg_finish_compress() call */
  167386. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167387. cinfo->global_state = CSTATE_WRCOEFS;
  167388. }
  167389. /*
  167390. * Initialize the compression object with default parameters,
  167391. * then copy from the source object all parameters needed for lossless
  167392. * transcoding. Parameters that can be varied without loss (such as
  167393. * scan script and Huffman optimization) are left in their default states.
  167394. */
  167395. GLOBAL(void)
  167396. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167397. j_compress_ptr dstinfo)
  167398. {
  167399. JQUANT_TBL ** qtblptr;
  167400. jpeg_component_info *incomp, *outcomp;
  167401. JQUANT_TBL *c_quant, *slot_quant;
  167402. int tblno, ci, coefi;
  167403. /* Safety check to ensure start_compress not called yet. */
  167404. if (dstinfo->global_state != CSTATE_START)
  167405. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167406. /* Copy fundamental image dimensions */
  167407. dstinfo->image_width = srcinfo->image_width;
  167408. dstinfo->image_height = srcinfo->image_height;
  167409. dstinfo->input_components = srcinfo->num_components;
  167410. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167411. /* Initialize all parameters to default values */
  167412. jpeg_set_defaults(dstinfo);
  167413. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167414. * Fix it to get the right header markers for the image colorspace.
  167415. */
  167416. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167417. dstinfo->data_precision = srcinfo->data_precision;
  167418. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167419. /* Copy the source's quantization tables. */
  167420. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167421. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167422. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167423. if (*qtblptr == NULL)
  167424. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167425. MEMCOPY((*qtblptr)->quantval,
  167426. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167427. SIZEOF((*qtblptr)->quantval));
  167428. (*qtblptr)->sent_table = FALSE;
  167429. }
  167430. }
  167431. /* Copy the source's per-component info.
  167432. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167433. */
  167434. dstinfo->num_components = srcinfo->num_components;
  167435. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167436. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167437. MAX_COMPONENTS);
  167438. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167439. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167440. outcomp->component_id = incomp->component_id;
  167441. outcomp->h_samp_factor = incomp->h_samp_factor;
  167442. outcomp->v_samp_factor = incomp->v_samp_factor;
  167443. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167444. /* Make sure saved quantization table for component matches the qtable
  167445. * slot. If not, the input file re-used this qtable slot.
  167446. * IJG encoder currently cannot duplicate this.
  167447. */
  167448. tblno = outcomp->quant_tbl_no;
  167449. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167450. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167451. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167452. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167453. c_quant = incomp->quant_table;
  167454. if (c_quant != NULL) {
  167455. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167456. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167457. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167458. }
  167459. }
  167460. /* Note: we do not copy the source's Huffman table assignments;
  167461. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167462. */
  167463. }
  167464. /* Also copy JFIF version and resolution information, if available.
  167465. * Strictly speaking this isn't "critical" info, but it's nearly
  167466. * always appropriate to copy it if available. In particular,
  167467. * if the application chooses to copy JFIF 1.02 extension markers from
  167468. * the source file, we need to copy the version to make sure we don't
  167469. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167470. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167471. */
  167472. if (srcinfo->saw_JFIF_marker) {
  167473. if (srcinfo->JFIF_major_version == 1) {
  167474. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167475. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167476. }
  167477. dstinfo->density_unit = srcinfo->density_unit;
  167478. dstinfo->X_density = srcinfo->X_density;
  167479. dstinfo->Y_density = srcinfo->Y_density;
  167480. }
  167481. }
  167482. /*
  167483. * Master selection of compression modules for transcoding.
  167484. * This substitutes for jcinit.c's initialization of the full compressor.
  167485. */
  167486. LOCAL(void)
  167487. transencode_master_selection (j_compress_ptr cinfo,
  167488. jvirt_barray_ptr * coef_arrays)
  167489. {
  167490. /* Although we don't actually use input_components for transcoding,
  167491. * jcmaster.c's initial_setup will complain if input_components is 0.
  167492. */
  167493. cinfo->input_components = 1;
  167494. /* Initialize master control (includes parameter checking/processing) */
  167495. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167496. /* Entropy encoding: either Huffman or arithmetic coding. */
  167497. if (cinfo->arith_code) {
  167498. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167499. } else {
  167500. if (cinfo->progressive_mode) {
  167501. #ifdef C_PROGRESSIVE_SUPPORTED
  167502. jinit_phuff_encoder(cinfo);
  167503. #else
  167504. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167505. #endif
  167506. } else
  167507. jinit_huff_encoder(cinfo);
  167508. }
  167509. /* We need a special coefficient buffer controller. */
  167510. transencode_coef_controller(cinfo, coef_arrays);
  167511. jinit_marker_writer(cinfo);
  167512. /* We can now tell the memory manager to allocate virtual arrays. */
  167513. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167514. /* Write the datastream header (SOI, JFIF) immediately.
  167515. * Frame and scan headers are postponed till later.
  167516. * This lets application insert special markers after the SOI.
  167517. */
  167518. (*cinfo->marker->write_file_header) (cinfo);
  167519. }
  167520. /*
  167521. * The rest of this file is a special implementation of the coefficient
  167522. * buffer controller. This is similar to jccoefct.c, but it handles only
  167523. * output from presupplied virtual arrays. Furthermore, we generate any
  167524. * dummy padding blocks on-the-fly rather than expecting them to be present
  167525. * in the arrays.
  167526. */
  167527. /* Private buffer controller object */
  167528. typedef struct {
  167529. struct jpeg_c_coef_controller pub; /* public fields */
  167530. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167531. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167532. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167533. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167534. /* Virtual block array for each component. */
  167535. jvirt_barray_ptr * whole_image;
  167536. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167537. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167538. } my_coef_controller2;
  167539. typedef my_coef_controller2 * my_coef_ptr2;
  167540. LOCAL(void)
  167541. start_iMCU_row2 (j_compress_ptr cinfo)
  167542. /* Reset within-iMCU-row counters for a new row */
  167543. {
  167544. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167545. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167546. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167547. * But at the bottom of the image, process only what's left.
  167548. */
  167549. if (cinfo->comps_in_scan > 1) {
  167550. coef->MCU_rows_per_iMCU_row = 1;
  167551. } else {
  167552. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167553. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167554. else
  167555. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167556. }
  167557. coef->mcu_ctr = 0;
  167558. coef->MCU_vert_offset = 0;
  167559. }
  167560. /*
  167561. * Initialize for a processing pass.
  167562. */
  167563. METHODDEF(void)
  167564. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167565. {
  167566. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167567. if (pass_mode != JBUF_CRANK_DEST)
  167568. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167569. coef->iMCU_row_num = 0;
  167570. start_iMCU_row2(cinfo);
  167571. }
  167572. /*
  167573. * Process some data.
  167574. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167575. * per call, ie, v_samp_factor block rows for each component in the scan.
  167576. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167577. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167578. *
  167579. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167580. */
  167581. METHODDEF(boolean)
  167582. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167583. {
  167584. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167585. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167586. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167587. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167588. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167589. JDIMENSION start_col;
  167590. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167591. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167592. JBLOCKROW buffer_ptr;
  167593. jpeg_component_info *compptr;
  167594. /* Align the virtual buffers for the components used in this scan. */
  167595. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167596. compptr = cinfo->cur_comp_info[ci];
  167597. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167598. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167599. coef->iMCU_row_num * compptr->v_samp_factor,
  167600. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167601. }
  167602. /* Loop to process one whole iMCU row */
  167603. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167604. yoffset++) {
  167605. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167606. MCU_col_num++) {
  167607. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167608. blkn = 0; /* index of current DCT block within MCU */
  167609. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167610. compptr = cinfo->cur_comp_info[ci];
  167611. start_col = MCU_col_num * compptr->MCU_width;
  167612. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167613. : compptr->last_col_width;
  167614. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167615. if (coef->iMCU_row_num < last_iMCU_row ||
  167616. yindex+yoffset < compptr->last_row_height) {
  167617. /* Fill in pointers to real blocks in this row */
  167618. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167619. for (xindex = 0; xindex < blockcnt; xindex++)
  167620. MCU_buffer[blkn++] = buffer_ptr++;
  167621. } else {
  167622. /* At bottom of image, need a whole row of dummy blocks */
  167623. xindex = 0;
  167624. }
  167625. /* Fill in any dummy blocks needed in this row.
  167626. * Dummy blocks are filled in the same way as in jccoefct.c:
  167627. * all zeroes in the AC entries, DC entries equal to previous
  167628. * block's DC value. The init routine has already zeroed the
  167629. * AC entries, so we need only set the DC entries correctly.
  167630. */
  167631. for (; xindex < compptr->MCU_width; xindex++) {
  167632. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167633. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167634. blkn++;
  167635. }
  167636. }
  167637. }
  167638. /* Try to write the MCU. */
  167639. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167640. /* Suspension forced; update state counters and exit */
  167641. coef->MCU_vert_offset = yoffset;
  167642. coef->mcu_ctr = MCU_col_num;
  167643. return FALSE;
  167644. }
  167645. }
  167646. /* Completed an MCU row, but perhaps not an iMCU row */
  167647. coef->mcu_ctr = 0;
  167648. }
  167649. /* Completed the iMCU row, advance counters for next one */
  167650. coef->iMCU_row_num++;
  167651. start_iMCU_row2(cinfo);
  167652. return TRUE;
  167653. }
  167654. /*
  167655. * Initialize coefficient buffer controller.
  167656. *
  167657. * Each passed coefficient array must be the right size for that
  167658. * coefficient: width_in_blocks wide and height_in_blocks high,
  167659. * with unitheight at least v_samp_factor.
  167660. */
  167661. LOCAL(void)
  167662. transencode_coef_controller (j_compress_ptr cinfo,
  167663. jvirt_barray_ptr * coef_arrays)
  167664. {
  167665. my_coef_ptr2 coef;
  167666. JBLOCKROW buffer;
  167667. int i;
  167668. coef = (my_coef_ptr2)
  167669. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167670. SIZEOF(my_coef_controller2));
  167671. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167672. coef->pub.start_pass = start_pass_coef2;
  167673. coef->pub.compress_data = compress_output2;
  167674. /* Save pointer to virtual arrays */
  167675. coef->whole_image = coef_arrays;
  167676. /* Allocate and pre-zero space for dummy DCT blocks. */
  167677. buffer = (JBLOCKROW)
  167678. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167679. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167680. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167681. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167682. coef->dummy_buffer[i] = buffer + i;
  167683. }
  167684. }
  167685. /*** End of inlined file: jctrans.c ***/
  167686. /*** Start of inlined file: jdapistd.c ***/
  167687. #define JPEG_INTERNALS
  167688. /* Forward declarations */
  167689. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167690. /*
  167691. * Decompression initialization.
  167692. * jpeg_read_header must be completed before calling this.
  167693. *
  167694. * If a multipass operating mode was selected, this will do all but the
  167695. * last pass, and thus may take a great deal of time.
  167696. *
  167697. * Returns FALSE if suspended. The return value need be inspected only if
  167698. * a suspending data source is used.
  167699. */
  167700. GLOBAL(boolean)
  167701. jpeg_start_decompress (j_decompress_ptr cinfo)
  167702. {
  167703. if (cinfo->global_state == DSTATE_READY) {
  167704. /* First call: initialize master control, select active modules */
  167705. jinit_master_decompress(cinfo);
  167706. if (cinfo->buffered_image) {
  167707. /* No more work here; expecting jpeg_start_output next */
  167708. cinfo->global_state = DSTATE_BUFIMAGE;
  167709. return TRUE;
  167710. }
  167711. cinfo->global_state = DSTATE_PRELOAD;
  167712. }
  167713. if (cinfo->global_state == DSTATE_PRELOAD) {
  167714. /* If file has multiple scans, absorb them all into the coef buffer */
  167715. if (cinfo->inputctl->has_multiple_scans) {
  167716. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167717. for (;;) {
  167718. int retcode;
  167719. /* Call progress monitor hook if present */
  167720. if (cinfo->progress != NULL)
  167721. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167722. /* Absorb some more input */
  167723. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167724. if (retcode == JPEG_SUSPENDED)
  167725. return FALSE;
  167726. if (retcode == JPEG_REACHED_EOI)
  167727. break;
  167728. /* Advance progress counter if appropriate */
  167729. if (cinfo->progress != NULL &&
  167730. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167731. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167732. /* jdmaster underestimated number of scans; ratchet up one scan */
  167733. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167734. }
  167735. }
  167736. }
  167737. #else
  167738. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167739. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167740. }
  167741. cinfo->output_scan_number = cinfo->input_scan_number;
  167742. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167743. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167744. /* Perform any dummy output passes, and set up for the final pass */
  167745. return output_pass_setup(cinfo);
  167746. }
  167747. /*
  167748. * Set up for an output pass, and perform any dummy pass(es) needed.
  167749. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167750. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167751. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167752. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167753. */
  167754. LOCAL(boolean)
  167755. output_pass_setup (j_decompress_ptr cinfo)
  167756. {
  167757. if (cinfo->global_state != DSTATE_PRESCAN) {
  167758. /* First call: do pass setup */
  167759. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167760. cinfo->output_scanline = 0;
  167761. cinfo->global_state = DSTATE_PRESCAN;
  167762. }
  167763. /* Loop over any required dummy passes */
  167764. while (cinfo->master->is_dummy_pass) {
  167765. #ifdef QUANT_2PASS_SUPPORTED
  167766. /* Crank through the dummy pass */
  167767. while (cinfo->output_scanline < cinfo->output_height) {
  167768. JDIMENSION last_scanline;
  167769. /* Call progress monitor hook if present */
  167770. if (cinfo->progress != NULL) {
  167771. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167772. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167773. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167774. }
  167775. /* Process some data */
  167776. last_scanline = cinfo->output_scanline;
  167777. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167778. &cinfo->output_scanline, (JDIMENSION) 0);
  167779. if (cinfo->output_scanline == last_scanline)
  167780. return FALSE; /* No progress made, must suspend */
  167781. }
  167782. /* Finish up dummy pass, and set up for another one */
  167783. (*cinfo->master->finish_output_pass) (cinfo);
  167784. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167785. cinfo->output_scanline = 0;
  167786. #else
  167787. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167788. #endif /* QUANT_2PASS_SUPPORTED */
  167789. }
  167790. /* Ready for application to drive output pass through
  167791. * jpeg_read_scanlines or jpeg_read_raw_data.
  167792. */
  167793. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167794. return TRUE;
  167795. }
  167796. /*
  167797. * Read some scanlines of data from the JPEG decompressor.
  167798. *
  167799. * The return value will be the number of lines actually read.
  167800. * This may be less than the number requested in several cases,
  167801. * including bottom of image, data source suspension, and operating
  167802. * modes that emit multiple scanlines at a time.
  167803. *
  167804. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167805. * this likely signals an application programmer error. However,
  167806. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167807. */
  167808. GLOBAL(JDIMENSION)
  167809. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167810. JDIMENSION max_lines)
  167811. {
  167812. JDIMENSION row_ctr;
  167813. if (cinfo->global_state != DSTATE_SCANNING)
  167814. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167815. if (cinfo->output_scanline >= cinfo->output_height) {
  167816. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167817. return 0;
  167818. }
  167819. /* Call progress monitor hook if present */
  167820. if (cinfo->progress != NULL) {
  167821. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167822. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167823. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167824. }
  167825. /* Process some data */
  167826. row_ctr = 0;
  167827. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167828. cinfo->output_scanline += row_ctr;
  167829. return row_ctr;
  167830. }
  167831. /*
  167832. * Alternate entry point to read raw data.
  167833. * Processes exactly one iMCU row per call, unless suspended.
  167834. */
  167835. GLOBAL(JDIMENSION)
  167836. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167837. JDIMENSION max_lines)
  167838. {
  167839. JDIMENSION lines_per_iMCU_row;
  167840. if (cinfo->global_state != DSTATE_RAW_OK)
  167841. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167842. if (cinfo->output_scanline >= cinfo->output_height) {
  167843. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167844. return 0;
  167845. }
  167846. /* Call progress monitor hook if present */
  167847. if (cinfo->progress != NULL) {
  167848. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167849. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167850. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167851. }
  167852. /* Verify that at least one iMCU row can be returned. */
  167853. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167854. if (max_lines < lines_per_iMCU_row)
  167855. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167856. /* Decompress directly into user's buffer. */
  167857. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167858. return 0; /* suspension forced, can do nothing more */
  167859. /* OK, we processed one iMCU row. */
  167860. cinfo->output_scanline += lines_per_iMCU_row;
  167861. return lines_per_iMCU_row;
  167862. }
  167863. /* Additional entry points for buffered-image mode. */
  167864. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167865. /*
  167866. * Initialize for an output pass in buffered-image mode.
  167867. */
  167868. GLOBAL(boolean)
  167869. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167870. {
  167871. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167872. cinfo->global_state != DSTATE_PRESCAN)
  167873. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167874. /* Limit scan number to valid range */
  167875. if (scan_number <= 0)
  167876. scan_number = 1;
  167877. if (cinfo->inputctl->eoi_reached &&
  167878. scan_number > cinfo->input_scan_number)
  167879. scan_number = cinfo->input_scan_number;
  167880. cinfo->output_scan_number = scan_number;
  167881. /* Perform any dummy output passes, and set up for the real pass */
  167882. return output_pass_setup(cinfo);
  167883. }
  167884. /*
  167885. * Finish up after an output pass in buffered-image mode.
  167886. *
  167887. * Returns FALSE if suspended. The return value need be inspected only if
  167888. * a suspending data source is used.
  167889. */
  167890. GLOBAL(boolean)
  167891. jpeg_finish_output (j_decompress_ptr cinfo)
  167892. {
  167893. if ((cinfo->global_state == DSTATE_SCANNING ||
  167894. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167895. /* Terminate this pass. */
  167896. /* We do not require the whole pass to have been completed. */
  167897. (*cinfo->master->finish_output_pass) (cinfo);
  167898. cinfo->global_state = DSTATE_BUFPOST;
  167899. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167900. /* BUFPOST = repeat call after a suspension, anything else is error */
  167901. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167902. }
  167903. /* Read markers looking for SOS or EOI */
  167904. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167905. ! cinfo->inputctl->eoi_reached) {
  167906. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167907. return FALSE; /* Suspend, come back later */
  167908. }
  167909. cinfo->global_state = DSTATE_BUFIMAGE;
  167910. return TRUE;
  167911. }
  167912. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167913. /*** End of inlined file: jdapistd.c ***/
  167914. /*** Start of inlined file: jdapimin.c ***/
  167915. #define JPEG_INTERNALS
  167916. /*
  167917. * Initialization of a JPEG decompression object.
  167918. * The error manager must already be set up (in case memory manager fails).
  167919. */
  167920. GLOBAL(void)
  167921. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167922. {
  167923. int i;
  167924. /* Guard against version mismatches between library and caller. */
  167925. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167926. if (version != JPEG_LIB_VERSION)
  167927. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167928. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167929. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167930. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167931. /* For debugging purposes, we zero the whole master structure.
  167932. * But the application has already set the err pointer, and may have set
  167933. * client_data, so we have to save and restore those fields.
  167934. * Note: if application hasn't set client_data, tools like Purify may
  167935. * complain here.
  167936. */
  167937. {
  167938. struct jpeg_error_mgr * err = cinfo->err;
  167939. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167940. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167941. cinfo->err = err;
  167942. cinfo->client_data = client_data;
  167943. }
  167944. cinfo->is_decompressor = TRUE;
  167945. /* Initialize a memory manager instance for this object */
  167946. jinit_memory_mgr((j_common_ptr) cinfo);
  167947. /* Zero out pointers to permanent structures. */
  167948. cinfo->progress = NULL;
  167949. cinfo->src = NULL;
  167950. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167951. cinfo->quant_tbl_ptrs[i] = NULL;
  167952. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167953. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167954. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167955. }
  167956. /* Initialize marker processor so application can override methods
  167957. * for COM, APPn markers before calling jpeg_read_header.
  167958. */
  167959. cinfo->marker_list = NULL;
  167960. jinit_marker_reader(cinfo);
  167961. /* And initialize the overall input controller. */
  167962. jinit_input_controller(cinfo);
  167963. /* OK, I'm ready */
  167964. cinfo->global_state = DSTATE_START;
  167965. }
  167966. /*
  167967. * Destruction of a JPEG decompression object
  167968. */
  167969. GLOBAL(void)
  167970. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167971. {
  167972. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167973. }
  167974. /*
  167975. * Abort processing of a JPEG decompression operation,
  167976. * but don't destroy the object itself.
  167977. */
  167978. GLOBAL(void)
  167979. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167980. {
  167981. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167982. }
  167983. /*
  167984. * Set default decompression parameters.
  167985. */
  167986. LOCAL(void)
  167987. default_decompress_parms (j_decompress_ptr cinfo)
  167988. {
  167989. /* Guess the input colorspace, and set output colorspace accordingly. */
  167990. /* (Wish JPEG committee had provided a real way to specify this...) */
  167991. /* Note application may override our guesses. */
  167992. switch (cinfo->num_components) {
  167993. case 1:
  167994. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167995. cinfo->out_color_space = JCS_GRAYSCALE;
  167996. break;
  167997. case 3:
  167998. if (cinfo->saw_JFIF_marker) {
  167999. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168000. } else if (cinfo->saw_Adobe_marker) {
  168001. switch (cinfo->Adobe_transform) {
  168002. case 0:
  168003. cinfo->jpeg_color_space = JCS_RGB;
  168004. break;
  168005. case 1:
  168006. cinfo->jpeg_color_space = JCS_YCbCr;
  168007. break;
  168008. default:
  168009. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168010. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168011. break;
  168012. }
  168013. } else {
  168014. /* Saw no special markers, try to guess from the component IDs */
  168015. int cid0 = cinfo->comp_info[0].component_id;
  168016. int cid1 = cinfo->comp_info[1].component_id;
  168017. int cid2 = cinfo->comp_info[2].component_id;
  168018. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168019. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168020. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168021. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168022. else {
  168023. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168024. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168025. }
  168026. }
  168027. /* Always guess RGB is proper output colorspace. */
  168028. cinfo->out_color_space = JCS_RGB;
  168029. break;
  168030. case 4:
  168031. if (cinfo->saw_Adobe_marker) {
  168032. switch (cinfo->Adobe_transform) {
  168033. case 0:
  168034. cinfo->jpeg_color_space = JCS_CMYK;
  168035. break;
  168036. case 2:
  168037. cinfo->jpeg_color_space = JCS_YCCK;
  168038. break;
  168039. default:
  168040. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168041. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168042. break;
  168043. }
  168044. } else {
  168045. /* No special markers, assume straight CMYK. */
  168046. cinfo->jpeg_color_space = JCS_CMYK;
  168047. }
  168048. cinfo->out_color_space = JCS_CMYK;
  168049. break;
  168050. default:
  168051. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168052. cinfo->out_color_space = JCS_UNKNOWN;
  168053. break;
  168054. }
  168055. /* Set defaults for other decompression parameters. */
  168056. cinfo->scale_num = 1; /* 1:1 scaling */
  168057. cinfo->scale_denom = 1;
  168058. cinfo->output_gamma = 1.0;
  168059. cinfo->buffered_image = FALSE;
  168060. cinfo->raw_data_out = FALSE;
  168061. cinfo->dct_method = JDCT_DEFAULT;
  168062. cinfo->do_fancy_upsampling = TRUE;
  168063. cinfo->do_block_smoothing = TRUE;
  168064. cinfo->quantize_colors = FALSE;
  168065. /* We set these in case application only sets quantize_colors. */
  168066. cinfo->dither_mode = JDITHER_FS;
  168067. #ifdef QUANT_2PASS_SUPPORTED
  168068. cinfo->two_pass_quantize = TRUE;
  168069. #else
  168070. cinfo->two_pass_quantize = FALSE;
  168071. #endif
  168072. cinfo->desired_number_of_colors = 256;
  168073. cinfo->colormap = NULL;
  168074. /* Initialize for no mode change in buffered-image mode. */
  168075. cinfo->enable_1pass_quant = FALSE;
  168076. cinfo->enable_external_quant = FALSE;
  168077. cinfo->enable_2pass_quant = FALSE;
  168078. }
  168079. /*
  168080. * Decompression startup: read start of JPEG datastream to see what's there.
  168081. * Need only initialize JPEG object and supply a data source before calling.
  168082. *
  168083. * This routine will read as far as the first SOS marker (ie, actual start of
  168084. * compressed data), and will save all tables and parameters in the JPEG
  168085. * object. It will also initialize the decompression parameters to default
  168086. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168087. * adjust the decompression parameters and then call jpeg_start_decompress.
  168088. * (Or, if the application only wanted to determine the image parameters,
  168089. * the data need not be decompressed. In that case, call jpeg_abort or
  168090. * jpeg_destroy to release any temporary space.)
  168091. * If an abbreviated (tables only) datastream is presented, the routine will
  168092. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168093. * re-use the JPEG object to read the abbreviated image datastream(s).
  168094. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168095. * The JPEG_SUSPENDED return code only occurs if the data source module
  168096. * requests suspension of the decompressor. In this case the application
  168097. * should load more source data and then re-call jpeg_read_header to resume
  168098. * processing.
  168099. * If a non-suspending data source is used and require_image is TRUE, then the
  168100. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168101. *
  168102. * This routine is now just a front end to jpeg_consume_input, with some
  168103. * extra error checking.
  168104. */
  168105. GLOBAL(int)
  168106. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168107. {
  168108. int retcode;
  168109. if (cinfo->global_state != DSTATE_START &&
  168110. cinfo->global_state != DSTATE_INHEADER)
  168111. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168112. retcode = jpeg_consume_input(cinfo);
  168113. switch (retcode) {
  168114. case JPEG_REACHED_SOS:
  168115. retcode = JPEG_HEADER_OK;
  168116. break;
  168117. case JPEG_REACHED_EOI:
  168118. if (require_image) /* Complain if application wanted an image */
  168119. ERREXIT(cinfo, JERR_NO_IMAGE);
  168120. /* Reset to start state; it would be safer to require the application to
  168121. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168122. * A side effect is to free any temporary memory (there shouldn't be any).
  168123. */
  168124. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168125. retcode = JPEG_HEADER_TABLES_ONLY;
  168126. break;
  168127. case JPEG_SUSPENDED:
  168128. /* no work */
  168129. break;
  168130. }
  168131. return retcode;
  168132. }
  168133. /*
  168134. * Consume data in advance of what the decompressor requires.
  168135. * This can be called at any time once the decompressor object has
  168136. * been created and a data source has been set up.
  168137. *
  168138. * This routine is essentially a state machine that handles a couple
  168139. * of critical state-transition actions, namely initial setup and
  168140. * transition from header scanning to ready-for-start_decompress.
  168141. * All the actual input is done via the input controller's consume_input
  168142. * method.
  168143. */
  168144. GLOBAL(int)
  168145. jpeg_consume_input (j_decompress_ptr cinfo)
  168146. {
  168147. int retcode = JPEG_SUSPENDED;
  168148. /* NB: every possible DSTATE value should be listed in this switch */
  168149. switch (cinfo->global_state) {
  168150. case DSTATE_START:
  168151. /* Start-of-datastream actions: reset appropriate modules */
  168152. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168153. /* Initialize application's data source module */
  168154. (*cinfo->src->init_source) (cinfo);
  168155. cinfo->global_state = DSTATE_INHEADER;
  168156. /*FALLTHROUGH*/
  168157. case DSTATE_INHEADER:
  168158. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168159. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168160. /* Set up default parameters based on header data */
  168161. default_decompress_parms(cinfo);
  168162. /* Set global state: ready for start_decompress */
  168163. cinfo->global_state = DSTATE_READY;
  168164. }
  168165. break;
  168166. case DSTATE_READY:
  168167. /* Can't advance past first SOS until start_decompress is called */
  168168. retcode = JPEG_REACHED_SOS;
  168169. break;
  168170. case DSTATE_PRELOAD:
  168171. case DSTATE_PRESCAN:
  168172. case DSTATE_SCANNING:
  168173. case DSTATE_RAW_OK:
  168174. case DSTATE_BUFIMAGE:
  168175. case DSTATE_BUFPOST:
  168176. case DSTATE_STOPPING:
  168177. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168178. break;
  168179. default:
  168180. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168181. }
  168182. return retcode;
  168183. }
  168184. /*
  168185. * Have we finished reading the input file?
  168186. */
  168187. GLOBAL(boolean)
  168188. jpeg_input_complete (j_decompress_ptr cinfo)
  168189. {
  168190. /* Check for valid jpeg object */
  168191. if (cinfo->global_state < DSTATE_START ||
  168192. cinfo->global_state > DSTATE_STOPPING)
  168193. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168194. return cinfo->inputctl->eoi_reached;
  168195. }
  168196. /*
  168197. * Is there more than one scan?
  168198. */
  168199. GLOBAL(boolean)
  168200. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168201. {
  168202. /* Only valid after jpeg_read_header completes */
  168203. if (cinfo->global_state < DSTATE_READY ||
  168204. cinfo->global_state > DSTATE_STOPPING)
  168205. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168206. return cinfo->inputctl->has_multiple_scans;
  168207. }
  168208. /*
  168209. * Finish JPEG decompression.
  168210. *
  168211. * This will normally just verify the file trailer and release temp storage.
  168212. *
  168213. * Returns FALSE if suspended. The return value need be inspected only if
  168214. * a suspending data source is used.
  168215. */
  168216. GLOBAL(boolean)
  168217. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168218. {
  168219. if ((cinfo->global_state == DSTATE_SCANNING ||
  168220. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168221. /* Terminate final pass of non-buffered mode */
  168222. if (cinfo->output_scanline < cinfo->output_height)
  168223. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168224. (*cinfo->master->finish_output_pass) (cinfo);
  168225. cinfo->global_state = DSTATE_STOPPING;
  168226. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168227. /* Finishing after a buffered-image operation */
  168228. cinfo->global_state = DSTATE_STOPPING;
  168229. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168230. /* STOPPING = repeat call after a suspension, anything else is error */
  168231. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168232. }
  168233. /* Read until EOI */
  168234. while (! cinfo->inputctl->eoi_reached) {
  168235. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168236. return FALSE; /* Suspend, come back later */
  168237. }
  168238. /* Do final cleanup */
  168239. (*cinfo->src->term_source) (cinfo);
  168240. /* We can use jpeg_abort to release memory and reset global_state */
  168241. jpeg_abort((j_common_ptr) cinfo);
  168242. return TRUE;
  168243. }
  168244. /*** End of inlined file: jdapimin.c ***/
  168245. /*** Start of inlined file: jdatasrc.c ***/
  168246. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168247. /*** Start of inlined file: jerror.h ***/
  168248. /*
  168249. * To define the enum list of message codes, include this file without
  168250. * defining macro JMESSAGE. To create a message string table, include it
  168251. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168252. */
  168253. #ifndef JMESSAGE
  168254. #ifndef JERROR_H
  168255. /* First time through, define the enum list */
  168256. #define JMAKE_ENUM_LIST
  168257. #else
  168258. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168259. #define JMESSAGE(code,string)
  168260. #endif /* JERROR_H */
  168261. #endif /* JMESSAGE */
  168262. #ifdef JMAKE_ENUM_LIST
  168263. typedef enum {
  168264. #define JMESSAGE(code,string) code ,
  168265. #endif /* JMAKE_ENUM_LIST */
  168266. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168267. /* For maintenance convenience, list is alphabetical by message code name */
  168268. JMESSAGE(JERR_ARITH_NOTIMPL,
  168269. "Sorry, there are legal restrictions on arithmetic coding")
  168270. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168271. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168272. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168273. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168274. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168275. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168276. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168277. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168278. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168279. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168280. JMESSAGE(JERR_BAD_LIB_VERSION,
  168281. "Wrong JPEG library version: library is %d, caller expects %d")
  168282. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168283. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168284. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168285. JMESSAGE(JERR_BAD_PROGRESSION,
  168286. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168287. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168288. "Invalid progressive parameters at scan script entry %d")
  168289. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168290. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168291. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168292. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168293. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168294. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168295. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168296. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168297. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168298. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168299. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168300. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168301. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168302. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168303. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168304. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168305. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168306. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168307. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168308. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168309. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168310. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168311. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168312. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168313. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168314. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168315. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168316. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168317. "Cannot transcode due to multiple use of quantization table %d")
  168318. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168319. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168320. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168321. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168322. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168323. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168324. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168325. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168326. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168327. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168328. JMESSAGE(JERR_QUANT_COMPONENTS,
  168329. "Cannot quantize more than %d color components")
  168330. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168331. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168332. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168333. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168334. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168335. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168336. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168337. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168338. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168339. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168340. JMESSAGE(JERR_TFILE_WRITE,
  168341. "Write failed on temporary file --- out of disk space?")
  168342. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168343. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168344. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168345. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168346. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168347. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168348. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168349. JMESSAGE(JMSG_VERSION, JVERSION)
  168350. JMESSAGE(JTRC_16BIT_TABLES,
  168351. "Caution: quantization tables are too coarse for baseline JPEG")
  168352. JMESSAGE(JTRC_ADOBE,
  168353. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168354. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168355. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168356. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168357. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168358. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168359. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168360. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168361. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168362. JMESSAGE(JTRC_EOI, "End Of Image")
  168363. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168364. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168365. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168366. "Warning: thumbnail image size does not match data length %u")
  168367. JMESSAGE(JTRC_JFIF_EXTENSION,
  168368. "JFIF extension marker: type 0x%02x, length %u")
  168369. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168370. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168371. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168372. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168373. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168374. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168375. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168376. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168377. JMESSAGE(JTRC_RST, "RST%d")
  168378. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168379. "Smoothing not supported with nonstandard sampling ratios")
  168380. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168381. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168382. JMESSAGE(JTRC_SOI, "Start of Image")
  168383. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168384. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168385. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168386. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168387. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168388. JMESSAGE(JTRC_THUMB_JPEG,
  168389. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168390. JMESSAGE(JTRC_THUMB_PALETTE,
  168391. "JFIF extension marker: palette thumbnail image, length %u")
  168392. JMESSAGE(JTRC_THUMB_RGB,
  168393. "JFIF extension marker: RGB thumbnail image, length %u")
  168394. JMESSAGE(JTRC_UNKNOWN_IDS,
  168395. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168396. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168397. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168398. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168399. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168400. "Inconsistent progression sequence for component %d coefficient %d")
  168401. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168402. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168403. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168404. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168405. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168406. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168407. JMESSAGE(JWRN_MUST_RESYNC,
  168408. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168409. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168410. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168411. #ifdef JMAKE_ENUM_LIST
  168412. JMSG_LASTMSGCODE
  168413. } J_MESSAGE_CODE;
  168414. #undef JMAKE_ENUM_LIST
  168415. #endif /* JMAKE_ENUM_LIST */
  168416. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168417. #undef JMESSAGE
  168418. #ifndef JERROR_H
  168419. #define JERROR_H
  168420. /* Macros to simplify using the error and trace message stuff */
  168421. /* The first parameter is either type of cinfo pointer */
  168422. /* Fatal errors (print message and exit) */
  168423. #define ERREXIT(cinfo,code) \
  168424. ((cinfo)->err->msg_code = (code), \
  168425. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168426. #define ERREXIT1(cinfo,code,p1) \
  168427. ((cinfo)->err->msg_code = (code), \
  168428. (cinfo)->err->msg_parm.i[0] = (p1), \
  168429. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168430. #define ERREXIT2(cinfo,code,p1,p2) \
  168431. ((cinfo)->err->msg_code = (code), \
  168432. (cinfo)->err->msg_parm.i[0] = (p1), \
  168433. (cinfo)->err->msg_parm.i[1] = (p2), \
  168434. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168435. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168436. ((cinfo)->err->msg_code = (code), \
  168437. (cinfo)->err->msg_parm.i[0] = (p1), \
  168438. (cinfo)->err->msg_parm.i[1] = (p2), \
  168439. (cinfo)->err->msg_parm.i[2] = (p3), \
  168440. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168441. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168442. ((cinfo)->err->msg_code = (code), \
  168443. (cinfo)->err->msg_parm.i[0] = (p1), \
  168444. (cinfo)->err->msg_parm.i[1] = (p2), \
  168445. (cinfo)->err->msg_parm.i[2] = (p3), \
  168446. (cinfo)->err->msg_parm.i[3] = (p4), \
  168447. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168448. #define ERREXITS(cinfo,code,str) \
  168449. ((cinfo)->err->msg_code = (code), \
  168450. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168451. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168452. #define MAKESTMT(stuff) do { stuff } while (0)
  168453. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168454. #define WARNMS(cinfo,code) \
  168455. ((cinfo)->err->msg_code = (code), \
  168456. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168457. #define WARNMS1(cinfo,code,p1) \
  168458. ((cinfo)->err->msg_code = (code), \
  168459. (cinfo)->err->msg_parm.i[0] = (p1), \
  168460. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168461. #define WARNMS2(cinfo,code,p1,p2) \
  168462. ((cinfo)->err->msg_code = (code), \
  168463. (cinfo)->err->msg_parm.i[0] = (p1), \
  168464. (cinfo)->err->msg_parm.i[1] = (p2), \
  168465. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168466. /* Informational/debugging messages */
  168467. #define TRACEMS(cinfo,lvl,code) \
  168468. ((cinfo)->err->msg_code = (code), \
  168469. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168470. #define TRACEMS1(cinfo,lvl,code,p1) \
  168471. ((cinfo)->err->msg_code = (code), \
  168472. (cinfo)->err->msg_parm.i[0] = (p1), \
  168473. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168474. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168475. ((cinfo)->err->msg_code = (code), \
  168476. (cinfo)->err->msg_parm.i[0] = (p1), \
  168477. (cinfo)->err->msg_parm.i[1] = (p2), \
  168478. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168479. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168480. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168481. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168482. (cinfo)->err->msg_code = (code); \
  168483. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168484. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168485. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168486. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168487. (cinfo)->err->msg_code = (code); \
  168488. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168489. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168490. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168491. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168492. _mp[4] = (p5); \
  168493. (cinfo)->err->msg_code = (code); \
  168494. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168495. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168496. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168497. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168498. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168499. (cinfo)->err->msg_code = (code); \
  168500. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168501. #define TRACEMSS(cinfo,lvl,code,str) \
  168502. ((cinfo)->err->msg_code = (code), \
  168503. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168504. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168505. #endif /* JERROR_H */
  168506. /*** End of inlined file: jerror.h ***/
  168507. /* Expanded data source object for stdio input */
  168508. typedef struct {
  168509. struct jpeg_source_mgr pub; /* public fields */
  168510. FILE * infile; /* source stream */
  168511. JOCTET * buffer; /* start of buffer */
  168512. boolean start_of_file; /* have we gotten any data yet? */
  168513. } my_source_mgr;
  168514. typedef my_source_mgr * my_src_ptr;
  168515. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168516. /*
  168517. * Initialize source --- called by jpeg_read_header
  168518. * before any data is actually read.
  168519. */
  168520. METHODDEF(void)
  168521. init_source (j_decompress_ptr cinfo)
  168522. {
  168523. my_src_ptr src = (my_src_ptr) cinfo->src;
  168524. /* We reset the empty-input-file flag for each image,
  168525. * but we don't clear the input buffer.
  168526. * This is correct behavior for reading a series of images from one source.
  168527. */
  168528. src->start_of_file = TRUE;
  168529. }
  168530. /*
  168531. * Fill the input buffer --- called whenever buffer is emptied.
  168532. *
  168533. * In typical applications, this should read fresh data into the buffer
  168534. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168535. * reset the pointer & count to the start of the buffer, and return TRUE
  168536. * indicating that the buffer has been reloaded. It is not necessary to
  168537. * fill the buffer entirely, only to obtain at least one more byte.
  168538. *
  168539. * There is no such thing as an EOF return. If the end of the file has been
  168540. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168541. * the buffer. In most cases, generating a warning message and inserting a
  168542. * fake EOI marker is the best course of action --- this will allow the
  168543. * decompressor to output however much of the image is there. However,
  168544. * the resulting error message is misleading if the real problem is an empty
  168545. * input file, so we handle that case specially.
  168546. *
  168547. * In applications that need to be able to suspend compression due to input
  168548. * not being available yet, a FALSE return indicates that no more data can be
  168549. * obtained right now, but more may be forthcoming later. In this situation,
  168550. * the decompressor will return to its caller (with an indication of the
  168551. * number of scanlines it has read, if any). The application should resume
  168552. * decompression after it has loaded more data into the input buffer. Note
  168553. * that there are substantial restrictions on the use of suspension --- see
  168554. * the documentation.
  168555. *
  168556. * When suspending, the decompressor will back up to a convenient restart point
  168557. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168558. * indicate where the restart point will be if the current call returns FALSE.
  168559. * Data beyond this point must be rescanned after resumption, so move it to
  168560. * the front of the buffer rather than discarding it.
  168561. */
  168562. METHODDEF(boolean)
  168563. fill_input_buffer (j_decompress_ptr cinfo)
  168564. {
  168565. my_src_ptr src = (my_src_ptr) cinfo->src;
  168566. size_t nbytes;
  168567. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168568. if (nbytes <= 0) {
  168569. if (src->start_of_file) /* Treat empty input file as fatal error */
  168570. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168571. WARNMS(cinfo, JWRN_JPEG_EOF);
  168572. /* Insert a fake EOI marker */
  168573. src->buffer[0] = (JOCTET) 0xFF;
  168574. src->buffer[1] = (JOCTET) JPEG_EOI;
  168575. nbytes = 2;
  168576. }
  168577. src->pub.next_input_byte = src->buffer;
  168578. src->pub.bytes_in_buffer = nbytes;
  168579. src->start_of_file = FALSE;
  168580. return TRUE;
  168581. }
  168582. /*
  168583. * Skip data --- used to skip over a potentially large amount of
  168584. * uninteresting data (such as an APPn marker).
  168585. *
  168586. * Writers of suspendable-input applications must note that skip_input_data
  168587. * is not granted the right to give a suspension return. If the skip extends
  168588. * beyond the data currently in the buffer, the buffer can be marked empty so
  168589. * that the next read will cause a fill_input_buffer call that can suspend.
  168590. * Arranging for additional bytes to be discarded before reloading the input
  168591. * buffer is the application writer's problem.
  168592. */
  168593. METHODDEF(void)
  168594. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168595. {
  168596. my_src_ptr src = (my_src_ptr) cinfo->src;
  168597. /* Just a dumb implementation for now. Could use fseek() except
  168598. * it doesn't work on pipes. Not clear that being smart is worth
  168599. * any trouble anyway --- large skips are infrequent.
  168600. */
  168601. if (num_bytes > 0) {
  168602. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168603. num_bytes -= (long) src->pub.bytes_in_buffer;
  168604. (void) fill_input_buffer(cinfo);
  168605. /* note we assume that fill_input_buffer will never return FALSE,
  168606. * so suspension need not be handled.
  168607. */
  168608. }
  168609. src->pub.next_input_byte += (size_t) num_bytes;
  168610. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168611. }
  168612. }
  168613. /*
  168614. * An additional method that can be provided by data source modules is the
  168615. * resync_to_restart method for error recovery in the presence of RST markers.
  168616. * For the moment, this source module just uses the default resync method
  168617. * provided by the JPEG library. That method assumes that no backtracking
  168618. * is possible.
  168619. */
  168620. /*
  168621. * Terminate source --- called by jpeg_finish_decompress
  168622. * after all data has been read. Often a no-op.
  168623. *
  168624. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168625. * application must deal with any cleanup that should happen even
  168626. * for error exit.
  168627. */
  168628. METHODDEF(void)
  168629. term_source (j_decompress_ptr)
  168630. {
  168631. /* no work necessary here */
  168632. }
  168633. /*
  168634. * Prepare for input from a stdio stream.
  168635. * The caller must have already opened the stream, and is responsible
  168636. * for closing it after finishing decompression.
  168637. */
  168638. GLOBAL(void)
  168639. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168640. {
  168641. my_src_ptr src;
  168642. /* The source object and input buffer are made permanent so that a series
  168643. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168644. * only before the first one. (If we discarded the buffer at the end of
  168645. * one image, we'd likely lose the start of the next one.)
  168646. * This makes it unsafe to use this manager and a different source
  168647. * manager serially with the same JPEG object. Caveat programmer.
  168648. */
  168649. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168650. cinfo->src = (struct jpeg_source_mgr *)
  168651. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168652. SIZEOF(my_source_mgr));
  168653. src = (my_src_ptr) cinfo->src;
  168654. src->buffer = (JOCTET *)
  168655. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168656. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168657. }
  168658. src = (my_src_ptr) cinfo->src;
  168659. src->pub.init_source = init_source;
  168660. src->pub.fill_input_buffer = fill_input_buffer;
  168661. src->pub.skip_input_data = skip_input_data;
  168662. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168663. src->pub.term_source = term_source;
  168664. src->infile = infile;
  168665. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168666. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168667. }
  168668. /*** End of inlined file: jdatasrc.c ***/
  168669. /*** Start of inlined file: jdcoefct.c ***/
  168670. #define JPEG_INTERNALS
  168671. /* Block smoothing is only applicable for progressive JPEG, so: */
  168672. #ifndef D_PROGRESSIVE_SUPPORTED
  168673. #undef BLOCK_SMOOTHING_SUPPORTED
  168674. #endif
  168675. /* Private buffer controller object */
  168676. typedef struct {
  168677. struct jpeg_d_coef_controller pub; /* public fields */
  168678. /* These variables keep track of the current location of the input side. */
  168679. /* cinfo->input_iMCU_row is also used for this. */
  168680. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168681. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168682. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168683. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168684. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168685. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168686. * and let the entropy decoder write into that workspace each time.
  168687. * (On 80x86, the workspace is FAR even though it's not really very big;
  168688. * this is to keep the module interfaces unchanged when a large coefficient
  168689. * buffer is necessary.)
  168690. * In multi-pass modes, this array points to the current MCU's blocks
  168691. * within the virtual arrays; it is used only by the input side.
  168692. */
  168693. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168694. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168695. /* In multi-pass modes, we need a virtual block array for each component. */
  168696. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168697. #endif
  168698. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168699. /* When doing block smoothing, we latch coefficient Al values here */
  168700. int * coef_bits_latch;
  168701. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168702. #endif
  168703. } my_coef_controller3;
  168704. typedef my_coef_controller3 * my_coef_ptr3;
  168705. /* Forward declarations */
  168706. METHODDEF(int) decompress_onepass
  168707. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168708. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168709. METHODDEF(int) decompress_data
  168710. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168711. #endif
  168712. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168713. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168714. METHODDEF(int) decompress_smooth_data
  168715. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168716. #endif
  168717. LOCAL(void)
  168718. start_iMCU_row3 (j_decompress_ptr cinfo)
  168719. /* Reset within-iMCU-row counters for a new row (input side) */
  168720. {
  168721. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168722. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168723. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168724. * But at the bottom of the image, process only what's left.
  168725. */
  168726. if (cinfo->comps_in_scan > 1) {
  168727. coef->MCU_rows_per_iMCU_row = 1;
  168728. } else {
  168729. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168730. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168731. else
  168732. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168733. }
  168734. coef->MCU_ctr = 0;
  168735. coef->MCU_vert_offset = 0;
  168736. }
  168737. /*
  168738. * Initialize for an input processing pass.
  168739. */
  168740. METHODDEF(void)
  168741. start_input_pass (j_decompress_ptr cinfo)
  168742. {
  168743. cinfo->input_iMCU_row = 0;
  168744. start_iMCU_row3(cinfo);
  168745. }
  168746. /*
  168747. * Initialize for an output processing pass.
  168748. */
  168749. METHODDEF(void)
  168750. start_output_pass (j_decompress_ptr cinfo)
  168751. {
  168752. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168753. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168754. /* If multipass, check to see whether to use block smoothing on this pass */
  168755. if (coef->pub.coef_arrays != NULL) {
  168756. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168757. coef->pub.decompress_data = decompress_smooth_data;
  168758. else
  168759. coef->pub.decompress_data = decompress_data;
  168760. }
  168761. #endif
  168762. cinfo->output_iMCU_row = 0;
  168763. }
  168764. /*
  168765. * Decompress and return some data in the single-pass case.
  168766. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168767. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168768. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168769. *
  168770. * NB: output_buf contains a plane for each component in image,
  168771. * which we index according to the component's SOF position.
  168772. */
  168773. METHODDEF(int)
  168774. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168775. {
  168776. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168777. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168778. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168779. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168780. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168781. JSAMPARRAY output_ptr;
  168782. JDIMENSION start_col, output_col;
  168783. jpeg_component_info *compptr;
  168784. inverse_DCT_method_ptr inverse_DCT;
  168785. /* Loop to process as much as one whole iMCU row */
  168786. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168787. yoffset++) {
  168788. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168789. MCU_col_num++) {
  168790. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168791. jzero_far((void FAR *) coef->MCU_buffer[0],
  168792. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168793. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168794. /* Suspension forced; update state counters and exit */
  168795. coef->MCU_vert_offset = yoffset;
  168796. coef->MCU_ctr = MCU_col_num;
  168797. return JPEG_SUSPENDED;
  168798. }
  168799. /* Determine where data should go in output_buf and do the IDCT thing.
  168800. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168801. * incremented past them!). Note the inner loop relies on having
  168802. * allocated the MCU_buffer[] blocks sequentially.
  168803. */
  168804. blkn = 0; /* index of current DCT block within MCU */
  168805. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168806. compptr = cinfo->cur_comp_info[ci];
  168807. /* Don't bother to IDCT an uninteresting component. */
  168808. if (! compptr->component_needed) {
  168809. blkn += compptr->MCU_blocks;
  168810. continue;
  168811. }
  168812. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168813. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168814. : compptr->last_col_width;
  168815. output_ptr = output_buf[compptr->component_index] +
  168816. yoffset * compptr->DCT_scaled_size;
  168817. start_col = MCU_col_num * compptr->MCU_sample_width;
  168818. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168819. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168820. yoffset+yindex < compptr->last_row_height) {
  168821. output_col = start_col;
  168822. for (xindex = 0; xindex < useful_width; xindex++) {
  168823. (*inverse_DCT) (cinfo, compptr,
  168824. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168825. output_ptr, output_col);
  168826. output_col += compptr->DCT_scaled_size;
  168827. }
  168828. }
  168829. blkn += compptr->MCU_width;
  168830. output_ptr += compptr->DCT_scaled_size;
  168831. }
  168832. }
  168833. }
  168834. /* Completed an MCU row, but perhaps not an iMCU row */
  168835. coef->MCU_ctr = 0;
  168836. }
  168837. /* Completed the iMCU row, advance counters for next one */
  168838. cinfo->output_iMCU_row++;
  168839. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168840. start_iMCU_row3(cinfo);
  168841. return JPEG_ROW_COMPLETED;
  168842. }
  168843. /* Completed the scan */
  168844. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168845. return JPEG_SCAN_COMPLETED;
  168846. }
  168847. /*
  168848. * Dummy consume-input routine for single-pass operation.
  168849. */
  168850. METHODDEF(int)
  168851. dummy_consume_data (j_decompress_ptr)
  168852. {
  168853. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168854. }
  168855. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168856. /*
  168857. * Consume input data and store it in the full-image coefficient buffer.
  168858. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168859. * ie, v_samp_factor block rows for each component in the scan.
  168860. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168861. */
  168862. METHODDEF(int)
  168863. consume_data (j_decompress_ptr cinfo)
  168864. {
  168865. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168866. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168867. int blkn, ci, xindex, yindex, yoffset;
  168868. JDIMENSION start_col;
  168869. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168870. JBLOCKROW buffer_ptr;
  168871. jpeg_component_info *compptr;
  168872. /* Align the virtual buffers for the components used in this scan. */
  168873. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168874. compptr = cinfo->cur_comp_info[ci];
  168875. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168876. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168877. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168878. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168879. /* Note: entropy decoder expects buffer to be zeroed,
  168880. * but this is handled automatically by the memory manager
  168881. * because we requested a pre-zeroed array.
  168882. */
  168883. }
  168884. /* Loop to process one whole iMCU row */
  168885. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168886. yoffset++) {
  168887. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168888. MCU_col_num++) {
  168889. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168890. blkn = 0; /* index of current DCT block within MCU */
  168891. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168892. compptr = cinfo->cur_comp_info[ci];
  168893. start_col = MCU_col_num * compptr->MCU_width;
  168894. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168895. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168896. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168897. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168898. }
  168899. }
  168900. }
  168901. /* Try to fetch the MCU. */
  168902. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168903. /* Suspension forced; update state counters and exit */
  168904. coef->MCU_vert_offset = yoffset;
  168905. coef->MCU_ctr = MCU_col_num;
  168906. return JPEG_SUSPENDED;
  168907. }
  168908. }
  168909. /* Completed an MCU row, but perhaps not an iMCU row */
  168910. coef->MCU_ctr = 0;
  168911. }
  168912. /* Completed the iMCU row, advance counters for next one */
  168913. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168914. start_iMCU_row3(cinfo);
  168915. return JPEG_ROW_COMPLETED;
  168916. }
  168917. /* Completed the scan */
  168918. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168919. return JPEG_SCAN_COMPLETED;
  168920. }
  168921. /*
  168922. * Decompress and return some data in the multi-pass case.
  168923. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168924. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168925. *
  168926. * NB: output_buf contains a plane for each component in image.
  168927. */
  168928. METHODDEF(int)
  168929. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168930. {
  168931. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168932. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168933. JDIMENSION block_num;
  168934. int ci, block_row, block_rows;
  168935. JBLOCKARRAY buffer;
  168936. JBLOCKROW buffer_ptr;
  168937. JSAMPARRAY output_ptr;
  168938. JDIMENSION output_col;
  168939. jpeg_component_info *compptr;
  168940. inverse_DCT_method_ptr inverse_DCT;
  168941. /* Force some input to be done if we are getting ahead of the input. */
  168942. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168943. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168944. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168945. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168946. return JPEG_SUSPENDED;
  168947. }
  168948. /* OK, output from the virtual arrays. */
  168949. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168950. ci++, compptr++) {
  168951. /* Don't bother to IDCT an uninteresting component. */
  168952. if (! compptr->component_needed)
  168953. continue;
  168954. /* Align the virtual buffer for this component. */
  168955. buffer = (*cinfo->mem->access_virt_barray)
  168956. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168957. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168958. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168959. /* Count non-dummy DCT block rows in this iMCU row. */
  168960. if (cinfo->output_iMCU_row < last_iMCU_row)
  168961. block_rows = compptr->v_samp_factor;
  168962. else {
  168963. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168964. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168965. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168966. }
  168967. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168968. output_ptr = output_buf[ci];
  168969. /* Loop over all DCT blocks to be processed. */
  168970. for (block_row = 0; block_row < block_rows; block_row++) {
  168971. buffer_ptr = buffer[block_row];
  168972. output_col = 0;
  168973. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168974. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168975. output_ptr, output_col);
  168976. buffer_ptr++;
  168977. output_col += compptr->DCT_scaled_size;
  168978. }
  168979. output_ptr += compptr->DCT_scaled_size;
  168980. }
  168981. }
  168982. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168983. return JPEG_ROW_COMPLETED;
  168984. return JPEG_SCAN_COMPLETED;
  168985. }
  168986. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168987. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168988. /*
  168989. * This code applies interblock smoothing as described by section K.8
  168990. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168991. * the DC values of a DCT block and its 8 neighboring blocks.
  168992. * We apply smoothing only for progressive JPEG decoding, and only if
  168993. * the coefficients it can estimate are not yet known to full precision.
  168994. */
  168995. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168996. #define Q01_POS 1
  168997. #define Q10_POS 8
  168998. #define Q20_POS 16
  168999. #define Q11_POS 9
  169000. #define Q02_POS 2
  169001. /*
  169002. * Determine whether block smoothing is applicable and safe.
  169003. * We also latch the current states of the coef_bits[] entries for the
  169004. * AC coefficients; otherwise, if the input side of the decompressor
  169005. * advances into a new scan, we might think the coefficients are known
  169006. * more accurately than they really are.
  169007. */
  169008. LOCAL(boolean)
  169009. smoothing_ok (j_decompress_ptr cinfo)
  169010. {
  169011. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169012. boolean smoothing_useful = FALSE;
  169013. int ci, coefi;
  169014. jpeg_component_info *compptr;
  169015. JQUANT_TBL * qtable;
  169016. int * coef_bits;
  169017. int * coef_bits_latch;
  169018. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169019. return FALSE;
  169020. /* Allocate latch area if not already done */
  169021. if (coef->coef_bits_latch == NULL)
  169022. coef->coef_bits_latch = (int *)
  169023. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169024. cinfo->num_components *
  169025. (SAVED_COEFS * SIZEOF(int)));
  169026. coef_bits_latch = coef->coef_bits_latch;
  169027. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169028. ci++, compptr++) {
  169029. /* All components' quantization values must already be latched. */
  169030. if ((qtable = compptr->quant_table) == NULL)
  169031. return FALSE;
  169032. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169033. if (qtable->quantval[0] == 0 ||
  169034. qtable->quantval[Q01_POS] == 0 ||
  169035. qtable->quantval[Q10_POS] == 0 ||
  169036. qtable->quantval[Q20_POS] == 0 ||
  169037. qtable->quantval[Q11_POS] == 0 ||
  169038. qtable->quantval[Q02_POS] == 0)
  169039. return FALSE;
  169040. /* DC values must be at least partly known for all components. */
  169041. coef_bits = cinfo->coef_bits[ci];
  169042. if (coef_bits[0] < 0)
  169043. return FALSE;
  169044. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169045. for (coefi = 1; coefi <= 5; coefi++) {
  169046. coef_bits_latch[coefi] = coef_bits[coefi];
  169047. if (coef_bits[coefi] != 0)
  169048. smoothing_useful = TRUE;
  169049. }
  169050. coef_bits_latch += SAVED_COEFS;
  169051. }
  169052. return smoothing_useful;
  169053. }
  169054. /*
  169055. * Variant of decompress_data for use when doing block smoothing.
  169056. */
  169057. METHODDEF(int)
  169058. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169059. {
  169060. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169061. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169062. JDIMENSION block_num, last_block_column;
  169063. int ci, block_row, block_rows, access_rows;
  169064. JBLOCKARRAY buffer;
  169065. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169066. JSAMPARRAY output_ptr;
  169067. JDIMENSION output_col;
  169068. jpeg_component_info *compptr;
  169069. inverse_DCT_method_ptr inverse_DCT;
  169070. boolean first_row, last_row;
  169071. JBLOCK workspace;
  169072. int *coef_bits;
  169073. JQUANT_TBL *quanttbl;
  169074. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169075. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169076. int Al, pred;
  169077. /* Force some input to be done if we are getting ahead of the input. */
  169078. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169079. ! cinfo->inputctl->eoi_reached) {
  169080. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169081. /* If input is working on current scan, we ordinarily want it to
  169082. * have completed the current row. But if input scan is DC,
  169083. * we want it to keep one row ahead so that next block row's DC
  169084. * values are up to date.
  169085. */
  169086. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169087. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169088. break;
  169089. }
  169090. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169091. return JPEG_SUSPENDED;
  169092. }
  169093. /* OK, output from the virtual arrays. */
  169094. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169095. ci++, compptr++) {
  169096. /* Don't bother to IDCT an uninteresting component. */
  169097. if (! compptr->component_needed)
  169098. continue;
  169099. /* Count non-dummy DCT block rows in this iMCU row. */
  169100. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169101. block_rows = compptr->v_samp_factor;
  169102. access_rows = block_rows * 2; /* this and next iMCU row */
  169103. last_row = FALSE;
  169104. } else {
  169105. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169106. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169107. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169108. access_rows = block_rows; /* this iMCU row only */
  169109. last_row = TRUE;
  169110. }
  169111. /* Align the virtual buffer for this component. */
  169112. if (cinfo->output_iMCU_row > 0) {
  169113. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169114. buffer = (*cinfo->mem->access_virt_barray)
  169115. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169116. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169117. (JDIMENSION) access_rows, FALSE);
  169118. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169119. first_row = FALSE;
  169120. } else {
  169121. buffer = (*cinfo->mem->access_virt_barray)
  169122. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169123. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169124. first_row = TRUE;
  169125. }
  169126. /* Fetch component-dependent info */
  169127. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169128. quanttbl = compptr->quant_table;
  169129. Q00 = quanttbl->quantval[0];
  169130. Q01 = quanttbl->quantval[Q01_POS];
  169131. Q10 = quanttbl->quantval[Q10_POS];
  169132. Q20 = quanttbl->quantval[Q20_POS];
  169133. Q11 = quanttbl->quantval[Q11_POS];
  169134. Q02 = quanttbl->quantval[Q02_POS];
  169135. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169136. output_ptr = output_buf[ci];
  169137. /* Loop over all DCT blocks to be processed. */
  169138. for (block_row = 0; block_row < block_rows; block_row++) {
  169139. buffer_ptr = buffer[block_row];
  169140. if (first_row && block_row == 0)
  169141. prev_block_row = buffer_ptr;
  169142. else
  169143. prev_block_row = buffer[block_row-1];
  169144. if (last_row && block_row == block_rows-1)
  169145. next_block_row = buffer_ptr;
  169146. else
  169147. next_block_row = buffer[block_row+1];
  169148. /* We fetch the surrounding DC values using a sliding-register approach.
  169149. * Initialize all nine here so as to do the right thing on narrow pics.
  169150. */
  169151. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169152. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169153. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169154. output_col = 0;
  169155. last_block_column = compptr->width_in_blocks - 1;
  169156. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169157. /* Fetch current DCT block into workspace so we can modify it. */
  169158. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169159. /* Update DC values */
  169160. if (block_num < last_block_column) {
  169161. DC3 = (int) prev_block_row[1][0];
  169162. DC6 = (int) buffer_ptr[1][0];
  169163. DC9 = (int) next_block_row[1][0];
  169164. }
  169165. /* Compute coefficient estimates per K.8.
  169166. * An estimate is applied only if coefficient is still zero,
  169167. * and is not known to be fully accurate.
  169168. */
  169169. /* AC01 */
  169170. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169171. num = 36 * Q00 * (DC4 - DC6);
  169172. if (num >= 0) {
  169173. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169174. if (Al > 0 && pred >= (1<<Al))
  169175. pred = (1<<Al)-1;
  169176. } else {
  169177. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169178. if (Al > 0 && pred >= (1<<Al))
  169179. pred = (1<<Al)-1;
  169180. pred = -pred;
  169181. }
  169182. workspace[1] = (JCOEF) pred;
  169183. }
  169184. /* AC10 */
  169185. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169186. num = 36 * Q00 * (DC2 - DC8);
  169187. if (num >= 0) {
  169188. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169189. if (Al > 0 && pred >= (1<<Al))
  169190. pred = (1<<Al)-1;
  169191. } else {
  169192. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169193. if (Al > 0 && pred >= (1<<Al))
  169194. pred = (1<<Al)-1;
  169195. pred = -pred;
  169196. }
  169197. workspace[8] = (JCOEF) pred;
  169198. }
  169199. /* AC20 */
  169200. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169201. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169202. if (num >= 0) {
  169203. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169204. if (Al > 0 && pred >= (1<<Al))
  169205. pred = (1<<Al)-1;
  169206. } else {
  169207. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169208. if (Al > 0 && pred >= (1<<Al))
  169209. pred = (1<<Al)-1;
  169210. pred = -pred;
  169211. }
  169212. workspace[16] = (JCOEF) pred;
  169213. }
  169214. /* AC11 */
  169215. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169216. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169217. if (num >= 0) {
  169218. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169219. if (Al > 0 && pred >= (1<<Al))
  169220. pred = (1<<Al)-1;
  169221. } else {
  169222. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169223. if (Al > 0 && pred >= (1<<Al))
  169224. pred = (1<<Al)-1;
  169225. pred = -pred;
  169226. }
  169227. workspace[9] = (JCOEF) pred;
  169228. }
  169229. /* AC02 */
  169230. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169231. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169232. if (num >= 0) {
  169233. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169234. if (Al > 0 && pred >= (1<<Al))
  169235. pred = (1<<Al)-1;
  169236. } else {
  169237. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169238. if (Al > 0 && pred >= (1<<Al))
  169239. pred = (1<<Al)-1;
  169240. pred = -pred;
  169241. }
  169242. workspace[2] = (JCOEF) pred;
  169243. }
  169244. /* OK, do the IDCT */
  169245. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169246. output_ptr, output_col);
  169247. /* Advance for next column */
  169248. DC1 = DC2; DC2 = DC3;
  169249. DC4 = DC5; DC5 = DC6;
  169250. DC7 = DC8; DC8 = DC9;
  169251. buffer_ptr++, prev_block_row++, next_block_row++;
  169252. output_col += compptr->DCT_scaled_size;
  169253. }
  169254. output_ptr += compptr->DCT_scaled_size;
  169255. }
  169256. }
  169257. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169258. return JPEG_ROW_COMPLETED;
  169259. return JPEG_SCAN_COMPLETED;
  169260. }
  169261. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169262. /*
  169263. * Initialize coefficient buffer controller.
  169264. */
  169265. GLOBAL(void)
  169266. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169267. {
  169268. my_coef_ptr3 coef;
  169269. coef = (my_coef_ptr3)
  169270. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169271. SIZEOF(my_coef_controller3));
  169272. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169273. coef->pub.start_input_pass = start_input_pass;
  169274. coef->pub.start_output_pass = start_output_pass;
  169275. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169276. coef->coef_bits_latch = NULL;
  169277. #endif
  169278. /* Create the coefficient buffer. */
  169279. if (need_full_buffer) {
  169280. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169281. /* Allocate a full-image virtual array for each component, */
  169282. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169283. /* Note we ask for a pre-zeroed array. */
  169284. int ci, access_rows;
  169285. jpeg_component_info *compptr;
  169286. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169287. ci++, compptr++) {
  169288. access_rows = compptr->v_samp_factor;
  169289. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169290. /* If block smoothing could be used, need a bigger window */
  169291. if (cinfo->progressive_mode)
  169292. access_rows *= 3;
  169293. #endif
  169294. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169295. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169296. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169297. (long) compptr->h_samp_factor),
  169298. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169299. (long) compptr->v_samp_factor),
  169300. (JDIMENSION) access_rows);
  169301. }
  169302. coef->pub.consume_data = consume_data;
  169303. coef->pub.decompress_data = decompress_data;
  169304. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169305. #else
  169306. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169307. #endif
  169308. } else {
  169309. /* We only need a single-MCU buffer. */
  169310. JBLOCKROW buffer;
  169311. int i;
  169312. buffer = (JBLOCKROW)
  169313. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169314. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169315. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169316. coef->MCU_buffer[i] = buffer + i;
  169317. }
  169318. coef->pub.consume_data = dummy_consume_data;
  169319. coef->pub.decompress_data = decompress_onepass;
  169320. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169321. }
  169322. }
  169323. /*** End of inlined file: jdcoefct.c ***/
  169324. #undef FIX
  169325. /*** Start of inlined file: jdcolor.c ***/
  169326. #define JPEG_INTERNALS
  169327. /* Private subobject */
  169328. typedef struct {
  169329. struct jpeg_color_deconverter pub; /* public fields */
  169330. /* Private state for YCC->RGB conversion */
  169331. int * Cr_r_tab; /* => table for Cr to R conversion */
  169332. int * Cb_b_tab; /* => table for Cb to B conversion */
  169333. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169334. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169335. } my_color_deconverter2;
  169336. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169337. /**************** YCbCr -> RGB conversion: most common case **************/
  169338. /*
  169339. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169340. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169341. * The conversion equations to be implemented are therefore
  169342. * R = Y + 1.40200 * Cr
  169343. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169344. * B = Y + 1.77200 * Cb
  169345. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169346. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169347. *
  169348. * To avoid floating-point arithmetic, we represent the fractional constants
  169349. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169350. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169351. * Notice that Y, being an integral input, does not contribute any fraction
  169352. * so it need not participate in the rounding.
  169353. *
  169354. * For even more speed, we avoid doing any multiplications in the inner loop
  169355. * by precalculating the constants times Cb and Cr for all possible values.
  169356. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169357. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169358. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169359. * colorspace anyway.
  169360. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169361. * values for the G calculation are left scaled up, since we must add them
  169362. * together before rounding.
  169363. */
  169364. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169365. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169366. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169367. /*
  169368. * Initialize tables for YCC->RGB colorspace conversion.
  169369. */
  169370. LOCAL(void)
  169371. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169372. {
  169373. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169374. int i;
  169375. INT32 x;
  169376. SHIFT_TEMPS
  169377. cconvert->Cr_r_tab = (int *)
  169378. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169379. (MAXJSAMPLE+1) * SIZEOF(int));
  169380. cconvert->Cb_b_tab = (int *)
  169381. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169382. (MAXJSAMPLE+1) * SIZEOF(int));
  169383. cconvert->Cr_g_tab = (INT32 *)
  169384. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169385. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169386. cconvert->Cb_g_tab = (INT32 *)
  169387. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169388. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169389. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169390. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169391. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169392. /* Cr=>R value is nearest int to 1.40200 * x */
  169393. cconvert->Cr_r_tab[i] = (int)
  169394. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169395. /* Cb=>B value is nearest int to 1.77200 * x */
  169396. cconvert->Cb_b_tab[i] = (int)
  169397. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169398. /* Cr=>G value is scaled-up -0.71414 * x */
  169399. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169400. /* Cb=>G value is scaled-up -0.34414 * x */
  169401. /* We also add in ONE_HALF so that need not do it in inner loop */
  169402. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169403. }
  169404. }
  169405. /*
  169406. * Convert some rows of samples to the output colorspace.
  169407. *
  169408. * Note that we change from noninterleaved, one-plane-per-component format
  169409. * to interleaved-pixel format. The output buffer is therefore three times
  169410. * as wide as the input buffer.
  169411. * A starting row offset is provided only for the input buffer. The caller
  169412. * can easily adjust the passed output_buf value to accommodate any row
  169413. * offset required on that side.
  169414. */
  169415. METHODDEF(void)
  169416. ycc_rgb_convert (j_decompress_ptr cinfo,
  169417. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169418. JSAMPARRAY output_buf, int num_rows)
  169419. {
  169420. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169421. register int y, cb, cr;
  169422. register JSAMPROW outptr;
  169423. register JSAMPROW inptr0, inptr1, inptr2;
  169424. register JDIMENSION col;
  169425. JDIMENSION num_cols = cinfo->output_width;
  169426. /* copy these pointers into registers if possible */
  169427. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169428. register int * Crrtab = cconvert->Cr_r_tab;
  169429. register int * Cbbtab = cconvert->Cb_b_tab;
  169430. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169431. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169432. SHIFT_TEMPS
  169433. while (--num_rows >= 0) {
  169434. inptr0 = input_buf[0][input_row];
  169435. inptr1 = input_buf[1][input_row];
  169436. inptr2 = input_buf[2][input_row];
  169437. input_row++;
  169438. outptr = *output_buf++;
  169439. for (col = 0; col < num_cols; col++) {
  169440. y = GETJSAMPLE(inptr0[col]);
  169441. cb = GETJSAMPLE(inptr1[col]);
  169442. cr = GETJSAMPLE(inptr2[col]);
  169443. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169444. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169445. outptr[RGB_GREEN] = range_limit[y +
  169446. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169447. SCALEBITS))];
  169448. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169449. outptr += RGB_PIXELSIZE;
  169450. }
  169451. }
  169452. }
  169453. /**************** Cases other than YCbCr -> RGB **************/
  169454. /*
  169455. * Color conversion for no colorspace change: just copy the data,
  169456. * converting from separate-planes to interleaved representation.
  169457. */
  169458. METHODDEF(void)
  169459. null_convert2 (j_decompress_ptr cinfo,
  169460. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169461. JSAMPARRAY output_buf, int num_rows)
  169462. {
  169463. register JSAMPROW inptr, outptr;
  169464. register JDIMENSION count;
  169465. register int num_components = cinfo->num_components;
  169466. JDIMENSION num_cols = cinfo->output_width;
  169467. int ci;
  169468. while (--num_rows >= 0) {
  169469. for (ci = 0; ci < num_components; ci++) {
  169470. inptr = input_buf[ci][input_row];
  169471. outptr = output_buf[0] + ci;
  169472. for (count = num_cols; count > 0; count--) {
  169473. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169474. outptr += num_components;
  169475. }
  169476. }
  169477. input_row++;
  169478. output_buf++;
  169479. }
  169480. }
  169481. /*
  169482. * Color conversion for grayscale: just copy the data.
  169483. * This also works for YCbCr -> grayscale conversion, in which
  169484. * we just copy the Y (luminance) component and ignore chrominance.
  169485. */
  169486. METHODDEF(void)
  169487. grayscale_convert2 (j_decompress_ptr cinfo,
  169488. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169489. JSAMPARRAY output_buf, int num_rows)
  169490. {
  169491. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169492. num_rows, cinfo->output_width);
  169493. }
  169494. /*
  169495. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169496. * This is provided to support applications that don't want to cope
  169497. * with grayscale as a separate case.
  169498. */
  169499. METHODDEF(void)
  169500. gray_rgb_convert (j_decompress_ptr cinfo,
  169501. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169502. JSAMPARRAY output_buf, int num_rows)
  169503. {
  169504. register JSAMPROW inptr, outptr;
  169505. register JDIMENSION col;
  169506. JDIMENSION num_cols = cinfo->output_width;
  169507. while (--num_rows >= 0) {
  169508. inptr = input_buf[0][input_row++];
  169509. outptr = *output_buf++;
  169510. for (col = 0; col < num_cols; col++) {
  169511. /* We can dispense with GETJSAMPLE() here */
  169512. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169513. outptr += RGB_PIXELSIZE;
  169514. }
  169515. }
  169516. }
  169517. /*
  169518. * Adobe-style YCCK->CMYK conversion.
  169519. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169520. * conversion as above, while passing K (black) unchanged.
  169521. * We assume build_ycc_rgb_table has been called.
  169522. */
  169523. METHODDEF(void)
  169524. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169525. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169526. JSAMPARRAY output_buf, int num_rows)
  169527. {
  169528. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169529. register int y, cb, cr;
  169530. register JSAMPROW outptr;
  169531. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169532. register JDIMENSION col;
  169533. JDIMENSION num_cols = cinfo->output_width;
  169534. /* copy these pointers into registers if possible */
  169535. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169536. register int * Crrtab = cconvert->Cr_r_tab;
  169537. register int * Cbbtab = cconvert->Cb_b_tab;
  169538. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169539. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169540. SHIFT_TEMPS
  169541. while (--num_rows >= 0) {
  169542. inptr0 = input_buf[0][input_row];
  169543. inptr1 = input_buf[1][input_row];
  169544. inptr2 = input_buf[2][input_row];
  169545. inptr3 = input_buf[3][input_row];
  169546. input_row++;
  169547. outptr = *output_buf++;
  169548. for (col = 0; col < num_cols; col++) {
  169549. y = GETJSAMPLE(inptr0[col]);
  169550. cb = GETJSAMPLE(inptr1[col]);
  169551. cr = GETJSAMPLE(inptr2[col]);
  169552. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169553. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169554. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169555. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169556. SCALEBITS)))];
  169557. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169558. /* K passes through unchanged */
  169559. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169560. outptr += 4;
  169561. }
  169562. }
  169563. }
  169564. /*
  169565. * Empty method for start_pass.
  169566. */
  169567. METHODDEF(void)
  169568. start_pass_dcolor (j_decompress_ptr)
  169569. {
  169570. /* no work needed */
  169571. }
  169572. /*
  169573. * Module initialization routine for output colorspace conversion.
  169574. */
  169575. GLOBAL(void)
  169576. jinit_color_deconverter (j_decompress_ptr cinfo)
  169577. {
  169578. my_cconvert_ptr2 cconvert;
  169579. int ci;
  169580. cconvert = (my_cconvert_ptr2)
  169581. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169582. SIZEOF(my_color_deconverter2));
  169583. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169584. cconvert->pub.start_pass = start_pass_dcolor;
  169585. /* Make sure num_components agrees with jpeg_color_space */
  169586. switch (cinfo->jpeg_color_space) {
  169587. case JCS_GRAYSCALE:
  169588. if (cinfo->num_components != 1)
  169589. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169590. break;
  169591. case JCS_RGB:
  169592. case JCS_YCbCr:
  169593. if (cinfo->num_components != 3)
  169594. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169595. break;
  169596. case JCS_CMYK:
  169597. case JCS_YCCK:
  169598. if (cinfo->num_components != 4)
  169599. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169600. break;
  169601. default: /* JCS_UNKNOWN can be anything */
  169602. if (cinfo->num_components < 1)
  169603. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169604. break;
  169605. }
  169606. /* Set out_color_components and conversion method based on requested space.
  169607. * Also clear the component_needed flags for any unused components,
  169608. * so that earlier pipeline stages can avoid useless computation.
  169609. */
  169610. switch (cinfo->out_color_space) {
  169611. case JCS_GRAYSCALE:
  169612. cinfo->out_color_components = 1;
  169613. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169614. cinfo->jpeg_color_space == JCS_YCbCr) {
  169615. cconvert->pub.color_convert = grayscale_convert2;
  169616. /* For color->grayscale conversion, only the Y (0) component is needed */
  169617. for (ci = 1; ci < cinfo->num_components; ci++)
  169618. cinfo->comp_info[ci].component_needed = FALSE;
  169619. } else
  169620. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169621. break;
  169622. case JCS_RGB:
  169623. cinfo->out_color_components = RGB_PIXELSIZE;
  169624. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169625. cconvert->pub.color_convert = ycc_rgb_convert;
  169626. build_ycc_rgb_table(cinfo);
  169627. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169628. cconvert->pub.color_convert = gray_rgb_convert;
  169629. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169630. cconvert->pub.color_convert = null_convert2;
  169631. } else
  169632. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169633. break;
  169634. case JCS_CMYK:
  169635. cinfo->out_color_components = 4;
  169636. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169637. cconvert->pub.color_convert = ycck_cmyk_convert;
  169638. build_ycc_rgb_table(cinfo);
  169639. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169640. cconvert->pub.color_convert = null_convert2;
  169641. } else
  169642. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169643. break;
  169644. default:
  169645. /* Permit null conversion to same output space */
  169646. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169647. cinfo->out_color_components = cinfo->num_components;
  169648. cconvert->pub.color_convert = null_convert2;
  169649. } else /* unsupported non-null conversion */
  169650. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169651. break;
  169652. }
  169653. if (cinfo->quantize_colors)
  169654. cinfo->output_components = 1; /* single colormapped output component */
  169655. else
  169656. cinfo->output_components = cinfo->out_color_components;
  169657. }
  169658. /*** End of inlined file: jdcolor.c ***/
  169659. #undef FIX
  169660. /*** Start of inlined file: jddctmgr.c ***/
  169661. #define JPEG_INTERNALS
  169662. /*
  169663. * The decompressor input side (jdinput.c) saves away the appropriate
  169664. * quantization table for each component at the start of the first scan
  169665. * involving that component. (This is necessary in order to correctly
  169666. * decode files that reuse Q-table slots.)
  169667. * When we are ready to make an output pass, the saved Q-table is converted
  169668. * to a multiplier table that will actually be used by the IDCT routine.
  169669. * The multiplier table contents are IDCT-method-dependent. To support
  169670. * application changes in IDCT method between scans, we can remake the
  169671. * multiplier tables if necessary.
  169672. * In buffered-image mode, the first output pass may occur before any data
  169673. * has been seen for some components, and thus before their Q-tables have
  169674. * been saved away. To handle this case, multiplier tables are preset
  169675. * to zeroes; the result of the IDCT will be a neutral gray level.
  169676. */
  169677. /* Private subobject for this module */
  169678. typedef struct {
  169679. struct jpeg_inverse_dct pub; /* public fields */
  169680. /* This array contains the IDCT method code that each multiplier table
  169681. * is currently set up for, or -1 if it's not yet set up.
  169682. * The actual multiplier tables are pointed to by dct_table in the
  169683. * per-component comp_info structures.
  169684. */
  169685. int cur_method[MAX_COMPONENTS];
  169686. } my_idct_controller;
  169687. typedef my_idct_controller * my_idct_ptr;
  169688. /* Allocated multiplier tables: big enough for any supported variant */
  169689. typedef union {
  169690. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169691. #ifdef DCT_IFAST_SUPPORTED
  169692. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169693. #endif
  169694. #ifdef DCT_FLOAT_SUPPORTED
  169695. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169696. #endif
  169697. } multiplier_table;
  169698. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169699. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169700. */
  169701. #ifdef DCT_ISLOW_SUPPORTED
  169702. #define PROVIDE_ISLOW_TABLES
  169703. #else
  169704. #ifdef IDCT_SCALING_SUPPORTED
  169705. #define PROVIDE_ISLOW_TABLES
  169706. #endif
  169707. #endif
  169708. /*
  169709. * Prepare for an output pass.
  169710. * Here we select the proper IDCT routine for each component and build
  169711. * a matching multiplier table.
  169712. */
  169713. METHODDEF(void)
  169714. start_pass (j_decompress_ptr cinfo)
  169715. {
  169716. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169717. int ci, i;
  169718. jpeg_component_info *compptr;
  169719. int method = 0;
  169720. inverse_DCT_method_ptr method_ptr = NULL;
  169721. JQUANT_TBL * qtbl;
  169722. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169723. ci++, compptr++) {
  169724. /* Select the proper IDCT routine for this component's scaling */
  169725. switch (compptr->DCT_scaled_size) {
  169726. #ifdef IDCT_SCALING_SUPPORTED
  169727. case 1:
  169728. method_ptr = jpeg_idct_1x1;
  169729. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169730. break;
  169731. case 2:
  169732. method_ptr = jpeg_idct_2x2;
  169733. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169734. break;
  169735. case 4:
  169736. method_ptr = jpeg_idct_4x4;
  169737. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169738. break;
  169739. #endif
  169740. case DCTSIZE:
  169741. switch (cinfo->dct_method) {
  169742. #ifdef DCT_ISLOW_SUPPORTED
  169743. case JDCT_ISLOW:
  169744. method_ptr = jpeg_idct_islow;
  169745. method = JDCT_ISLOW;
  169746. break;
  169747. #endif
  169748. #ifdef DCT_IFAST_SUPPORTED
  169749. case JDCT_IFAST:
  169750. method_ptr = jpeg_idct_ifast;
  169751. method = JDCT_IFAST;
  169752. break;
  169753. #endif
  169754. #ifdef DCT_FLOAT_SUPPORTED
  169755. case JDCT_FLOAT:
  169756. method_ptr = jpeg_idct_float;
  169757. method = JDCT_FLOAT;
  169758. break;
  169759. #endif
  169760. default:
  169761. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169762. break;
  169763. }
  169764. break;
  169765. default:
  169766. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169767. break;
  169768. }
  169769. idct->pub.inverse_DCT[ci] = method_ptr;
  169770. /* Create multiplier table from quant table.
  169771. * However, we can skip this if the component is uninteresting
  169772. * or if we already built the table. Also, if no quant table
  169773. * has yet been saved for the component, we leave the
  169774. * multiplier table all-zero; we'll be reading zeroes from the
  169775. * coefficient controller's buffer anyway.
  169776. */
  169777. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169778. continue;
  169779. qtbl = compptr->quant_table;
  169780. if (qtbl == NULL) /* happens if no data yet for component */
  169781. continue;
  169782. idct->cur_method[ci] = method;
  169783. switch (method) {
  169784. #ifdef PROVIDE_ISLOW_TABLES
  169785. case JDCT_ISLOW:
  169786. {
  169787. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169788. * coefficients, but are stored as ints to ensure access efficiency.
  169789. */
  169790. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169791. for (i = 0; i < DCTSIZE2; i++) {
  169792. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169793. }
  169794. }
  169795. break;
  169796. #endif
  169797. #ifdef DCT_IFAST_SUPPORTED
  169798. case JDCT_IFAST:
  169799. {
  169800. /* For AA&N IDCT method, multipliers are equal to quantization
  169801. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169802. * scalefactor[0] = 1
  169803. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169804. * For integer operation, the multiplier table is to be scaled by
  169805. * IFAST_SCALE_BITS.
  169806. */
  169807. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169808. #define CONST_BITS 14
  169809. static const INT16 aanscales[DCTSIZE2] = {
  169810. /* precomputed values scaled up by 14 bits */
  169811. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169812. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169813. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169814. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169815. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169816. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169817. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169818. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169819. };
  169820. SHIFT_TEMPS
  169821. for (i = 0; i < DCTSIZE2; i++) {
  169822. ifmtbl[i] = (IFAST_MULT_TYPE)
  169823. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169824. (INT32) aanscales[i]),
  169825. CONST_BITS-IFAST_SCALE_BITS);
  169826. }
  169827. }
  169828. break;
  169829. #endif
  169830. #ifdef DCT_FLOAT_SUPPORTED
  169831. case JDCT_FLOAT:
  169832. {
  169833. /* For float AA&N IDCT method, multipliers are equal to quantization
  169834. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169835. * scalefactor[0] = 1
  169836. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169837. */
  169838. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169839. int row, col;
  169840. static const double aanscalefactor[DCTSIZE] = {
  169841. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169842. 1.0, 0.785694958, 0.541196100, 0.275899379
  169843. };
  169844. i = 0;
  169845. for (row = 0; row < DCTSIZE; row++) {
  169846. for (col = 0; col < DCTSIZE; col++) {
  169847. fmtbl[i] = (FLOAT_MULT_TYPE)
  169848. ((double) qtbl->quantval[i] *
  169849. aanscalefactor[row] * aanscalefactor[col]);
  169850. i++;
  169851. }
  169852. }
  169853. }
  169854. break;
  169855. #endif
  169856. default:
  169857. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169858. break;
  169859. }
  169860. }
  169861. }
  169862. /*
  169863. * Initialize IDCT manager.
  169864. */
  169865. GLOBAL(void)
  169866. jinit_inverse_dct (j_decompress_ptr cinfo)
  169867. {
  169868. my_idct_ptr idct;
  169869. int ci;
  169870. jpeg_component_info *compptr;
  169871. idct = (my_idct_ptr)
  169872. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169873. SIZEOF(my_idct_controller));
  169874. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169875. idct->pub.start_pass = start_pass;
  169876. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169877. ci++, compptr++) {
  169878. /* Allocate and pre-zero a multiplier table for each component */
  169879. compptr->dct_table =
  169880. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169881. SIZEOF(multiplier_table));
  169882. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169883. /* Mark multiplier table not yet set up for any method */
  169884. idct->cur_method[ci] = -1;
  169885. }
  169886. }
  169887. /*** End of inlined file: jddctmgr.c ***/
  169888. #undef CONST_BITS
  169889. #undef ASSIGN_STATE
  169890. /*** Start of inlined file: jdhuff.c ***/
  169891. #define JPEG_INTERNALS
  169892. /*** Start of inlined file: jdhuff.h ***/
  169893. /* Short forms of external names for systems with brain-damaged linkers. */
  169894. #ifndef __jdhuff_h__
  169895. #define __jdhuff_h__
  169896. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169897. #define jpeg_make_d_derived_tbl jMkDDerived
  169898. #define jpeg_fill_bit_buffer jFilBitBuf
  169899. #define jpeg_huff_decode jHufDecode
  169900. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169901. /* Derived data constructed for each Huffman table */
  169902. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169903. typedef struct {
  169904. /* Basic tables: (element [0] of each array is unused) */
  169905. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169906. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169907. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169908. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169909. * the smallest code of length k; so given a code of length k, the
  169910. * corresponding symbol is huffval[code + valoffset[k]]
  169911. */
  169912. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169913. JHUFF_TBL *pub;
  169914. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169915. * the input data stream. If the next Huffman code is no more
  169916. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169917. * the corresponding symbol directly from these tables.
  169918. */
  169919. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169920. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169921. } d_derived_tbl;
  169922. /* Expand a Huffman table definition into the derived format */
  169923. EXTERN(void) jpeg_make_d_derived_tbl
  169924. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169925. d_derived_tbl ** pdtbl));
  169926. /*
  169927. * Fetching the next N bits from the input stream is a time-critical operation
  169928. * for the Huffman decoders. We implement it with a combination of inline
  169929. * macros and out-of-line subroutines. Note that N (the number of bits
  169930. * demanded at one time) never exceeds 15 for JPEG use.
  169931. *
  169932. * We read source bytes into get_buffer and dole out bits as needed.
  169933. * If get_buffer already contains enough bits, they are fetched in-line
  169934. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169935. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169936. * as full as possible (not just to the number of bits needed; this
  169937. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169938. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169939. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169940. * at least the requested number of bits --- dummy zeroes are inserted if
  169941. * necessary.
  169942. */
  169943. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169944. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169945. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169946. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169947. * appropriately should be a win. Unfortunately we can't define the size
  169948. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169949. * because not all machines measure sizeof in 8-bit bytes.
  169950. */
  169951. typedef struct { /* Bitreading state saved across MCUs */
  169952. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169953. int bits_left; /* # of unused bits in it */
  169954. } bitread_perm_state;
  169955. typedef struct { /* Bitreading working state within an MCU */
  169956. /* Current data source location */
  169957. /* We need a copy, rather than munging the original, in case of suspension */
  169958. const JOCTET * next_input_byte; /* => next byte to read from source */
  169959. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169960. /* Bit input buffer --- note these values are kept in register variables,
  169961. * not in this struct, inside the inner loops.
  169962. */
  169963. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169964. int bits_left; /* # of unused bits in it */
  169965. /* Pointer needed by jpeg_fill_bit_buffer. */
  169966. j_decompress_ptr cinfo; /* back link to decompress master record */
  169967. } bitread_working_state;
  169968. /* Macros to declare and load/save bitread local variables. */
  169969. #define BITREAD_STATE_VARS \
  169970. register bit_buf_type get_buffer; \
  169971. register int bits_left; \
  169972. bitread_working_state br_state
  169973. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169974. br_state.cinfo = cinfop; \
  169975. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169976. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169977. get_buffer = permstate.get_buffer; \
  169978. bits_left = permstate.bits_left;
  169979. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169980. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169981. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169982. permstate.get_buffer = get_buffer; \
  169983. permstate.bits_left = bits_left
  169984. /*
  169985. * These macros provide the in-line portion of bit fetching.
  169986. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169987. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169988. * The variables get_buffer and bits_left are assumed to be locals,
  169989. * but the state struct might not be (jpeg_huff_decode needs this).
  169990. * CHECK_BIT_BUFFER(state,n,action);
  169991. * Ensure there are N bits in get_buffer; if suspend, take action.
  169992. * val = GET_BITS(n);
  169993. * Fetch next N bits.
  169994. * val = PEEK_BITS(n);
  169995. * Fetch next N bits without removing them from the buffer.
  169996. * DROP_BITS(n);
  169997. * Discard next N bits.
  169998. * The value N should be a simple variable, not an expression, because it
  169999. * is evaluated multiple times.
  170000. */
  170001. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170002. { if (bits_left < (nbits)) { \
  170003. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170004. { action; } \
  170005. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170006. #define GET_BITS(nbits) \
  170007. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170008. #define PEEK_BITS(nbits) \
  170009. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170010. #define DROP_BITS(nbits) \
  170011. (bits_left -= (nbits))
  170012. /* Load up the bit buffer to a depth of at least nbits */
  170013. EXTERN(boolean) jpeg_fill_bit_buffer
  170014. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170015. register int bits_left, int nbits));
  170016. /*
  170017. * Code for extracting next Huffman-coded symbol from input bit stream.
  170018. * Again, this is time-critical and we make the main paths be macros.
  170019. *
  170020. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170021. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170022. * or fewer bits long. The few overlength codes are handled with a loop,
  170023. * which need not be inline code.
  170024. *
  170025. * Notes about the HUFF_DECODE macro:
  170026. * 1. Near the end of the data segment, we may fail to get enough bits
  170027. * for a lookahead. In that case, we do it the hard way.
  170028. * 2. If the lookahead table contains no entry, the next code must be
  170029. * more than HUFF_LOOKAHEAD bits long.
  170030. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170031. */
  170032. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170033. { register int nb, look; \
  170034. if (bits_left < HUFF_LOOKAHEAD) { \
  170035. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170036. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170037. if (bits_left < HUFF_LOOKAHEAD) { \
  170038. nb = 1; goto slowlabel; \
  170039. } \
  170040. } \
  170041. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170042. if ((nb = htbl->look_nbits[look]) != 0) { \
  170043. DROP_BITS(nb); \
  170044. result = htbl->look_sym[look]; \
  170045. } else { \
  170046. nb = HUFF_LOOKAHEAD+1; \
  170047. slowlabel: \
  170048. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170049. { failaction; } \
  170050. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170051. } \
  170052. }
  170053. /* Out-of-line case for Huffman code fetching */
  170054. EXTERN(int) jpeg_huff_decode
  170055. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170056. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170057. #endif
  170058. /*** End of inlined file: jdhuff.h ***/
  170059. /* Declarations shared with jdphuff.c */
  170060. /*
  170061. * Expanded entropy decoder object for Huffman decoding.
  170062. *
  170063. * The savable_state subrecord contains fields that change within an MCU,
  170064. * but must not be updated permanently until we complete the MCU.
  170065. */
  170066. typedef struct {
  170067. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170068. } savable_state2;
  170069. /* This macro is to work around compilers with missing or broken
  170070. * structure assignment. You'll need to fix this code if you have
  170071. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170072. */
  170073. #ifndef NO_STRUCT_ASSIGN
  170074. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170075. #else
  170076. #if MAX_COMPS_IN_SCAN == 4
  170077. #define ASSIGN_STATE(dest,src) \
  170078. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170079. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170080. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170081. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170082. #endif
  170083. #endif
  170084. typedef struct {
  170085. struct jpeg_entropy_decoder pub; /* public fields */
  170086. /* These fields are loaded into local variables at start of each MCU.
  170087. * In case of suspension, we exit WITHOUT updating them.
  170088. */
  170089. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170090. savable_state2 saved; /* Other state at start of MCU */
  170091. /* These fields are NOT loaded into local working state. */
  170092. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170093. /* Pointers to derived tables (these workspaces have image lifespan) */
  170094. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170095. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170096. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170097. /* Pointers to derived tables to be used for each block within an MCU */
  170098. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170099. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170100. /* Whether we care about the DC and AC coefficient values for each block */
  170101. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170102. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170103. } huff_entropy_decoder2;
  170104. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170105. /*
  170106. * Initialize for a Huffman-compressed scan.
  170107. */
  170108. METHODDEF(void)
  170109. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170110. {
  170111. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170112. int ci, blkn, dctbl, actbl;
  170113. jpeg_component_info * compptr;
  170114. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170115. * This ought to be an error condition, but we make it a warning because
  170116. * there are some baseline files out there with all zeroes in these bytes.
  170117. */
  170118. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170119. cinfo->Ah != 0 || cinfo->Al != 0)
  170120. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170121. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170122. compptr = cinfo->cur_comp_info[ci];
  170123. dctbl = compptr->dc_tbl_no;
  170124. actbl = compptr->ac_tbl_no;
  170125. /* Compute derived values for Huffman tables */
  170126. /* We may do this more than once for a table, but it's not expensive */
  170127. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170128. & entropy->dc_derived_tbls[dctbl]);
  170129. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170130. & entropy->ac_derived_tbls[actbl]);
  170131. /* Initialize DC predictions to 0 */
  170132. entropy->saved.last_dc_val[ci] = 0;
  170133. }
  170134. /* Precalculate decoding info for each block in an MCU of this scan */
  170135. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170136. ci = cinfo->MCU_membership[blkn];
  170137. compptr = cinfo->cur_comp_info[ci];
  170138. /* Precalculate which table to use for each block */
  170139. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170140. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170141. /* Decide whether we really care about the coefficient values */
  170142. if (compptr->component_needed) {
  170143. entropy->dc_needed[blkn] = TRUE;
  170144. /* we don't need the ACs if producing a 1/8th-size image */
  170145. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170146. } else {
  170147. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170148. }
  170149. }
  170150. /* Initialize bitread state variables */
  170151. entropy->bitstate.bits_left = 0;
  170152. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170153. entropy->pub.insufficient_data = FALSE;
  170154. /* Initialize restart counter */
  170155. entropy->restarts_to_go = cinfo->restart_interval;
  170156. }
  170157. /*
  170158. * Compute the derived values for a Huffman table.
  170159. * This routine also performs some validation checks on the table.
  170160. *
  170161. * Note this is also used by jdphuff.c.
  170162. */
  170163. GLOBAL(void)
  170164. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170165. d_derived_tbl ** pdtbl)
  170166. {
  170167. JHUFF_TBL *htbl;
  170168. d_derived_tbl *dtbl;
  170169. int p, i, l, si, numsymbols;
  170170. int lookbits, ctr;
  170171. char huffsize[257];
  170172. unsigned int huffcode[257];
  170173. unsigned int code;
  170174. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170175. * paralleling the order of the symbols themselves in htbl->huffval[].
  170176. */
  170177. /* Find the input Huffman table */
  170178. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170179. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170180. htbl =
  170181. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170182. if (htbl == NULL)
  170183. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170184. /* Allocate a workspace if we haven't already done so. */
  170185. if (*pdtbl == NULL)
  170186. *pdtbl = (d_derived_tbl *)
  170187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170188. SIZEOF(d_derived_tbl));
  170189. dtbl = *pdtbl;
  170190. dtbl->pub = htbl; /* fill in back link */
  170191. /* Figure C.1: make table of Huffman code length for each symbol */
  170192. p = 0;
  170193. for (l = 1; l <= 16; l++) {
  170194. i = (int) htbl->bits[l];
  170195. if (i < 0 || p + i > 256) /* protect against table overrun */
  170196. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170197. while (i--)
  170198. huffsize[p++] = (char) l;
  170199. }
  170200. huffsize[p] = 0;
  170201. numsymbols = p;
  170202. /* Figure C.2: generate the codes themselves */
  170203. /* We also validate that the counts represent a legal Huffman code tree. */
  170204. code = 0;
  170205. si = huffsize[0];
  170206. p = 0;
  170207. while (huffsize[p]) {
  170208. while (((int) huffsize[p]) == si) {
  170209. huffcode[p++] = code;
  170210. code++;
  170211. }
  170212. /* code is now 1 more than the last code used for codelength si; but
  170213. * it must still fit in si bits, since no code is allowed to be all ones.
  170214. */
  170215. if (((INT32) code) >= (((INT32) 1) << si))
  170216. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170217. code <<= 1;
  170218. si++;
  170219. }
  170220. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170221. p = 0;
  170222. for (l = 1; l <= 16; l++) {
  170223. if (htbl->bits[l]) {
  170224. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170225. * minus the minimum code of length l
  170226. */
  170227. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170228. p += htbl->bits[l];
  170229. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170230. } else {
  170231. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170232. }
  170233. }
  170234. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170235. /* Compute lookahead tables to speed up decoding.
  170236. * First we set all the table entries to 0, indicating "too long";
  170237. * then we iterate through the Huffman codes that are short enough and
  170238. * fill in all the entries that correspond to bit sequences starting
  170239. * with that code.
  170240. */
  170241. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170242. p = 0;
  170243. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170244. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170245. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170246. /* Generate left-justified code followed by all possible bit sequences */
  170247. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170248. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170249. dtbl->look_nbits[lookbits] = l;
  170250. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170251. lookbits++;
  170252. }
  170253. }
  170254. }
  170255. /* Validate symbols as being reasonable.
  170256. * For AC tables, we make no check, but accept all byte values 0..255.
  170257. * For DC tables, we require the symbols to be in range 0..15.
  170258. * (Tighter bounds could be applied depending on the data depth and mode,
  170259. * but this is sufficient to ensure safe decoding.)
  170260. */
  170261. if (isDC) {
  170262. for (i = 0; i < numsymbols; i++) {
  170263. int sym = htbl->huffval[i];
  170264. if (sym < 0 || sym > 15)
  170265. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170266. }
  170267. }
  170268. }
  170269. /*
  170270. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170271. * See jdhuff.h for info about usage.
  170272. * Note: current values of get_buffer and bits_left are passed as parameters,
  170273. * but are returned in the corresponding fields of the state struct.
  170274. *
  170275. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170276. * of get_buffer to be used. (On machines with wider words, an even larger
  170277. * buffer could be used.) However, on some machines 32-bit shifts are
  170278. * quite slow and take time proportional to the number of places shifted.
  170279. * (This is true with most PC compilers, for instance.) In this case it may
  170280. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170281. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170282. */
  170283. #ifdef SLOW_SHIFT_32
  170284. #define MIN_GET_BITS 15 /* minimum allowable value */
  170285. #else
  170286. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170287. #endif
  170288. GLOBAL(boolean)
  170289. jpeg_fill_bit_buffer (bitread_working_state * state,
  170290. register bit_buf_type get_buffer, register int bits_left,
  170291. int nbits)
  170292. /* Load up the bit buffer to a depth of at least nbits */
  170293. {
  170294. /* Copy heavily used state fields into locals (hopefully registers) */
  170295. register const JOCTET * next_input_byte = state->next_input_byte;
  170296. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170297. j_decompress_ptr cinfo = state->cinfo;
  170298. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170299. /* (It is assumed that no request will be for more than that many bits.) */
  170300. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170301. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170302. while (bits_left < MIN_GET_BITS) {
  170303. register int c;
  170304. /* Attempt to read a byte */
  170305. if (bytes_in_buffer == 0) {
  170306. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170307. return FALSE;
  170308. next_input_byte = cinfo->src->next_input_byte;
  170309. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170310. }
  170311. bytes_in_buffer--;
  170312. c = GETJOCTET(*next_input_byte++);
  170313. /* If it's 0xFF, check and discard stuffed zero byte */
  170314. if (c == 0xFF) {
  170315. /* Loop here to discard any padding FF's on terminating marker,
  170316. * so that we can save a valid unread_marker value. NOTE: we will
  170317. * accept multiple FF's followed by a 0 as meaning a single FF data
  170318. * byte. This data pattern is not valid according to the standard.
  170319. */
  170320. do {
  170321. if (bytes_in_buffer == 0) {
  170322. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170323. return FALSE;
  170324. next_input_byte = cinfo->src->next_input_byte;
  170325. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170326. }
  170327. bytes_in_buffer--;
  170328. c = GETJOCTET(*next_input_byte++);
  170329. } while (c == 0xFF);
  170330. if (c == 0) {
  170331. /* Found FF/00, which represents an FF data byte */
  170332. c = 0xFF;
  170333. } else {
  170334. /* Oops, it's actually a marker indicating end of compressed data.
  170335. * Save the marker code for later use.
  170336. * Fine point: it might appear that we should save the marker into
  170337. * bitread working state, not straight into permanent state. But
  170338. * once we have hit a marker, we cannot need to suspend within the
  170339. * current MCU, because we will read no more bytes from the data
  170340. * source. So it is OK to update permanent state right away.
  170341. */
  170342. cinfo->unread_marker = c;
  170343. /* See if we need to insert some fake zero bits. */
  170344. goto no_more_bytes;
  170345. }
  170346. }
  170347. /* OK, load c into get_buffer */
  170348. get_buffer = (get_buffer << 8) | c;
  170349. bits_left += 8;
  170350. } /* end while */
  170351. } else {
  170352. no_more_bytes:
  170353. /* We get here if we've read the marker that terminates the compressed
  170354. * data segment. There should be enough bits in the buffer register
  170355. * to satisfy the request; if so, no problem.
  170356. */
  170357. if (nbits > bits_left) {
  170358. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170359. * the data stream, so that we can produce some kind of image.
  170360. * We use a nonvolatile flag to ensure that only one warning message
  170361. * appears per data segment.
  170362. */
  170363. if (! cinfo->entropy->insufficient_data) {
  170364. WARNMS(cinfo, JWRN_HIT_MARKER);
  170365. cinfo->entropy->insufficient_data = TRUE;
  170366. }
  170367. /* Fill the buffer with zero bits */
  170368. get_buffer <<= MIN_GET_BITS - bits_left;
  170369. bits_left = MIN_GET_BITS;
  170370. }
  170371. }
  170372. /* Unload the local registers */
  170373. state->next_input_byte = next_input_byte;
  170374. state->bytes_in_buffer = bytes_in_buffer;
  170375. state->get_buffer = get_buffer;
  170376. state->bits_left = bits_left;
  170377. return TRUE;
  170378. }
  170379. /*
  170380. * Out-of-line code for Huffman code decoding.
  170381. * See jdhuff.h for info about usage.
  170382. */
  170383. GLOBAL(int)
  170384. jpeg_huff_decode (bitread_working_state * state,
  170385. register bit_buf_type get_buffer, register int bits_left,
  170386. d_derived_tbl * htbl, int min_bits)
  170387. {
  170388. register int l = min_bits;
  170389. register INT32 code;
  170390. /* HUFF_DECODE has determined that the code is at least min_bits */
  170391. /* bits long, so fetch that many bits in one swoop. */
  170392. CHECK_BIT_BUFFER(*state, l, return -1);
  170393. code = GET_BITS(l);
  170394. /* Collect the rest of the Huffman code one bit at a time. */
  170395. /* This is per Figure F.16 in the JPEG spec. */
  170396. while (code > htbl->maxcode[l]) {
  170397. code <<= 1;
  170398. CHECK_BIT_BUFFER(*state, 1, return -1);
  170399. code |= GET_BITS(1);
  170400. l++;
  170401. }
  170402. /* Unload the local registers */
  170403. state->get_buffer = get_buffer;
  170404. state->bits_left = bits_left;
  170405. /* With garbage input we may reach the sentinel value l = 17. */
  170406. if (l > 16) {
  170407. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170408. return 0; /* fake a zero as the safest result */
  170409. }
  170410. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170411. }
  170412. /*
  170413. * Check for a restart marker & resynchronize decoder.
  170414. * Returns FALSE if must suspend.
  170415. */
  170416. LOCAL(boolean)
  170417. process_restart (j_decompress_ptr cinfo)
  170418. {
  170419. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170420. int ci;
  170421. /* Throw away any unused bits remaining in bit buffer; */
  170422. /* include any full bytes in next_marker's count of discarded bytes */
  170423. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170424. entropy->bitstate.bits_left = 0;
  170425. /* Advance past the RSTn marker */
  170426. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170427. return FALSE;
  170428. /* Re-initialize DC predictions to 0 */
  170429. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170430. entropy->saved.last_dc_val[ci] = 0;
  170431. /* Reset restart counter */
  170432. entropy->restarts_to_go = cinfo->restart_interval;
  170433. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170434. * against a marker. In that case we will end up treating the next data
  170435. * segment as empty, and we can avoid producing bogus output pixels by
  170436. * leaving the flag set.
  170437. */
  170438. if (cinfo->unread_marker == 0)
  170439. entropy->pub.insufficient_data = FALSE;
  170440. return TRUE;
  170441. }
  170442. /*
  170443. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170444. * The coefficients are reordered from zigzag order into natural array order,
  170445. * but are not dequantized.
  170446. *
  170447. * The i'th block of the MCU is stored into the block pointed to by
  170448. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170449. * (Wholesale zeroing is usually a little faster than retail...)
  170450. *
  170451. * Returns FALSE if data source requested suspension. In that case no
  170452. * changes have been made to permanent state. (Exception: some output
  170453. * coefficients may already have been assigned. This is harmless for
  170454. * this module, since we'll just re-assign them on the next call.)
  170455. */
  170456. METHODDEF(boolean)
  170457. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170458. {
  170459. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170460. int blkn;
  170461. BITREAD_STATE_VARS;
  170462. savable_state2 state;
  170463. /* Process restart marker if needed; may have to suspend */
  170464. if (cinfo->restart_interval) {
  170465. if (entropy->restarts_to_go == 0)
  170466. if (! process_restart(cinfo))
  170467. return FALSE;
  170468. }
  170469. /* If we've run out of data, just leave the MCU set to zeroes.
  170470. * This way, we return uniform gray for the remainder of the segment.
  170471. */
  170472. if (! entropy->pub.insufficient_data) {
  170473. /* Load up working state */
  170474. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170475. ASSIGN_STATE(state, entropy->saved);
  170476. /* Outer loop handles each block in the MCU */
  170477. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170478. JBLOCKROW block = MCU_data[blkn];
  170479. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170480. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170481. register int s, k, r;
  170482. /* Decode a single block's worth of coefficients */
  170483. /* Section F.2.2.1: decode the DC coefficient difference */
  170484. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170485. if (s) {
  170486. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170487. r = GET_BITS(s);
  170488. s = HUFF_EXTEND(r, s);
  170489. }
  170490. if (entropy->dc_needed[blkn]) {
  170491. /* Convert DC difference to actual value, update last_dc_val */
  170492. int ci = cinfo->MCU_membership[blkn];
  170493. s += state.last_dc_val[ci];
  170494. state.last_dc_val[ci] = s;
  170495. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170496. (*block)[0] = (JCOEF) s;
  170497. }
  170498. if (entropy->ac_needed[blkn]) {
  170499. /* Section F.2.2.2: decode the AC coefficients */
  170500. /* Since zeroes are skipped, output area must be cleared beforehand */
  170501. for (k = 1; k < DCTSIZE2; k++) {
  170502. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170503. r = s >> 4;
  170504. s &= 15;
  170505. if (s) {
  170506. k += r;
  170507. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170508. r = GET_BITS(s);
  170509. s = HUFF_EXTEND(r, s);
  170510. /* Output coefficient in natural (dezigzagged) order.
  170511. * Note: the extra entries in jpeg_natural_order[] will save us
  170512. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170513. */
  170514. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170515. } else {
  170516. if (r != 15)
  170517. break;
  170518. k += 15;
  170519. }
  170520. }
  170521. } else {
  170522. /* Section F.2.2.2: decode the AC coefficients */
  170523. /* In this path we just discard the values */
  170524. for (k = 1; k < DCTSIZE2; k++) {
  170525. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170526. r = s >> 4;
  170527. s &= 15;
  170528. if (s) {
  170529. k += r;
  170530. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170531. DROP_BITS(s);
  170532. } else {
  170533. if (r != 15)
  170534. break;
  170535. k += 15;
  170536. }
  170537. }
  170538. }
  170539. }
  170540. /* Completed MCU, so update state */
  170541. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170542. ASSIGN_STATE(entropy->saved, state);
  170543. }
  170544. /* Account for restart interval (no-op if not using restarts) */
  170545. entropy->restarts_to_go--;
  170546. return TRUE;
  170547. }
  170548. /*
  170549. * Module initialization routine for Huffman entropy decoding.
  170550. */
  170551. GLOBAL(void)
  170552. jinit_huff_decoder (j_decompress_ptr cinfo)
  170553. {
  170554. huff_entropy_ptr2 entropy;
  170555. int i;
  170556. entropy = (huff_entropy_ptr2)
  170557. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170558. SIZEOF(huff_entropy_decoder2));
  170559. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170560. entropy->pub.start_pass = start_pass_huff_decoder;
  170561. entropy->pub.decode_mcu = decode_mcu;
  170562. /* Mark tables unallocated */
  170563. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170564. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170565. }
  170566. }
  170567. /*** End of inlined file: jdhuff.c ***/
  170568. /*** Start of inlined file: jdinput.c ***/
  170569. #define JPEG_INTERNALS
  170570. /* Private state */
  170571. typedef struct {
  170572. struct jpeg_input_controller pub; /* public fields */
  170573. boolean inheaders; /* TRUE until first SOS is reached */
  170574. } my_input_controller;
  170575. typedef my_input_controller * my_inputctl_ptr;
  170576. /* Forward declarations */
  170577. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170578. /*
  170579. * Routines to calculate various quantities related to the size of the image.
  170580. */
  170581. LOCAL(void)
  170582. initial_setup2 (j_decompress_ptr cinfo)
  170583. /* Called once, when first SOS marker is reached */
  170584. {
  170585. int ci;
  170586. jpeg_component_info *compptr;
  170587. /* Make sure image isn't bigger than I can handle */
  170588. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170589. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170590. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170591. /* For now, precision must match compiled-in value... */
  170592. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170593. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170594. /* Check that number of components won't exceed internal array sizes */
  170595. if (cinfo->num_components > MAX_COMPONENTS)
  170596. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170597. MAX_COMPONENTS);
  170598. /* Compute maximum sampling factors; check factor validity */
  170599. cinfo->max_h_samp_factor = 1;
  170600. cinfo->max_v_samp_factor = 1;
  170601. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170602. ci++, compptr++) {
  170603. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170604. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170605. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170606. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170607. compptr->h_samp_factor);
  170608. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170609. compptr->v_samp_factor);
  170610. }
  170611. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170612. * In the full decompressor, this will be overridden by jdmaster.c;
  170613. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170614. */
  170615. cinfo->min_DCT_scaled_size = DCTSIZE;
  170616. /* Compute dimensions of components */
  170617. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170618. ci++, compptr++) {
  170619. compptr->DCT_scaled_size = DCTSIZE;
  170620. /* Size in DCT blocks */
  170621. compptr->width_in_blocks = (JDIMENSION)
  170622. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170623. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170624. compptr->height_in_blocks = (JDIMENSION)
  170625. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170626. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170627. /* downsampled_width and downsampled_height will also be overridden by
  170628. * jdmaster.c if we are doing full decompression. The transcoder library
  170629. * doesn't use these values, but the calling application might.
  170630. */
  170631. /* Size in samples */
  170632. compptr->downsampled_width = (JDIMENSION)
  170633. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170634. (long) cinfo->max_h_samp_factor);
  170635. compptr->downsampled_height = (JDIMENSION)
  170636. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170637. (long) cinfo->max_v_samp_factor);
  170638. /* Mark component needed, until color conversion says otherwise */
  170639. compptr->component_needed = TRUE;
  170640. /* Mark no quantization table yet saved for component */
  170641. compptr->quant_table = NULL;
  170642. }
  170643. /* Compute number of fully interleaved MCU rows. */
  170644. cinfo->total_iMCU_rows = (JDIMENSION)
  170645. jdiv_round_up((long) cinfo->image_height,
  170646. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170647. /* Decide whether file contains multiple scans */
  170648. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170649. cinfo->inputctl->has_multiple_scans = TRUE;
  170650. else
  170651. cinfo->inputctl->has_multiple_scans = FALSE;
  170652. }
  170653. LOCAL(void)
  170654. per_scan_setup2 (j_decompress_ptr cinfo)
  170655. /* Do computations that are needed before processing a JPEG scan */
  170656. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170657. {
  170658. int ci, mcublks, tmp;
  170659. jpeg_component_info *compptr;
  170660. if (cinfo->comps_in_scan == 1) {
  170661. /* Noninterleaved (single-component) scan */
  170662. compptr = cinfo->cur_comp_info[0];
  170663. /* Overall image size in MCUs */
  170664. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170665. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170666. /* For noninterleaved scan, always one block per MCU */
  170667. compptr->MCU_width = 1;
  170668. compptr->MCU_height = 1;
  170669. compptr->MCU_blocks = 1;
  170670. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170671. compptr->last_col_width = 1;
  170672. /* For noninterleaved scans, it is convenient to define last_row_height
  170673. * as the number of block rows present in the last iMCU row.
  170674. */
  170675. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170676. if (tmp == 0) tmp = compptr->v_samp_factor;
  170677. compptr->last_row_height = tmp;
  170678. /* Prepare array describing MCU composition */
  170679. cinfo->blocks_in_MCU = 1;
  170680. cinfo->MCU_membership[0] = 0;
  170681. } else {
  170682. /* Interleaved (multi-component) scan */
  170683. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170684. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170685. MAX_COMPS_IN_SCAN);
  170686. /* Overall image size in MCUs */
  170687. cinfo->MCUs_per_row = (JDIMENSION)
  170688. jdiv_round_up((long) cinfo->image_width,
  170689. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170690. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170691. jdiv_round_up((long) cinfo->image_height,
  170692. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170693. cinfo->blocks_in_MCU = 0;
  170694. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170695. compptr = cinfo->cur_comp_info[ci];
  170696. /* Sampling factors give # of blocks of component in each MCU */
  170697. compptr->MCU_width = compptr->h_samp_factor;
  170698. compptr->MCU_height = compptr->v_samp_factor;
  170699. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170700. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170701. /* Figure number of non-dummy blocks in last MCU column & row */
  170702. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170703. if (tmp == 0) tmp = compptr->MCU_width;
  170704. compptr->last_col_width = tmp;
  170705. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170706. if (tmp == 0) tmp = compptr->MCU_height;
  170707. compptr->last_row_height = tmp;
  170708. /* Prepare array describing MCU composition */
  170709. mcublks = compptr->MCU_blocks;
  170710. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170711. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170712. while (mcublks-- > 0) {
  170713. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170714. }
  170715. }
  170716. }
  170717. }
  170718. /*
  170719. * Save away a copy of the Q-table referenced by each component present
  170720. * in the current scan, unless already saved during a prior scan.
  170721. *
  170722. * In a multiple-scan JPEG file, the encoder could assign different components
  170723. * the same Q-table slot number, but change table definitions between scans
  170724. * so that each component uses a different Q-table. (The IJG encoder is not
  170725. * currently capable of doing this, but other encoders might.) Since we want
  170726. * to be able to dequantize all the components at the end of the file, this
  170727. * means that we have to save away the table actually used for each component.
  170728. * We do this by copying the table at the start of the first scan containing
  170729. * the component.
  170730. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170731. * slot between scans of a component using that slot. If the encoder does so
  170732. * anyway, this decoder will simply use the Q-table values that were current
  170733. * at the start of the first scan for the component.
  170734. *
  170735. * The decompressor output side looks only at the saved quant tables,
  170736. * not at the current Q-table slots.
  170737. */
  170738. LOCAL(void)
  170739. latch_quant_tables (j_decompress_ptr cinfo)
  170740. {
  170741. int ci, qtblno;
  170742. jpeg_component_info *compptr;
  170743. JQUANT_TBL * qtbl;
  170744. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170745. compptr = cinfo->cur_comp_info[ci];
  170746. /* No work if we already saved Q-table for this component */
  170747. if (compptr->quant_table != NULL)
  170748. continue;
  170749. /* Make sure specified quantization table is present */
  170750. qtblno = compptr->quant_tbl_no;
  170751. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170752. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170753. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170754. /* OK, save away the quantization table */
  170755. qtbl = (JQUANT_TBL *)
  170756. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170757. SIZEOF(JQUANT_TBL));
  170758. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170759. compptr->quant_table = qtbl;
  170760. }
  170761. }
  170762. /*
  170763. * Initialize the input modules to read a scan of compressed data.
  170764. * The first call to this is done by jdmaster.c after initializing
  170765. * the entire decompressor (during jpeg_start_decompress).
  170766. * Subsequent calls come from consume_markers, below.
  170767. */
  170768. METHODDEF(void)
  170769. start_input_pass2 (j_decompress_ptr cinfo)
  170770. {
  170771. per_scan_setup2(cinfo);
  170772. latch_quant_tables(cinfo);
  170773. (*cinfo->entropy->start_pass) (cinfo);
  170774. (*cinfo->coef->start_input_pass) (cinfo);
  170775. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170776. }
  170777. /*
  170778. * Finish up after inputting a compressed-data scan.
  170779. * This is called by the coefficient controller after it's read all
  170780. * the expected data of the scan.
  170781. */
  170782. METHODDEF(void)
  170783. finish_input_pass (j_decompress_ptr cinfo)
  170784. {
  170785. cinfo->inputctl->consume_input = consume_markers;
  170786. }
  170787. /*
  170788. * Read JPEG markers before, between, or after compressed-data scans.
  170789. * Change state as necessary when a new scan is reached.
  170790. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170791. *
  170792. * The consume_input method pointer points either here or to the
  170793. * coefficient controller's consume_data routine, depending on whether
  170794. * we are reading a compressed data segment or inter-segment markers.
  170795. */
  170796. METHODDEF(int)
  170797. consume_markers (j_decompress_ptr cinfo)
  170798. {
  170799. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170800. int val;
  170801. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170802. return JPEG_REACHED_EOI;
  170803. val = (*cinfo->marker->read_markers) (cinfo);
  170804. switch (val) {
  170805. case JPEG_REACHED_SOS: /* Found SOS */
  170806. if (inputctl->inheaders) { /* 1st SOS */
  170807. initial_setup2(cinfo);
  170808. inputctl->inheaders = FALSE;
  170809. /* Note: start_input_pass must be called by jdmaster.c
  170810. * before any more input can be consumed. jdapimin.c is
  170811. * responsible for enforcing this sequencing.
  170812. */
  170813. } else { /* 2nd or later SOS marker */
  170814. if (! inputctl->pub.has_multiple_scans)
  170815. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170816. start_input_pass2(cinfo);
  170817. }
  170818. break;
  170819. case JPEG_REACHED_EOI: /* Found EOI */
  170820. inputctl->pub.eoi_reached = TRUE;
  170821. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170822. if (cinfo->marker->saw_SOF)
  170823. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170824. } else {
  170825. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170826. * if user set output_scan_number larger than number of scans.
  170827. */
  170828. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170829. cinfo->output_scan_number = cinfo->input_scan_number;
  170830. }
  170831. break;
  170832. case JPEG_SUSPENDED:
  170833. break;
  170834. }
  170835. return val;
  170836. }
  170837. /*
  170838. * Reset state to begin a fresh datastream.
  170839. */
  170840. METHODDEF(void)
  170841. reset_input_controller (j_decompress_ptr cinfo)
  170842. {
  170843. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170844. inputctl->pub.consume_input = consume_markers;
  170845. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170846. inputctl->pub.eoi_reached = FALSE;
  170847. inputctl->inheaders = TRUE;
  170848. /* Reset other modules */
  170849. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170850. (*cinfo->marker->reset_marker_reader) (cinfo);
  170851. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170852. cinfo->coef_bits = NULL;
  170853. }
  170854. /*
  170855. * Initialize the input controller module.
  170856. * This is called only once, when the decompression object is created.
  170857. */
  170858. GLOBAL(void)
  170859. jinit_input_controller (j_decompress_ptr cinfo)
  170860. {
  170861. my_inputctl_ptr inputctl;
  170862. /* Create subobject in permanent pool */
  170863. inputctl = (my_inputctl_ptr)
  170864. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170865. SIZEOF(my_input_controller));
  170866. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170867. /* Initialize method pointers */
  170868. inputctl->pub.consume_input = consume_markers;
  170869. inputctl->pub.reset_input_controller = reset_input_controller;
  170870. inputctl->pub.start_input_pass = start_input_pass2;
  170871. inputctl->pub.finish_input_pass = finish_input_pass;
  170872. /* Initialize state: can't use reset_input_controller since we don't
  170873. * want to try to reset other modules yet.
  170874. */
  170875. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170876. inputctl->pub.eoi_reached = FALSE;
  170877. inputctl->inheaders = TRUE;
  170878. }
  170879. /*** End of inlined file: jdinput.c ***/
  170880. /*** Start of inlined file: jdmainct.c ***/
  170881. #define JPEG_INTERNALS
  170882. /*
  170883. * In the current system design, the main buffer need never be a full-image
  170884. * buffer; any full-height buffers will be found inside the coefficient or
  170885. * postprocessing controllers. Nonetheless, the main controller is not
  170886. * trivial. Its responsibility is to provide context rows for upsampling/
  170887. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170888. *
  170889. * Postprocessor input data is counted in "row groups". A row group
  170890. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170891. * sample rows of each component. (We require DCT_scaled_size values to be
  170892. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170893. * values will likely be powers of two, so we actually have the stronger
  170894. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170895. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170896. * row group (times any additional scale factor that the upsampler is
  170897. * applying).
  170898. *
  170899. * The coefficient controller will deliver data to us one iMCU row at a time;
  170900. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170901. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170902. * to one row of MCUs when the image is fully interleaved.) Note that the
  170903. * number of sample rows varies across components, but the number of row
  170904. * groups does not. Some garbage sample rows may be included in the last iMCU
  170905. * row at the bottom of the image.
  170906. *
  170907. * Depending on the vertical scaling algorithm used, the upsampler may need
  170908. * access to the sample row(s) above and below its current input row group.
  170909. * The upsampler is required to set need_context_rows TRUE at global selection
  170910. * time if so. When need_context_rows is FALSE, this controller can simply
  170911. * obtain one iMCU row at a time from the coefficient controller and dole it
  170912. * out as row groups to the postprocessor.
  170913. *
  170914. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170915. * passed to postprocessing contains at least one row group's worth of samples
  170916. * above and below the row group(s) being processed. Note that the context
  170917. * rows "above" the first passed row group appear at negative row offsets in
  170918. * the passed buffer. At the top and bottom of the image, the required
  170919. * context rows are manufactured by duplicating the first or last real sample
  170920. * row; this avoids having special cases in the upsampling inner loops.
  170921. *
  170922. * The amount of context is fixed at one row group just because that's a
  170923. * convenient number for this controller to work with. The existing
  170924. * upsamplers really only need one sample row of context. An upsampler
  170925. * supporting arbitrary output rescaling might wish for more than one row
  170926. * group of context when shrinking the image; tough, we don't handle that.
  170927. * (This is justified by the assumption that downsizing will be handled mostly
  170928. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170929. * the upsample step needn't be much less than one.)
  170930. *
  170931. * To provide the desired context, we have to retain the last two row groups
  170932. * of one iMCU row while reading in the next iMCU row. (The last row group
  170933. * can't be processed until we have another row group for its below-context,
  170934. * and so we have to save the next-to-last group too for its above-context.)
  170935. * We could do this most simply by copying data around in our buffer, but
  170936. * that'd be very slow. We can avoid copying any data by creating a rather
  170937. * strange pointer structure. Here's how it works. We allocate a workspace
  170938. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170939. * of row groups per iMCU row). We create two sets of redundant pointers to
  170940. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170941. * pointer lists look like this:
  170942. * M+1 M-1
  170943. * master pointer --> 0 master pointer --> 0
  170944. * 1 1
  170945. * ... ...
  170946. * M-3 M-3
  170947. * M-2 M
  170948. * M-1 M+1
  170949. * M M-2
  170950. * M+1 M-1
  170951. * 0 0
  170952. * We read alternate iMCU rows using each master pointer; thus the last two
  170953. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170954. * The pointer lists are set up so that the required context rows appear to
  170955. * be adjacent to the proper places when we pass the pointer lists to the
  170956. * upsampler.
  170957. *
  170958. * The above pictures describe the normal state of the pointer lists.
  170959. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170960. * the first or last sample row as necessary (this is cheaper than copying
  170961. * sample rows around).
  170962. *
  170963. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170964. * situation each iMCU row provides only one row group so the buffering logic
  170965. * must be different (eg, we must read two iMCU rows before we can emit the
  170966. * first row group). For now, we simply do not support providing context
  170967. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170968. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170969. * want it quick and dirty, so a context-free upsampler is sufficient.
  170970. */
  170971. /* Private buffer controller object */
  170972. typedef struct {
  170973. struct jpeg_d_main_controller pub; /* public fields */
  170974. /* Pointer to allocated workspace (M or M+2 row groups). */
  170975. JSAMPARRAY buffer[MAX_COMPONENTS];
  170976. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170977. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170978. /* Remaining fields are only used in the context case. */
  170979. /* These are the master pointers to the funny-order pointer lists. */
  170980. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170981. int whichptr; /* indicates which pointer set is now in use */
  170982. int context_state; /* process_data state machine status */
  170983. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170984. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170985. } my_main_controller4;
  170986. typedef my_main_controller4 * my_main_ptr4;
  170987. /* context_state values: */
  170988. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170989. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170990. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170991. /* Forward declarations */
  170992. METHODDEF(void) process_data_simple_main2
  170993. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170994. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170995. METHODDEF(void) process_data_context_main
  170996. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170997. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170998. #ifdef QUANT_2PASS_SUPPORTED
  170999. METHODDEF(void) process_data_crank_post
  171000. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171001. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171002. #endif
  171003. LOCAL(void)
  171004. alloc_funny_pointers (j_decompress_ptr cinfo)
  171005. /* Allocate space for the funny pointer lists.
  171006. * This is done only once, not once per pass.
  171007. */
  171008. {
  171009. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171010. int ci, rgroup;
  171011. int M = cinfo->min_DCT_scaled_size;
  171012. jpeg_component_info *compptr;
  171013. JSAMPARRAY xbuf;
  171014. /* Get top-level space for component array pointers.
  171015. * We alloc both arrays with one call to save a few cycles.
  171016. */
  171017. main_->xbuffer[0] = (JSAMPIMAGE)
  171018. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171019. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171020. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171021. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171022. ci++, compptr++) {
  171023. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171024. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171025. /* Get space for pointer lists --- M+4 row groups in each list.
  171026. * We alloc both pointer lists with one call to save a few cycles.
  171027. */
  171028. xbuf = (JSAMPARRAY)
  171029. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171030. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171031. xbuf += rgroup; /* want one row group at negative offsets */
  171032. main_->xbuffer[0][ci] = xbuf;
  171033. xbuf += rgroup * (M + 4);
  171034. main_->xbuffer[1][ci] = xbuf;
  171035. }
  171036. }
  171037. LOCAL(void)
  171038. make_funny_pointers (j_decompress_ptr cinfo)
  171039. /* Create the funny pointer lists discussed in the comments above.
  171040. * The actual workspace is already allocated (in main->buffer),
  171041. * and the space for the pointer lists is allocated too.
  171042. * This routine just fills in the curiously ordered lists.
  171043. * This will be repeated at the beginning of each pass.
  171044. */
  171045. {
  171046. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171047. int ci, i, rgroup;
  171048. int M = cinfo->min_DCT_scaled_size;
  171049. jpeg_component_info *compptr;
  171050. JSAMPARRAY buf, xbuf0, xbuf1;
  171051. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171052. ci++, compptr++) {
  171053. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171054. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171055. xbuf0 = main_->xbuffer[0][ci];
  171056. xbuf1 = main_->xbuffer[1][ci];
  171057. /* First copy the workspace pointers as-is */
  171058. buf = main_->buffer[ci];
  171059. for (i = 0; i < rgroup * (M + 2); i++) {
  171060. xbuf0[i] = xbuf1[i] = buf[i];
  171061. }
  171062. /* In the second list, put the last four row groups in swapped order */
  171063. for (i = 0; i < rgroup * 2; i++) {
  171064. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171065. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171066. }
  171067. /* The wraparound pointers at top and bottom will be filled later
  171068. * (see set_wraparound_pointers, below). Initially we want the "above"
  171069. * pointers to duplicate the first actual data line. This only needs
  171070. * to happen in xbuffer[0].
  171071. */
  171072. for (i = 0; i < rgroup; i++) {
  171073. xbuf0[i - rgroup] = xbuf0[0];
  171074. }
  171075. }
  171076. }
  171077. LOCAL(void)
  171078. set_wraparound_pointers (j_decompress_ptr cinfo)
  171079. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171080. * This changes the pointer list state from top-of-image to the normal state.
  171081. */
  171082. {
  171083. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171084. int ci, i, rgroup;
  171085. int M = cinfo->min_DCT_scaled_size;
  171086. jpeg_component_info *compptr;
  171087. JSAMPARRAY xbuf0, xbuf1;
  171088. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171089. ci++, compptr++) {
  171090. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171091. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171092. xbuf0 = main_->xbuffer[0][ci];
  171093. xbuf1 = main_->xbuffer[1][ci];
  171094. for (i = 0; i < rgroup; i++) {
  171095. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171096. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171097. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171098. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171099. }
  171100. }
  171101. }
  171102. LOCAL(void)
  171103. set_bottom_pointers (j_decompress_ptr cinfo)
  171104. /* Change the pointer lists to duplicate the last sample row at the bottom
  171105. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171106. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171107. */
  171108. {
  171109. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171110. int ci, i, rgroup, iMCUheight, rows_left;
  171111. jpeg_component_info *compptr;
  171112. JSAMPARRAY xbuf;
  171113. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171114. ci++, compptr++) {
  171115. /* Count sample rows in one iMCU row and in one row group */
  171116. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171117. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171118. /* Count nondummy sample rows remaining for this component */
  171119. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171120. if (rows_left == 0) rows_left = iMCUheight;
  171121. /* Count nondummy row groups. Should get same answer for each component,
  171122. * so we need only do it once.
  171123. */
  171124. if (ci == 0) {
  171125. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171126. }
  171127. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171128. * last partial rowgroup and ensures at least one full rowgroup of context.
  171129. */
  171130. xbuf = main_->xbuffer[main_->whichptr][ci];
  171131. for (i = 0; i < rgroup * 2; i++) {
  171132. xbuf[rows_left + i] = xbuf[rows_left-1];
  171133. }
  171134. }
  171135. }
  171136. /*
  171137. * Initialize for a processing pass.
  171138. */
  171139. METHODDEF(void)
  171140. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171141. {
  171142. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171143. switch (pass_mode) {
  171144. case JBUF_PASS_THRU:
  171145. if (cinfo->upsample->need_context_rows) {
  171146. main_->pub.process_data = process_data_context_main;
  171147. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171148. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171149. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171150. main_->iMCU_row_ctr = 0;
  171151. } else {
  171152. /* Simple case with no context needed */
  171153. main_->pub.process_data = process_data_simple_main2;
  171154. }
  171155. main_->buffer_full = FALSE; /* Mark buffer empty */
  171156. main_->rowgroup_ctr = 0;
  171157. break;
  171158. #ifdef QUANT_2PASS_SUPPORTED
  171159. case JBUF_CRANK_DEST:
  171160. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171161. main_->pub.process_data = process_data_crank_post;
  171162. break;
  171163. #endif
  171164. default:
  171165. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171166. break;
  171167. }
  171168. }
  171169. /*
  171170. * Process some data.
  171171. * This handles the simple case where no context is required.
  171172. */
  171173. METHODDEF(void)
  171174. process_data_simple_main2 (j_decompress_ptr cinfo,
  171175. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171176. JDIMENSION out_rows_avail)
  171177. {
  171178. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171179. JDIMENSION rowgroups_avail;
  171180. /* Read input data if we haven't filled the main buffer yet */
  171181. if (! main_->buffer_full) {
  171182. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171183. return; /* suspension forced, can do nothing more */
  171184. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171185. }
  171186. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171187. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171188. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171189. * to the postprocessor. The postprocessor has to check for bottom
  171190. * of image anyway (at row resolution), so no point in us doing it too.
  171191. */
  171192. /* Feed the postprocessor */
  171193. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171194. &main_->rowgroup_ctr, rowgroups_avail,
  171195. output_buf, out_row_ctr, out_rows_avail);
  171196. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171197. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171198. main_->buffer_full = FALSE;
  171199. main_->rowgroup_ctr = 0;
  171200. }
  171201. }
  171202. /*
  171203. * Process some data.
  171204. * This handles the case where context rows must be provided.
  171205. */
  171206. METHODDEF(void)
  171207. process_data_context_main (j_decompress_ptr cinfo,
  171208. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171209. JDIMENSION out_rows_avail)
  171210. {
  171211. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171212. /* Read input data if we haven't filled the main buffer yet */
  171213. if (! main_->buffer_full) {
  171214. if (! (*cinfo->coef->decompress_data) (cinfo,
  171215. main_->xbuffer[main_->whichptr]))
  171216. return; /* suspension forced, can do nothing more */
  171217. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171218. main_->iMCU_row_ctr++; /* count rows received */
  171219. }
  171220. /* Postprocessor typically will not swallow all the input data it is handed
  171221. * in one call (due to filling the output buffer first). Must be prepared
  171222. * to exit and restart. This switch lets us keep track of how far we got.
  171223. * Note that each case falls through to the next on successful completion.
  171224. */
  171225. switch (main_->context_state) {
  171226. case CTX_POSTPONED_ROW:
  171227. /* Call postprocessor using previously set pointers for postponed row */
  171228. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171229. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171230. output_buf, out_row_ctr, out_rows_avail);
  171231. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171232. return; /* Need to suspend */
  171233. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171234. if (*out_row_ctr >= out_rows_avail)
  171235. return; /* Postprocessor exactly filled output buf */
  171236. /*FALLTHROUGH*/
  171237. case CTX_PREPARE_FOR_IMCU:
  171238. /* Prepare to process first M-1 row groups of this iMCU row */
  171239. main_->rowgroup_ctr = 0;
  171240. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171241. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171242. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171243. */
  171244. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171245. set_bottom_pointers(cinfo);
  171246. main_->context_state = CTX_PROCESS_IMCU;
  171247. /*FALLTHROUGH*/
  171248. case CTX_PROCESS_IMCU:
  171249. /* Call postprocessor using previously set pointers */
  171250. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171251. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171252. output_buf, out_row_ctr, out_rows_avail);
  171253. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171254. return; /* Need to suspend */
  171255. /* After the first iMCU, change wraparound pointers to normal state */
  171256. if (main_->iMCU_row_ctr == 1)
  171257. set_wraparound_pointers(cinfo);
  171258. /* Prepare to load new iMCU row using other xbuffer list */
  171259. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171260. main_->buffer_full = FALSE;
  171261. /* Still need to process last row group of this iMCU row, */
  171262. /* which is saved at index M+1 of the other xbuffer */
  171263. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171264. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171265. main_->context_state = CTX_POSTPONED_ROW;
  171266. }
  171267. }
  171268. /*
  171269. * Process some data.
  171270. * Final pass of two-pass quantization: just call the postprocessor.
  171271. * Source data will be the postprocessor controller's internal buffer.
  171272. */
  171273. #ifdef QUANT_2PASS_SUPPORTED
  171274. METHODDEF(void)
  171275. process_data_crank_post (j_decompress_ptr cinfo,
  171276. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171277. JDIMENSION out_rows_avail)
  171278. {
  171279. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171280. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171281. output_buf, out_row_ctr, out_rows_avail);
  171282. }
  171283. #endif /* QUANT_2PASS_SUPPORTED */
  171284. /*
  171285. * Initialize main buffer controller.
  171286. */
  171287. GLOBAL(void)
  171288. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171289. {
  171290. my_main_ptr4 main_;
  171291. int ci, rgroup, ngroups;
  171292. jpeg_component_info *compptr;
  171293. main_ = (my_main_ptr4)
  171294. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171295. SIZEOF(my_main_controller4));
  171296. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171297. main_->pub.start_pass = start_pass_main2;
  171298. if (need_full_buffer) /* shouldn't happen */
  171299. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171300. /* Allocate the workspace.
  171301. * ngroups is the number of row groups we need.
  171302. */
  171303. if (cinfo->upsample->need_context_rows) {
  171304. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171305. ERREXIT(cinfo, JERR_NOTIMPL);
  171306. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171307. ngroups = cinfo->min_DCT_scaled_size + 2;
  171308. } else {
  171309. ngroups = cinfo->min_DCT_scaled_size;
  171310. }
  171311. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171312. ci++, compptr++) {
  171313. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171314. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171315. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171316. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171317. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171318. (JDIMENSION) (rgroup * ngroups));
  171319. }
  171320. }
  171321. /*** End of inlined file: jdmainct.c ***/
  171322. /*** Start of inlined file: jdmarker.c ***/
  171323. #define JPEG_INTERNALS
  171324. /* Private state */
  171325. typedef struct {
  171326. struct jpeg_marker_reader pub; /* public fields */
  171327. /* Application-overridable marker processing methods */
  171328. jpeg_marker_parser_method process_COM;
  171329. jpeg_marker_parser_method process_APPn[16];
  171330. /* Limit on marker data length to save for each marker type */
  171331. unsigned int length_limit_COM;
  171332. unsigned int length_limit_APPn[16];
  171333. /* Status of COM/APPn marker saving */
  171334. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171335. unsigned int bytes_read; /* data bytes read so far in marker */
  171336. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171337. } my_marker_reader;
  171338. typedef my_marker_reader * my_marker_ptr2;
  171339. /*
  171340. * Macros for fetching data from the data source module.
  171341. *
  171342. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171343. * the current restart point; we update them only when we have reached a
  171344. * suitable place to restart if a suspension occurs.
  171345. */
  171346. /* Declare and initialize local copies of input pointer/count */
  171347. #define INPUT_VARS(cinfo) \
  171348. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171349. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171350. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171351. /* Unload the local copies --- do this only at a restart boundary */
  171352. #define INPUT_SYNC(cinfo) \
  171353. ( datasrc->next_input_byte = next_input_byte, \
  171354. datasrc->bytes_in_buffer = bytes_in_buffer )
  171355. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171356. #define INPUT_RELOAD(cinfo) \
  171357. ( next_input_byte = datasrc->next_input_byte, \
  171358. bytes_in_buffer = datasrc->bytes_in_buffer )
  171359. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171360. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171361. * but we must reload the local copies after a successful fill.
  171362. */
  171363. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171364. if (bytes_in_buffer == 0) { \
  171365. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171366. { action; } \
  171367. INPUT_RELOAD(cinfo); \
  171368. }
  171369. /* Read a byte into variable V.
  171370. * If must suspend, take the specified action (typically "return FALSE").
  171371. */
  171372. #define INPUT_BYTE(cinfo,V,action) \
  171373. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171374. bytes_in_buffer--; \
  171375. V = GETJOCTET(*next_input_byte++); )
  171376. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171377. * V should be declared unsigned int or perhaps INT32.
  171378. */
  171379. #define INPUT_2BYTES(cinfo,V,action) \
  171380. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171381. bytes_in_buffer--; \
  171382. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171383. MAKE_BYTE_AVAIL(cinfo,action); \
  171384. bytes_in_buffer--; \
  171385. V += GETJOCTET(*next_input_byte++); )
  171386. /*
  171387. * Routines to process JPEG markers.
  171388. *
  171389. * Entry condition: JPEG marker itself has been read and its code saved
  171390. * in cinfo->unread_marker; input restart point is just after the marker.
  171391. *
  171392. * Exit: if return TRUE, have read and processed any parameters, and have
  171393. * updated the restart point to point after the parameters.
  171394. * If return FALSE, was forced to suspend before reaching end of
  171395. * marker parameters; restart point has not been moved. Same routine
  171396. * will be called again after application supplies more input data.
  171397. *
  171398. * This approach to suspension assumes that all of a marker's parameters
  171399. * can fit into a single input bufferload. This should hold for "normal"
  171400. * markers. Some COM/APPn markers might have large parameter segments
  171401. * that might not fit. If we are simply dropping such a marker, we use
  171402. * skip_input_data to get past it, and thereby put the problem on the
  171403. * source manager's shoulders. If we are saving the marker's contents
  171404. * into memory, we use a slightly different convention: when forced to
  171405. * suspend, the marker processor updates the restart point to the end of
  171406. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171407. * On resumption, cinfo->unread_marker still contains the marker code,
  171408. * but the data source will point to the next chunk of marker data.
  171409. * The marker processor must retain internal state to deal with this.
  171410. *
  171411. * Note that we don't bother to avoid duplicate trace messages if a
  171412. * suspension occurs within marker parameters. Other side effects
  171413. * require more care.
  171414. */
  171415. LOCAL(boolean)
  171416. get_soi (j_decompress_ptr cinfo)
  171417. /* Process an SOI marker */
  171418. {
  171419. int i;
  171420. TRACEMS(cinfo, 1, JTRC_SOI);
  171421. if (cinfo->marker->saw_SOI)
  171422. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171423. /* Reset all parameters that are defined to be reset by SOI */
  171424. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171425. cinfo->arith_dc_L[i] = 0;
  171426. cinfo->arith_dc_U[i] = 1;
  171427. cinfo->arith_ac_K[i] = 5;
  171428. }
  171429. cinfo->restart_interval = 0;
  171430. /* Set initial assumptions for colorspace etc */
  171431. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171432. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171433. cinfo->saw_JFIF_marker = FALSE;
  171434. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171435. cinfo->JFIF_minor_version = 1;
  171436. cinfo->density_unit = 0;
  171437. cinfo->X_density = 1;
  171438. cinfo->Y_density = 1;
  171439. cinfo->saw_Adobe_marker = FALSE;
  171440. cinfo->Adobe_transform = 0;
  171441. cinfo->marker->saw_SOI = TRUE;
  171442. return TRUE;
  171443. }
  171444. LOCAL(boolean)
  171445. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171446. /* Process a SOFn marker */
  171447. {
  171448. INT32 length;
  171449. int c, ci;
  171450. jpeg_component_info * compptr;
  171451. INPUT_VARS(cinfo);
  171452. cinfo->progressive_mode = is_prog;
  171453. cinfo->arith_code = is_arith;
  171454. INPUT_2BYTES(cinfo, length, return FALSE);
  171455. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171456. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171457. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171458. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171459. length -= 8;
  171460. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171461. (int) cinfo->image_width, (int) cinfo->image_height,
  171462. cinfo->num_components);
  171463. if (cinfo->marker->saw_SOF)
  171464. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171465. /* We don't support files in which the image height is initially specified */
  171466. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171467. /* might as well have a general sanity check. */
  171468. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171469. || cinfo->num_components <= 0)
  171470. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171471. if (length != (cinfo->num_components * 3))
  171472. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171473. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171474. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171475. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171476. cinfo->num_components * SIZEOF(jpeg_component_info));
  171477. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171478. ci++, compptr++) {
  171479. compptr->component_index = ci;
  171480. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171481. INPUT_BYTE(cinfo, c, return FALSE);
  171482. compptr->h_samp_factor = (c >> 4) & 15;
  171483. compptr->v_samp_factor = (c ) & 15;
  171484. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171485. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171486. compptr->component_id, compptr->h_samp_factor,
  171487. compptr->v_samp_factor, compptr->quant_tbl_no);
  171488. }
  171489. cinfo->marker->saw_SOF = TRUE;
  171490. INPUT_SYNC(cinfo);
  171491. return TRUE;
  171492. }
  171493. LOCAL(boolean)
  171494. get_sos (j_decompress_ptr cinfo)
  171495. /* Process a SOS marker */
  171496. {
  171497. INT32 length;
  171498. int i, ci, n, c, cc;
  171499. jpeg_component_info * compptr;
  171500. INPUT_VARS(cinfo);
  171501. if (! cinfo->marker->saw_SOF)
  171502. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171503. INPUT_2BYTES(cinfo, length, return FALSE);
  171504. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171505. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171506. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171507. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171508. cinfo->comps_in_scan = n;
  171509. /* Collect the component-spec parameters */
  171510. for (i = 0; i < n; i++) {
  171511. INPUT_BYTE(cinfo, cc, return FALSE);
  171512. INPUT_BYTE(cinfo, c, return FALSE);
  171513. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171514. ci++, compptr++) {
  171515. if (cc == compptr->component_id)
  171516. goto id_found;
  171517. }
  171518. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171519. id_found:
  171520. cinfo->cur_comp_info[i] = compptr;
  171521. compptr->dc_tbl_no = (c >> 4) & 15;
  171522. compptr->ac_tbl_no = (c ) & 15;
  171523. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171524. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171525. }
  171526. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171527. INPUT_BYTE(cinfo, c, return FALSE);
  171528. cinfo->Ss = c;
  171529. INPUT_BYTE(cinfo, c, return FALSE);
  171530. cinfo->Se = c;
  171531. INPUT_BYTE(cinfo, c, return FALSE);
  171532. cinfo->Ah = (c >> 4) & 15;
  171533. cinfo->Al = (c ) & 15;
  171534. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171535. cinfo->Ah, cinfo->Al);
  171536. /* Prepare to scan data & restart markers */
  171537. cinfo->marker->next_restart_num = 0;
  171538. /* Count another SOS marker */
  171539. cinfo->input_scan_number++;
  171540. INPUT_SYNC(cinfo);
  171541. return TRUE;
  171542. }
  171543. #ifdef D_ARITH_CODING_SUPPORTED
  171544. LOCAL(boolean)
  171545. get_dac (j_decompress_ptr cinfo)
  171546. /* Process a DAC marker */
  171547. {
  171548. INT32 length;
  171549. int index, val;
  171550. INPUT_VARS(cinfo);
  171551. INPUT_2BYTES(cinfo, length, return FALSE);
  171552. length -= 2;
  171553. while (length > 0) {
  171554. INPUT_BYTE(cinfo, index, return FALSE);
  171555. INPUT_BYTE(cinfo, val, return FALSE);
  171556. length -= 2;
  171557. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171558. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171559. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171560. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171561. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171562. } else { /* define DC table */
  171563. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171564. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171565. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171566. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171567. }
  171568. }
  171569. if (length != 0)
  171570. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171571. INPUT_SYNC(cinfo);
  171572. return TRUE;
  171573. }
  171574. #else /* ! D_ARITH_CODING_SUPPORTED */
  171575. #define get_dac(cinfo) skip_variable(cinfo)
  171576. #endif /* D_ARITH_CODING_SUPPORTED */
  171577. LOCAL(boolean)
  171578. get_dht (j_decompress_ptr cinfo)
  171579. /* Process a DHT marker */
  171580. {
  171581. INT32 length;
  171582. UINT8 bits[17];
  171583. UINT8 huffval[256];
  171584. int i, index, count;
  171585. JHUFF_TBL **htblptr;
  171586. INPUT_VARS(cinfo);
  171587. INPUT_2BYTES(cinfo, length, return FALSE);
  171588. length -= 2;
  171589. while (length > 16) {
  171590. INPUT_BYTE(cinfo, index, return FALSE);
  171591. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171592. bits[0] = 0;
  171593. count = 0;
  171594. for (i = 1; i <= 16; i++) {
  171595. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171596. count += bits[i];
  171597. }
  171598. length -= 1 + 16;
  171599. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171600. bits[1], bits[2], bits[3], bits[4],
  171601. bits[5], bits[6], bits[7], bits[8]);
  171602. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171603. bits[9], bits[10], bits[11], bits[12],
  171604. bits[13], bits[14], bits[15], bits[16]);
  171605. /* Here we just do minimal validation of the counts to avoid walking
  171606. * off the end of our table space. jdhuff.c will check more carefully.
  171607. */
  171608. if (count > 256 || ((INT32) count) > length)
  171609. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171610. for (i = 0; i < count; i++)
  171611. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171612. length -= count;
  171613. if (index & 0x10) { /* AC table definition */
  171614. index -= 0x10;
  171615. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171616. } else { /* DC table definition */
  171617. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171618. }
  171619. if (index < 0 || index >= NUM_HUFF_TBLS)
  171620. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171621. if (*htblptr == NULL)
  171622. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171623. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171624. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171625. }
  171626. if (length != 0)
  171627. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171628. INPUT_SYNC(cinfo);
  171629. return TRUE;
  171630. }
  171631. LOCAL(boolean)
  171632. get_dqt (j_decompress_ptr cinfo)
  171633. /* Process a DQT marker */
  171634. {
  171635. INT32 length;
  171636. int n, i, prec;
  171637. unsigned int tmp;
  171638. JQUANT_TBL *quant_ptr;
  171639. INPUT_VARS(cinfo);
  171640. INPUT_2BYTES(cinfo, length, return FALSE);
  171641. length -= 2;
  171642. while (length > 0) {
  171643. INPUT_BYTE(cinfo, n, return FALSE);
  171644. prec = n >> 4;
  171645. n &= 0x0F;
  171646. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171647. if (n >= NUM_QUANT_TBLS)
  171648. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171649. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171650. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171651. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171652. for (i = 0; i < DCTSIZE2; i++) {
  171653. if (prec)
  171654. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171655. else
  171656. INPUT_BYTE(cinfo, tmp, return FALSE);
  171657. /* We convert the zigzag-order table to natural array order. */
  171658. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171659. }
  171660. if (cinfo->err->trace_level >= 2) {
  171661. for (i = 0; i < DCTSIZE2; i += 8) {
  171662. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171663. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171664. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171665. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171666. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171667. }
  171668. }
  171669. length -= DCTSIZE2+1;
  171670. if (prec) length -= DCTSIZE2;
  171671. }
  171672. if (length != 0)
  171673. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171674. INPUT_SYNC(cinfo);
  171675. return TRUE;
  171676. }
  171677. LOCAL(boolean)
  171678. get_dri (j_decompress_ptr cinfo)
  171679. /* Process a DRI marker */
  171680. {
  171681. INT32 length;
  171682. unsigned int tmp;
  171683. INPUT_VARS(cinfo);
  171684. INPUT_2BYTES(cinfo, length, return FALSE);
  171685. if (length != 4)
  171686. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171687. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171688. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171689. cinfo->restart_interval = tmp;
  171690. INPUT_SYNC(cinfo);
  171691. return TRUE;
  171692. }
  171693. /*
  171694. * Routines for processing APPn and COM markers.
  171695. * These are either saved in memory or discarded, per application request.
  171696. * APP0 and APP14 are specially checked to see if they are
  171697. * JFIF and Adobe markers, respectively.
  171698. */
  171699. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171700. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171701. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171702. LOCAL(void)
  171703. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171704. unsigned int datalen, INT32 remaining)
  171705. /* Examine first few bytes from an APP0.
  171706. * Take appropriate action if it is a JFIF marker.
  171707. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171708. */
  171709. {
  171710. INT32 totallen = (INT32) datalen + remaining;
  171711. if (datalen >= APP0_DATA_LEN &&
  171712. GETJOCTET(data[0]) == 0x4A &&
  171713. GETJOCTET(data[1]) == 0x46 &&
  171714. GETJOCTET(data[2]) == 0x49 &&
  171715. GETJOCTET(data[3]) == 0x46 &&
  171716. GETJOCTET(data[4]) == 0) {
  171717. /* Found JFIF APP0 marker: save info */
  171718. cinfo->saw_JFIF_marker = TRUE;
  171719. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171720. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171721. cinfo->density_unit = GETJOCTET(data[7]);
  171722. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171723. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171724. /* Check version.
  171725. * Major version must be 1, anything else signals an incompatible change.
  171726. * (We used to treat this as an error, but now it's a nonfatal warning,
  171727. * because some bozo at Hijaak couldn't read the spec.)
  171728. * Minor version should be 0..2, but process anyway if newer.
  171729. */
  171730. if (cinfo->JFIF_major_version != 1)
  171731. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171732. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171733. /* Generate trace messages */
  171734. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171735. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171736. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171737. /* Validate thumbnail dimensions and issue appropriate messages */
  171738. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171739. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171740. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171741. totallen -= APP0_DATA_LEN;
  171742. if (totallen !=
  171743. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171744. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171745. } else if (datalen >= 6 &&
  171746. GETJOCTET(data[0]) == 0x4A &&
  171747. GETJOCTET(data[1]) == 0x46 &&
  171748. GETJOCTET(data[2]) == 0x58 &&
  171749. GETJOCTET(data[3]) == 0x58 &&
  171750. GETJOCTET(data[4]) == 0) {
  171751. /* Found JFIF "JFXX" extension APP0 marker */
  171752. /* The library doesn't actually do anything with these,
  171753. * but we try to produce a helpful trace message.
  171754. */
  171755. switch (GETJOCTET(data[5])) {
  171756. case 0x10:
  171757. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171758. break;
  171759. case 0x11:
  171760. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171761. break;
  171762. case 0x13:
  171763. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171764. break;
  171765. default:
  171766. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171767. GETJOCTET(data[5]), (int) totallen);
  171768. break;
  171769. }
  171770. } else {
  171771. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171772. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171773. }
  171774. }
  171775. LOCAL(void)
  171776. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171777. unsigned int datalen, INT32 remaining)
  171778. /* Examine first few bytes from an APP14.
  171779. * Take appropriate action if it is an Adobe marker.
  171780. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171781. */
  171782. {
  171783. unsigned int version, flags0, flags1, transform;
  171784. if (datalen >= APP14_DATA_LEN &&
  171785. GETJOCTET(data[0]) == 0x41 &&
  171786. GETJOCTET(data[1]) == 0x64 &&
  171787. GETJOCTET(data[2]) == 0x6F &&
  171788. GETJOCTET(data[3]) == 0x62 &&
  171789. GETJOCTET(data[4]) == 0x65) {
  171790. /* Found Adobe APP14 marker */
  171791. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171792. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171793. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171794. transform = GETJOCTET(data[11]);
  171795. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171796. cinfo->saw_Adobe_marker = TRUE;
  171797. cinfo->Adobe_transform = (UINT8) transform;
  171798. } else {
  171799. /* Start of APP14 does not match "Adobe", or too short */
  171800. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171801. }
  171802. }
  171803. METHODDEF(boolean)
  171804. get_interesting_appn (j_decompress_ptr cinfo)
  171805. /* Process an APP0 or APP14 marker without saving it */
  171806. {
  171807. INT32 length;
  171808. JOCTET b[APPN_DATA_LEN];
  171809. unsigned int i, numtoread;
  171810. INPUT_VARS(cinfo);
  171811. INPUT_2BYTES(cinfo, length, return FALSE);
  171812. length -= 2;
  171813. /* get the interesting part of the marker data */
  171814. if (length >= APPN_DATA_LEN)
  171815. numtoread = APPN_DATA_LEN;
  171816. else if (length > 0)
  171817. numtoread = (unsigned int) length;
  171818. else
  171819. numtoread = 0;
  171820. for (i = 0; i < numtoread; i++)
  171821. INPUT_BYTE(cinfo, b[i], return FALSE);
  171822. length -= numtoread;
  171823. /* process it */
  171824. switch (cinfo->unread_marker) {
  171825. case M_APP0:
  171826. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171827. break;
  171828. case M_APP14:
  171829. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171830. break;
  171831. default:
  171832. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171833. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171834. break;
  171835. }
  171836. /* skip any remaining data -- could be lots */
  171837. INPUT_SYNC(cinfo);
  171838. if (length > 0)
  171839. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171840. return TRUE;
  171841. }
  171842. #ifdef SAVE_MARKERS_SUPPORTED
  171843. METHODDEF(boolean)
  171844. save_marker (j_decompress_ptr cinfo)
  171845. /* Save an APPn or COM marker into the marker list */
  171846. {
  171847. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171848. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171849. unsigned int bytes_read, data_length;
  171850. JOCTET FAR * data;
  171851. INT32 length = 0;
  171852. INPUT_VARS(cinfo);
  171853. if (cur_marker == NULL) {
  171854. /* begin reading a marker */
  171855. INPUT_2BYTES(cinfo, length, return FALSE);
  171856. length -= 2;
  171857. if (length >= 0) { /* watch out for bogus length word */
  171858. /* figure out how much we want to save */
  171859. unsigned int limit;
  171860. if (cinfo->unread_marker == (int) M_COM)
  171861. limit = marker->length_limit_COM;
  171862. else
  171863. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171864. if ((unsigned int) length < limit)
  171865. limit = (unsigned int) length;
  171866. /* allocate and initialize the marker item */
  171867. cur_marker = (jpeg_saved_marker_ptr)
  171868. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171869. SIZEOF(struct jpeg_marker_struct) + limit);
  171870. cur_marker->next = NULL;
  171871. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171872. cur_marker->original_length = (unsigned int) length;
  171873. cur_marker->data_length = limit;
  171874. /* data area is just beyond the jpeg_marker_struct */
  171875. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171876. marker->cur_marker = cur_marker;
  171877. marker->bytes_read = 0;
  171878. bytes_read = 0;
  171879. data_length = limit;
  171880. } else {
  171881. /* deal with bogus length word */
  171882. bytes_read = data_length = 0;
  171883. data = NULL;
  171884. }
  171885. } else {
  171886. /* resume reading a marker */
  171887. bytes_read = marker->bytes_read;
  171888. data_length = cur_marker->data_length;
  171889. data = cur_marker->data + bytes_read;
  171890. }
  171891. while (bytes_read < data_length) {
  171892. INPUT_SYNC(cinfo); /* move the restart point to here */
  171893. marker->bytes_read = bytes_read;
  171894. /* If there's not at least one byte in buffer, suspend */
  171895. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171896. /* Copy bytes with reasonable rapidity */
  171897. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171898. *data++ = *next_input_byte++;
  171899. bytes_in_buffer--;
  171900. bytes_read++;
  171901. }
  171902. }
  171903. /* Done reading what we want to read */
  171904. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171905. /* Add new marker to end of list */
  171906. if (cinfo->marker_list == NULL) {
  171907. cinfo->marker_list = cur_marker;
  171908. } else {
  171909. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171910. while (prev->next != NULL)
  171911. prev = prev->next;
  171912. prev->next = cur_marker;
  171913. }
  171914. /* Reset pointer & calc remaining data length */
  171915. data = cur_marker->data;
  171916. length = cur_marker->original_length - data_length;
  171917. }
  171918. /* Reset to initial state for next marker */
  171919. marker->cur_marker = NULL;
  171920. /* Process the marker if interesting; else just make a generic trace msg */
  171921. switch (cinfo->unread_marker) {
  171922. case M_APP0:
  171923. examine_app0(cinfo, data, data_length, length);
  171924. break;
  171925. case M_APP14:
  171926. examine_app14(cinfo, data, data_length, length);
  171927. break;
  171928. default:
  171929. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171930. (int) (data_length + length));
  171931. break;
  171932. }
  171933. /* skip any remaining data -- could be lots */
  171934. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171935. if (length > 0)
  171936. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171937. return TRUE;
  171938. }
  171939. #endif /* SAVE_MARKERS_SUPPORTED */
  171940. METHODDEF(boolean)
  171941. skip_variable (j_decompress_ptr cinfo)
  171942. /* Skip over an unknown or uninteresting variable-length marker */
  171943. {
  171944. INT32 length;
  171945. INPUT_VARS(cinfo);
  171946. INPUT_2BYTES(cinfo, length, return FALSE);
  171947. length -= 2;
  171948. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171949. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171950. if (length > 0)
  171951. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171952. return TRUE;
  171953. }
  171954. /*
  171955. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171956. * Returns FALSE if had to suspend before reaching a marker;
  171957. * in that case cinfo->unread_marker is unchanged.
  171958. *
  171959. * Note that the result might not be a valid marker code,
  171960. * but it will never be 0 or FF.
  171961. */
  171962. LOCAL(boolean)
  171963. next_marker (j_decompress_ptr cinfo)
  171964. {
  171965. int c;
  171966. INPUT_VARS(cinfo);
  171967. for (;;) {
  171968. INPUT_BYTE(cinfo, c, return FALSE);
  171969. /* Skip any non-FF bytes.
  171970. * This may look a bit inefficient, but it will not occur in a valid file.
  171971. * We sync after each discarded byte so that a suspending data source
  171972. * can discard the byte from its buffer.
  171973. */
  171974. while (c != 0xFF) {
  171975. cinfo->marker->discarded_bytes++;
  171976. INPUT_SYNC(cinfo);
  171977. INPUT_BYTE(cinfo, c, return FALSE);
  171978. }
  171979. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171980. * pad bytes, so don't count them in discarded_bytes. We assume there
  171981. * will not be so many consecutive FF bytes as to overflow a suspending
  171982. * data source's input buffer.
  171983. */
  171984. do {
  171985. INPUT_BYTE(cinfo, c, return FALSE);
  171986. } while (c == 0xFF);
  171987. if (c != 0)
  171988. break; /* found a valid marker, exit loop */
  171989. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171990. * Discard it and loop back to try again.
  171991. */
  171992. cinfo->marker->discarded_bytes += 2;
  171993. INPUT_SYNC(cinfo);
  171994. }
  171995. if (cinfo->marker->discarded_bytes != 0) {
  171996. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171997. cinfo->marker->discarded_bytes = 0;
  171998. }
  171999. cinfo->unread_marker = c;
  172000. INPUT_SYNC(cinfo);
  172001. return TRUE;
  172002. }
  172003. LOCAL(boolean)
  172004. first_marker (j_decompress_ptr cinfo)
  172005. /* Like next_marker, but used to obtain the initial SOI marker. */
  172006. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172007. * we might well scan an entire input file before realizing it ain't JPEG.
  172008. * If an application wants to process non-JFIF files, it must seek to the
  172009. * SOI before calling the JPEG library.
  172010. */
  172011. {
  172012. int c, c2;
  172013. INPUT_VARS(cinfo);
  172014. INPUT_BYTE(cinfo, c, return FALSE);
  172015. INPUT_BYTE(cinfo, c2, return FALSE);
  172016. if (c != 0xFF || c2 != (int) M_SOI)
  172017. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172018. cinfo->unread_marker = c2;
  172019. INPUT_SYNC(cinfo);
  172020. return TRUE;
  172021. }
  172022. /*
  172023. * Read markers until SOS or EOI.
  172024. *
  172025. * Returns same codes as are defined for jpeg_consume_input:
  172026. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172027. */
  172028. METHODDEF(int)
  172029. read_markers (j_decompress_ptr cinfo)
  172030. {
  172031. /* Outer loop repeats once for each marker. */
  172032. for (;;) {
  172033. /* Collect the marker proper, unless we already did. */
  172034. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172035. if (cinfo->unread_marker == 0) {
  172036. if (! cinfo->marker->saw_SOI) {
  172037. if (! first_marker(cinfo))
  172038. return JPEG_SUSPENDED;
  172039. } else {
  172040. if (! next_marker(cinfo))
  172041. return JPEG_SUSPENDED;
  172042. }
  172043. }
  172044. /* At this point cinfo->unread_marker contains the marker code and the
  172045. * input point is just past the marker proper, but before any parameters.
  172046. * A suspension will cause us to return with this state still true.
  172047. */
  172048. switch (cinfo->unread_marker) {
  172049. case M_SOI:
  172050. if (! get_soi(cinfo))
  172051. return JPEG_SUSPENDED;
  172052. break;
  172053. case M_SOF0: /* Baseline */
  172054. case M_SOF1: /* Extended sequential, Huffman */
  172055. if (! get_sof(cinfo, FALSE, FALSE))
  172056. return JPEG_SUSPENDED;
  172057. break;
  172058. case M_SOF2: /* Progressive, Huffman */
  172059. if (! get_sof(cinfo, TRUE, FALSE))
  172060. return JPEG_SUSPENDED;
  172061. break;
  172062. case M_SOF9: /* Extended sequential, arithmetic */
  172063. if (! get_sof(cinfo, FALSE, TRUE))
  172064. return JPEG_SUSPENDED;
  172065. break;
  172066. case M_SOF10: /* Progressive, arithmetic */
  172067. if (! get_sof(cinfo, TRUE, TRUE))
  172068. return JPEG_SUSPENDED;
  172069. break;
  172070. /* Currently unsupported SOFn types */
  172071. case M_SOF3: /* Lossless, Huffman */
  172072. case M_SOF5: /* Differential sequential, Huffman */
  172073. case M_SOF6: /* Differential progressive, Huffman */
  172074. case M_SOF7: /* Differential lossless, Huffman */
  172075. case M_JPG: /* Reserved for JPEG extensions */
  172076. case M_SOF11: /* Lossless, arithmetic */
  172077. case M_SOF13: /* Differential sequential, arithmetic */
  172078. case M_SOF14: /* Differential progressive, arithmetic */
  172079. case M_SOF15: /* Differential lossless, arithmetic */
  172080. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172081. break;
  172082. case M_SOS:
  172083. if (! get_sos(cinfo))
  172084. return JPEG_SUSPENDED;
  172085. cinfo->unread_marker = 0; /* processed the marker */
  172086. return JPEG_REACHED_SOS;
  172087. case M_EOI:
  172088. TRACEMS(cinfo, 1, JTRC_EOI);
  172089. cinfo->unread_marker = 0; /* processed the marker */
  172090. return JPEG_REACHED_EOI;
  172091. case M_DAC:
  172092. if (! get_dac(cinfo))
  172093. return JPEG_SUSPENDED;
  172094. break;
  172095. case M_DHT:
  172096. if (! get_dht(cinfo))
  172097. return JPEG_SUSPENDED;
  172098. break;
  172099. case M_DQT:
  172100. if (! get_dqt(cinfo))
  172101. return JPEG_SUSPENDED;
  172102. break;
  172103. case M_DRI:
  172104. if (! get_dri(cinfo))
  172105. return JPEG_SUSPENDED;
  172106. break;
  172107. case M_APP0:
  172108. case M_APP1:
  172109. case M_APP2:
  172110. case M_APP3:
  172111. case M_APP4:
  172112. case M_APP5:
  172113. case M_APP6:
  172114. case M_APP7:
  172115. case M_APP8:
  172116. case M_APP9:
  172117. case M_APP10:
  172118. case M_APP11:
  172119. case M_APP12:
  172120. case M_APP13:
  172121. case M_APP14:
  172122. case M_APP15:
  172123. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172124. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172125. return JPEG_SUSPENDED;
  172126. break;
  172127. case M_COM:
  172128. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172129. return JPEG_SUSPENDED;
  172130. break;
  172131. case M_RST0: /* these are all parameterless */
  172132. case M_RST1:
  172133. case M_RST2:
  172134. case M_RST3:
  172135. case M_RST4:
  172136. case M_RST5:
  172137. case M_RST6:
  172138. case M_RST7:
  172139. case M_TEM:
  172140. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172141. break;
  172142. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172143. if (! skip_variable(cinfo))
  172144. return JPEG_SUSPENDED;
  172145. break;
  172146. default: /* must be DHP, EXP, JPGn, or RESn */
  172147. /* For now, we treat the reserved markers as fatal errors since they are
  172148. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172149. * Once the JPEG 3 version-number marker is well defined, this code
  172150. * ought to change!
  172151. */
  172152. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172153. break;
  172154. }
  172155. /* Successfully processed marker, so reset state variable */
  172156. cinfo->unread_marker = 0;
  172157. } /* end loop */
  172158. }
  172159. /*
  172160. * Read a restart marker, which is expected to appear next in the datastream;
  172161. * if the marker is not there, take appropriate recovery action.
  172162. * Returns FALSE if suspension is required.
  172163. *
  172164. * This is called by the entropy decoder after it has read an appropriate
  172165. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172166. * has already read a marker from the data source. Under normal conditions
  172167. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172168. * it holds a marker which the decoder will be unable to read past.
  172169. */
  172170. METHODDEF(boolean)
  172171. read_restart_marker (j_decompress_ptr cinfo)
  172172. {
  172173. /* Obtain a marker unless we already did. */
  172174. /* Note that next_marker will complain if it skips any data. */
  172175. if (cinfo->unread_marker == 0) {
  172176. if (! next_marker(cinfo))
  172177. return FALSE;
  172178. }
  172179. if (cinfo->unread_marker ==
  172180. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172181. /* Normal case --- swallow the marker and let entropy decoder continue */
  172182. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172183. cinfo->unread_marker = 0;
  172184. } else {
  172185. /* Uh-oh, the restart markers have been messed up. */
  172186. /* Let the data source manager determine how to resync. */
  172187. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172188. cinfo->marker->next_restart_num))
  172189. return FALSE;
  172190. }
  172191. /* Update next-restart state */
  172192. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172193. return TRUE;
  172194. }
  172195. /*
  172196. * This is the default resync_to_restart method for data source managers
  172197. * to use if they don't have any better approach. Some data source managers
  172198. * may be able to back up, or may have additional knowledge about the data
  172199. * which permits a more intelligent recovery strategy; such managers would
  172200. * presumably supply their own resync method.
  172201. *
  172202. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172203. * the restart marker it was expecting. (This code is *not* used unless
  172204. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172205. * the marker code actually found (might be anything, except 0 or FF).
  172206. * The desired restart marker number (0..7) is passed as a parameter.
  172207. * This routine is supposed to apply whatever error recovery strategy seems
  172208. * appropriate in order to position the input stream to the next data segment.
  172209. * Note that cinfo->unread_marker is treated as a marker appearing before
  172210. * the current data-source input point; usually it should be reset to zero
  172211. * before returning.
  172212. * Returns FALSE if suspension is required.
  172213. *
  172214. * This implementation is substantially constrained by wanting to treat the
  172215. * input as a data stream; this means we can't back up. Therefore, we have
  172216. * only the following actions to work with:
  172217. * 1. Simply discard the marker and let the entropy decoder resume at next
  172218. * byte of file.
  172219. * 2. Read forward until we find another marker, discarding intervening
  172220. * data. (In theory we could look ahead within the current bufferload,
  172221. * without having to discard data if we don't find the desired marker.
  172222. * This idea is not implemented here, in part because it makes behavior
  172223. * dependent on buffer size and chance buffer-boundary positions.)
  172224. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172225. * This will cause the entropy decoder to process an empty data segment,
  172226. * inserting dummy zeroes, and then we will reprocess the marker.
  172227. *
  172228. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172229. * appropriate if the found marker is a future restart marker (indicating
  172230. * that we have missed the desired restart marker, probably because it got
  172231. * corrupted).
  172232. * We apply #2 or #3 if the found marker is a restart marker no more than
  172233. * two counts behind or ahead of the expected one. We also apply #2 if the
  172234. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172235. * If the found marker is a restart marker more than 2 counts away, we do #1
  172236. * (too much risk that the marker is erroneous; with luck we will be able to
  172237. * resync at some future point).
  172238. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172239. * overrunning the end of a scan. An implementation limited to single-scan
  172240. * files might find it better to apply #2 for markers other than EOI, since
  172241. * any other marker would have to be bogus data in that case.
  172242. */
  172243. GLOBAL(boolean)
  172244. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172245. {
  172246. int marker = cinfo->unread_marker;
  172247. int action = 1;
  172248. /* Always put up a warning. */
  172249. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172250. /* Outer loop handles repeated decision after scanning forward. */
  172251. for (;;) {
  172252. if (marker < (int) M_SOF0)
  172253. action = 2; /* invalid marker */
  172254. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172255. action = 3; /* valid non-restart marker */
  172256. else {
  172257. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172258. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172259. action = 3; /* one of the next two expected restarts */
  172260. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172261. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172262. action = 2; /* a prior restart, so advance */
  172263. else
  172264. action = 1; /* desired restart or too far away */
  172265. }
  172266. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172267. switch (action) {
  172268. case 1:
  172269. /* Discard marker and let entropy decoder resume processing. */
  172270. cinfo->unread_marker = 0;
  172271. return TRUE;
  172272. case 2:
  172273. /* Scan to the next marker, and repeat the decision loop. */
  172274. if (! next_marker(cinfo))
  172275. return FALSE;
  172276. marker = cinfo->unread_marker;
  172277. break;
  172278. case 3:
  172279. /* Return without advancing past this marker. */
  172280. /* Entropy decoder will be forced to process an empty segment. */
  172281. return TRUE;
  172282. }
  172283. } /* end loop */
  172284. }
  172285. /*
  172286. * Reset marker processing state to begin a fresh datastream.
  172287. */
  172288. METHODDEF(void)
  172289. reset_marker_reader (j_decompress_ptr cinfo)
  172290. {
  172291. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172292. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172293. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172294. cinfo->unread_marker = 0; /* no pending marker */
  172295. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172296. marker->pub.saw_SOF = FALSE;
  172297. marker->pub.discarded_bytes = 0;
  172298. marker->cur_marker = NULL;
  172299. }
  172300. /*
  172301. * Initialize the marker reader module.
  172302. * This is called only once, when the decompression object is created.
  172303. */
  172304. GLOBAL(void)
  172305. jinit_marker_reader (j_decompress_ptr cinfo)
  172306. {
  172307. my_marker_ptr2 marker;
  172308. int i;
  172309. /* Create subobject in permanent pool */
  172310. marker = (my_marker_ptr2)
  172311. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172312. SIZEOF(my_marker_reader));
  172313. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172314. /* Initialize public method pointers */
  172315. marker->pub.reset_marker_reader = reset_marker_reader;
  172316. marker->pub.read_markers = read_markers;
  172317. marker->pub.read_restart_marker = read_restart_marker;
  172318. /* Initialize COM/APPn processing.
  172319. * By default, we examine and then discard APP0 and APP14,
  172320. * but simply discard COM and all other APPn.
  172321. */
  172322. marker->process_COM = skip_variable;
  172323. marker->length_limit_COM = 0;
  172324. for (i = 0; i < 16; i++) {
  172325. marker->process_APPn[i] = skip_variable;
  172326. marker->length_limit_APPn[i] = 0;
  172327. }
  172328. marker->process_APPn[0] = get_interesting_appn;
  172329. marker->process_APPn[14] = get_interesting_appn;
  172330. /* Reset marker processing state */
  172331. reset_marker_reader(cinfo);
  172332. }
  172333. /*
  172334. * Control saving of COM and APPn markers into marker_list.
  172335. */
  172336. #ifdef SAVE_MARKERS_SUPPORTED
  172337. GLOBAL(void)
  172338. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172339. unsigned int length_limit)
  172340. {
  172341. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172342. long maxlength;
  172343. jpeg_marker_parser_method processor;
  172344. /* Length limit mustn't be larger than what we can allocate
  172345. * (should only be a concern in a 16-bit environment).
  172346. */
  172347. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172348. if (((long) length_limit) > maxlength)
  172349. length_limit = (unsigned int) maxlength;
  172350. /* Choose processor routine to use.
  172351. * APP0/APP14 have special requirements.
  172352. */
  172353. if (length_limit) {
  172354. processor = save_marker;
  172355. /* If saving APP0/APP14, save at least enough for our internal use. */
  172356. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172357. length_limit = APP0_DATA_LEN;
  172358. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172359. length_limit = APP14_DATA_LEN;
  172360. } else {
  172361. processor = skip_variable;
  172362. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172363. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172364. processor = get_interesting_appn;
  172365. }
  172366. if (marker_code == (int) M_COM) {
  172367. marker->process_COM = processor;
  172368. marker->length_limit_COM = length_limit;
  172369. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172370. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172371. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172372. } else
  172373. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172374. }
  172375. #endif /* SAVE_MARKERS_SUPPORTED */
  172376. /*
  172377. * Install a special processing method for COM or APPn markers.
  172378. */
  172379. GLOBAL(void)
  172380. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172381. jpeg_marker_parser_method routine)
  172382. {
  172383. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172384. if (marker_code == (int) M_COM)
  172385. marker->process_COM = routine;
  172386. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172387. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172388. else
  172389. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172390. }
  172391. /*** End of inlined file: jdmarker.c ***/
  172392. /*** Start of inlined file: jdmaster.c ***/
  172393. #define JPEG_INTERNALS
  172394. /* Private state */
  172395. typedef struct {
  172396. struct jpeg_decomp_master pub; /* public fields */
  172397. int pass_number; /* # of passes completed */
  172398. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172399. /* Saved references to initialized quantizer modules,
  172400. * in case we need to switch modes.
  172401. */
  172402. struct jpeg_color_quantizer * quantizer_1pass;
  172403. struct jpeg_color_quantizer * quantizer_2pass;
  172404. } my_decomp_master;
  172405. typedef my_decomp_master * my_master_ptr6;
  172406. /*
  172407. * Determine whether merged upsample/color conversion should be used.
  172408. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172409. */
  172410. LOCAL(boolean)
  172411. use_merged_upsample (j_decompress_ptr cinfo)
  172412. {
  172413. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172414. /* Merging is the equivalent of plain box-filter upsampling */
  172415. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172416. return FALSE;
  172417. /* jdmerge.c only supports YCC=>RGB color conversion */
  172418. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172419. cinfo->out_color_space != JCS_RGB ||
  172420. cinfo->out_color_components != RGB_PIXELSIZE)
  172421. return FALSE;
  172422. /* and it only handles 2h1v or 2h2v sampling ratios */
  172423. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172424. cinfo->comp_info[1].h_samp_factor != 1 ||
  172425. cinfo->comp_info[2].h_samp_factor != 1 ||
  172426. cinfo->comp_info[0].v_samp_factor > 2 ||
  172427. cinfo->comp_info[1].v_samp_factor != 1 ||
  172428. cinfo->comp_info[2].v_samp_factor != 1)
  172429. return FALSE;
  172430. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172431. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172432. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172433. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172434. return FALSE;
  172435. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172436. return TRUE; /* by golly, it'll work... */
  172437. #else
  172438. return FALSE;
  172439. #endif
  172440. }
  172441. /*
  172442. * Compute output image dimensions and related values.
  172443. * NOTE: this is exported for possible use by application.
  172444. * Hence it mustn't do anything that can't be done twice.
  172445. * Also note that it may be called before the master module is initialized!
  172446. */
  172447. GLOBAL(void)
  172448. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172449. /* Do computations that are needed before master selection phase */
  172450. {
  172451. #ifdef IDCT_SCALING_SUPPORTED
  172452. int ci;
  172453. jpeg_component_info *compptr;
  172454. #endif
  172455. /* Prevent application from calling me at wrong times */
  172456. if (cinfo->global_state != DSTATE_READY)
  172457. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172458. #ifdef IDCT_SCALING_SUPPORTED
  172459. /* Compute actual output image dimensions and DCT scaling choices. */
  172460. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172461. /* Provide 1/8 scaling */
  172462. cinfo->output_width = (JDIMENSION)
  172463. jdiv_round_up((long) cinfo->image_width, 8L);
  172464. cinfo->output_height = (JDIMENSION)
  172465. jdiv_round_up((long) cinfo->image_height, 8L);
  172466. cinfo->min_DCT_scaled_size = 1;
  172467. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172468. /* Provide 1/4 scaling */
  172469. cinfo->output_width = (JDIMENSION)
  172470. jdiv_round_up((long) cinfo->image_width, 4L);
  172471. cinfo->output_height = (JDIMENSION)
  172472. jdiv_round_up((long) cinfo->image_height, 4L);
  172473. cinfo->min_DCT_scaled_size = 2;
  172474. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172475. /* Provide 1/2 scaling */
  172476. cinfo->output_width = (JDIMENSION)
  172477. jdiv_round_up((long) cinfo->image_width, 2L);
  172478. cinfo->output_height = (JDIMENSION)
  172479. jdiv_round_up((long) cinfo->image_height, 2L);
  172480. cinfo->min_DCT_scaled_size = 4;
  172481. } else {
  172482. /* Provide 1/1 scaling */
  172483. cinfo->output_width = cinfo->image_width;
  172484. cinfo->output_height = cinfo->image_height;
  172485. cinfo->min_DCT_scaled_size = DCTSIZE;
  172486. }
  172487. /* In selecting the actual DCT scaling for each component, we try to
  172488. * scale up the chroma components via IDCT scaling rather than upsampling.
  172489. * This saves time if the upsampler gets to use 1:1 scaling.
  172490. * Note this code assumes that the supported DCT scalings are powers of 2.
  172491. */
  172492. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172493. ci++, compptr++) {
  172494. int ssize = cinfo->min_DCT_scaled_size;
  172495. while (ssize < DCTSIZE &&
  172496. (compptr->h_samp_factor * ssize * 2 <=
  172497. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172498. (compptr->v_samp_factor * ssize * 2 <=
  172499. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172500. ssize = ssize * 2;
  172501. }
  172502. compptr->DCT_scaled_size = ssize;
  172503. }
  172504. /* Recompute downsampled dimensions of components;
  172505. * application needs to know these if using raw downsampled data.
  172506. */
  172507. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172508. ci++, compptr++) {
  172509. /* Size in samples, after IDCT scaling */
  172510. compptr->downsampled_width = (JDIMENSION)
  172511. jdiv_round_up((long) cinfo->image_width *
  172512. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172513. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172514. compptr->downsampled_height = (JDIMENSION)
  172515. jdiv_round_up((long) cinfo->image_height *
  172516. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172517. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172518. }
  172519. #else /* !IDCT_SCALING_SUPPORTED */
  172520. /* Hardwire it to "no scaling" */
  172521. cinfo->output_width = cinfo->image_width;
  172522. cinfo->output_height = cinfo->image_height;
  172523. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172524. * and has computed unscaled downsampled_width and downsampled_height.
  172525. */
  172526. #endif /* IDCT_SCALING_SUPPORTED */
  172527. /* Report number of components in selected colorspace. */
  172528. /* Probably this should be in the color conversion module... */
  172529. switch (cinfo->out_color_space) {
  172530. case JCS_GRAYSCALE:
  172531. cinfo->out_color_components = 1;
  172532. break;
  172533. case JCS_RGB:
  172534. #if RGB_PIXELSIZE != 3
  172535. cinfo->out_color_components = RGB_PIXELSIZE;
  172536. break;
  172537. #endif /* else share code with YCbCr */
  172538. case JCS_YCbCr:
  172539. cinfo->out_color_components = 3;
  172540. break;
  172541. case JCS_CMYK:
  172542. case JCS_YCCK:
  172543. cinfo->out_color_components = 4;
  172544. break;
  172545. default: /* else must be same colorspace as in file */
  172546. cinfo->out_color_components = cinfo->num_components;
  172547. break;
  172548. }
  172549. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172550. cinfo->out_color_components);
  172551. /* See if upsampler will want to emit more than one row at a time */
  172552. if (use_merged_upsample(cinfo))
  172553. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172554. else
  172555. cinfo->rec_outbuf_height = 1;
  172556. }
  172557. /*
  172558. * Several decompression processes need to range-limit values to the range
  172559. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172560. * due to noise introduced by quantization, roundoff error, etc. These
  172561. * processes are inner loops and need to be as fast as possible. On most
  172562. * machines, particularly CPUs with pipelines or instruction prefetch,
  172563. * a (subscript-check-less) C table lookup
  172564. * x = sample_range_limit[x];
  172565. * is faster than explicit tests
  172566. * if (x < 0) x = 0;
  172567. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172568. * These processes all use a common table prepared by the routine below.
  172569. *
  172570. * For most steps we can mathematically guarantee that the initial value
  172571. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172572. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172573. * limiting step (just after the IDCT), a wildly out-of-range value is
  172574. * possible if the input data is corrupt. To avoid any chance of indexing
  172575. * off the end of memory and getting a bad-pointer trap, we perform the
  172576. * post-IDCT limiting thus:
  172577. * x = range_limit[x & MASK];
  172578. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172579. * samples. Under normal circumstances this is more than enough range and
  172580. * a correct output will be generated; with bogus input data the mask will
  172581. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172582. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172583. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172584. * So the post-IDCT limiting table ends up looking like this:
  172585. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172586. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172587. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172588. * 0,1,...,CENTERJSAMPLE-1
  172589. * Negative inputs select values from the upper half of the table after
  172590. * masking.
  172591. *
  172592. * We can save some space by overlapping the start of the post-IDCT table
  172593. * with the simpler range limiting table. The post-IDCT table begins at
  172594. * sample_range_limit + CENTERJSAMPLE.
  172595. *
  172596. * Note that the table is allocated in near data space on PCs; it's small
  172597. * enough and used often enough to justify this.
  172598. */
  172599. LOCAL(void)
  172600. prepare_range_limit_table (j_decompress_ptr cinfo)
  172601. /* Allocate and fill in the sample_range_limit table */
  172602. {
  172603. JSAMPLE * table;
  172604. int i;
  172605. table = (JSAMPLE *)
  172606. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172607. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172608. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172609. cinfo->sample_range_limit = table;
  172610. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172611. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172612. /* Main part of "simple" table: limit[x] = x */
  172613. for (i = 0; i <= MAXJSAMPLE; i++)
  172614. table[i] = (JSAMPLE) i;
  172615. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172616. /* End of simple table, rest of first half of post-IDCT table */
  172617. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172618. table[i] = MAXJSAMPLE;
  172619. /* Second half of post-IDCT table */
  172620. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172621. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172622. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172623. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172624. }
  172625. /*
  172626. * Master selection of decompression modules.
  172627. * This is done once at jpeg_start_decompress time. We determine
  172628. * which modules will be used and give them appropriate initialization calls.
  172629. * We also initialize the decompressor input side to begin consuming data.
  172630. *
  172631. * Since jpeg_read_header has finished, we know what is in the SOF
  172632. * and (first) SOS markers. We also have all the application parameter
  172633. * settings.
  172634. */
  172635. LOCAL(void)
  172636. master_selection (j_decompress_ptr cinfo)
  172637. {
  172638. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172639. boolean use_c_buffer;
  172640. long samplesperrow;
  172641. JDIMENSION jd_samplesperrow;
  172642. /* Initialize dimensions and other stuff */
  172643. jpeg_calc_output_dimensions(cinfo);
  172644. prepare_range_limit_table(cinfo);
  172645. /* Width of an output scanline must be representable as JDIMENSION. */
  172646. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172647. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172648. if ((long) jd_samplesperrow != samplesperrow)
  172649. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172650. /* Initialize my private state */
  172651. master->pass_number = 0;
  172652. master->using_merged_upsample = use_merged_upsample(cinfo);
  172653. /* Color quantizer selection */
  172654. master->quantizer_1pass = NULL;
  172655. master->quantizer_2pass = NULL;
  172656. /* No mode changes if not using buffered-image mode. */
  172657. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172658. cinfo->enable_1pass_quant = FALSE;
  172659. cinfo->enable_external_quant = FALSE;
  172660. cinfo->enable_2pass_quant = FALSE;
  172661. }
  172662. if (cinfo->quantize_colors) {
  172663. if (cinfo->raw_data_out)
  172664. ERREXIT(cinfo, JERR_NOTIMPL);
  172665. /* 2-pass quantizer only works in 3-component color space. */
  172666. if (cinfo->out_color_components != 3) {
  172667. cinfo->enable_1pass_quant = TRUE;
  172668. cinfo->enable_external_quant = FALSE;
  172669. cinfo->enable_2pass_quant = FALSE;
  172670. cinfo->colormap = NULL;
  172671. } else if (cinfo->colormap != NULL) {
  172672. cinfo->enable_external_quant = TRUE;
  172673. } else if (cinfo->two_pass_quantize) {
  172674. cinfo->enable_2pass_quant = TRUE;
  172675. } else {
  172676. cinfo->enable_1pass_quant = TRUE;
  172677. }
  172678. if (cinfo->enable_1pass_quant) {
  172679. #ifdef QUANT_1PASS_SUPPORTED
  172680. jinit_1pass_quantizer(cinfo);
  172681. master->quantizer_1pass = cinfo->cquantize;
  172682. #else
  172683. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172684. #endif
  172685. }
  172686. /* We use the 2-pass code to map to external colormaps. */
  172687. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172688. #ifdef QUANT_2PASS_SUPPORTED
  172689. jinit_2pass_quantizer(cinfo);
  172690. master->quantizer_2pass = cinfo->cquantize;
  172691. #else
  172692. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172693. #endif
  172694. }
  172695. /* If both quantizers are initialized, the 2-pass one is left active;
  172696. * this is necessary for starting with quantization to an external map.
  172697. */
  172698. }
  172699. /* Post-processing: in particular, color conversion first */
  172700. if (! cinfo->raw_data_out) {
  172701. if (master->using_merged_upsample) {
  172702. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172703. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172704. #else
  172705. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172706. #endif
  172707. } else {
  172708. jinit_color_deconverter(cinfo);
  172709. jinit_upsampler(cinfo);
  172710. }
  172711. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172712. }
  172713. /* Inverse DCT */
  172714. jinit_inverse_dct(cinfo);
  172715. /* Entropy decoding: either Huffman or arithmetic coding. */
  172716. if (cinfo->arith_code) {
  172717. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172718. } else {
  172719. if (cinfo->progressive_mode) {
  172720. #ifdef D_PROGRESSIVE_SUPPORTED
  172721. jinit_phuff_decoder(cinfo);
  172722. #else
  172723. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172724. #endif
  172725. } else
  172726. jinit_huff_decoder(cinfo);
  172727. }
  172728. /* Initialize principal buffer controllers. */
  172729. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172730. jinit_d_coef_controller(cinfo, use_c_buffer);
  172731. if (! cinfo->raw_data_out)
  172732. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172733. /* We can now tell the memory manager to allocate virtual arrays. */
  172734. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172735. /* Initialize input side of decompressor to consume first scan. */
  172736. (*cinfo->inputctl->start_input_pass) (cinfo);
  172737. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172738. /* If jpeg_start_decompress will read the whole file, initialize
  172739. * progress monitoring appropriately. The input step is counted
  172740. * as one pass.
  172741. */
  172742. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172743. cinfo->inputctl->has_multiple_scans) {
  172744. int nscans;
  172745. /* Estimate number of scans to set pass_limit. */
  172746. if (cinfo->progressive_mode) {
  172747. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172748. nscans = 2 + 3 * cinfo->num_components;
  172749. } else {
  172750. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172751. nscans = cinfo->num_components;
  172752. }
  172753. cinfo->progress->pass_counter = 0L;
  172754. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172755. cinfo->progress->completed_passes = 0;
  172756. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172757. /* Count the input pass as done */
  172758. master->pass_number++;
  172759. }
  172760. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172761. }
  172762. /*
  172763. * Per-pass setup.
  172764. * This is called at the beginning of each output pass. We determine which
  172765. * modules will be active during this pass and give them appropriate
  172766. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172767. * is a "real" output pass or a dummy pass for color quantization.
  172768. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172769. */
  172770. METHODDEF(void)
  172771. prepare_for_output_pass (j_decompress_ptr cinfo)
  172772. {
  172773. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172774. if (master->pub.is_dummy_pass) {
  172775. #ifdef QUANT_2PASS_SUPPORTED
  172776. /* Final pass of 2-pass quantization */
  172777. master->pub.is_dummy_pass = FALSE;
  172778. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172779. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172780. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172781. #else
  172782. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172783. #endif /* QUANT_2PASS_SUPPORTED */
  172784. } else {
  172785. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172786. /* Select new quantization method */
  172787. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172788. cinfo->cquantize = master->quantizer_2pass;
  172789. master->pub.is_dummy_pass = TRUE;
  172790. } else if (cinfo->enable_1pass_quant) {
  172791. cinfo->cquantize = master->quantizer_1pass;
  172792. } else {
  172793. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172794. }
  172795. }
  172796. (*cinfo->idct->start_pass) (cinfo);
  172797. (*cinfo->coef->start_output_pass) (cinfo);
  172798. if (! cinfo->raw_data_out) {
  172799. if (! master->using_merged_upsample)
  172800. (*cinfo->cconvert->start_pass) (cinfo);
  172801. (*cinfo->upsample->start_pass) (cinfo);
  172802. if (cinfo->quantize_colors)
  172803. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172804. (*cinfo->post->start_pass) (cinfo,
  172805. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172806. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172807. }
  172808. }
  172809. /* Set up progress monitor's pass info if present */
  172810. if (cinfo->progress != NULL) {
  172811. cinfo->progress->completed_passes = master->pass_number;
  172812. cinfo->progress->total_passes = master->pass_number +
  172813. (master->pub.is_dummy_pass ? 2 : 1);
  172814. /* In buffered-image mode, we assume one more output pass if EOI not
  172815. * yet reached, but no more passes if EOI has been reached.
  172816. */
  172817. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172818. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172819. }
  172820. }
  172821. }
  172822. /*
  172823. * Finish up at end of an output pass.
  172824. */
  172825. METHODDEF(void)
  172826. finish_output_pass (j_decompress_ptr cinfo)
  172827. {
  172828. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172829. if (cinfo->quantize_colors)
  172830. (*cinfo->cquantize->finish_pass) (cinfo);
  172831. master->pass_number++;
  172832. }
  172833. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172834. /*
  172835. * Switch to a new external colormap between output passes.
  172836. */
  172837. GLOBAL(void)
  172838. jpeg_new_colormap (j_decompress_ptr cinfo)
  172839. {
  172840. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172841. /* Prevent application from calling me at wrong times */
  172842. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172843. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172844. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172845. cinfo->colormap != NULL) {
  172846. /* Select 2-pass quantizer for external colormap use */
  172847. cinfo->cquantize = master->quantizer_2pass;
  172848. /* Notify quantizer of colormap change */
  172849. (*cinfo->cquantize->new_color_map) (cinfo);
  172850. master->pub.is_dummy_pass = FALSE; /* just in case */
  172851. } else
  172852. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172853. }
  172854. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172855. /*
  172856. * Initialize master decompression control and select active modules.
  172857. * This is performed at the start of jpeg_start_decompress.
  172858. */
  172859. GLOBAL(void)
  172860. jinit_master_decompress (j_decompress_ptr cinfo)
  172861. {
  172862. my_master_ptr6 master;
  172863. master = (my_master_ptr6)
  172864. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172865. SIZEOF(my_decomp_master));
  172866. cinfo->master = (struct jpeg_decomp_master *) master;
  172867. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172868. master->pub.finish_output_pass = finish_output_pass;
  172869. master->pub.is_dummy_pass = FALSE;
  172870. master_selection(cinfo);
  172871. }
  172872. /*** End of inlined file: jdmaster.c ***/
  172873. #undef FIX
  172874. /*** Start of inlined file: jdmerge.c ***/
  172875. #define JPEG_INTERNALS
  172876. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172877. /* Private subobject */
  172878. typedef struct {
  172879. struct jpeg_upsampler pub; /* public fields */
  172880. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172881. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172882. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172883. JSAMPARRAY output_buf));
  172884. /* Private state for YCC->RGB conversion */
  172885. int * Cr_r_tab; /* => table for Cr to R conversion */
  172886. int * Cb_b_tab; /* => table for Cb to B conversion */
  172887. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172888. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172889. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172890. * We need a "spare" row buffer to hold the second output row if the
  172891. * application provides just a one-row buffer; we also use the spare
  172892. * to discard the dummy last row if the image height is odd.
  172893. */
  172894. JSAMPROW spare_row;
  172895. boolean spare_full; /* T if spare buffer is occupied */
  172896. JDIMENSION out_row_width; /* samples per output row */
  172897. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172898. } my_upsampler;
  172899. typedef my_upsampler * my_upsample_ptr;
  172900. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172901. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172902. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172903. /*
  172904. * Initialize tables for YCC->RGB colorspace conversion.
  172905. * This is taken directly from jdcolor.c; see that file for more info.
  172906. */
  172907. LOCAL(void)
  172908. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172909. {
  172910. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172911. int i;
  172912. INT32 x;
  172913. SHIFT_TEMPS
  172914. upsample->Cr_r_tab = (int *)
  172915. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172916. (MAXJSAMPLE+1) * SIZEOF(int));
  172917. upsample->Cb_b_tab = (int *)
  172918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172919. (MAXJSAMPLE+1) * SIZEOF(int));
  172920. upsample->Cr_g_tab = (INT32 *)
  172921. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172922. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172923. upsample->Cb_g_tab = (INT32 *)
  172924. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172925. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172926. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172927. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172928. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172929. /* Cr=>R value is nearest int to 1.40200 * x */
  172930. upsample->Cr_r_tab[i] = (int)
  172931. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172932. /* Cb=>B value is nearest int to 1.77200 * x */
  172933. upsample->Cb_b_tab[i] = (int)
  172934. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172935. /* Cr=>G value is scaled-up -0.71414 * x */
  172936. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172937. /* Cb=>G value is scaled-up -0.34414 * x */
  172938. /* We also add in ONE_HALF so that need not do it in inner loop */
  172939. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172940. }
  172941. }
  172942. /*
  172943. * Initialize for an upsampling pass.
  172944. */
  172945. METHODDEF(void)
  172946. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172947. {
  172948. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172949. /* Mark the spare buffer empty */
  172950. upsample->spare_full = FALSE;
  172951. /* Initialize total-height counter for detecting bottom of image */
  172952. upsample->rows_to_go = cinfo->output_height;
  172953. }
  172954. /*
  172955. * Control routine to do upsampling (and color conversion).
  172956. *
  172957. * The control routine just handles the row buffering considerations.
  172958. */
  172959. METHODDEF(void)
  172960. merged_2v_upsample (j_decompress_ptr cinfo,
  172961. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172962. JDIMENSION,
  172963. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172964. JDIMENSION out_rows_avail)
  172965. /* 2:1 vertical sampling case: may need a spare row. */
  172966. {
  172967. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172968. JSAMPROW work_ptrs[2];
  172969. JDIMENSION num_rows; /* number of rows returned to caller */
  172970. if (upsample->spare_full) {
  172971. /* If we have a spare row saved from a previous cycle, just return it. */
  172972. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172973. 1, upsample->out_row_width);
  172974. num_rows = 1;
  172975. upsample->spare_full = FALSE;
  172976. } else {
  172977. /* Figure number of rows to return to caller. */
  172978. num_rows = 2;
  172979. /* Not more than the distance to the end of the image. */
  172980. if (num_rows > upsample->rows_to_go)
  172981. num_rows = upsample->rows_to_go;
  172982. /* And not more than what the client can accept: */
  172983. out_rows_avail -= *out_row_ctr;
  172984. if (num_rows > out_rows_avail)
  172985. num_rows = out_rows_avail;
  172986. /* Create output pointer array for upsampler. */
  172987. work_ptrs[0] = output_buf[*out_row_ctr];
  172988. if (num_rows > 1) {
  172989. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172990. } else {
  172991. work_ptrs[1] = upsample->spare_row;
  172992. upsample->spare_full = TRUE;
  172993. }
  172994. /* Now do the upsampling. */
  172995. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172996. }
  172997. /* Adjust counts */
  172998. *out_row_ctr += num_rows;
  172999. upsample->rows_to_go -= num_rows;
  173000. /* When the buffer is emptied, declare this input row group consumed */
  173001. if (! upsample->spare_full)
  173002. (*in_row_group_ctr)++;
  173003. }
  173004. METHODDEF(void)
  173005. merged_1v_upsample (j_decompress_ptr cinfo,
  173006. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173007. JDIMENSION,
  173008. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173009. JDIMENSION)
  173010. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173011. {
  173012. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173013. /* Just do the upsampling. */
  173014. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173015. output_buf + *out_row_ctr);
  173016. /* Adjust counts */
  173017. (*out_row_ctr)++;
  173018. (*in_row_group_ctr)++;
  173019. }
  173020. /*
  173021. * These are the routines invoked by the control routines to do
  173022. * the actual upsampling/conversion. One row group is processed per call.
  173023. *
  173024. * Note: since we may be writing directly into application-supplied buffers,
  173025. * we have to be honest about the output width; we can't assume the buffer
  173026. * has been rounded up to an even width.
  173027. */
  173028. /*
  173029. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173030. */
  173031. METHODDEF(void)
  173032. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173033. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173034. JSAMPARRAY output_buf)
  173035. {
  173036. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173037. register int y, cred, cgreen, cblue;
  173038. int cb, cr;
  173039. register JSAMPROW outptr;
  173040. JSAMPROW inptr0, inptr1, inptr2;
  173041. JDIMENSION col;
  173042. /* copy these pointers into registers if possible */
  173043. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173044. int * Crrtab = upsample->Cr_r_tab;
  173045. int * Cbbtab = upsample->Cb_b_tab;
  173046. INT32 * Crgtab = upsample->Cr_g_tab;
  173047. INT32 * Cbgtab = upsample->Cb_g_tab;
  173048. SHIFT_TEMPS
  173049. inptr0 = input_buf[0][in_row_group_ctr];
  173050. inptr1 = input_buf[1][in_row_group_ctr];
  173051. inptr2 = input_buf[2][in_row_group_ctr];
  173052. outptr = output_buf[0];
  173053. /* Loop for each pair of output pixels */
  173054. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173055. /* Do the chroma part of the calculation */
  173056. cb = GETJSAMPLE(*inptr1++);
  173057. cr = GETJSAMPLE(*inptr2++);
  173058. cred = Crrtab[cr];
  173059. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173060. cblue = Cbbtab[cb];
  173061. /* Fetch 2 Y values and emit 2 pixels */
  173062. y = GETJSAMPLE(*inptr0++);
  173063. outptr[RGB_RED] = range_limit[y + cred];
  173064. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173065. outptr[RGB_BLUE] = range_limit[y + cblue];
  173066. outptr += RGB_PIXELSIZE;
  173067. y = GETJSAMPLE(*inptr0++);
  173068. outptr[RGB_RED] = range_limit[y + cred];
  173069. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173070. outptr[RGB_BLUE] = range_limit[y + cblue];
  173071. outptr += RGB_PIXELSIZE;
  173072. }
  173073. /* If image width is odd, do the last output column separately */
  173074. if (cinfo->output_width & 1) {
  173075. cb = GETJSAMPLE(*inptr1);
  173076. cr = GETJSAMPLE(*inptr2);
  173077. cred = Crrtab[cr];
  173078. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173079. cblue = Cbbtab[cb];
  173080. y = GETJSAMPLE(*inptr0);
  173081. outptr[RGB_RED] = range_limit[y + cred];
  173082. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173083. outptr[RGB_BLUE] = range_limit[y + cblue];
  173084. }
  173085. }
  173086. /*
  173087. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173088. */
  173089. METHODDEF(void)
  173090. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173091. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173092. JSAMPARRAY output_buf)
  173093. {
  173094. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173095. register int y, cred, cgreen, cblue;
  173096. int cb, cr;
  173097. register JSAMPROW outptr0, outptr1;
  173098. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173099. JDIMENSION col;
  173100. /* copy these pointers into registers if possible */
  173101. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173102. int * Crrtab = upsample->Cr_r_tab;
  173103. int * Cbbtab = upsample->Cb_b_tab;
  173104. INT32 * Crgtab = upsample->Cr_g_tab;
  173105. INT32 * Cbgtab = upsample->Cb_g_tab;
  173106. SHIFT_TEMPS
  173107. inptr00 = input_buf[0][in_row_group_ctr*2];
  173108. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173109. inptr1 = input_buf[1][in_row_group_ctr];
  173110. inptr2 = input_buf[2][in_row_group_ctr];
  173111. outptr0 = output_buf[0];
  173112. outptr1 = output_buf[1];
  173113. /* Loop for each group of output pixels */
  173114. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173115. /* Do the chroma part of the calculation */
  173116. cb = GETJSAMPLE(*inptr1++);
  173117. cr = GETJSAMPLE(*inptr2++);
  173118. cred = Crrtab[cr];
  173119. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173120. cblue = Cbbtab[cb];
  173121. /* Fetch 4 Y values and emit 4 pixels */
  173122. y = GETJSAMPLE(*inptr00++);
  173123. outptr0[RGB_RED] = range_limit[y + cred];
  173124. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173125. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173126. outptr0 += RGB_PIXELSIZE;
  173127. y = GETJSAMPLE(*inptr00++);
  173128. outptr0[RGB_RED] = range_limit[y + cred];
  173129. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173130. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173131. outptr0 += RGB_PIXELSIZE;
  173132. y = GETJSAMPLE(*inptr01++);
  173133. outptr1[RGB_RED] = range_limit[y + cred];
  173134. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173135. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173136. outptr1 += RGB_PIXELSIZE;
  173137. y = GETJSAMPLE(*inptr01++);
  173138. outptr1[RGB_RED] = range_limit[y + cred];
  173139. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173140. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173141. outptr1 += RGB_PIXELSIZE;
  173142. }
  173143. /* If image width is odd, do the last output column separately */
  173144. if (cinfo->output_width & 1) {
  173145. cb = GETJSAMPLE(*inptr1);
  173146. cr = GETJSAMPLE(*inptr2);
  173147. cred = Crrtab[cr];
  173148. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173149. cblue = Cbbtab[cb];
  173150. y = GETJSAMPLE(*inptr00);
  173151. outptr0[RGB_RED] = range_limit[y + cred];
  173152. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173153. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173154. y = GETJSAMPLE(*inptr01);
  173155. outptr1[RGB_RED] = range_limit[y + cred];
  173156. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173157. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173158. }
  173159. }
  173160. /*
  173161. * Module initialization routine for merged upsampling/color conversion.
  173162. *
  173163. * NB: this is called under the conditions determined by use_merged_upsample()
  173164. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173165. * of this module; no safety checks are made here.
  173166. */
  173167. GLOBAL(void)
  173168. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173169. {
  173170. my_upsample_ptr upsample;
  173171. upsample = (my_upsample_ptr)
  173172. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173173. SIZEOF(my_upsampler));
  173174. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173175. upsample->pub.start_pass = start_pass_merged_upsample;
  173176. upsample->pub.need_context_rows = FALSE;
  173177. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173178. if (cinfo->max_v_samp_factor == 2) {
  173179. upsample->pub.upsample = merged_2v_upsample;
  173180. upsample->upmethod = h2v2_merged_upsample;
  173181. /* Allocate a spare row buffer */
  173182. upsample->spare_row = (JSAMPROW)
  173183. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173184. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173185. } else {
  173186. upsample->pub.upsample = merged_1v_upsample;
  173187. upsample->upmethod = h2v1_merged_upsample;
  173188. /* No spare row needed */
  173189. upsample->spare_row = NULL;
  173190. }
  173191. build_ycc_rgb_table2(cinfo);
  173192. }
  173193. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173194. /*** End of inlined file: jdmerge.c ***/
  173195. #undef ASSIGN_STATE
  173196. /*** Start of inlined file: jdphuff.c ***/
  173197. #define JPEG_INTERNALS
  173198. #ifdef D_PROGRESSIVE_SUPPORTED
  173199. /*
  173200. * Expanded entropy decoder object for progressive Huffman decoding.
  173201. *
  173202. * The savable_state subrecord contains fields that change within an MCU,
  173203. * but must not be updated permanently until we complete the MCU.
  173204. */
  173205. typedef struct {
  173206. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173207. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173208. } savable_state3;
  173209. /* This macro is to work around compilers with missing or broken
  173210. * structure assignment. You'll need to fix this code if you have
  173211. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173212. */
  173213. #ifndef NO_STRUCT_ASSIGN
  173214. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173215. #else
  173216. #if MAX_COMPS_IN_SCAN == 4
  173217. #define ASSIGN_STATE(dest,src) \
  173218. ((dest).EOBRUN = (src).EOBRUN, \
  173219. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173220. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173221. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173222. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173223. #endif
  173224. #endif
  173225. typedef struct {
  173226. struct jpeg_entropy_decoder pub; /* public fields */
  173227. /* These fields are loaded into local variables at start of each MCU.
  173228. * In case of suspension, we exit WITHOUT updating them.
  173229. */
  173230. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173231. savable_state3 saved; /* Other state at start of MCU */
  173232. /* These fields are NOT loaded into local working state. */
  173233. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173234. /* Pointers to derived tables (these workspaces have image lifespan) */
  173235. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173236. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173237. } phuff_entropy_decoder;
  173238. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173239. /* Forward declarations */
  173240. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173241. JBLOCKROW *MCU_data));
  173242. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173243. JBLOCKROW *MCU_data));
  173244. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173245. JBLOCKROW *MCU_data));
  173246. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173247. JBLOCKROW *MCU_data));
  173248. /*
  173249. * Initialize for a Huffman-compressed scan.
  173250. */
  173251. METHODDEF(void)
  173252. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173253. {
  173254. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173255. boolean is_DC_band, bad;
  173256. int ci, coefi, tbl;
  173257. int *coef_bit_ptr;
  173258. jpeg_component_info * compptr;
  173259. is_DC_band = (cinfo->Ss == 0);
  173260. /* Validate scan parameters */
  173261. bad = FALSE;
  173262. if (is_DC_band) {
  173263. if (cinfo->Se != 0)
  173264. bad = TRUE;
  173265. } else {
  173266. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173267. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173268. bad = TRUE;
  173269. /* AC scans may have only one component */
  173270. if (cinfo->comps_in_scan != 1)
  173271. bad = TRUE;
  173272. }
  173273. if (cinfo->Ah != 0) {
  173274. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173275. if (cinfo->Al != cinfo->Ah-1)
  173276. bad = TRUE;
  173277. }
  173278. if (cinfo->Al > 13) /* need not check for < 0 */
  173279. bad = TRUE;
  173280. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173281. * but the spec doesn't say so, and we try to be liberal about what we
  173282. * accept. Note: large Al values could result in out-of-range DC
  173283. * coefficients during early scans, leading to bizarre displays due to
  173284. * overflows in the IDCT math. But we won't crash.
  173285. */
  173286. if (bad)
  173287. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173288. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173289. /* Update progression status, and verify that scan order is legal.
  173290. * Note that inter-scan inconsistencies are treated as warnings
  173291. * not fatal errors ... not clear if this is right way to behave.
  173292. */
  173293. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173294. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173295. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173296. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173297. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173298. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173299. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173300. if (cinfo->Ah != expected)
  173301. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173302. coef_bit_ptr[coefi] = cinfo->Al;
  173303. }
  173304. }
  173305. /* Select MCU decoding routine */
  173306. if (cinfo->Ah == 0) {
  173307. if (is_DC_band)
  173308. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173309. else
  173310. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173311. } else {
  173312. if (is_DC_band)
  173313. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173314. else
  173315. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173316. }
  173317. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173318. compptr = cinfo->cur_comp_info[ci];
  173319. /* Make sure requested tables are present, and compute derived tables.
  173320. * We may build same derived table more than once, but it's not expensive.
  173321. */
  173322. if (is_DC_band) {
  173323. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173324. tbl = compptr->dc_tbl_no;
  173325. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173326. & entropy->derived_tbls[tbl]);
  173327. }
  173328. } else {
  173329. tbl = compptr->ac_tbl_no;
  173330. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173331. & entropy->derived_tbls[tbl]);
  173332. /* remember the single active table */
  173333. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173334. }
  173335. /* Initialize DC predictions to 0 */
  173336. entropy->saved.last_dc_val[ci] = 0;
  173337. }
  173338. /* Initialize bitread state variables */
  173339. entropy->bitstate.bits_left = 0;
  173340. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173341. entropy->pub.insufficient_data = FALSE;
  173342. /* Initialize private state variables */
  173343. entropy->saved.EOBRUN = 0;
  173344. /* Initialize restart counter */
  173345. entropy->restarts_to_go = cinfo->restart_interval;
  173346. }
  173347. /*
  173348. * Check for a restart marker & resynchronize decoder.
  173349. * Returns FALSE if must suspend.
  173350. */
  173351. LOCAL(boolean)
  173352. process_restartp (j_decompress_ptr cinfo)
  173353. {
  173354. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173355. int ci;
  173356. /* Throw away any unused bits remaining in bit buffer; */
  173357. /* include any full bytes in next_marker's count of discarded bytes */
  173358. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173359. entropy->bitstate.bits_left = 0;
  173360. /* Advance past the RSTn marker */
  173361. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173362. return FALSE;
  173363. /* Re-initialize DC predictions to 0 */
  173364. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173365. entropy->saved.last_dc_val[ci] = 0;
  173366. /* Re-init EOB run count, too */
  173367. entropy->saved.EOBRUN = 0;
  173368. /* Reset restart counter */
  173369. entropy->restarts_to_go = cinfo->restart_interval;
  173370. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173371. * against a marker. In that case we will end up treating the next data
  173372. * segment as empty, and we can avoid producing bogus output pixels by
  173373. * leaving the flag set.
  173374. */
  173375. if (cinfo->unread_marker == 0)
  173376. entropy->pub.insufficient_data = FALSE;
  173377. return TRUE;
  173378. }
  173379. /*
  173380. * Huffman MCU decoding.
  173381. * Each of these routines decodes and returns one MCU's worth of
  173382. * Huffman-compressed coefficients.
  173383. * The coefficients are reordered from zigzag order into natural array order,
  173384. * but are not dequantized.
  173385. *
  173386. * The i'th block of the MCU is stored into the block pointed to by
  173387. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173388. *
  173389. * We return FALSE if data source requested suspension. In that case no
  173390. * changes have been made to permanent state. (Exception: some output
  173391. * coefficients may already have been assigned. This is harmless for
  173392. * spectral selection, since we'll just re-assign them on the next call.
  173393. * Successive approximation AC refinement has to be more careful, however.)
  173394. */
  173395. /*
  173396. * MCU decoding for DC initial scan (either spectral selection,
  173397. * or first pass of successive approximation).
  173398. */
  173399. METHODDEF(boolean)
  173400. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173401. {
  173402. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173403. int Al = cinfo->Al;
  173404. register int s, r;
  173405. int blkn, ci;
  173406. JBLOCKROW block;
  173407. BITREAD_STATE_VARS;
  173408. savable_state3 state;
  173409. d_derived_tbl * tbl;
  173410. jpeg_component_info * compptr;
  173411. /* Process restart marker if needed; may have to suspend */
  173412. if (cinfo->restart_interval) {
  173413. if (entropy->restarts_to_go == 0)
  173414. if (! process_restartp(cinfo))
  173415. return FALSE;
  173416. }
  173417. /* If we've run out of data, just leave the MCU set to zeroes.
  173418. * This way, we return uniform gray for the remainder of the segment.
  173419. */
  173420. if (! entropy->pub.insufficient_data) {
  173421. /* Load up working state */
  173422. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173423. ASSIGN_STATE(state, entropy->saved);
  173424. /* Outer loop handles each block in the MCU */
  173425. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173426. block = MCU_data[blkn];
  173427. ci = cinfo->MCU_membership[blkn];
  173428. compptr = cinfo->cur_comp_info[ci];
  173429. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173430. /* Decode a single block's worth of coefficients */
  173431. /* Section F.2.2.1: decode the DC coefficient difference */
  173432. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173433. if (s) {
  173434. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173435. r = GET_BITS(s);
  173436. s = HUFF_EXTEND(r, s);
  173437. }
  173438. /* Convert DC difference to actual value, update last_dc_val */
  173439. s += state.last_dc_val[ci];
  173440. state.last_dc_val[ci] = s;
  173441. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173442. (*block)[0] = (JCOEF) (s << Al);
  173443. }
  173444. /* Completed MCU, so update state */
  173445. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173446. ASSIGN_STATE(entropy->saved, state);
  173447. }
  173448. /* Account for restart interval (no-op if not using restarts) */
  173449. entropy->restarts_to_go--;
  173450. return TRUE;
  173451. }
  173452. /*
  173453. * MCU decoding for AC initial scan (either spectral selection,
  173454. * or first pass of successive approximation).
  173455. */
  173456. METHODDEF(boolean)
  173457. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173458. {
  173459. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173460. int Se = cinfo->Se;
  173461. int Al = cinfo->Al;
  173462. register int s, k, r;
  173463. unsigned int EOBRUN;
  173464. JBLOCKROW block;
  173465. BITREAD_STATE_VARS;
  173466. d_derived_tbl * tbl;
  173467. /* Process restart marker if needed; may have to suspend */
  173468. if (cinfo->restart_interval) {
  173469. if (entropy->restarts_to_go == 0)
  173470. if (! process_restartp(cinfo))
  173471. return FALSE;
  173472. }
  173473. /* If we've run out of data, just leave the MCU set to zeroes.
  173474. * This way, we return uniform gray for the remainder of the segment.
  173475. */
  173476. if (! entropy->pub.insufficient_data) {
  173477. /* Load up working state.
  173478. * We can avoid loading/saving bitread state if in an EOB run.
  173479. */
  173480. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173481. /* There is always only one block per MCU */
  173482. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173483. EOBRUN--; /* ...process it now (we do nothing) */
  173484. else {
  173485. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173486. block = MCU_data[0];
  173487. tbl = entropy->ac_derived_tbl;
  173488. for (k = cinfo->Ss; k <= Se; k++) {
  173489. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173490. r = s >> 4;
  173491. s &= 15;
  173492. if (s) {
  173493. k += r;
  173494. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173495. r = GET_BITS(s);
  173496. s = HUFF_EXTEND(r, s);
  173497. /* Scale and output coefficient in natural (dezigzagged) order */
  173498. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173499. } else {
  173500. if (r == 15) { /* ZRL */
  173501. k += 15; /* skip 15 zeroes in band */
  173502. } else { /* EOBr, run length is 2^r + appended bits */
  173503. EOBRUN = 1 << r;
  173504. if (r) { /* EOBr, r > 0 */
  173505. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173506. r = GET_BITS(r);
  173507. EOBRUN += r;
  173508. }
  173509. EOBRUN--; /* this band is processed at this moment */
  173510. break; /* force end-of-band */
  173511. }
  173512. }
  173513. }
  173514. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173515. }
  173516. /* Completed MCU, so update state */
  173517. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173518. }
  173519. /* Account for restart interval (no-op if not using restarts) */
  173520. entropy->restarts_to_go--;
  173521. return TRUE;
  173522. }
  173523. /*
  173524. * MCU decoding for DC successive approximation refinement scan.
  173525. * Note: we assume such scans can be multi-component, although the spec
  173526. * is not very clear on the point.
  173527. */
  173528. METHODDEF(boolean)
  173529. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173530. {
  173531. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173532. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173533. int blkn;
  173534. JBLOCKROW block;
  173535. BITREAD_STATE_VARS;
  173536. /* Process restart marker if needed; may have to suspend */
  173537. if (cinfo->restart_interval) {
  173538. if (entropy->restarts_to_go == 0)
  173539. if (! process_restartp(cinfo))
  173540. return FALSE;
  173541. }
  173542. /* Not worth the cycles to check insufficient_data here,
  173543. * since we will not change the data anyway if we read zeroes.
  173544. */
  173545. /* Load up working state */
  173546. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173547. /* Outer loop handles each block in the MCU */
  173548. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173549. block = MCU_data[blkn];
  173550. /* Encoded data is simply the next bit of the two's-complement DC value */
  173551. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173552. if (GET_BITS(1))
  173553. (*block)[0] |= p1;
  173554. /* Note: since we use |=, repeating the assignment later is safe */
  173555. }
  173556. /* Completed MCU, so update state */
  173557. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173558. /* Account for restart interval (no-op if not using restarts) */
  173559. entropy->restarts_to_go--;
  173560. return TRUE;
  173561. }
  173562. /*
  173563. * MCU decoding for AC successive approximation refinement scan.
  173564. */
  173565. METHODDEF(boolean)
  173566. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173567. {
  173568. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173569. int Se = cinfo->Se;
  173570. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173571. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173572. register int s, k, r;
  173573. unsigned int EOBRUN;
  173574. JBLOCKROW block;
  173575. JCOEFPTR thiscoef;
  173576. BITREAD_STATE_VARS;
  173577. d_derived_tbl * tbl;
  173578. int num_newnz;
  173579. int newnz_pos[DCTSIZE2];
  173580. /* Process restart marker if needed; may have to suspend */
  173581. if (cinfo->restart_interval) {
  173582. if (entropy->restarts_to_go == 0)
  173583. if (! process_restartp(cinfo))
  173584. return FALSE;
  173585. }
  173586. /* If we've run out of data, don't modify the MCU.
  173587. */
  173588. if (! entropy->pub.insufficient_data) {
  173589. /* Load up working state */
  173590. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173591. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173592. /* There is always only one block per MCU */
  173593. block = MCU_data[0];
  173594. tbl = entropy->ac_derived_tbl;
  173595. /* If we are forced to suspend, we must undo the assignments to any newly
  173596. * nonzero coefficients in the block, because otherwise we'd get confused
  173597. * next time about which coefficients were already nonzero.
  173598. * But we need not undo addition of bits to already-nonzero coefficients;
  173599. * instead, we can test the current bit to see if we already did it.
  173600. */
  173601. num_newnz = 0;
  173602. /* initialize coefficient loop counter to start of band */
  173603. k = cinfo->Ss;
  173604. if (EOBRUN == 0) {
  173605. for (; k <= Se; k++) {
  173606. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173607. r = s >> 4;
  173608. s &= 15;
  173609. if (s) {
  173610. if (s != 1) /* size of new coef should always be 1 */
  173611. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173612. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173613. if (GET_BITS(1))
  173614. s = p1; /* newly nonzero coef is positive */
  173615. else
  173616. s = m1; /* newly nonzero coef is negative */
  173617. } else {
  173618. if (r != 15) {
  173619. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173620. if (r) {
  173621. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173622. r = GET_BITS(r);
  173623. EOBRUN += r;
  173624. }
  173625. break; /* rest of block is handled by EOB logic */
  173626. }
  173627. /* note s = 0 for processing ZRL */
  173628. }
  173629. /* Advance over already-nonzero coefs and r still-zero coefs,
  173630. * appending correction bits to the nonzeroes. A correction bit is 1
  173631. * if the absolute value of the coefficient must be increased.
  173632. */
  173633. do {
  173634. thiscoef = *block + jpeg_natural_order[k];
  173635. if (*thiscoef != 0) {
  173636. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173637. if (GET_BITS(1)) {
  173638. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173639. if (*thiscoef >= 0)
  173640. *thiscoef += p1;
  173641. else
  173642. *thiscoef += m1;
  173643. }
  173644. }
  173645. } else {
  173646. if (--r < 0)
  173647. break; /* reached target zero coefficient */
  173648. }
  173649. k++;
  173650. } while (k <= Se);
  173651. if (s) {
  173652. int pos = jpeg_natural_order[k];
  173653. /* Output newly nonzero coefficient */
  173654. (*block)[pos] = (JCOEF) s;
  173655. /* Remember its position in case we have to suspend */
  173656. newnz_pos[num_newnz++] = pos;
  173657. }
  173658. }
  173659. }
  173660. if (EOBRUN > 0) {
  173661. /* Scan any remaining coefficient positions after the end-of-band
  173662. * (the last newly nonzero coefficient, if any). Append a correction
  173663. * bit to each already-nonzero coefficient. A correction bit is 1
  173664. * if the absolute value of the coefficient must be increased.
  173665. */
  173666. for (; k <= Se; k++) {
  173667. thiscoef = *block + jpeg_natural_order[k];
  173668. if (*thiscoef != 0) {
  173669. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173670. if (GET_BITS(1)) {
  173671. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173672. if (*thiscoef >= 0)
  173673. *thiscoef += p1;
  173674. else
  173675. *thiscoef += m1;
  173676. }
  173677. }
  173678. }
  173679. }
  173680. /* Count one block completed in EOB run */
  173681. EOBRUN--;
  173682. }
  173683. /* Completed MCU, so update state */
  173684. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173685. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173686. }
  173687. /* Account for restart interval (no-op if not using restarts) */
  173688. entropy->restarts_to_go--;
  173689. return TRUE;
  173690. undoit:
  173691. /* Re-zero any output coefficients that we made newly nonzero */
  173692. while (num_newnz > 0)
  173693. (*block)[newnz_pos[--num_newnz]] = 0;
  173694. return FALSE;
  173695. }
  173696. /*
  173697. * Module initialization routine for progressive Huffman entropy decoding.
  173698. */
  173699. GLOBAL(void)
  173700. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173701. {
  173702. phuff_entropy_ptr2 entropy;
  173703. int *coef_bit_ptr;
  173704. int ci, i;
  173705. entropy = (phuff_entropy_ptr2)
  173706. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173707. SIZEOF(phuff_entropy_decoder));
  173708. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173709. entropy->pub.start_pass = start_pass_phuff_decoder;
  173710. /* Mark derived tables unallocated */
  173711. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173712. entropy->derived_tbls[i] = NULL;
  173713. }
  173714. /* Create progression status table */
  173715. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173716. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173717. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173718. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173719. for (ci = 0; ci < cinfo->num_components; ci++)
  173720. for (i = 0; i < DCTSIZE2; i++)
  173721. *coef_bit_ptr++ = -1;
  173722. }
  173723. #endif /* D_PROGRESSIVE_SUPPORTED */
  173724. /*** End of inlined file: jdphuff.c ***/
  173725. /*** Start of inlined file: jdpostct.c ***/
  173726. #define JPEG_INTERNALS
  173727. /* Private buffer controller object */
  173728. typedef struct {
  173729. struct jpeg_d_post_controller pub; /* public fields */
  173730. /* Color quantization source buffer: this holds output data from
  173731. * the upsample/color conversion step to be passed to the quantizer.
  173732. * For two-pass color quantization, we need a full-image buffer;
  173733. * for one-pass operation, a strip buffer is sufficient.
  173734. */
  173735. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173736. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173737. JDIMENSION strip_height; /* buffer size in rows */
  173738. /* for two-pass mode only: */
  173739. JDIMENSION starting_row; /* row # of first row in current strip */
  173740. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173741. } my_post_controller;
  173742. typedef my_post_controller * my_post_ptr;
  173743. /* Forward declarations */
  173744. METHODDEF(void) post_process_1pass
  173745. JPP((j_decompress_ptr cinfo,
  173746. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173747. JDIMENSION in_row_groups_avail,
  173748. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173749. JDIMENSION out_rows_avail));
  173750. #ifdef QUANT_2PASS_SUPPORTED
  173751. METHODDEF(void) post_process_prepass
  173752. JPP((j_decompress_ptr cinfo,
  173753. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173754. JDIMENSION in_row_groups_avail,
  173755. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173756. JDIMENSION out_rows_avail));
  173757. METHODDEF(void) post_process_2pass
  173758. JPP((j_decompress_ptr cinfo,
  173759. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173760. JDIMENSION in_row_groups_avail,
  173761. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173762. JDIMENSION out_rows_avail));
  173763. #endif
  173764. /*
  173765. * Initialize for a processing pass.
  173766. */
  173767. METHODDEF(void)
  173768. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173769. {
  173770. my_post_ptr post = (my_post_ptr) cinfo->post;
  173771. switch (pass_mode) {
  173772. case JBUF_PASS_THRU:
  173773. if (cinfo->quantize_colors) {
  173774. /* Single-pass processing with color quantization. */
  173775. post->pub.post_process_data = post_process_1pass;
  173776. /* We could be doing buffered-image output before starting a 2-pass
  173777. * color quantization; in that case, jinit_d_post_controller did not
  173778. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173779. */
  173780. if (post->buffer == NULL) {
  173781. post->buffer = (*cinfo->mem->access_virt_sarray)
  173782. ((j_common_ptr) cinfo, post->whole_image,
  173783. (JDIMENSION) 0, post->strip_height, TRUE);
  173784. }
  173785. } else {
  173786. /* For single-pass processing without color quantization,
  173787. * I have no work to do; just call the upsampler directly.
  173788. */
  173789. post->pub.post_process_data = cinfo->upsample->upsample;
  173790. }
  173791. break;
  173792. #ifdef QUANT_2PASS_SUPPORTED
  173793. case JBUF_SAVE_AND_PASS:
  173794. /* First pass of 2-pass quantization */
  173795. if (post->whole_image == NULL)
  173796. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173797. post->pub.post_process_data = post_process_prepass;
  173798. break;
  173799. case JBUF_CRANK_DEST:
  173800. /* Second pass of 2-pass quantization */
  173801. if (post->whole_image == NULL)
  173802. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173803. post->pub.post_process_data = post_process_2pass;
  173804. break;
  173805. #endif /* QUANT_2PASS_SUPPORTED */
  173806. default:
  173807. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173808. break;
  173809. }
  173810. post->starting_row = post->next_row = 0;
  173811. }
  173812. /*
  173813. * Process some data in the one-pass (strip buffer) case.
  173814. * This is used for color precision reduction as well as one-pass quantization.
  173815. */
  173816. METHODDEF(void)
  173817. post_process_1pass (j_decompress_ptr cinfo,
  173818. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173819. JDIMENSION in_row_groups_avail,
  173820. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173821. JDIMENSION out_rows_avail)
  173822. {
  173823. my_post_ptr post = (my_post_ptr) cinfo->post;
  173824. JDIMENSION num_rows, max_rows;
  173825. /* Fill the buffer, but not more than what we can dump out in one go. */
  173826. /* Note we rely on the upsampler to detect bottom of image. */
  173827. max_rows = out_rows_avail - *out_row_ctr;
  173828. if (max_rows > post->strip_height)
  173829. max_rows = post->strip_height;
  173830. num_rows = 0;
  173831. (*cinfo->upsample->upsample) (cinfo,
  173832. input_buf, in_row_group_ctr, in_row_groups_avail,
  173833. post->buffer, &num_rows, max_rows);
  173834. /* Quantize and emit data. */
  173835. (*cinfo->cquantize->color_quantize) (cinfo,
  173836. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173837. *out_row_ctr += num_rows;
  173838. }
  173839. #ifdef QUANT_2PASS_SUPPORTED
  173840. /*
  173841. * Process some data in the first pass of 2-pass quantization.
  173842. */
  173843. METHODDEF(void)
  173844. post_process_prepass (j_decompress_ptr cinfo,
  173845. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173846. JDIMENSION in_row_groups_avail,
  173847. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173848. JDIMENSION)
  173849. {
  173850. my_post_ptr post = (my_post_ptr) cinfo->post;
  173851. JDIMENSION old_next_row, num_rows;
  173852. /* Reposition virtual buffer if at start of strip. */
  173853. if (post->next_row == 0) {
  173854. post->buffer = (*cinfo->mem->access_virt_sarray)
  173855. ((j_common_ptr) cinfo, post->whole_image,
  173856. post->starting_row, post->strip_height, TRUE);
  173857. }
  173858. /* Upsample some data (up to a strip height's worth). */
  173859. old_next_row = post->next_row;
  173860. (*cinfo->upsample->upsample) (cinfo,
  173861. input_buf, in_row_group_ctr, in_row_groups_avail,
  173862. post->buffer, &post->next_row, post->strip_height);
  173863. /* Allow quantizer to scan new data. No data is emitted, */
  173864. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173865. if (post->next_row > old_next_row) {
  173866. num_rows = post->next_row - old_next_row;
  173867. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173868. (JSAMPARRAY) NULL, (int) num_rows);
  173869. *out_row_ctr += num_rows;
  173870. }
  173871. /* Advance if we filled the strip. */
  173872. if (post->next_row >= post->strip_height) {
  173873. post->starting_row += post->strip_height;
  173874. post->next_row = 0;
  173875. }
  173876. }
  173877. /*
  173878. * Process some data in the second pass of 2-pass quantization.
  173879. */
  173880. METHODDEF(void)
  173881. post_process_2pass (j_decompress_ptr cinfo,
  173882. JSAMPIMAGE, JDIMENSION *,
  173883. JDIMENSION,
  173884. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173885. JDIMENSION out_rows_avail)
  173886. {
  173887. my_post_ptr post = (my_post_ptr) cinfo->post;
  173888. JDIMENSION num_rows, max_rows;
  173889. /* Reposition virtual buffer if at start of strip. */
  173890. if (post->next_row == 0) {
  173891. post->buffer = (*cinfo->mem->access_virt_sarray)
  173892. ((j_common_ptr) cinfo, post->whole_image,
  173893. post->starting_row, post->strip_height, FALSE);
  173894. }
  173895. /* Determine number of rows to emit. */
  173896. num_rows = post->strip_height - post->next_row; /* available in strip */
  173897. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173898. if (num_rows > max_rows)
  173899. num_rows = max_rows;
  173900. /* We have to check bottom of image here, can't depend on upsampler. */
  173901. max_rows = cinfo->output_height - post->starting_row;
  173902. if (num_rows > max_rows)
  173903. num_rows = max_rows;
  173904. /* Quantize and emit data. */
  173905. (*cinfo->cquantize->color_quantize) (cinfo,
  173906. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173907. (int) num_rows);
  173908. *out_row_ctr += num_rows;
  173909. /* Advance if we filled the strip. */
  173910. post->next_row += num_rows;
  173911. if (post->next_row >= post->strip_height) {
  173912. post->starting_row += post->strip_height;
  173913. post->next_row = 0;
  173914. }
  173915. }
  173916. #endif /* QUANT_2PASS_SUPPORTED */
  173917. /*
  173918. * Initialize postprocessing controller.
  173919. */
  173920. GLOBAL(void)
  173921. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173922. {
  173923. my_post_ptr post;
  173924. post = (my_post_ptr)
  173925. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173926. SIZEOF(my_post_controller));
  173927. cinfo->post = (struct jpeg_d_post_controller *) post;
  173928. post->pub.start_pass = start_pass_dpost;
  173929. post->whole_image = NULL; /* flag for no virtual arrays */
  173930. post->buffer = NULL; /* flag for no strip buffer */
  173931. /* Create the quantization buffer, if needed */
  173932. if (cinfo->quantize_colors) {
  173933. /* The buffer strip height is max_v_samp_factor, which is typically
  173934. * an efficient number of rows for upsampling to return.
  173935. * (In the presence of output rescaling, we might want to be smarter?)
  173936. */
  173937. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173938. if (need_full_buffer) {
  173939. /* Two-pass color quantization: need full-image storage. */
  173940. /* We round up the number of rows to a multiple of the strip height. */
  173941. #ifdef QUANT_2PASS_SUPPORTED
  173942. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173943. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173944. cinfo->output_width * cinfo->out_color_components,
  173945. (JDIMENSION) jround_up((long) cinfo->output_height,
  173946. (long) post->strip_height),
  173947. post->strip_height);
  173948. #else
  173949. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173950. #endif /* QUANT_2PASS_SUPPORTED */
  173951. } else {
  173952. /* One-pass color quantization: just make a strip buffer. */
  173953. post->buffer = (*cinfo->mem->alloc_sarray)
  173954. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173955. cinfo->output_width * cinfo->out_color_components,
  173956. post->strip_height);
  173957. }
  173958. }
  173959. }
  173960. /*** End of inlined file: jdpostct.c ***/
  173961. #undef FIX
  173962. /*** Start of inlined file: jdsample.c ***/
  173963. #define JPEG_INTERNALS
  173964. /* Pointer to routine to upsample a single component */
  173965. typedef JMETHOD(void, upsample1_ptr,
  173966. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173967. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173968. /* Private subobject */
  173969. typedef struct {
  173970. struct jpeg_upsampler pub; /* public fields */
  173971. /* Color conversion buffer. When using separate upsampling and color
  173972. * conversion steps, this buffer holds one upsampled row group until it
  173973. * has been color converted and output.
  173974. * Note: we do not allocate any storage for component(s) which are full-size,
  173975. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173976. * simply set to point to the input data array, thereby avoiding copying.
  173977. */
  173978. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173979. /* Per-component upsampling method pointers */
  173980. upsample1_ptr methods[MAX_COMPONENTS];
  173981. int next_row_out; /* counts rows emitted from color_buf */
  173982. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173983. /* Height of an input row group for each component. */
  173984. int rowgroup_height[MAX_COMPONENTS];
  173985. /* These arrays save pixel expansion factors so that int_expand need not
  173986. * recompute them each time. They are unused for other upsampling methods.
  173987. */
  173988. UINT8 h_expand[MAX_COMPONENTS];
  173989. UINT8 v_expand[MAX_COMPONENTS];
  173990. } my_upsampler2;
  173991. typedef my_upsampler2 * my_upsample_ptr2;
  173992. /*
  173993. * Initialize for an upsampling pass.
  173994. */
  173995. METHODDEF(void)
  173996. start_pass_upsample (j_decompress_ptr cinfo)
  173997. {
  173998. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173999. /* Mark the conversion buffer empty */
  174000. upsample->next_row_out = cinfo->max_v_samp_factor;
  174001. /* Initialize total-height counter for detecting bottom of image */
  174002. upsample->rows_to_go = cinfo->output_height;
  174003. }
  174004. /*
  174005. * Control routine to do upsampling (and color conversion).
  174006. *
  174007. * In this version we upsample each component independently.
  174008. * We upsample one row group into the conversion buffer, then apply
  174009. * color conversion a row at a time.
  174010. */
  174011. METHODDEF(void)
  174012. sep_upsample (j_decompress_ptr cinfo,
  174013. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174014. JDIMENSION,
  174015. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174016. JDIMENSION out_rows_avail)
  174017. {
  174018. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174019. int ci;
  174020. jpeg_component_info * compptr;
  174021. JDIMENSION num_rows;
  174022. /* Fill the conversion buffer, if it's empty */
  174023. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174024. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174025. ci++, compptr++) {
  174026. /* Invoke per-component upsample method. Notice we pass a POINTER
  174027. * to color_buf[ci], so that fullsize_upsample can change it.
  174028. */
  174029. (*upsample->methods[ci]) (cinfo, compptr,
  174030. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174031. upsample->color_buf + ci);
  174032. }
  174033. upsample->next_row_out = 0;
  174034. }
  174035. /* Color-convert and emit rows */
  174036. /* How many we have in the buffer: */
  174037. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174038. /* Not more than the distance to the end of the image. Need this test
  174039. * in case the image height is not a multiple of max_v_samp_factor:
  174040. */
  174041. if (num_rows > upsample->rows_to_go)
  174042. num_rows = upsample->rows_to_go;
  174043. /* And not more than what the client can accept: */
  174044. out_rows_avail -= *out_row_ctr;
  174045. if (num_rows > out_rows_avail)
  174046. num_rows = out_rows_avail;
  174047. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174048. (JDIMENSION) upsample->next_row_out,
  174049. output_buf + *out_row_ctr,
  174050. (int) num_rows);
  174051. /* Adjust counts */
  174052. *out_row_ctr += num_rows;
  174053. upsample->rows_to_go -= num_rows;
  174054. upsample->next_row_out += num_rows;
  174055. /* When the buffer is emptied, declare this input row group consumed */
  174056. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174057. (*in_row_group_ctr)++;
  174058. }
  174059. /*
  174060. * These are the routines invoked by sep_upsample to upsample pixel values
  174061. * of a single component. One row group is processed per call.
  174062. */
  174063. /*
  174064. * For full-size components, we just make color_buf[ci] point at the
  174065. * input buffer, and thus avoid copying any data. Note that this is
  174066. * safe only because sep_upsample doesn't declare the input row group
  174067. * "consumed" until we are done color converting and emitting it.
  174068. */
  174069. METHODDEF(void)
  174070. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174071. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174072. {
  174073. *output_data_ptr = input_data;
  174074. }
  174075. /*
  174076. * This is a no-op version used for "uninteresting" components.
  174077. * These components will not be referenced by color conversion.
  174078. */
  174079. METHODDEF(void)
  174080. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174081. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174082. {
  174083. *output_data_ptr = NULL; /* safety check */
  174084. }
  174085. /*
  174086. * This version handles any integral sampling ratios.
  174087. * This is not used for typical JPEG files, so it need not be fast.
  174088. * Nor, for that matter, is it particularly accurate: the algorithm is
  174089. * simple replication of the input pixel onto the corresponding output
  174090. * pixels. The hi-falutin sampling literature refers to this as a
  174091. * "box filter". A box filter tends to introduce visible artifacts,
  174092. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174093. * you would be well advised to improve this code.
  174094. */
  174095. METHODDEF(void)
  174096. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174097. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174098. {
  174099. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174100. JSAMPARRAY output_data = *output_data_ptr;
  174101. register JSAMPROW inptr, outptr;
  174102. register JSAMPLE invalue;
  174103. register int h;
  174104. JSAMPROW outend;
  174105. int h_expand, v_expand;
  174106. int inrow, outrow;
  174107. h_expand = upsample->h_expand[compptr->component_index];
  174108. v_expand = upsample->v_expand[compptr->component_index];
  174109. inrow = outrow = 0;
  174110. while (outrow < cinfo->max_v_samp_factor) {
  174111. /* Generate one output row with proper horizontal expansion */
  174112. inptr = input_data[inrow];
  174113. outptr = output_data[outrow];
  174114. outend = outptr + cinfo->output_width;
  174115. while (outptr < outend) {
  174116. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174117. for (h = h_expand; h > 0; h--) {
  174118. *outptr++ = invalue;
  174119. }
  174120. }
  174121. /* Generate any additional output rows by duplicating the first one */
  174122. if (v_expand > 1) {
  174123. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174124. v_expand-1, cinfo->output_width);
  174125. }
  174126. inrow++;
  174127. outrow += v_expand;
  174128. }
  174129. }
  174130. /*
  174131. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174132. * It's still a box filter.
  174133. */
  174134. METHODDEF(void)
  174135. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174136. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174137. {
  174138. JSAMPARRAY output_data = *output_data_ptr;
  174139. register JSAMPROW inptr, outptr;
  174140. register JSAMPLE invalue;
  174141. JSAMPROW outend;
  174142. int inrow;
  174143. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174144. inptr = input_data[inrow];
  174145. outptr = output_data[inrow];
  174146. outend = outptr + cinfo->output_width;
  174147. while (outptr < outend) {
  174148. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174149. *outptr++ = invalue;
  174150. *outptr++ = invalue;
  174151. }
  174152. }
  174153. }
  174154. /*
  174155. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174156. * It's still a box filter.
  174157. */
  174158. METHODDEF(void)
  174159. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174160. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174161. {
  174162. JSAMPARRAY output_data = *output_data_ptr;
  174163. register JSAMPROW inptr, outptr;
  174164. register JSAMPLE invalue;
  174165. JSAMPROW outend;
  174166. int inrow, outrow;
  174167. inrow = outrow = 0;
  174168. while (outrow < cinfo->max_v_samp_factor) {
  174169. inptr = input_data[inrow];
  174170. outptr = output_data[outrow];
  174171. outend = outptr + cinfo->output_width;
  174172. while (outptr < outend) {
  174173. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174174. *outptr++ = invalue;
  174175. *outptr++ = invalue;
  174176. }
  174177. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174178. 1, cinfo->output_width);
  174179. inrow++;
  174180. outrow += 2;
  174181. }
  174182. }
  174183. /*
  174184. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174185. *
  174186. * The upsampling algorithm is linear interpolation between pixel centers,
  174187. * also known as a "triangle filter". This is a good compromise between
  174188. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174189. * of the way between input pixel centers.
  174190. *
  174191. * A note about the "bias" calculations: when rounding fractional values to
  174192. * integer, we do not want to always round 0.5 up to the next integer.
  174193. * If we did that, we'd introduce a noticeable bias towards larger values.
  174194. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174195. * alternate pixel locations (a simple ordered dither pattern).
  174196. */
  174197. METHODDEF(void)
  174198. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174199. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174200. {
  174201. JSAMPARRAY output_data = *output_data_ptr;
  174202. register JSAMPROW inptr, outptr;
  174203. register int invalue;
  174204. register JDIMENSION colctr;
  174205. int inrow;
  174206. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174207. inptr = input_data[inrow];
  174208. outptr = output_data[inrow];
  174209. /* Special case for first column */
  174210. invalue = GETJSAMPLE(*inptr++);
  174211. *outptr++ = (JSAMPLE) invalue;
  174212. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174213. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174214. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174215. invalue = GETJSAMPLE(*inptr++) * 3;
  174216. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174217. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174218. }
  174219. /* Special case for last column */
  174220. invalue = GETJSAMPLE(*inptr);
  174221. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174222. *outptr++ = (JSAMPLE) invalue;
  174223. }
  174224. }
  174225. /*
  174226. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174227. * Again a triangle filter; see comments for h2v1 case, above.
  174228. *
  174229. * It is OK for us to reference the adjacent input rows because we demanded
  174230. * context from the main buffer controller (see initialization code).
  174231. */
  174232. METHODDEF(void)
  174233. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174234. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174235. {
  174236. JSAMPARRAY output_data = *output_data_ptr;
  174237. register JSAMPROW inptr0, inptr1, outptr;
  174238. #if BITS_IN_JSAMPLE == 8
  174239. register int thiscolsum, lastcolsum, nextcolsum;
  174240. #else
  174241. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174242. #endif
  174243. register JDIMENSION colctr;
  174244. int inrow, outrow, v;
  174245. inrow = outrow = 0;
  174246. while (outrow < cinfo->max_v_samp_factor) {
  174247. for (v = 0; v < 2; v++) {
  174248. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174249. inptr0 = input_data[inrow];
  174250. if (v == 0) /* next nearest is row above */
  174251. inptr1 = input_data[inrow-1];
  174252. else /* next nearest is row below */
  174253. inptr1 = input_data[inrow+1];
  174254. outptr = output_data[outrow++];
  174255. /* Special case for first column */
  174256. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174257. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174258. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174259. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174260. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174261. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174262. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174263. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174264. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174265. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174266. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174267. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174268. }
  174269. /* Special case for last column */
  174270. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174271. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174272. }
  174273. inrow++;
  174274. }
  174275. }
  174276. /*
  174277. * Module initialization routine for upsampling.
  174278. */
  174279. GLOBAL(void)
  174280. jinit_upsampler (j_decompress_ptr cinfo)
  174281. {
  174282. my_upsample_ptr2 upsample;
  174283. int ci;
  174284. jpeg_component_info * compptr;
  174285. boolean need_buffer, do_fancy;
  174286. int h_in_group, v_in_group, h_out_group, v_out_group;
  174287. upsample = (my_upsample_ptr2)
  174288. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174289. SIZEOF(my_upsampler2));
  174290. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174291. upsample->pub.start_pass = start_pass_upsample;
  174292. upsample->pub.upsample = sep_upsample;
  174293. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174294. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174295. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174296. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174297. * so don't ask for it.
  174298. */
  174299. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174300. /* Verify we can handle the sampling factors, select per-component methods,
  174301. * and create storage as needed.
  174302. */
  174303. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174304. ci++, compptr++) {
  174305. /* Compute size of an "input group" after IDCT scaling. This many samples
  174306. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174307. */
  174308. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174309. cinfo->min_DCT_scaled_size;
  174310. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174311. cinfo->min_DCT_scaled_size;
  174312. h_out_group = cinfo->max_h_samp_factor;
  174313. v_out_group = cinfo->max_v_samp_factor;
  174314. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174315. need_buffer = TRUE;
  174316. if (! compptr->component_needed) {
  174317. /* Don't bother to upsample an uninteresting component. */
  174318. upsample->methods[ci] = noop_upsample;
  174319. need_buffer = FALSE;
  174320. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174321. /* Fullsize components can be processed without any work. */
  174322. upsample->methods[ci] = fullsize_upsample;
  174323. need_buffer = FALSE;
  174324. } else if (h_in_group * 2 == h_out_group &&
  174325. v_in_group == v_out_group) {
  174326. /* Special cases for 2h1v upsampling */
  174327. if (do_fancy && compptr->downsampled_width > 2)
  174328. upsample->methods[ci] = h2v1_fancy_upsample;
  174329. else
  174330. upsample->methods[ci] = h2v1_upsample;
  174331. } else if (h_in_group * 2 == h_out_group &&
  174332. v_in_group * 2 == v_out_group) {
  174333. /* Special cases for 2h2v upsampling */
  174334. if (do_fancy && compptr->downsampled_width > 2) {
  174335. upsample->methods[ci] = h2v2_fancy_upsample;
  174336. upsample->pub.need_context_rows = TRUE;
  174337. } else
  174338. upsample->methods[ci] = h2v2_upsample;
  174339. } else if ((h_out_group % h_in_group) == 0 &&
  174340. (v_out_group % v_in_group) == 0) {
  174341. /* Generic integral-factors upsampling method */
  174342. upsample->methods[ci] = int_upsample;
  174343. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174344. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174345. } else
  174346. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174347. if (need_buffer) {
  174348. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174349. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174350. (JDIMENSION) jround_up((long) cinfo->output_width,
  174351. (long) cinfo->max_h_samp_factor),
  174352. (JDIMENSION) cinfo->max_v_samp_factor);
  174353. }
  174354. }
  174355. }
  174356. /*** End of inlined file: jdsample.c ***/
  174357. /*** Start of inlined file: jdtrans.c ***/
  174358. #define JPEG_INTERNALS
  174359. /* Forward declarations */
  174360. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174361. /*
  174362. * Read the coefficient arrays from a JPEG file.
  174363. * jpeg_read_header must be completed before calling this.
  174364. *
  174365. * The entire image is read into a set of virtual coefficient-block arrays,
  174366. * one per component. The return value is a pointer to the array of
  174367. * virtual-array descriptors. These can be manipulated directly via the
  174368. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174369. * To release the memory occupied by the virtual arrays, call
  174370. * jpeg_finish_decompress() when done with the data.
  174371. *
  174372. * An alternative usage is to simply obtain access to the coefficient arrays
  174373. * during a buffered-image-mode decompression operation. This is allowed
  174374. * after any jpeg_finish_output() call. The arrays can be accessed until
  174375. * jpeg_finish_decompress() is called. (Note that any call to the library
  174376. * may reposition the arrays, so don't rely on access_virt_barray() results
  174377. * to stay valid across library calls.)
  174378. *
  174379. * Returns NULL if suspended. This case need be checked only if
  174380. * a suspending data source is used.
  174381. */
  174382. GLOBAL(jvirt_barray_ptr *)
  174383. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174384. {
  174385. if (cinfo->global_state == DSTATE_READY) {
  174386. /* First call: initialize active modules */
  174387. transdecode_master_selection(cinfo);
  174388. cinfo->global_state = DSTATE_RDCOEFS;
  174389. }
  174390. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174391. /* Absorb whole file into the coef buffer */
  174392. for (;;) {
  174393. int retcode;
  174394. /* Call progress monitor hook if present */
  174395. if (cinfo->progress != NULL)
  174396. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174397. /* Absorb some more input */
  174398. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174399. if (retcode == JPEG_SUSPENDED)
  174400. return NULL;
  174401. if (retcode == JPEG_REACHED_EOI)
  174402. break;
  174403. /* Advance progress counter if appropriate */
  174404. if (cinfo->progress != NULL &&
  174405. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174406. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174407. /* startup underestimated number of scans; ratchet up one scan */
  174408. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174409. }
  174410. }
  174411. }
  174412. /* Set state so that jpeg_finish_decompress does the right thing */
  174413. cinfo->global_state = DSTATE_STOPPING;
  174414. }
  174415. /* At this point we should be in state DSTATE_STOPPING if being used
  174416. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174417. * to the coefficients during a full buffered-image-mode decompression.
  174418. */
  174419. if ((cinfo->global_state == DSTATE_STOPPING ||
  174420. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174421. return cinfo->coef->coef_arrays;
  174422. }
  174423. /* Oops, improper usage */
  174424. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174425. return NULL; /* keep compiler happy */
  174426. }
  174427. /*
  174428. * Master selection of decompression modules for transcoding.
  174429. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174430. */
  174431. LOCAL(void)
  174432. transdecode_master_selection (j_decompress_ptr cinfo)
  174433. {
  174434. /* This is effectively a buffered-image operation. */
  174435. cinfo->buffered_image = TRUE;
  174436. /* Entropy decoding: either Huffman or arithmetic coding. */
  174437. if (cinfo->arith_code) {
  174438. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174439. } else {
  174440. if (cinfo->progressive_mode) {
  174441. #ifdef D_PROGRESSIVE_SUPPORTED
  174442. jinit_phuff_decoder(cinfo);
  174443. #else
  174444. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174445. #endif
  174446. } else
  174447. jinit_huff_decoder(cinfo);
  174448. }
  174449. /* Always get a full-image coefficient buffer. */
  174450. jinit_d_coef_controller(cinfo, TRUE);
  174451. /* We can now tell the memory manager to allocate virtual arrays. */
  174452. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174453. /* Initialize input side of decompressor to consume first scan. */
  174454. (*cinfo->inputctl->start_input_pass) (cinfo);
  174455. /* Initialize progress monitoring. */
  174456. if (cinfo->progress != NULL) {
  174457. int nscans;
  174458. /* Estimate number of scans to set pass_limit. */
  174459. if (cinfo->progressive_mode) {
  174460. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174461. nscans = 2 + 3 * cinfo->num_components;
  174462. } else if (cinfo->inputctl->has_multiple_scans) {
  174463. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174464. nscans = cinfo->num_components;
  174465. } else {
  174466. nscans = 1;
  174467. }
  174468. cinfo->progress->pass_counter = 0L;
  174469. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174470. cinfo->progress->completed_passes = 0;
  174471. cinfo->progress->total_passes = 1;
  174472. }
  174473. }
  174474. /*** End of inlined file: jdtrans.c ***/
  174475. /*** Start of inlined file: jfdctflt.c ***/
  174476. #define JPEG_INTERNALS
  174477. #ifdef DCT_FLOAT_SUPPORTED
  174478. /*
  174479. * This module is specialized to the case DCTSIZE = 8.
  174480. */
  174481. #if DCTSIZE != 8
  174482. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174483. #endif
  174484. /*
  174485. * Perform the forward DCT on one block of samples.
  174486. */
  174487. GLOBAL(void)
  174488. jpeg_fdct_float (FAST_FLOAT * data)
  174489. {
  174490. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174491. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174492. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174493. FAST_FLOAT *dataptr;
  174494. int ctr;
  174495. /* Pass 1: process rows. */
  174496. dataptr = data;
  174497. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174498. tmp0 = dataptr[0] + dataptr[7];
  174499. tmp7 = dataptr[0] - dataptr[7];
  174500. tmp1 = dataptr[1] + dataptr[6];
  174501. tmp6 = dataptr[1] - dataptr[6];
  174502. tmp2 = dataptr[2] + dataptr[5];
  174503. tmp5 = dataptr[2] - dataptr[5];
  174504. tmp3 = dataptr[3] + dataptr[4];
  174505. tmp4 = dataptr[3] - dataptr[4];
  174506. /* Even part */
  174507. tmp10 = tmp0 + tmp3; /* phase 2 */
  174508. tmp13 = tmp0 - tmp3;
  174509. tmp11 = tmp1 + tmp2;
  174510. tmp12 = tmp1 - tmp2;
  174511. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174512. dataptr[4] = tmp10 - tmp11;
  174513. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174514. dataptr[2] = tmp13 + z1; /* phase 5 */
  174515. dataptr[6] = tmp13 - z1;
  174516. /* Odd part */
  174517. tmp10 = tmp4 + tmp5; /* phase 2 */
  174518. tmp11 = tmp5 + tmp6;
  174519. tmp12 = tmp6 + tmp7;
  174520. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174521. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174522. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174523. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174524. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174525. z11 = tmp7 + z3; /* phase 5 */
  174526. z13 = tmp7 - z3;
  174527. dataptr[5] = z13 + z2; /* phase 6 */
  174528. dataptr[3] = z13 - z2;
  174529. dataptr[1] = z11 + z4;
  174530. dataptr[7] = z11 - z4;
  174531. dataptr += DCTSIZE; /* advance pointer to next row */
  174532. }
  174533. /* Pass 2: process columns. */
  174534. dataptr = data;
  174535. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174536. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174537. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174538. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174539. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174540. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174541. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174542. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174543. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174544. /* Even part */
  174545. tmp10 = tmp0 + tmp3; /* phase 2 */
  174546. tmp13 = tmp0 - tmp3;
  174547. tmp11 = tmp1 + tmp2;
  174548. tmp12 = tmp1 - tmp2;
  174549. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174550. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174551. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174552. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174553. dataptr[DCTSIZE*6] = tmp13 - z1;
  174554. /* Odd part */
  174555. tmp10 = tmp4 + tmp5; /* phase 2 */
  174556. tmp11 = tmp5 + tmp6;
  174557. tmp12 = tmp6 + tmp7;
  174558. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174559. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174560. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174561. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174562. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174563. z11 = tmp7 + z3; /* phase 5 */
  174564. z13 = tmp7 - z3;
  174565. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174566. dataptr[DCTSIZE*3] = z13 - z2;
  174567. dataptr[DCTSIZE*1] = z11 + z4;
  174568. dataptr[DCTSIZE*7] = z11 - z4;
  174569. dataptr++; /* advance pointer to next column */
  174570. }
  174571. }
  174572. #endif /* DCT_FLOAT_SUPPORTED */
  174573. /*** End of inlined file: jfdctflt.c ***/
  174574. /*** Start of inlined file: jfdctint.c ***/
  174575. #define JPEG_INTERNALS
  174576. #ifdef DCT_ISLOW_SUPPORTED
  174577. /*
  174578. * This module is specialized to the case DCTSIZE = 8.
  174579. */
  174580. #if DCTSIZE != 8
  174581. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174582. #endif
  174583. /*
  174584. * The poop on this scaling stuff is as follows:
  174585. *
  174586. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174587. * larger than the true DCT outputs. The final outputs are therefore
  174588. * a factor of N larger than desired; since N=8 this can be cured by
  174589. * a simple right shift at the end of the algorithm. The advantage of
  174590. * this arrangement is that we save two multiplications per 1-D DCT,
  174591. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174592. * In the IJG code, this factor of 8 is removed by the quantization step
  174593. * (in jcdctmgr.c), NOT in this module.
  174594. *
  174595. * We have to do addition and subtraction of the integer inputs, which
  174596. * is no problem, and multiplication by fractional constants, which is
  174597. * a problem to do in integer arithmetic. We multiply all the constants
  174598. * by CONST_SCALE and convert them to integer constants (thus retaining
  174599. * CONST_BITS bits of precision in the constants). After doing a
  174600. * multiplication we have to divide the product by CONST_SCALE, with proper
  174601. * rounding, to produce the correct output. This division can be done
  174602. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174603. * as long as possible so that partial sums can be added together with
  174604. * full fractional precision.
  174605. *
  174606. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174607. * they are represented to better-than-integral precision. These outputs
  174608. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174609. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174610. * array is INT32 anyway.)
  174611. *
  174612. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174613. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174614. * shows that the values given below are the most effective.
  174615. */
  174616. #if BITS_IN_JSAMPLE == 8
  174617. #define CONST_BITS 13
  174618. #define PASS1_BITS 2
  174619. #else
  174620. #define CONST_BITS 13
  174621. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174622. #endif
  174623. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174624. * causing a lot of useless floating-point operations at run time.
  174625. * To get around this we use the following pre-calculated constants.
  174626. * If you change CONST_BITS you may want to add appropriate values.
  174627. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174628. */
  174629. #if CONST_BITS == 13
  174630. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174631. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174632. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174633. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174634. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174635. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174636. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174637. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174638. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174639. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174640. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174641. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174642. #else
  174643. #define FIX_0_298631336 FIX(0.298631336)
  174644. #define FIX_0_390180644 FIX(0.390180644)
  174645. #define FIX_0_541196100 FIX(0.541196100)
  174646. #define FIX_0_765366865 FIX(0.765366865)
  174647. #define FIX_0_899976223 FIX(0.899976223)
  174648. #define FIX_1_175875602 FIX(1.175875602)
  174649. #define FIX_1_501321110 FIX(1.501321110)
  174650. #define FIX_1_847759065 FIX(1.847759065)
  174651. #define FIX_1_961570560 FIX(1.961570560)
  174652. #define FIX_2_053119869 FIX(2.053119869)
  174653. #define FIX_2_562915447 FIX(2.562915447)
  174654. #define FIX_3_072711026 FIX(3.072711026)
  174655. #endif
  174656. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174657. * For 8-bit samples with the recommended scaling, all the variable
  174658. * and constant values involved are no more than 16 bits wide, so a
  174659. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174660. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174661. */
  174662. #if BITS_IN_JSAMPLE == 8
  174663. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174664. #else
  174665. #define MULTIPLY(var,const) ((var) * (const))
  174666. #endif
  174667. /*
  174668. * Perform the forward DCT on one block of samples.
  174669. */
  174670. GLOBAL(void)
  174671. jpeg_fdct_islow (DCTELEM * data)
  174672. {
  174673. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174674. INT32 tmp10, tmp11, tmp12, tmp13;
  174675. INT32 z1, z2, z3, z4, z5;
  174676. DCTELEM *dataptr;
  174677. int ctr;
  174678. SHIFT_TEMPS
  174679. /* Pass 1: process rows. */
  174680. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174681. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174682. dataptr = data;
  174683. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174684. tmp0 = dataptr[0] + dataptr[7];
  174685. tmp7 = dataptr[0] - dataptr[7];
  174686. tmp1 = dataptr[1] + dataptr[6];
  174687. tmp6 = dataptr[1] - dataptr[6];
  174688. tmp2 = dataptr[2] + dataptr[5];
  174689. tmp5 = dataptr[2] - dataptr[5];
  174690. tmp3 = dataptr[3] + dataptr[4];
  174691. tmp4 = dataptr[3] - dataptr[4];
  174692. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174693. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174694. */
  174695. tmp10 = tmp0 + tmp3;
  174696. tmp13 = tmp0 - tmp3;
  174697. tmp11 = tmp1 + tmp2;
  174698. tmp12 = tmp1 - tmp2;
  174699. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174700. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174701. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174702. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174703. CONST_BITS-PASS1_BITS);
  174704. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174705. CONST_BITS-PASS1_BITS);
  174706. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174707. * cK represents cos(K*pi/16).
  174708. * i0..i3 in the paper are tmp4..tmp7 here.
  174709. */
  174710. z1 = tmp4 + tmp7;
  174711. z2 = tmp5 + tmp6;
  174712. z3 = tmp4 + tmp6;
  174713. z4 = tmp5 + tmp7;
  174714. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174715. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174716. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174717. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174718. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174719. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174720. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174721. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174722. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174723. z3 += z5;
  174724. z4 += z5;
  174725. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174726. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174727. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174728. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174729. dataptr += DCTSIZE; /* advance pointer to next row */
  174730. }
  174731. /* Pass 2: process columns.
  174732. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174733. * by an overall factor of 8.
  174734. */
  174735. dataptr = data;
  174736. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174737. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174738. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174739. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174740. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174741. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174742. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174743. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174744. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174745. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174746. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174747. */
  174748. tmp10 = tmp0 + tmp3;
  174749. tmp13 = tmp0 - tmp3;
  174750. tmp11 = tmp1 + tmp2;
  174751. tmp12 = tmp1 - tmp2;
  174752. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174753. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174754. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174755. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174756. CONST_BITS+PASS1_BITS);
  174757. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174758. CONST_BITS+PASS1_BITS);
  174759. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174760. * cK represents cos(K*pi/16).
  174761. * i0..i3 in the paper are tmp4..tmp7 here.
  174762. */
  174763. z1 = tmp4 + tmp7;
  174764. z2 = tmp5 + tmp6;
  174765. z3 = tmp4 + tmp6;
  174766. z4 = tmp5 + tmp7;
  174767. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174768. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174769. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174770. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174771. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174772. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174773. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174774. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174775. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174776. z3 += z5;
  174777. z4 += z5;
  174778. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174779. CONST_BITS+PASS1_BITS);
  174780. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174781. CONST_BITS+PASS1_BITS);
  174782. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174783. CONST_BITS+PASS1_BITS);
  174784. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174785. CONST_BITS+PASS1_BITS);
  174786. dataptr++; /* advance pointer to next column */
  174787. }
  174788. }
  174789. #endif /* DCT_ISLOW_SUPPORTED */
  174790. /*** End of inlined file: jfdctint.c ***/
  174791. #undef CONST_BITS
  174792. #undef MULTIPLY
  174793. #undef FIX_0_541196100
  174794. /*** Start of inlined file: jfdctfst.c ***/
  174795. #define JPEG_INTERNALS
  174796. #ifdef DCT_IFAST_SUPPORTED
  174797. /*
  174798. * This module is specialized to the case DCTSIZE = 8.
  174799. */
  174800. #if DCTSIZE != 8
  174801. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174802. #endif
  174803. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174804. * see jfdctint.c for more details. However, we choose to descale
  174805. * (right shift) multiplication products as soon as they are formed,
  174806. * rather than carrying additional fractional bits into subsequent additions.
  174807. * This compromises accuracy slightly, but it lets us save a few shifts.
  174808. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174809. * everywhere except in the multiplications proper; this saves a good deal
  174810. * of work on 16-bit-int machines.
  174811. *
  174812. * Again to save a few shifts, the intermediate results between pass 1 and
  174813. * pass 2 are not upscaled, but are represented only to integral precision.
  174814. *
  174815. * A final compromise is to represent the multiplicative constants to only
  174816. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174817. * machines, and may also reduce the cost of multiplication (since there
  174818. * are fewer one-bits in the constants).
  174819. */
  174820. #define CONST_BITS 8
  174821. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174822. * causing a lot of useless floating-point operations at run time.
  174823. * To get around this we use the following pre-calculated constants.
  174824. * If you change CONST_BITS you may want to add appropriate values.
  174825. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174826. */
  174827. #if CONST_BITS == 8
  174828. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174829. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174830. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174831. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174832. #else
  174833. #define FIX_0_382683433 FIX(0.382683433)
  174834. #define FIX_0_541196100 FIX(0.541196100)
  174835. #define FIX_0_707106781 FIX(0.707106781)
  174836. #define FIX_1_306562965 FIX(1.306562965)
  174837. #endif
  174838. /* We can gain a little more speed, with a further compromise in accuracy,
  174839. * by omitting the addition in a descaling shift. This yields an incorrectly
  174840. * rounded result half the time...
  174841. */
  174842. #ifndef USE_ACCURATE_ROUNDING
  174843. #undef DESCALE
  174844. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174845. #endif
  174846. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174847. * descale to yield a DCTELEM result.
  174848. */
  174849. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174850. /*
  174851. * Perform the forward DCT on one block of samples.
  174852. */
  174853. GLOBAL(void)
  174854. jpeg_fdct_ifast (DCTELEM * data)
  174855. {
  174856. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174857. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174858. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174859. DCTELEM *dataptr;
  174860. int ctr;
  174861. SHIFT_TEMPS
  174862. /* Pass 1: process rows. */
  174863. dataptr = data;
  174864. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174865. tmp0 = dataptr[0] + dataptr[7];
  174866. tmp7 = dataptr[0] - dataptr[7];
  174867. tmp1 = dataptr[1] + dataptr[6];
  174868. tmp6 = dataptr[1] - dataptr[6];
  174869. tmp2 = dataptr[2] + dataptr[5];
  174870. tmp5 = dataptr[2] - dataptr[5];
  174871. tmp3 = dataptr[3] + dataptr[4];
  174872. tmp4 = dataptr[3] - dataptr[4];
  174873. /* Even part */
  174874. tmp10 = tmp0 + tmp3; /* phase 2 */
  174875. tmp13 = tmp0 - tmp3;
  174876. tmp11 = tmp1 + tmp2;
  174877. tmp12 = tmp1 - tmp2;
  174878. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174879. dataptr[4] = tmp10 - tmp11;
  174880. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174881. dataptr[2] = tmp13 + z1; /* phase 5 */
  174882. dataptr[6] = tmp13 - z1;
  174883. /* Odd part */
  174884. tmp10 = tmp4 + tmp5; /* phase 2 */
  174885. tmp11 = tmp5 + tmp6;
  174886. tmp12 = tmp6 + tmp7;
  174887. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174888. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174889. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174890. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174891. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174892. z11 = tmp7 + z3; /* phase 5 */
  174893. z13 = tmp7 - z3;
  174894. dataptr[5] = z13 + z2; /* phase 6 */
  174895. dataptr[3] = z13 - z2;
  174896. dataptr[1] = z11 + z4;
  174897. dataptr[7] = z11 - z4;
  174898. dataptr += DCTSIZE; /* advance pointer to next row */
  174899. }
  174900. /* Pass 2: process columns. */
  174901. dataptr = data;
  174902. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174903. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174904. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174905. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174906. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174907. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174908. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174909. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174910. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174911. /* Even part */
  174912. tmp10 = tmp0 + tmp3; /* phase 2 */
  174913. tmp13 = tmp0 - tmp3;
  174914. tmp11 = tmp1 + tmp2;
  174915. tmp12 = tmp1 - tmp2;
  174916. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174917. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174918. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174919. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174920. dataptr[DCTSIZE*6] = tmp13 - z1;
  174921. /* Odd part */
  174922. tmp10 = tmp4 + tmp5; /* phase 2 */
  174923. tmp11 = tmp5 + tmp6;
  174924. tmp12 = tmp6 + tmp7;
  174925. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174926. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174927. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174928. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174929. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174930. z11 = tmp7 + z3; /* phase 5 */
  174931. z13 = tmp7 - z3;
  174932. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174933. dataptr[DCTSIZE*3] = z13 - z2;
  174934. dataptr[DCTSIZE*1] = z11 + z4;
  174935. dataptr[DCTSIZE*7] = z11 - z4;
  174936. dataptr++; /* advance pointer to next column */
  174937. }
  174938. }
  174939. #endif /* DCT_IFAST_SUPPORTED */
  174940. /*** End of inlined file: jfdctfst.c ***/
  174941. #undef FIX_0_541196100
  174942. /*** Start of inlined file: jidctflt.c ***/
  174943. #define JPEG_INTERNALS
  174944. #ifdef DCT_FLOAT_SUPPORTED
  174945. /*
  174946. * This module is specialized to the case DCTSIZE = 8.
  174947. */
  174948. #if DCTSIZE != 8
  174949. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174950. #endif
  174951. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174952. * entry; produce a float result.
  174953. */
  174954. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174955. /*
  174956. * Perform dequantization and inverse DCT on one block of coefficients.
  174957. */
  174958. GLOBAL(void)
  174959. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174960. JCOEFPTR coef_block,
  174961. JSAMPARRAY output_buf, JDIMENSION output_col)
  174962. {
  174963. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174964. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174965. FAST_FLOAT z5, z10, z11, z12, z13;
  174966. JCOEFPTR inptr;
  174967. FLOAT_MULT_TYPE * quantptr;
  174968. FAST_FLOAT * wsptr;
  174969. JSAMPROW outptr;
  174970. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174971. int ctr;
  174972. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174973. SHIFT_TEMPS
  174974. /* Pass 1: process columns from input, store into work array. */
  174975. inptr = coef_block;
  174976. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174977. wsptr = workspace;
  174978. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174979. /* Due to quantization, we will usually find that many of the input
  174980. * coefficients are zero, especially the AC terms. We can exploit this
  174981. * by short-circuiting the IDCT calculation for any column in which all
  174982. * the AC terms are zero. In that case each output is equal to the
  174983. * DC coefficient (with scale factor as needed).
  174984. * With typical images and quantization tables, half or more of the
  174985. * column DCT calculations can be simplified this way.
  174986. */
  174987. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174988. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174989. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174990. inptr[DCTSIZE*7] == 0) {
  174991. /* AC terms all zero */
  174992. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174993. wsptr[DCTSIZE*0] = dcval;
  174994. wsptr[DCTSIZE*1] = dcval;
  174995. wsptr[DCTSIZE*2] = dcval;
  174996. wsptr[DCTSIZE*3] = dcval;
  174997. wsptr[DCTSIZE*4] = dcval;
  174998. wsptr[DCTSIZE*5] = dcval;
  174999. wsptr[DCTSIZE*6] = dcval;
  175000. wsptr[DCTSIZE*7] = dcval;
  175001. inptr++; /* advance pointers to next column */
  175002. quantptr++;
  175003. wsptr++;
  175004. continue;
  175005. }
  175006. /* Even part */
  175007. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175008. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175009. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175010. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175011. tmp10 = tmp0 + tmp2; /* phase 3 */
  175012. tmp11 = tmp0 - tmp2;
  175013. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175014. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175015. tmp0 = tmp10 + tmp13; /* phase 2 */
  175016. tmp3 = tmp10 - tmp13;
  175017. tmp1 = tmp11 + tmp12;
  175018. tmp2 = tmp11 - tmp12;
  175019. /* Odd part */
  175020. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175021. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175022. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175023. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175024. z13 = tmp6 + tmp5; /* phase 6 */
  175025. z10 = tmp6 - tmp5;
  175026. z11 = tmp4 + tmp7;
  175027. z12 = tmp4 - tmp7;
  175028. tmp7 = z11 + z13; /* phase 5 */
  175029. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175030. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175031. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175032. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175033. tmp6 = tmp12 - tmp7; /* phase 2 */
  175034. tmp5 = tmp11 - tmp6;
  175035. tmp4 = tmp10 + tmp5;
  175036. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175037. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175038. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175039. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175040. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175041. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175042. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175043. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175044. inptr++; /* advance pointers to next column */
  175045. quantptr++;
  175046. wsptr++;
  175047. }
  175048. /* Pass 2: process rows from work array, store into output array. */
  175049. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175050. wsptr = workspace;
  175051. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175052. outptr = output_buf[ctr] + output_col;
  175053. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175054. * However, the column calculation has created many nonzero AC terms, so
  175055. * the simplification applies less often (typically 5% to 10% of the time).
  175056. * And testing floats for zero is relatively expensive, so we don't bother.
  175057. */
  175058. /* Even part */
  175059. tmp10 = wsptr[0] + wsptr[4];
  175060. tmp11 = wsptr[0] - wsptr[4];
  175061. tmp13 = wsptr[2] + wsptr[6];
  175062. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175063. tmp0 = tmp10 + tmp13;
  175064. tmp3 = tmp10 - tmp13;
  175065. tmp1 = tmp11 + tmp12;
  175066. tmp2 = tmp11 - tmp12;
  175067. /* Odd part */
  175068. z13 = wsptr[5] + wsptr[3];
  175069. z10 = wsptr[5] - wsptr[3];
  175070. z11 = wsptr[1] + wsptr[7];
  175071. z12 = wsptr[1] - wsptr[7];
  175072. tmp7 = z11 + z13;
  175073. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175074. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175075. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175076. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175077. tmp6 = tmp12 - tmp7;
  175078. tmp5 = tmp11 - tmp6;
  175079. tmp4 = tmp10 + tmp5;
  175080. /* Final output stage: scale down by a factor of 8 and range-limit */
  175081. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175082. & RANGE_MASK];
  175083. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175084. & RANGE_MASK];
  175085. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175086. & RANGE_MASK];
  175087. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175088. & RANGE_MASK];
  175089. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175090. & RANGE_MASK];
  175091. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175092. & RANGE_MASK];
  175093. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175094. & RANGE_MASK];
  175095. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175096. & RANGE_MASK];
  175097. wsptr += DCTSIZE; /* advance pointer to next row */
  175098. }
  175099. }
  175100. #endif /* DCT_FLOAT_SUPPORTED */
  175101. /*** End of inlined file: jidctflt.c ***/
  175102. #undef CONST_BITS
  175103. #undef FIX_1_847759065
  175104. #undef MULTIPLY
  175105. #undef DEQUANTIZE
  175106. #undef DESCALE
  175107. /*** Start of inlined file: jidctfst.c ***/
  175108. #define JPEG_INTERNALS
  175109. #ifdef DCT_IFAST_SUPPORTED
  175110. /*
  175111. * This module is specialized to the case DCTSIZE = 8.
  175112. */
  175113. #if DCTSIZE != 8
  175114. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175115. #endif
  175116. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175117. * see jidctint.c for more details. However, we choose to descale
  175118. * (right shift) multiplication products as soon as they are formed,
  175119. * rather than carrying additional fractional bits into subsequent additions.
  175120. * This compromises accuracy slightly, but it lets us save a few shifts.
  175121. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175122. * everywhere except in the multiplications proper; this saves a good deal
  175123. * of work on 16-bit-int machines.
  175124. *
  175125. * The dequantized coefficients are not integers because the AA&N scaling
  175126. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175127. * so that the first and second IDCT rounds have the same input scaling.
  175128. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175129. * avoid a descaling shift; this compromises accuracy rather drastically
  175130. * for small quantization table entries, but it saves a lot of shifts.
  175131. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175132. * so we use a much larger scaling factor to preserve accuracy.
  175133. *
  175134. * A final compromise is to represent the multiplicative constants to only
  175135. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175136. * machines, and may also reduce the cost of multiplication (since there
  175137. * are fewer one-bits in the constants).
  175138. */
  175139. #if BITS_IN_JSAMPLE == 8
  175140. #define CONST_BITS 8
  175141. #define PASS1_BITS 2
  175142. #else
  175143. #define CONST_BITS 8
  175144. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175145. #endif
  175146. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175147. * causing a lot of useless floating-point operations at run time.
  175148. * To get around this we use the following pre-calculated constants.
  175149. * If you change CONST_BITS you may want to add appropriate values.
  175150. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175151. */
  175152. #if CONST_BITS == 8
  175153. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175154. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175155. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175156. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175157. #else
  175158. #define FIX_1_082392200 FIX(1.082392200)
  175159. #define FIX_1_414213562 FIX(1.414213562)
  175160. #define FIX_1_847759065 FIX(1.847759065)
  175161. #define FIX_2_613125930 FIX(2.613125930)
  175162. #endif
  175163. /* We can gain a little more speed, with a further compromise in accuracy,
  175164. * by omitting the addition in a descaling shift. This yields an incorrectly
  175165. * rounded result half the time...
  175166. */
  175167. #ifndef USE_ACCURATE_ROUNDING
  175168. #undef DESCALE
  175169. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175170. #endif
  175171. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175172. * descale to yield a DCTELEM result.
  175173. */
  175174. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175175. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175176. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175177. * multiplication will do. For 12-bit data, the multiplier table is
  175178. * declared INT32, so a 32-bit multiply will be used.
  175179. */
  175180. #if BITS_IN_JSAMPLE == 8
  175181. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175182. #else
  175183. #define DEQUANTIZE(coef,quantval) \
  175184. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175185. #endif
  175186. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175187. * We assume that int right shift is unsigned if INT32 right shift is.
  175188. */
  175189. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175190. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175191. #if BITS_IN_JSAMPLE == 8
  175192. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175193. #else
  175194. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175195. #endif
  175196. #define IRIGHT_SHIFT(x,shft) \
  175197. ((ishift_temp = (x)) < 0 ? \
  175198. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175199. (ishift_temp >> (shft)))
  175200. #else
  175201. #define ISHIFT_TEMPS
  175202. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175203. #endif
  175204. #ifdef USE_ACCURATE_ROUNDING
  175205. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175206. #else
  175207. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175208. #endif
  175209. /*
  175210. * Perform dequantization and inverse DCT on one block of coefficients.
  175211. */
  175212. GLOBAL(void)
  175213. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175214. JCOEFPTR coef_block,
  175215. JSAMPARRAY output_buf, JDIMENSION output_col)
  175216. {
  175217. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175218. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175219. DCTELEM z5, z10, z11, z12, z13;
  175220. JCOEFPTR inptr;
  175221. IFAST_MULT_TYPE * quantptr;
  175222. int * wsptr;
  175223. JSAMPROW outptr;
  175224. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175225. int ctr;
  175226. int workspace[DCTSIZE2]; /* buffers data between passes */
  175227. SHIFT_TEMPS /* for DESCALE */
  175228. ISHIFT_TEMPS /* for IDESCALE */
  175229. /* Pass 1: process columns from input, store into work array. */
  175230. inptr = coef_block;
  175231. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175232. wsptr = workspace;
  175233. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175234. /* Due to quantization, we will usually find that many of the input
  175235. * coefficients are zero, especially the AC terms. We can exploit this
  175236. * by short-circuiting the IDCT calculation for any column in which all
  175237. * the AC terms are zero. In that case each output is equal to the
  175238. * DC coefficient (with scale factor as needed).
  175239. * With typical images and quantization tables, half or more of the
  175240. * column DCT calculations can be simplified this way.
  175241. */
  175242. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175243. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175244. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175245. inptr[DCTSIZE*7] == 0) {
  175246. /* AC terms all zero */
  175247. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175248. wsptr[DCTSIZE*0] = dcval;
  175249. wsptr[DCTSIZE*1] = dcval;
  175250. wsptr[DCTSIZE*2] = dcval;
  175251. wsptr[DCTSIZE*3] = dcval;
  175252. wsptr[DCTSIZE*4] = dcval;
  175253. wsptr[DCTSIZE*5] = dcval;
  175254. wsptr[DCTSIZE*6] = dcval;
  175255. wsptr[DCTSIZE*7] = dcval;
  175256. inptr++; /* advance pointers to next column */
  175257. quantptr++;
  175258. wsptr++;
  175259. continue;
  175260. }
  175261. /* Even part */
  175262. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175263. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175264. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175265. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175266. tmp10 = tmp0 + tmp2; /* phase 3 */
  175267. tmp11 = tmp0 - tmp2;
  175268. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175269. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175270. tmp0 = tmp10 + tmp13; /* phase 2 */
  175271. tmp3 = tmp10 - tmp13;
  175272. tmp1 = tmp11 + tmp12;
  175273. tmp2 = tmp11 - tmp12;
  175274. /* Odd part */
  175275. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175276. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175277. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175278. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175279. z13 = tmp6 + tmp5; /* phase 6 */
  175280. z10 = tmp6 - tmp5;
  175281. z11 = tmp4 + tmp7;
  175282. z12 = tmp4 - tmp7;
  175283. tmp7 = z11 + z13; /* phase 5 */
  175284. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175285. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175286. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175287. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175288. tmp6 = tmp12 - tmp7; /* phase 2 */
  175289. tmp5 = tmp11 - tmp6;
  175290. tmp4 = tmp10 + tmp5;
  175291. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175292. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175293. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175294. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175295. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175296. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175297. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175298. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175299. inptr++; /* advance pointers to next column */
  175300. quantptr++;
  175301. wsptr++;
  175302. }
  175303. /* Pass 2: process rows from work array, store into output array. */
  175304. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175305. /* and also undo the PASS1_BITS scaling. */
  175306. wsptr = workspace;
  175307. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175308. outptr = output_buf[ctr] + output_col;
  175309. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175310. * However, the column calculation has created many nonzero AC terms, so
  175311. * the simplification applies less often (typically 5% to 10% of the time).
  175312. * On machines with very fast multiplication, it's possible that the
  175313. * test takes more time than it's worth. In that case this section
  175314. * may be commented out.
  175315. */
  175316. #ifndef NO_ZERO_ROW_TEST
  175317. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175318. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175319. /* AC terms all zero */
  175320. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175321. & RANGE_MASK];
  175322. outptr[0] = dcval;
  175323. outptr[1] = dcval;
  175324. outptr[2] = dcval;
  175325. outptr[3] = dcval;
  175326. outptr[4] = dcval;
  175327. outptr[5] = dcval;
  175328. outptr[6] = dcval;
  175329. outptr[7] = dcval;
  175330. wsptr += DCTSIZE; /* advance pointer to next row */
  175331. continue;
  175332. }
  175333. #endif
  175334. /* Even part */
  175335. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175336. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175337. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175338. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175339. - tmp13;
  175340. tmp0 = tmp10 + tmp13;
  175341. tmp3 = tmp10 - tmp13;
  175342. tmp1 = tmp11 + tmp12;
  175343. tmp2 = tmp11 - tmp12;
  175344. /* Odd part */
  175345. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175346. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175347. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175348. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175349. tmp7 = z11 + z13; /* phase 5 */
  175350. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175351. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175352. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175353. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175354. tmp6 = tmp12 - tmp7; /* phase 2 */
  175355. tmp5 = tmp11 - tmp6;
  175356. tmp4 = tmp10 + tmp5;
  175357. /* Final output stage: scale down by a factor of 8 and range-limit */
  175358. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175359. & RANGE_MASK];
  175360. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175361. & RANGE_MASK];
  175362. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175363. & RANGE_MASK];
  175364. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175365. & RANGE_MASK];
  175366. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175367. & RANGE_MASK];
  175368. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175369. & RANGE_MASK];
  175370. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175371. & RANGE_MASK];
  175372. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175373. & RANGE_MASK];
  175374. wsptr += DCTSIZE; /* advance pointer to next row */
  175375. }
  175376. }
  175377. #endif /* DCT_IFAST_SUPPORTED */
  175378. /*** End of inlined file: jidctfst.c ***/
  175379. #undef CONST_BITS
  175380. #undef FIX_1_847759065
  175381. #undef MULTIPLY
  175382. #undef DEQUANTIZE
  175383. /*** Start of inlined file: jidctint.c ***/
  175384. #define JPEG_INTERNALS
  175385. #ifdef DCT_ISLOW_SUPPORTED
  175386. /*
  175387. * This module is specialized to the case DCTSIZE = 8.
  175388. */
  175389. #if DCTSIZE != 8
  175390. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175391. #endif
  175392. /*
  175393. * The poop on this scaling stuff is as follows:
  175394. *
  175395. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175396. * larger than the true IDCT outputs. The final outputs are therefore
  175397. * a factor of N larger than desired; since N=8 this can be cured by
  175398. * a simple right shift at the end of the algorithm. The advantage of
  175399. * this arrangement is that we save two multiplications per 1-D IDCT,
  175400. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175401. *
  175402. * We have to do addition and subtraction of the integer inputs, which
  175403. * is no problem, and multiplication by fractional constants, which is
  175404. * a problem to do in integer arithmetic. We multiply all the constants
  175405. * by CONST_SCALE and convert them to integer constants (thus retaining
  175406. * CONST_BITS bits of precision in the constants). After doing a
  175407. * multiplication we have to divide the product by CONST_SCALE, with proper
  175408. * rounding, to produce the correct output. This division can be done
  175409. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175410. * as long as possible so that partial sums can be added together with
  175411. * full fractional precision.
  175412. *
  175413. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175414. * they are represented to better-than-integral precision. These outputs
  175415. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175416. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175417. * intermediate INT32 array would be needed.)
  175418. *
  175419. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175420. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175421. * shows that the values given below are the most effective.
  175422. */
  175423. #if BITS_IN_JSAMPLE == 8
  175424. #define CONST_BITS 13
  175425. #define PASS1_BITS 2
  175426. #else
  175427. #define CONST_BITS 13
  175428. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175429. #endif
  175430. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175431. * causing a lot of useless floating-point operations at run time.
  175432. * To get around this we use the following pre-calculated constants.
  175433. * If you change CONST_BITS you may want to add appropriate values.
  175434. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175435. */
  175436. #if CONST_BITS == 13
  175437. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175438. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175439. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175440. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175441. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175442. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175443. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175444. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175445. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175446. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175447. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175448. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175449. #else
  175450. #define FIX_0_298631336 FIX(0.298631336)
  175451. #define FIX_0_390180644 FIX(0.390180644)
  175452. #define FIX_0_541196100 FIX(0.541196100)
  175453. #define FIX_0_765366865 FIX(0.765366865)
  175454. #define FIX_0_899976223 FIX(0.899976223)
  175455. #define FIX_1_175875602 FIX(1.175875602)
  175456. #define FIX_1_501321110 FIX(1.501321110)
  175457. #define FIX_1_847759065 FIX(1.847759065)
  175458. #define FIX_1_961570560 FIX(1.961570560)
  175459. #define FIX_2_053119869 FIX(2.053119869)
  175460. #define FIX_2_562915447 FIX(2.562915447)
  175461. #define FIX_3_072711026 FIX(3.072711026)
  175462. #endif
  175463. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175464. * For 8-bit samples with the recommended scaling, all the variable
  175465. * and constant values involved are no more than 16 bits wide, so a
  175466. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175467. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175468. */
  175469. #if BITS_IN_JSAMPLE == 8
  175470. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175471. #else
  175472. #define MULTIPLY(var,const) ((var) * (const))
  175473. #endif
  175474. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175475. * entry; produce an int result. In this module, both inputs and result
  175476. * are 16 bits or less, so either int or short multiply will work.
  175477. */
  175478. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175479. /*
  175480. * Perform dequantization and inverse DCT on one block of coefficients.
  175481. */
  175482. GLOBAL(void)
  175483. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175484. JCOEFPTR coef_block,
  175485. JSAMPARRAY output_buf, JDIMENSION output_col)
  175486. {
  175487. INT32 tmp0, tmp1, tmp2, tmp3;
  175488. INT32 tmp10, tmp11, tmp12, tmp13;
  175489. INT32 z1, z2, z3, z4, z5;
  175490. JCOEFPTR inptr;
  175491. ISLOW_MULT_TYPE * quantptr;
  175492. int * wsptr;
  175493. JSAMPROW outptr;
  175494. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175495. int ctr;
  175496. int workspace[DCTSIZE2]; /* buffers data between passes */
  175497. SHIFT_TEMPS
  175498. /* Pass 1: process columns from input, store into work array. */
  175499. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175500. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175501. inptr = coef_block;
  175502. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175503. wsptr = workspace;
  175504. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175505. /* Due to quantization, we will usually find that many of the input
  175506. * coefficients are zero, especially the AC terms. We can exploit this
  175507. * by short-circuiting the IDCT calculation for any column in which all
  175508. * the AC terms are zero. In that case each output is equal to the
  175509. * DC coefficient (with scale factor as needed).
  175510. * With typical images and quantization tables, half or more of the
  175511. * column DCT calculations can be simplified this way.
  175512. */
  175513. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175514. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175515. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175516. inptr[DCTSIZE*7] == 0) {
  175517. /* AC terms all zero */
  175518. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175519. wsptr[DCTSIZE*0] = dcval;
  175520. wsptr[DCTSIZE*1] = dcval;
  175521. wsptr[DCTSIZE*2] = dcval;
  175522. wsptr[DCTSIZE*3] = dcval;
  175523. wsptr[DCTSIZE*4] = dcval;
  175524. wsptr[DCTSIZE*5] = dcval;
  175525. wsptr[DCTSIZE*6] = dcval;
  175526. wsptr[DCTSIZE*7] = dcval;
  175527. inptr++; /* advance pointers to next column */
  175528. quantptr++;
  175529. wsptr++;
  175530. continue;
  175531. }
  175532. /* Even part: reverse the even part of the forward DCT. */
  175533. /* The rotator is sqrt(2)*c(-6). */
  175534. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175535. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175536. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175537. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175538. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175539. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175540. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175541. tmp0 = (z2 + z3) << CONST_BITS;
  175542. tmp1 = (z2 - z3) << CONST_BITS;
  175543. tmp10 = tmp0 + tmp3;
  175544. tmp13 = tmp0 - tmp3;
  175545. tmp11 = tmp1 + tmp2;
  175546. tmp12 = tmp1 - tmp2;
  175547. /* Odd part per figure 8; the matrix is unitary and hence its
  175548. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175549. */
  175550. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175551. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175552. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175553. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175554. z1 = tmp0 + tmp3;
  175555. z2 = tmp1 + tmp2;
  175556. z3 = tmp0 + tmp2;
  175557. z4 = tmp1 + tmp3;
  175558. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175559. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175560. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175561. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175562. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175563. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175564. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175565. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175566. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175567. z3 += z5;
  175568. z4 += z5;
  175569. tmp0 += z1 + z3;
  175570. tmp1 += z2 + z4;
  175571. tmp2 += z2 + z3;
  175572. tmp3 += z1 + z4;
  175573. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175574. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175575. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175576. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175577. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175578. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175579. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175580. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175581. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175582. inptr++; /* advance pointers to next column */
  175583. quantptr++;
  175584. wsptr++;
  175585. }
  175586. /* Pass 2: process rows from work array, store into output array. */
  175587. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175588. /* and also undo the PASS1_BITS scaling. */
  175589. wsptr = workspace;
  175590. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175591. outptr = output_buf[ctr] + output_col;
  175592. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175593. * However, the column calculation has created many nonzero AC terms, so
  175594. * the simplification applies less often (typically 5% to 10% of the time).
  175595. * On machines with very fast multiplication, it's possible that the
  175596. * test takes more time than it's worth. In that case this section
  175597. * may be commented out.
  175598. */
  175599. #ifndef NO_ZERO_ROW_TEST
  175600. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175601. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175602. /* AC terms all zero */
  175603. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175604. & RANGE_MASK];
  175605. outptr[0] = dcval;
  175606. outptr[1] = dcval;
  175607. outptr[2] = dcval;
  175608. outptr[3] = dcval;
  175609. outptr[4] = dcval;
  175610. outptr[5] = dcval;
  175611. outptr[6] = dcval;
  175612. outptr[7] = dcval;
  175613. wsptr += DCTSIZE; /* advance pointer to next row */
  175614. continue;
  175615. }
  175616. #endif
  175617. /* Even part: reverse the even part of the forward DCT. */
  175618. /* The rotator is sqrt(2)*c(-6). */
  175619. z2 = (INT32) wsptr[2];
  175620. z3 = (INT32) wsptr[6];
  175621. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175622. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175623. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175624. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175625. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175626. tmp10 = tmp0 + tmp3;
  175627. tmp13 = tmp0 - tmp3;
  175628. tmp11 = tmp1 + tmp2;
  175629. tmp12 = tmp1 - tmp2;
  175630. /* Odd part per figure 8; the matrix is unitary and hence its
  175631. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175632. */
  175633. tmp0 = (INT32) wsptr[7];
  175634. tmp1 = (INT32) wsptr[5];
  175635. tmp2 = (INT32) wsptr[3];
  175636. tmp3 = (INT32) wsptr[1];
  175637. z1 = tmp0 + tmp3;
  175638. z2 = tmp1 + tmp2;
  175639. z3 = tmp0 + tmp2;
  175640. z4 = tmp1 + tmp3;
  175641. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175642. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175643. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175644. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175645. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175646. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175647. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175648. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175649. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175650. z3 += z5;
  175651. z4 += z5;
  175652. tmp0 += z1 + z3;
  175653. tmp1 += z2 + z4;
  175654. tmp2 += z2 + z3;
  175655. tmp3 += z1 + z4;
  175656. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175657. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175658. CONST_BITS+PASS1_BITS+3)
  175659. & RANGE_MASK];
  175660. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175661. CONST_BITS+PASS1_BITS+3)
  175662. & RANGE_MASK];
  175663. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175664. CONST_BITS+PASS1_BITS+3)
  175665. & RANGE_MASK];
  175666. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175667. CONST_BITS+PASS1_BITS+3)
  175668. & RANGE_MASK];
  175669. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175670. CONST_BITS+PASS1_BITS+3)
  175671. & RANGE_MASK];
  175672. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175673. CONST_BITS+PASS1_BITS+3)
  175674. & RANGE_MASK];
  175675. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175676. CONST_BITS+PASS1_BITS+3)
  175677. & RANGE_MASK];
  175678. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175679. CONST_BITS+PASS1_BITS+3)
  175680. & RANGE_MASK];
  175681. wsptr += DCTSIZE; /* advance pointer to next row */
  175682. }
  175683. }
  175684. #endif /* DCT_ISLOW_SUPPORTED */
  175685. /*** End of inlined file: jidctint.c ***/
  175686. /*** Start of inlined file: jidctred.c ***/
  175687. #define JPEG_INTERNALS
  175688. #ifdef IDCT_SCALING_SUPPORTED
  175689. /*
  175690. * This module is specialized to the case DCTSIZE = 8.
  175691. */
  175692. #if DCTSIZE != 8
  175693. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175694. #endif
  175695. /* Scaling is the same as in jidctint.c. */
  175696. #if BITS_IN_JSAMPLE == 8
  175697. #define CONST_BITS 13
  175698. #define PASS1_BITS 2
  175699. #else
  175700. #define CONST_BITS 13
  175701. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175702. #endif
  175703. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175704. * causing a lot of useless floating-point operations at run time.
  175705. * To get around this we use the following pre-calculated constants.
  175706. * If you change CONST_BITS you may want to add appropriate values.
  175707. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175708. */
  175709. #if CONST_BITS == 13
  175710. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175711. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175712. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175713. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175714. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175715. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175716. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175717. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175718. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175719. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175720. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175721. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175722. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175723. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175724. #else
  175725. #define FIX_0_211164243 FIX(0.211164243)
  175726. #define FIX_0_509795579 FIX(0.509795579)
  175727. #define FIX_0_601344887 FIX(0.601344887)
  175728. #define FIX_0_720959822 FIX(0.720959822)
  175729. #define FIX_0_765366865 FIX(0.765366865)
  175730. #define FIX_0_850430095 FIX(0.850430095)
  175731. #define FIX_0_899976223 FIX(0.899976223)
  175732. #define FIX_1_061594337 FIX(1.061594337)
  175733. #define FIX_1_272758580 FIX(1.272758580)
  175734. #define FIX_1_451774981 FIX(1.451774981)
  175735. #define FIX_1_847759065 FIX(1.847759065)
  175736. #define FIX_2_172734803 FIX(2.172734803)
  175737. #define FIX_2_562915447 FIX(2.562915447)
  175738. #define FIX_3_624509785 FIX(3.624509785)
  175739. #endif
  175740. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175741. * For 8-bit samples with the recommended scaling, all the variable
  175742. * and constant values involved are no more than 16 bits wide, so a
  175743. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175744. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175745. */
  175746. #if BITS_IN_JSAMPLE == 8
  175747. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175748. #else
  175749. #define MULTIPLY(var,const) ((var) * (const))
  175750. #endif
  175751. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175752. * entry; produce an int result. In this module, both inputs and result
  175753. * are 16 bits or less, so either int or short multiply will work.
  175754. */
  175755. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175756. /*
  175757. * Perform dequantization and inverse DCT on one block of coefficients,
  175758. * producing a reduced-size 4x4 output block.
  175759. */
  175760. GLOBAL(void)
  175761. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175762. JCOEFPTR coef_block,
  175763. JSAMPARRAY output_buf, JDIMENSION output_col)
  175764. {
  175765. INT32 tmp0, tmp2, tmp10, tmp12;
  175766. INT32 z1, z2, z3, z4;
  175767. JCOEFPTR inptr;
  175768. ISLOW_MULT_TYPE * quantptr;
  175769. int * wsptr;
  175770. JSAMPROW outptr;
  175771. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175772. int ctr;
  175773. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175774. SHIFT_TEMPS
  175775. /* Pass 1: process columns from input, store into work array. */
  175776. inptr = coef_block;
  175777. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175778. wsptr = workspace;
  175779. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175780. /* Don't bother to process column 4, because second pass won't use it */
  175781. if (ctr == DCTSIZE-4)
  175782. continue;
  175783. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175784. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175785. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175786. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175787. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175788. wsptr[DCTSIZE*0] = dcval;
  175789. wsptr[DCTSIZE*1] = dcval;
  175790. wsptr[DCTSIZE*2] = dcval;
  175791. wsptr[DCTSIZE*3] = dcval;
  175792. continue;
  175793. }
  175794. /* Even part */
  175795. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175796. tmp0 <<= (CONST_BITS+1);
  175797. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175798. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175799. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175800. tmp10 = tmp0 + tmp2;
  175801. tmp12 = tmp0 - tmp2;
  175802. /* Odd part */
  175803. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175804. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175805. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175806. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175807. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175808. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175809. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175810. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175811. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175812. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175813. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175814. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175815. /* Final output stage */
  175816. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175817. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175818. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175819. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175820. }
  175821. /* Pass 2: process 4 rows from work array, store into output array. */
  175822. wsptr = workspace;
  175823. for (ctr = 0; ctr < 4; ctr++) {
  175824. outptr = output_buf[ctr] + output_col;
  175825. /* It's not clear whether a zero row test is worthwhile here ... */
  175826. #ifndef NO_ZERO_ROW_TEST
  175827. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175828. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175829. /* AC terms all zero */
  175830. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175831. & RANGE_MASK];
  175832. outptr[0] = dcval;
  175833. outptr[1] = dcval;
  175834. outptr[2] = dcval;
  175835. outptr[3] = dcval;
  175836. wsptr += DCTSIZE; /* advance pointer to next row */
  175837. continue;
  175838. }
  175839. #endif
  175840. /* Even part */
  175841. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175842. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175843. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175844. tmp10 = tmp0 + tmp2;
  175845. tmp12 = tmp0 - tmp2;
  175846. /* Odd part */
  175847. z1 = (INT32) wsptr[7];
  175848. z2 = (INT32) wsptr[5];
  175849. z3 = (INT32) wsptr[3];
  175850. z4 = (INT32) wsptr[1];
  175851. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175852. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175853. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175854. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175855. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175856. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175857. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175858. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175859. /* Final output stage */
  175860. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175861. CONST_BITS+PASS1_BITS+3+1)
  175862. & RANGE_MASK];
  175863. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175864. CONST_BITS+PASS1_BITS+3+1)
  175865. & RANGE_MASK];
  175866. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175867. CONST_BITS+PASS1_BITS+3+1)
  175868. & RANGE_MASK];
  175869. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175870. CONST_BITS+PASS1_BITS+3+1)
  175871. & RANGE_MASK];
  175872. wsptr += DCTSIZE; /* advance pointer to next row */
  175873. }
  175874. }
  175875. /*
  175876. * Perform dequantization and inverse DCT on one block of coefficients,
  175877. * producing a reduced-size 2x2 output block.
  175878. */
  175879. GLOBAL(void)
  175880. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175881. JCOEFPTR coef_block,
  175882. JSAMPARRAY output_buf, JDIMENSION output_col)
  175883. {
  175884. INT32 tmp0, tmp10, z1;
  175885. JCOEFPTR inptr;
  175886. ISLOW_MULT_TYPE * quantptr;
  175887. int * wsptr;
  175888. JSAMPROW outptr;
  175889. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175890. int ctr;
  175891. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175892. SHIFT_TEMPS
  175893. /* Pass 1: process columns from input, store into work array. */
  175894. inptr = coef_block;
  175895. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175896. wsptr = workspace;
  175897. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175898. /* Don't bother to process columns 2,4,6 */
  175899. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175900. continue;
  175901. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175902. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175903. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175904. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175905. wsptr[DCTSIZE*0] = dcval;
  175906. wsptr[DCTSIZE*1] = dcval;
  175907. continue;
  175908. }
  175909. /* Even part */
  175910. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175911. tmp10 = z1 << (CONST_BITS+2);
  175912. /* Odd part */
  175913. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175914. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175915. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175916. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175917. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175918. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175919. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175920. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175921. /* Final output stage */
  175922. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175923. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175924. }
  175925. /* Pass 2: process 2 rows from work array, store into output array. */
  175926. wsptr = workspace;
  175927. for (ctr = 0; ctr < 2; ctr++) {
  175928. outptr = output_buf[ctr] + output_col;
  175929. /* It's not clear whether a zero row test is worthwhile here ... */
  175930. #ifndef NO_ZERO_ROW_TEST
  175931. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175932. /* AC terms all zero */
  175933. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175934. & RANGE_MASK];
  175935. outptr[0] = dcval;
  175936. outptr[1] = dcval;
  175937. wsptr += DCTSIZE; /* advance pointer to next row */
  175938. continue;
  175939. }
  175940. #endif
  175941. /* Even part */
  175942. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175943. /* Odd part */
  175944. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175945. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175946. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175947. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175948. /* Final output stage */
  175949. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175950. CONST_BITS+PASS1_BITS+3+2)
  175951. & RANGE_MASK];
  175952. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175953. CONST_BITS+PASS1_BITS+3+2)
  175954. & RANGE_MASK];
  175955. wsptr += DCTSIZE; /* advance pointer to next row */
  175956. }
  175957. }
  175958. /*
  175959. * Perform dequantization and inverse DCT on one block of coefficients,
  175960. * producing a reduced-size 1x1 output block.
  175961. */
  175962. GLOBAL(void)
  175963. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175964. JCOEFPTR coef_block,
  175965. JSAMPARRAY output_buf, JDIMENSION output_col)
  175966. {
  175967. int dcval;
  175968. ISLOW_MULT_TYPE * quantptr;
  175969. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175970. SHIFT_TEMPS
  175971. /* We hardly need an inverse DCT routine for this: just take the
  175972. * average pixel value, which is one-eighth of the DC coefficient.
  175973. */
  175974. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175975. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175976. dcval = (int) DESCALE((INT32) dcval, 3);
  175977. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175978. }
  175979. #endif /* IDCT_SCALING_SUPPORTED */
  175980. /*** End of inlined file: jidctred.c ***/
  175981. /*** Start of inlined file: jmemmgr.c ***/
  175982. #define JPEG_INTERNALS
  175983. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175984. /*** Start of inlined file: jmemsys.h ***/
  175985. #ifndef __jmemsys_h__
  175986. #define __jmemsys_h__
  175987. /* Short forms of external names for systems with brain-damaged linkers. */
  175988. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175989. #define jpeg_get_small jGetSmall
  175990. #define jpeg_free_small jFreeSmall
  175991. #define jpeg_get_large jGetLarge
  175992. #define jpeg_free_large jFreeLarge
  175993. #define jpeg_mem_available jMemAvail
  175994. #define jpeg_open_backing_store jOpenBackStore
  175995. #define jpeg_mem_init jMemInit
  175996. #define jpeg_mem_term jMemTerm
  175997. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175998. /*
  175999. * These two functions are used to allocate and release small chunks of
  176000. * memory. (Typically the total amount requested through jpeg_get_small is
  176001. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176002. * Behavior should be the same as for the standard library functions malloc
  176003. * and free; in particular, jpeg_get_small must return NULL on failure.
  176004. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176005. * size of the object being freed, just in case it's needed.
  176006. * On an 80x86 machine using small-data memory model, these manage near heap.
  176007. */
  176008. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176009. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176010. size_t sizeofobject));
  176011. /*
  176012. * These two functions are used to allocate and release large chunks of
  176013. * memory (up to the total free space designated by jpeg_mem_available).
  176014. * The interface is the same as above, except that on an 80x86 machine,
  176015. * far pointers are used. On most other machines these are identical to
  176016. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176017. * in case a different allocation strategy is desirable for large chunks.
  176018. */
  176019. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176020. size_t sizeofobject));
  176021. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176022. size_t sizeofobject));
  176023. /*
  176024. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176025. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176026. * matter, but that case should never come into play). This macro is needed
  176027. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176028. * On those machines, we expect that jconfig.h will provide a proper value.
  176029. * On machines with 32-bit flat address spaces, any large constant may be used.
  176030. *
  176031. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176032. * size_t and will be a multiple of sizeof(align_type).
  176033. */
  176034. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176035. #define MAX_ALLOC_CHUNK 1000000000L
  176036. #endif
  176037. /*
  176038. * This routine computes the total space still available for allocation by
  176039. * jpeg_get_large. If more space than this is needed, backing store will be
  176040. * used. NOTE: any memory already allocated must not be counted.
  176041. *
  176042. * There is a minimum space requirement, corresponding to the minimum
  176043. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176044. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176045. * all working storage in memory, is also passed in case it is useful.
  176046. * Finally, the total space already allocated is passed. If no better
  176047. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176048. * is often a suitable calculation.
  176049. *
  176050. * It is OK for jpeg_mem_available to underestimate the space available
  176051. * (that'll just lead to more backing-store access than is really necessary).
  176052. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176053. * a slop factor from the true available space. 5% should be enough.
  176054. *
  176055. * On machines with lots of virtual memory, any large constant may be returned.
  176056. * Conversely, zero may be returned to always use the minimum amount of memory.
  176057. */
  176058. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176059. long min_bytes_needed,
  176060. long max_bytes_needed,
  176061. long already_allocated));
  176062. /*
  176063. * This structure holds whatever state is needed to access a single
  176064. * backing-store object. The read/write/close method pointers are called
  176065. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176066. * are private to the system-dependent backing store routines.
  176067. */
  176068. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176069. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176070. typedef unsigned short XMSH; /* type of extended-memory handles */
  176071. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176072. typedef union {
  176073. short file_handle; /* DOS file handle if it's a temp file */
  176074. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176075. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176076. } handle_union;
  176077. #endif /* USE_MSDOS_MEMMGR */
  176078. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176079. #include <Files.h>
  176080. #endif /* USE_MAC_MEMMGR */
  176081. //typedef struct backing_store_struct * backing_store_ptr;
  176082. typedef struct backing_store_struct {
  176083. /* Methods for reading/writing/closing this backing-store object */
  176084. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176085. struct backing_store_struct *info,
  176086. void FAR * buffer_address,
  176087. long file_offset, long byte_count));
  176088. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176089. struct backing_store_struct *info,
  176090. void FAR * buffer_address,
  176091. long file_offset, long byte_count));
  176092. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176093. struct backing_store_struct *info));
  176094. /* Private fields for system-dependent backing-store management */
  176095. #ifdef USE_MSDOS_MEMMGR
  176096. /* For the MS-DOS manager (jmemdos.c), we need: */
  176097. handle_union handle; /* reference to backing-store storage object */
  176098. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176099. #else
  176100. #ifdef USE_MAC_MEMMGR
  176101. /* For the Mac manager (jmemmac.c), we need: */
  176102. short temp_file; /* file reference number to temp file */
  176103. FSSpec tempSpec; /* the FSSpec for the temp file */
  176104. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176105. #else
  176106. /* For a typical implementation with temp files, we need: */
  176107. FILE * temp_file; /* stdio reference to temp file */
  176108. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176109. #endif
  176110. #endif
  176111. } backing_store_info;
  176112. /*
  176113. * Initial opening of a backing-store object. This must fill in the
  176114. * read/write/close pointers in the object. The read/write routines
  176115. * may take an error exit if the specified maximum file size is exceeded.
  176116. * (If jpeg_mem_available always returns a large value, this routine can
  176117. * just take an error exit.)
  176118. */
  176119. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176120. struct backing_store_struct *info,
  176121. long total_bytes_needed));
  176122. /*
  176123. * These routines take care of any system-dependent initialization and
  176124. * cleanup required. jpeg_mem_init will be called before anything is
  176125. * allocated (and, therefore, nothing in cinfo is of use except the error
  176126. * manager pointer). It should return a suitable default value for
  176127. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176128. * application. (Note that max_memory_to_use is only important if
  176129. * jpeg_mem_available chooses to consult it ... no one else will.)
  176130. * jpeg_mem_term may assume that all requested memory has been freed and that
  176131. * all opened backing-store objects have been closed.
  176132. */
  176133. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176134. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176135. #endif
  176136. /*** End of inlined file: jmemsys.h ***/
  176137. /* import the system-dependent declarations */
  176138. #ifndef NO_GETENV
  176139. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176140. extern char * getenv JPP((const char * name));
  176141. #endif
  176142. #endif
  176143. /*
  176144. * Some important notes:
  176145. * The allocation routines provided here must never return NULL.
  176146. * They should exit to error_exit if unsuccessful.
  176147. *
  176148. * It's not a good idea to try to merge the sarray and barray routines,
  176149. * even though they are textually almost the same, because samples are
  176150. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176151. * in machines where byte pointers have a different representation from
  176152. * word pointers, the resulting machine code could not be the same.
  176153. */
  176154. /*
  176155. * Many machines require storage alignment: longs must start on 4-byte
  176156. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176157. * always returns pointers that are multiples of the worst-case alignment
  176158. * requirement, and we had better do so too.
  176159. * There isn't any really portable way to determine the worst-case alignment
  176160. * requirement. This module assumes that the alignment requirement is
  176161. * multiples of sizeof(ALIGN_TYPE).
  176162. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176163. * workstations (where doubles really do need 8-byte alignment) and will work
  176164. * fine on nearly everything. If your machine has lesser alignment needs,
  176165. * you can save a few bytes by making ALIGN_TYPE smaller.
  176166. * The only place I know of where this will NOT work is certain Macintosh
  176167. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176168. * Doing 10-byte alignment is counterproductive because longwords won't be
  176169. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176170. * such a compiler.
  176171. */
  176172. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176173. #define ALIGN_TYPE double
  176174. #endif
  176175. /*
  176176. * We allocate objects from "pools", where each pool is gotten with a single
  176177. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176178. * overhead within a pool, except for alignment padding. Each pool has a
  176179. * header with a link to the next pool of the same class.
  176180. * Small and large pool headers are identical except that the latter's
  176181. * link pointer must be FAR on 80x86 machines.
  176182. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176183. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176184. * of the alignment requirement of ALIGN_TYPE.
  176185. */
  176186. typedef union small_pool_struct * small_pool_ptr;
  176187. typedef union small_pool_struct {
  176188. struct {
  176189. small_pool_ptr next; /* next in list of pools */
  176190. size_t bytes_used; /* how many bytes already used within pool */
  176191. size_t bytes_left; /* bytes still available in this pool */
  176192. } hdr;
  176193. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176194. } small_pool_hdr;
  176195. typedef union large_pool_struct FAR * large_pool_ptr;
  176196. typedef union large_pool_struct {
  176197. struct {
  176198. large_pool_ptr next; /* next in list of pools */
  176199. size_t bytes_used; /* how many bytes already used within pool */
  176200. size_t bytes_left; /* bytes still available in this pool */
  176201. } hdr;
  176202. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176203. } large_pool_hdr;
  176204. /*
  176205. * Here is the full definition of a memory manager object.
  176206. */
  176207. typedef struct {
  176208. struct jpeg_memory_mgr pub; /* public fields */
  176209. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176210. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176211. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176212. /* Since we only have one lifetime class of virtual arrays, only one
  176213. * linked list is necessary (for each datatype). Note that the virtual
  176214. * array control blocks being linked together are actually stored somewhere
  176215. * in the small-pool list.
  176216. */
  176217. jvirt_sarray_ptr virt_sarray_list;
  176218. jvirt_barray_ptr virt_barray_list;
  176219. /* This counts total space obtained from jpeg_get_small/large */
  176220. long total_space_allocated;
  176221. /* alloc_sarray and alloc_barray set this value for use by virtual
  176222. * array routines.
  176223. */
  176224. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176225. } my_memory_mgr;
  176226. typedef my_memory_mgr * my_mem_ptr;
  176227. /*
  176228. * The control blocks for virtual arrays.
  176229. * Note that these blocks are allocated in the "small" pool area.
  176230. * System-dependent info for the associated backing store (if any) is hidden
  176231. * inside the backing_store_info struct.
  176232. */
  176233. struct jvirt_sarray_control {
  176234. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176235. JDIMENSION rows_in_array; /* total virtual array height */
  176236. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176237. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176238. JDIMENSION rows_in_mem; /* height of memory buffer */
  176239. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176240. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176241. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176242. boolean pre_zero; /* pre-zero mode requested? */
  176243. boolean dirty; /* do current buffer contents need written? */
  176244. boolean b_s_open; /* is backing-store data valid? */
  176245. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176246. backing_store_info b_s_info; /* System-dependent control info */
  176247. };
  176248. struct jvirt_barray_control {
  176249. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176250. JDIMENSION rows_in_array; /* total virtual array height */
  176251. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176252. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176253. JDIMENSION rows_in_mem; /* height of memory buffer */
  176254. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176255. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176256. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176257. boolean pre_zero; /* pre-zero mode requested? */
  176258. boolean dirty; /* do current buffer contents need written? */
  176259. boolean b_s_open; /* is backing-store data valid? */
  176260. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176261. backing_store_info b_s_info; /* System-dependent control info */
  176262. };
  176263. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176264. LOCAL(void)
  176265. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176266. {
  176267. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176268. small_pool_ptr shdr_ptr;
  176269. large_pool_ptr lhdr_ptr;
  176270. /* Since this is only a debugging stub, we can cheat a little by using
  176271. * fprintf directly rather than going through the trace message code.
  176272. * This is helpful because message parm array can't handle longs.
  176273. */
  176274. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176275. pool_id, mem->total_space_allocated);
  176276. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176277. lhdr_ptr = lhdr_ptr->hdr.next) {
  176278. fprintf(stderr, " Large chunk used %ld\n",
  176279. (long) lhdr_ptr->hdr.bytes_used);
  176280. }
  176281. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176282. shdr_ptr = shdr_ptr->hdr.next) {
  176283. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176284. (long) shdr_ptr->hdr.bytes_used,
  176285. (long) shdr_ptr->hdr.bytes_left);
  176286. }
  176287. }
  176288. #endif /* MEM_STATS */
  176289. LOCAL(void)
  176290. out_of_memory (j_common_ptr cinfo, int which)
  176291. /* Report an out-of-memory error and stop execution */
  176292. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176293. {
  176294. #ifdef MEM_STATS
  176295. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176296. #endif
  176297. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176298. }
  176299. /*
  176300. * Allocation of "small" objects.
  176301. *
  176302. * For these, we use pooled storage. When a new pool must be created,
  176303. * we try to get enough space for the current request plus a "slop" factor,
  176304. * where the slop will be the amount of leftover space in the new pool.
  176305. * The speed vs. space tradeoff is largely determined by the slop values.
  176306. * A different slop value is provided for each pool class (lifetime),
  176307. * and we also distinguish the first pool of a class from later ones.
  176308. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176309. * machines, but may be too small if longs are 64 bits or more.
  176310. */
  176311. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176312. {
  176313. 1600, /* first PERMANENT pool */
  176314. 16000 /* first IMAGE pool */
  176315. };
  176316. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176317. {
  176318. 0, /* additional PERMANENT pools */
  176319. 5000 /* additional IMAGE pools */
  176320. };
  176321. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176322. METHODDEF(void *)
  176323. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176324. /* Allocate a "small" object */
  176325. {
  176326. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176327. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176328. char * data_ptr;
  176329. size_t odd_bytes, min_request, slop;
  176330. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176331. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176332. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176333. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176334. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176335. if (odd_bytes > 0)
  176336. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176337. /* See if space is available in any existing pool */
  176338. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176339. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176340. prev_hdr_ptr = NULL;
  176341. hdr_ptr = mem->small_list[pool_id];
  176342. while (hdr_ptr != NULL) {
  176343. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176344. break; /* found pool with enough space */
  176345. prev_hdr_ptr = hdr_ptr;
  176346. hdr_ptr = hdr_ptr->hdr.next;
  176347. }
  176348. /* Time to make a new pool? */
  176349. if (hdr_ptr == NULL) {
  176350. /* min_request is what we need now, slop is what will be leftover */
  176351. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176352. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176353. slop = first_pool_slop[pool_id];
  176354. else
  176355. slop = extra_pool_slop[pool_id];
  176356. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176357. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176358. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176359. /* Try to get space, if fail reduce slop and try again */
  176360. for (;;) {
  176361. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176362. if (hdr_ptr != NULL)
  176363. break;
  176364. slop /= 2;
  176365. if (slop < MIN_SLOP) /* give up when it gets real small */
  176366. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176367. }
  176368. mem->total_space_allocated += min_request + slop;
  176369. /* Success, initialize the new pool header and add to end of list */
  176370. hdr_ptr->hdr.next = NULL;
  176371. hdr_ptr->hdr.bytes_used = 0;
  176372. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176373. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176374. mem->small_list[pool_id] = hdr_ptr;
  176375. else
  176376. prev_hdr_ptr->hdr.next = hdr_ptr;
  176377. }
  176378. /* OK, allocate the object from the current pool */
  176379. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176380. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176381. hdr_ptr->hdr.bytes_used += sizeofobject;
  176382. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176383. return (void *) data_ptr;
  176384. }
  176385. /*
  176386. * Allocation of "large" objects.
  176387. *
  176388. * The external semantics of these are the same as "small" objects,
  176389. * except that FAR pointers are used on 80x86. However the pool
  176390. * management heuristics are quite different. We assume that each
  176391. * request is large enough that it may as well be passed directly to
  176392. * jpeg_get_large; the pool management just links everything together
  176393. * so that we can free it all on demand.
  176394. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176395. * structures. The routines that create these structures (see below)
  176396. * deliberately bunch rows together to ensure a large request size.
  176397. */
  176398. METHODDEF(void FAR *)
  176399. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176400. /* Allocate a "large" object */
  176401. {
  176402. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176403. large_pool_ptr hdr_ptr;
  176404. size_t odd_bytes;
  176405. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176406. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176407. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176408. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176409. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176410. if (odd_bytes > 0)
  176411. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176412. /* Always make a new pool */
  176413. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176414. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176415. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176416. SIZEOF(large_pool_hdr));
  176417. if (hdr_ptr == NULL)
  176418. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176419. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176420. /* Success, initialize the new pool header and add to list */
  176421. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176422. /* We maintain space counts in each pool header for statistical purposes,
  176423. * even though they are not needed for allocation.
  176424. */
  176425. hdr_ptr->hdr.bytes_used = sizeofobject;
  176426. hdr_ptr->hdr.bytes_left = 0;
  176427. mem->large_list[pool_id] = hdr_ptr;
  176428. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176429. }
  176430. /*
  176431. * Creation of 2-D sample arrays.
  176432. * The pointers are in near heap, the samples themselves in FAR heap.
  176433. *
  176434. * To minimize allocation overhead and to allow I/O of large contiguous
  176435. * blocks, we allocate the sample rows in groups of as many rows as possible
  176436. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176437. * NB: the virtual array control routines, later in this file, know about
  176438. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176439. * object so that it can be saved away if this sarray is the workspace for
  176440. * a virtual array.
  176441. */
  176442. METHODDEF(JSAMPARRAY)
  176443. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176444. JDIMENSION samplesperrow, JDIMENSION numrows)
  176445. /* Allocate a 2-D sample array */
  176446. {
  176447. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176448. JSAMPARRAY result;
  176449. JSAMPROW workspace;
  176450. JDIMENSION rowsperchunk, currow, i;
  176451. long ltemp;
  176452. /* Calculate max # of rows allowed in one allocation chunk */
  176453. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176454. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176455. if (ltemp <= 0)
  176456. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176457. if (ltemp < (long) numrows)
  176458. rowsperchunk = (JDIMENSION) ltemp;
  176459. else
  176460. rowsperchunk = numrows;
  176461. mem->last_rowsperchunk = rowsperchunk;
  176462. /* Get space for row pointers (small object) */
  176463. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176464. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176465. /* Get the rows themselves (large objects) */
  176466. currow = 0;
  176467. while (currow < numrows) {
  176468. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176469. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176470. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176471. * SIZEOF(JSAMPLE)));
  176472. for (i = rowsperchunk; i > 0; i--) {
  176473. result[currow++] = workspace;
  176474. workspace += samplesperrow;
  176475. }
  176476. }
  176477. return result;
  176478. }
  176479. /*
  176480. * Creation of 2-D coefficient-block arrays.
  176481. * This is essentially the same as the code for sample arrays, above.
  176482. */
  176483. METHODDEF(JBLOCKARRAY)
  176484. alloc_barray (j_common_ptr cinfo, int pool_id,
  176485. JDIMENSION blocksperrow, JDIMENSION numrows)
  176486. /* Allocate a 2-D coefficient-block array */
  176487. {
  176488. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176489. JBLOCKARRAY result;
  176490. JBLOCKROW workspace;
  176491. JDIMENSION rowsperchunk, currow, i;
  176492. long ltemp;
  176493. /* Calculate max # of rows allowed in one allocation chunk */
  176494. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176495. ((long) blocksperrow * SIZEOF(JBLOCK));
  176496. if (ltemp <= 0)
  176497. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176498. if (ltemp < (long) numrows)
  176499. rowsperchunk = (JDIMENSION) ltemp;
  176500. else
  176501. rowsperchunk = numrows;
  176502. mem->last_rowsperchunk = rowsperchunk;
  176503. /* Get space for row pointers (small object) */
  176504. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176505. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176506. /* Get the rows themselves (large objects) */
  176507. currow = 0;
  176508. while (currow < numrows) {
  176509. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176510. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176511. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176512. * SIZEOF(JBLOCK)));
  176513. for (i = rowsperchunk; i > 0; i--) {
  176514. result[currow++] = workspace;
  176515. workspace += blocksperrow;
  176516. }
  176517. }
  176518. return result;
  176519. }
  176520. /*
  176521. * About virtual array management:
  176522. *
  176523. * The above "normal" array routines are only used to allocate strip buffers
  176524. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176525. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176526. * time, but the memory manager must save the whole array for repeated
  176527. * accesses. The intended implementation is that there is a strip buffer in
  176528. * memory (as high as is possible given the desired memory limit), plus a
  176529. * backing file that holds the rest of the array.
  176530. *
  176531. * The request_virt_array routines are told the total size of the image and
  176532. * the maximum number of rows that will be accessed at once. The in-memory
  176533. * buffer must be at least as large as the maxaccess value.
  176534. *
  176535. * The request routines create control blocks but not the in-memory buffers.
  176536. * That is postponed until realize_virt_arrays is called. At that time the
  176537. * total amount of space needed is known (approximately, anyway), so free
  176538. * memory can be divided up fairly.
  176539. *
  176540. * The access_virt_array routines are responsible for making a specific strip
  176541. * area accessible (after reading or writing the backing file, if necessary).
  176542. * Note that the access routines are told whether the caller intends to modify
  176543. * the accessed strip; during a read-only pass this saves having to rewrite
  176544. * data to disk. The access routines are also responsible for pre-zeroing
  176545. * any newly accessed rows, if pre-zeroing was requested.
  176546. *
  176547. * In current usage, the access requests are usually for nonoverlapping
  176548. * strips; that is, successive access start_row numbers differ by exactly
  176549. * num_rows = maxaccess. This means we can get good performance with simple
  176550. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176551. * of the access height; then there will never be accesses across bufferload
  176552. * boundaries. The code will still work with overlapping access requests,
  176553. * but it doesn't handle bufferload overlaps very efficiently.
  176554. */
  176555. METHODDEF(jvirt_sarray_ptr)
  176556. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176557. JDIMENSION samplesperrow, JDIMENSION numrows,
  176558. JDIMENSION maxaccess)
  176559. /* Request a virtual 2-D sample array */
  176560. {
  176561. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176562. jvirt_sarray_ptr result;
  176563. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176564. if (pool_id != JPOOL_IMAGE)
  176565. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176566. /* get control block */
  176567. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176568. SIZEOF(struct jvirt_sarray_control));
  176569. result->mem_buffer = NULL; /* marks array not yet realized */
  176570. result->rows_in_array = numrows;
  176571. result->samplesperrow = samplesperrow;
  176572. result->maxaccess = maxaccess;
  176573. result->pre_zero = pre_zero;
  176574. result->b_s_open = FALSE; /* no associated backing-store object */
  176575. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176576. mem->virt_sarray_list = result;
  176577. return result;
  176578. }
  176579. METHODDEF(jvirt_barray_ptr)
  176580. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176581. JDIMENSION blocksperrow, JDIMENSION numrows,
  176582. JDIMENSION maxaccess)
  176583. /* Request a virtual 2-D coefficient-block array */
  176584. {
  176585. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176586. jvirt_barray_ptr result;
  176587. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176588. if (pool_id != JPOOL_IMAGE)
  176589. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176590. /* get control block */
  176591. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176592. SIZEOF(struct jvirt_barray_control));
  176593. result->mem_buffer = NULL; /* marks array not yet realized */
  176594. result->rows_in_array = numrows;
  176595. result->blocksperrow = blocksperrow;
  176596. result->maxaccess = maxaccess;
  176597. result->pre_zero = pre_zero;
  176598. result->b_s_open = FALSE; /* no associated backing-store object */
  176599. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176600. mem->virt_barray_list = result;
  176601. return result;
  176602. }
  176603. METHODDEF(void)
  176604. realize_virt_arrays (j_common_ptr cinfo)
  176605. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176606. {
  176607. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176608. long space_per_minheight, maximum_space, avail_mem;
  176609. long minheights, max_minheights;
  176610. jvirt_sarray_ptr sptr;
  176611. jvirt_barray_ptr bptr;
  176612. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176613. * and the maximum space needed (full image height in each buffer).
  176614. * These may be of use to the system-dependent jpeg_mem_available routine.
  176615. */
  176616. space_per_minheight = 0;
  176617. maximum_space = 0;
  176618. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176619. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176620. space_per_minheight += (long) sptr->maxaccess *
  176621. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176622. maximum_space += (long) sptr->rows_in_array *
  176623. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176624. }
  176625. }
  176626. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176627. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176628. space_per_minheight += (long) bptr->maxaccess *
  176629. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176630. maximum_space += (long) bptr->rows_in_array *
  176631. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176632. }
  176633. }
  176634. if (space_per_minheight <= 0)
  176635. return; /* no unrealized arrays, no work */
  176636. /* Determine amount of memory to actually use; this is system-dependent. */
  176637. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176638. mem->total_space_allocated);
  176639. /* If the maximum space needed is available, make all the buffers full
  176640. * height; otherwise parcel it out with the same number of minheights
  176641. * in each buffer.
  176642. */
  176643. if (avail_mem >= maximum_space)
  176644. max_minheights = 1000000000L;
  176645. else {
  176646. max_minheights = avail_mem / space_per_minheight;
  176647. /* If there doesn't seem to be enough space, try to get the minimum
  176648. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176649. */
  176650. if (max_minheights <= 0)
  176651. max_minheights = 1;
  176652. }
  176653. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176654. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176655. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176656. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176657. if (minheights <= max_minheights) {
  176658. /* This buffer fits in memory */
  176659. sptr->rows_in_mem = sptr->rows_in_array;
  176660. } else {
  176661. /* It doesn't fit in memory, create backing store. */
  176662. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176663. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176664. (long) sptr->rows_in_array *
  176665. (long) sptr->samplesperrow *
  176666. (long) SIZEOF(JSAMPLE));
  176667. sptr->b_s_open = TRUE;
  176668. }
  176669. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176670. sptr->samplesperrow, sptr->rows_in_mem);
  176671. sptr->rowsperchunk = mem->last_rowsperchunk;
  176672. sptr->cur_start_row = 0;
  176673. sptr->first_undef_row = 0;
  176674. sptr->dirty = FALSE;
  176675. }
  176676. }
  176677. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176678. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176679. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176680. if (minheights <= max_minheights) {
  176681. /* This buffer fits in memory */
  176682. bptr->rows_in_mem = bptr->rows_in_array;
  176683. } else {
  176684. /* It doesn't fit in memory, create backing store. */
  176685. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176686. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176687. (long) bptr->rows_in_array *
  176688. (long) bptr->blocksperrow *
  176689. (long) SIZEOF(JBLOCK));
  176690. bptr->b_s_open = TRUE;
  176691. }
  176692. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176693. bptr->blocksperrow, bptr->rows_in_mem);
  176694. bptr->rowsperchunk = mem->last_rowsperchunk;
  176695. bptr->cur_start_row = 0;
  176696. bptr->first_undef_row = 0;
  176697. bptr->dirty = FALSE;
  176698. }
  176699. }
  176700. }
  176701. LOCAL(void)
  176702. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176703. /* Do backing store read or write of a virtual sample array */
  176704. {
  176705. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176706. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176707. file_offset = ptr->cur_start_row * bytesperrow;
  176708. /* Loop to read or write each allocation chunk in mem_buffer */
  176709. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176710. /* One chunk, but check for short chunk at end of buffer */
  176711. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176712. /* Transfer no more than is currently defined */
  176713. thisrow = (long) ptr->cur_start_row + i;
  176714. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176715. /* Transfer no more than fits in file */
  176716. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176717. if (rows <= 0) /* this chunk might be past end of file! */
  176718. break;
  176719. byte_count = rows * bytesperrow;
  176720. if (writing)
  176721. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176722. (void FAR *) ptr->mem_buffer[i],
  176723. file_offset, byte_count);
  176724. else
  176725. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176726. (void FAR *) ptr->mem_buffer[i],
  176727. file_offset, byte_count);
  176728. file_offset += byte_count;
  176729. }
  176730. }
  176731. LOCAL(void)
  176732. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176733. /* Do backing store read or write of a virtual coefficient-block array */
  176734. {
  176735. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176736. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176737. file_offset = ptr->cur_start_row * bytesperrow;
  176738. /* Loop to read or write each allocation chunk in mem_buffer */
  176739. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176740. /* One chunk, but check for short chunk at end of buffer */
  176741. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176742. /* Transfer no more than is currently defined */
  176743. thisrow = (long) ptr->cur_start_row + i;
  176744. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176745. /* Transfer no more than fits in file */
  176746. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176747. if (rows <= 0) /* this chunk might be past end of file! */
  176748. break;
  176749. byte_count = rows * bytesperrow;
  176750. if (writing)
  176751. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176752. (void FAR *) ptr->mem_buffer[i],
  176753. file_offset, byte_count);
  176754. else
  176755. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176756. (void FAR *) ptr->mem_buffer[i],
  176757. file_offset, byte_count);
  176758. file_offset += byte_count;
  176759. }
  176760. }
  176761. METHODDEF(JSAMPARRAY)
  176762. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176763. JDIMENSION start_row, JDIMENSION num_rows,
  176764. boolean writable)
  176765. /* Access the part of a virtual sample array starting at start_row */
  176766. /* and extending for num_rows rows. writable is true if */
  176767. /* caller intends to modify the accessed area. */
  176768. {
  176769. JDIMENSION end_row = start_row + num_rows;
  176770. JDIMENSION undef_row;
  176771. /* debugging check */
  176772. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176773. ptr->mem_buffer == NULL)
  176774. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176775. /* Make the desired part of the virtual array accessible */
  176776. if (start_row < ptr->cur_start_row ||
  176777. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176778. if (! ptr->b_s_open)
  176779. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176780. /* Flush old buffer contents if necessary */
  176781. if (ptr->dirty) {
  176782. do_sarray_io(cinfo, ptr, TRUE);
  176783. ptr->dirty = FALSE;
  176784. }
  176785. /* Decide what part of virtual array to access.
  176786. * Algorithm: if target address > current window, assume forward scan,
  176787. * load starting at target address. If target address < current window,
  176788. * assume backward scan, load so that target area is top of window.
  176789. * Note that when switching from forward write to forward read, will have
  176790. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176791. */
  176792. if (start_row > ptr->cur_start_row) {
  176793. ptr->cur_start_row = start_row;
  176794. } else {
  176795. /* use long arithmetic here to avoid overflow & unsigned problems */
  176796. long ltemp;
  176797. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176798. if (ltemp < 0)
  176799. ltemp = 0; /* don't fall off front end of file */
  176800. ptr->cur_start_row = (JDIMENSION) ltemp;
  176801. }
  176802. /* Read in the selected part of the array.
  176803. * During the initial write pass, we will do no actual read
  176804. * because the selected part is all undefined.
  176805. */
  176806. do_sarray_io(cinfo, ptr, FALSE);
  176807. }
  176808. /* Ensure the accessed part of the array is defined; prezero if needed.
  176809. * To improve locality of access, we only prezero the part of the array
  176810. * that the caller is about to access, not the entire in-memory array.
  176811. */
  176812. if (ptr->first_undef_row < end_row) {
  176813. if (ptr->first_undef_row < start_row) {
  176814. if (writable) /* writer skipped over a section of array */
  176815. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176816. undef_row = start_row; /* but reader is allowed to read ahead */
  176817. } else {
  176818. undef_row = ptr->first_undef_row;
  176819. }
  176820. if (writable)
  176821. ptr->first_undef_row = end_row;
  176822. if (ptr->pre_zero) {
  176823. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176824. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176825. end_row -= ptr->cur_start_row;
  176826. while (undef_row < end_row) {
  176827. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176828. undef_row++;
  176829. }
  176830. } else {
  176831. if (! writable) /* reader looking at undefined data */
  176832. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176833. }
  176834. }
  176835. /* Flag the buffer dirty if caller will write in it */
  176836. if (writable)
  176837. ptr->dirty = TRUE;
  176838. /* Return address of proper part of the buffer */
  176839. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176840. }
  176841. METHODDEF(JBLOCKARRAY)
  176842. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176843. JDIMENSION start_row, JDIMENSION num_rows,
  176844. boolean writable)
  176845. /* Access the part of a virtual block array starting at start_row */
  176846. /* and extending for num_rows rows. writable is true if */
  176847. /* caller intends to modify the accessed area. */
  176848. {
  176849. JDIMENSION end_row = start_row + num_rows;
  176850. JDIMENSION undef_row;
  176851. /* debugging check */
  176852. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176853. ptr->mem_buffer == NULL)
  176854. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176855. /* Make the desired part of the virtual array accessible */
  176856. if (start_row < ptr->cur_start_row ||
  176857. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176858. if (! ptr->b_s_open)
  176859. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176860. /* Flush old buffer contents if necessary */
  176861. if (ptr->dirty) {
  176862. do_barray_io(cinfo, ptr, TRUE);
  176863. ptr->dirty = FALSE;
  176864. }
  176865. /* Decide what part of virtual array to access.
  176866. * Algorithm: if target address > current window, assume forward scan,
  176867. * load starting at target address. If target address < current window,
  176868. * assume backward scan, load so that target area is top of window.
  176869. * Note that when switching from forward write to forward read, will have
  176870. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176871. */
  176872. if (start_row > ptr->cur_start_row) {
  176873. ptr->cur_start_row = start_row;
  176874. } else {
  176875. /* use long arithmetic here to avoid overflow & unsigned problems */
  176876. long ltemp;
  176877. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176878. if (ltemp < 0)
  176879. ltemp = 0; /* don't fall off front end of file */
  176880. ptr->cur_start_row = (JDIMENSION) ltemp;
  176881. }
  176882. /* Read in the selected part of the array.
  176883. * During the initial write pass, we will do no actual read
  176884. * because the selected part is all undefined.
  176885. */
  176886. do_barray_io(cinfo, ptr, FALSE);
  176887. }
  176888. /* Ensure the accessed part of the array is defined; prezero if needed.
  176889. * To improve locality of access, we only prezero the part of the array
  176890. * that the caller is about to access, not the entire in-memory array.
  176891. */
  176892. if (ptr->first_undef_row < end_row) {
  176893. if (ptr->first_undef_row < start_row) {
  176894. if (writable) /* writer skipped over a section of array */
  176895. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176896. undef_row = start_row; /* but reader is allowed to read ahead */
  176897. } else {
  176898. undef_row = ptr->first_undef_row;
  176899. }
  176900. if (writable)
  176901. ptr->first_undef_row = end_row;
  176902. if (ptr->pre_zero) {
  176903. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176904. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176905. end_row -= ptr->cur_start_row;
  176906. while (undef_row < end_row) {
  176907. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176908. undef_row++;
  176909. }
  176910. } else {
  176911. if (! writable) /* reader looking at undefined data */
  176912. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176913. }
  176914. }
  176915. /* Flag the buffer dirty if caller will write in it */
  176916. if (writable)
  176917. ptr->dirty = TRUE;
  176918. /* Return address of proper part of the buffer */
  176919. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176920. }
  176921. /*
  176922. * Release all objects belonging to a specified pool.
  176923. */
  176924. METHODDEF(void)
  176925. free_pool (j_common_ptr cinfo, int pool_id)
  176926. {
  176927. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176928. small_pool_ptr shdr_ptr;
  176929. large_pool_ptr lhdr_ptr;
  176930. size_t space_freed;
  176931. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176932. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176933. #ifdef MEM_STATS
  176934. if (cinfo->err->trace_level > 1)
  176935. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176936. #endif
  176937. /* If freeing IMAGE pool, close any virtual arrays first */
  176938. if (pool_id == JPOOL_IMAGE) {
  176939. jvirt_sarray_ptr sptr;
  176940. jvirt_barray_ptr bptr;
  176941. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176942. if (sptr->b_s_open) { /* there may be no backing store */
  176943. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176944. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176945. }
  176946. }
  176947. mem->virt_sarray_list = NULL;
  176948. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176949. if (bptr->b_s_open) { /* there may be no backing store */
  176950. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176951. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176952. }
  176953. }
  176954. mem->virt_barray_list = NULL;
  176955. }
  176956. /* Release large objects */
  176957. lhdr_ptr = mem->large_list[pool_id];
  176958. mem->large_list[pool_id] = NULL;
  176959. while (lhdr_ptr != NULL) {
  176960. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176961. space_freed = lhdr_ptr->hdr.bytes_used +
  176962. lhdr_ptr->hdr.bytes_left +
  176963. SIZEOF(large_pool_hdr);
  176964. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176965. mem->total_space_allocated -= space_freed;
  176966. lhdr_ptr = next_lhdr_ptr;
  176967. }
  176968. /* Release small objects */
  176969. shdr_ptr = mem->small_list[pool_id];
  176970. mem->small_list[pool_id] = NULL;
  176971. while (shdr_ptr != NULL) {
  176972. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176973. space_freed = shdr_ptr->hdr.bytes_used +
  176974. shdr_ptr->hdr.bytes_left +
  176975. SIZEOF(small_pool_hdr);
  176976. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176977. mem->total_space_allocated -= space_freed;
  176978. shdr_ptr = next_shdr_ptr;
  176979. }
  176980. }
  176981. /*
  176982. * Close up shop entirely.
  176983. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176984. */
  176985. METHODDEF(void)
  176986. self_destruct (j_common_ptr cinfo)
  176987. {
  176988. int pool;
  176989. /* Close all backing store, release all memory.
  176990. * Releasing pools in reverse order might help avoid fragmentation
  176991. * with some (brain-damaged) malloc libraries.
  176992. */
  176993. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176994. free_pool(cinfo, pool);
  176995. }
  176996. /* Release the memory manager control block too. */
  176997. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176998. cinfo->mem = NULL; /* ensures I will be called only once */
  176999. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177000. }
  177001. /*
  177002. * Memory manager initialization.
  177003. * When this is called, only the error manager pointer is valid in cinfo!
  177004. */
  177005. GLOBAL(void)
  177006. jinit_memory_mgr (j_common_ptr cinfo)
  177007. {
  177008. my_mem_ptr mem;
  177009. long max_to_use;
  177010. int pool;
  177011. size_t test_mac;
  177012. cinfo->mem = NULL; /* for safety if init fails */
  177013. /* Check for configuration errors.
  177014. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177015. * doesn't reflect any real hardware alignment requirement.
  177016. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177017. * in common if and only if X is a power of 2, ie has only one one-bit.
  177018. * Some compilers may give an "unreachable code" warning here; ignore it.
  177019. */
  177020. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177021. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177022. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177023. * a multiple of SIZEOF(ALIGN_TYPE).
  177024. * Again, an "unreachable code" warning may be ignored here.
  177025. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177026. */
  177027. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177028. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177029. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177030. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177031. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177032. /* Attempt to allocate memory manager's control block */
  177033. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177034. if (mem == NULL) {
  177035. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177036. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177037. }
  177038. /* OK, fill in the method pointers */
  177039. mem->pub.alloc_small = alloc_small;
  177040. mem->pub.alloc_large = alloc_large;
  177041. mem->pub.alloc_sarray = alloc_sarray;
  177042. mem->pub.alloc_barray = alloc_barray;
  177043. mem->pub.request_virt_sarray = request_virt_sarray;
  177044. mem->pub.request_virt_barray = request_virt_barray;
  177045. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177046. mem->pub.access_virt_sarray = access_virt_sarray;
  177047. mem->pub.access_virt_barray = access_virt_barray;
  177048. mem->pub.free_pool = free_pool;
  177049. mem->pub.self_destruct = self_destruct;
  177050. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177051. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177052. /* Initialize working state */
  177053. mem->pub.max_memory_to_use = max_to_use;
  177054. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177055. mem->small_list[pool] = NULL;
  177056. mem->large_list[pool] = NULL;
  177057. }
  177058. mem->virt_sarray_list = NULL;
  177059. mem->virt_barray_list = NULL;
  177060. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177061. /* Declare ourselves open for business */
  177062. cinfo->mem = & mem->pub;
  177063. /* Check for an environment variable JPEGMEM; if found, override the
  177064. * default max_memory setting from jpeg_mem_init. Note that the
  177065. * surrounding application may again override this value.
  177066. * If your system doesn't support getenv(), define NO_GETENV to disable
  177067. * this feature.
  177068. */
  177069. #ifndef NO_GETENV
  177070. { char * memenv;
  177071. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177072. char ch = 'x';
  177073. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177074. if (ch == 'm' || ch == 'M')
  177075. max_to_use *= 1000L;
  177076. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177077. }
  177078. }
  177079. }
  177080. #endif
  177081. }
  177082. /*** End of inlined file: jmemmgr.c ***/
  177083. /*** Start of inlined file: jmemnobs.c ***/
  177084. #define JPEG_INTERNALS
  177085. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177086. extern void * malloc JPP((size_t size));
  177087. extern void free JPP((void *ptr));
  177088. #endif
  177089. /*
  177090. * Memory allocation and freeing are controlled by the regular library
  177091. * routines malloc() and free().
  177092. */
  177093. GLOBAL(void *)
  177094. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177095. {
  177096. return (void *) malloc(sizeofobject);
  177097. }
  177098. GLOBAL(void)
  177099. jpeg_free_small (j_common_ptr , void * object, size_t)
  177100. {
  177101. free(object);
  177102. }
  177103. /*
  177104. * "Large" objects are treated the same as "small" ones.
  177105. * NB: although we include FAR keywords in the routine declarations,
  177106. * this file won't actually work in 80x86 small/medium model; at least,
  177107. * you probably won't be able to process useful-size images in only 64KB.
  177108. */
  177109. GLOBAL(void FAR *)
  177110. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177111. {
  177112. return (void FAR *) malloc(sizeofobject);
  177113. }
  177114. GLOBAL(void)
  177115. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177116. {
  177117. free(object);
  177118. }
  177119. /*
  177120. * This routine computes the total memory space available for allocation.
  177121. * Here we always say, "we got all you want bud!"
  177122. */
  177123. GLOBAL(long)
  177124. jpeg_mem_available (j_common_ptr, long,
  177125. long max_bytes_needed, long)
  177126. {
  177127. return max_bytes_needed;
  177128. }
  177129. /*
  177130. * Backing store (temporary file) management.
  177131. * Since jpeg_mem_available always promised the moon,
  177132. * this should never be called and we can just error out.
  177133. */
  177134. GLOBAL(void)
  177135. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177136. long )
  177137. {
  177138. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177139. }
  177140. /*
  177141. * These routines take care of any system-dependent initialization and
  177142. * cleanup required. Here, there isn't any.
  177143. */
  177144. GLOBAL(long)
  177145. jpeg_mem_init (j_common_ptr)
  177146. {
  177147. return 0; /* just set max_memory_to_use to 0 */
  177148. }
  177149. GLOBAL(void)
  177150. jpeg_mem_term (j_common_ptr)
  177151. {
  177152. /* no work */
  177153. }
  177154. /*** End of inlined file: jmemnobs.c ***/
  177155. /*** Start of inlined file: jquant1.c ***/
  177156. #define JPEG_INTERNALS
  177157. #ifdef QUANT_1PASS_SUPPORTED
  177158. /*
  177159. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177160. * high quality, colormapped output capability. A 2-pass quantizer usually
  177161. * gives better visual quality; however, for quantized grayscale output this
  177162. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177163. * quantizer, though you can turn it off if you really want to.
  177164. *
  177165. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177166. * image. We use a map consisting of all combinations of Ncolors[i] color
  177167. * values for the i'th component. The Ncolors[] values are chosen so that
  177168. * their product, the total number of colors, is no more than that requested.
  177169. * (In most cases, the product will be somewhat less.)
  177170. *
  177171. * Since the colormap is orthogonal, the representative value for each color
  177172. * component can be determined without considering the other components;
  177173. * then these indexes can be combined into a colormap index by a standard
  177174. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177175. * can be precalculated and stored in the lookup table colorindex[].
  177176. * colorindex[i][j] maps pixel value j in component i to the nearest
  177177. * representative value (grid plane) for that component; this index is
  177178. * multiplied by the array stride for component i, so that the
  177179. * index of the colormap entry closest to a given pixel value is just
  177180. * sum( colorindex[component-number][pixel-component-value] )
  177181. * Aside from being fast, this scheme allows for variable spacing between
  177182. * representative values with no additional lookup cost.
  177183. *
  177184. * If gamma correction has been applied in color conversion, it might be wise
  177185. * to adjust the color grid spacing so that the representative colors are
  177186. * equidistant in linear space. At this writing, gamma correction is not
  177187. * implemented by jdcolor, so nothing is done here.
  177188. */
  177189. /* Declarations for ordered dithering.
  177190. *
  177191. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177192. * dithering is described in many references, for instance Dale Schumacher's
  177193. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177194. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177195. * "dither" value to the input pixel and then round the result to the nearest
  177196. * output value. The dither value is equivalent to (0.5 - threshold) times
  177197. * the distance between output values. For ordered dithering, we assume that
  177198. * the output colors are equally spaced; if not, results will probably be
  177199. * worse, since the dither may be too much or too little at a given point.
  177200. *
  177201. * The normal calculation would be to form pixel value + dither, range-limit
  177202. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177203. * We can skip the separate range-limiting step by extending the colorindex
  177204. * table in both directions.
  177205. */
  177206. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177207. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177208. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177209. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177210. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177211. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177212. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177213. /* Bayer's order-4 dither array. Generated by the code given in
  177214. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177215. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177216. */
  177217. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177218. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177219. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177220. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177221. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177222. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177223. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177224. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177225. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177226. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177227. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177228. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177229. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177230. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177231. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177232. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177233. };
  177234. /* Declarations for Floyd-Steinberg dithering.
  177235. *
  177236. * Errors are accumulated into the array fserrors[], at a resolution of
  177237. * 1/16th of a pixel count. The error at a given pixel is propagated
  177238. * to its not-yet-processed neighbors using the standard F-S fractions,
  177239. * ... (here) 7/16
  177240. * 3/16 5/16 1/16
  177241. * We work left-to-right on even rows, right-to-left on odd rows.
  177242. *
  177243. * We can get away with a single array (holding one row's worth of errors)
  177244. * by using it to store the current row's errors at pixel columns not yet
  177245. * processed, but the next row's errors at columns already processed. We
  177246. * need only a few extra variables to hold the errors immediately around the
  177247. * current column. (If we are lucky, those variables are in registers, but
  177248. * even if not, they're probably cheaper to access than array elements are.)
  177249. *
  177250. * The fserrors[] array is indexed [component#][position].
  177251. * We provide (#columns + 2) entries per component; the extra entry at each
  177252. * end saves us from special-casing the first and last pixels.
  177253. *
  177254. * Note: on a wide image, we might not have enough room in a PC's near data
  177255. * segment to hold the error array; so it is allocated with alloc_large.
  177256. */
  177257. #if BITS_IN_JSAMPLE == 8
  177258. typedef INT16 FSERROR; /* 16 bits should be enough */
  177259. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177260. #else
  177261. typedef INT32 FSERROR; /* may need more than 16 bits */
  177262. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177263. #endif
  177264. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177265. /* Private subobject */
  177266. #define MAX_Q_COMPS 4 /* max components I can handle */
  177267. typedef struct {
  177268. struct jpeg_color_quantizer pub; /* public fields */
  177269. /* Initially allocated colormap is saved here */
  177270. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177271. int sv_actual; /* number of entries in use */
  177272. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177273. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177274. * premultiplied as described above. Since colormap indexes must fit into
  177275. * JSAMPLEs, the entries of this array will too.
  177276. */
  177277. boolean is_padded; /* is the colorindex padded for odither? */
  177278. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177279. /* Variables for ordered dithering */
  177280. int row_index; /* cur row's vertical index in dither matrix */
  177281. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177282. /* Variables for Floyd-Steinberg dithering */
  177283. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177284. boolean on_odd_row; /* flag to remember which row we are on */
  177285. } my_cquantizer;
  177286. typedef my_cquantizer * my_cquantize_ptr;
  177287. /*
  177288. * Policy-making subroutines for create_colormap and create_colorindex.
  177289. * These routines determine the colormap to be used. The rest of the module
  177290. * only assumes that the colormap is orthogonal.
  177291. *
  177292. * * select_ncolors decides how to divvy up the available colors
  177293. * among the components.
  177294. * * output_value defines the set of representative values for a component.
  177295. * * largest_input_value defines the mapping from input values to
  177296. * representative values for a component.
  177297. * Note that the latter two routines may impose different policies for
  177298. * different components, though this is not currently done.
  177299. */
  177300. LOCAL(int)
  177301. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177302. /* Determine allocation of desired colors to components, */
  177303. /* and fill in Ncolors[] array to indicate choice. */
  177304. /* Return value is total number of colors (product of Ncolors[] values). */
  177305. {
  177306. int nc = cinfo->out_color_components; /* number of color components */
  177307. int max_colors = cinfo->desired_number_of_colors;
  177308. int total_colors, iroot, i, j;
  177309. boolean changed;
  177310. long temp;
  177311. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177312. /* We can allocate at least the nc'th root of max_colors per component. */
  177313. /* Compute floor(nc'th root of max_colors). */
  177314. iroot = 1;
  177315. do {
  177316. iroot++;
  177317. temp = iroot; /* set temp = iroot ** nc */
  177318. for (i = 1; i < nc; i++)
  177319. temp *= iroot;
  177320. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177321. iroot--; /* now iroot = floor(root) */
  177322. /* Must have at least 2 color values per component */
  177323. if (iroot < 2)
  177324. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177325. /* Initialize to iroot color values for each component */
  177326. total_colors = 1;
  177327. for (i = 0; i < nc; i++) {
  177328. Ncolors[i] = iroot;
  177329. total_colors *= iroot;
  177330. }
  177331. /* We may be able to increment the count for one or more components without
  177332. * exceeding max_colors, though we know not all can be incremented.
  177333. * Sometimes, the first component can be incremented more than once!
  177334. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177335. * In RGB colorspace, try to increment G first, then R, then B.
  177336. */
  177337. do {
  177338. changed = FALSE;
  177339. for (i = 0; i < nc; i++) {
  177340. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177341. /* calculate new total_colors if Ncolors[j] is incremented */
  177342. temp = total_colors / Ncolors[j];
  177343. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177344. if (temp > (long) max_colors)
  177345. break; /* won't fit, done with this pass */
  177346. Ncolors[j]++; /* OK, apply the increment */
  177347. total_colors = (int) temp;
  177348. changed = TRUE;
  177349. }
  177350. } while (changed);
  177351. return total_colors;
  177352. }
  177353. LOCAL(int)
  177354. output_value (j_decompress_ptr, int, int j, int maxj)
  177355. /* Return j'th output value, where j will range from 0 to maxj */
  177356. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177357. {
  177358. /* We always provide values 0 and MAXJSAMPLE for each component;
  177359. * any additional values are equally spaced between these limits.
  177360. * (Forcing the upper and lower values to the limits ensures that
  177361. * dithering can't produce a color outside the selected gamut.)
  177362. */
  177363. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177364. }
  177365. LOCAL(int)
  177366. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177367. /* Return largest input value that should map to j'th output value */
  177368. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177369. {
  177370. /* Breakpoints are halfway between values returned by output_value */
  177371. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177372. }
  177373. /*
  177374. * Create the colormap.
  177375. */
  177376. LOCAL(void)
  177377. create_colormap (j_decompress_ptr cinfo)
  177378. {
  177379. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177380. JSAMPARRAY colormap; /* Created colormap */
  177381. int total_colors; /* Number of distinct output colors */
  177382. int i,j,k, nci, blksize, blkdist, ptr, val;
  177383. /* Select number of colors for each component */
  177384. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177385. /* Report selected color counts */
  177386. if (cinfo->out_color_components == 3)
  177387. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177388. total_colors, cquantize->Ncolors[0],
  177389. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177390. else
  177391. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177392. /* Allocate and fill in the colormap. */
  177393. /* The colors are ordered in the map in standard row-major order, */
  177394. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177395. colormap = (*cinfo->mem->alloc_sarray)
  177396. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177397. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177398. /* blksize is number of adjacent repeated entries for a component */
  177399. /* blkdist is distance between groups of identical entries for a component */
  177400. blkdist = total_colors;
  177401. for (i = 0; i < cinfo->out_color_components; i++) {
  177402. /* fill in colormap entries for i'th color component */
  177403. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177404. blksize = blkdist / nci;
  177405. for (j = 0; j < nci; j++) {
  177406. /* Compute j'th output value (out of nci) for component */
  177407. val = output_value(cinfo, i, j, nci-1);
  177408. /* Fill in all colormap entries that have this value of this component */
  177409. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177410. /* fill in blksize entries beginning at ptr */
  177411. for (k = 0; k < blksize; k++)
  177412. colormap[i][ptr+k] = (JSAMPLE) val;
  177413. }
  177414. }
  177415. blkdist = blksize; /* blksize of this color is blkdist of next */
  177416. }
  177417. /* Save the colormap in private storage,
  177418. * where it will survive color quantization mode changes.
  177419. */
  177420. cquantize->sv_colormap = colormap;
  177421. cquantize->sv_actual = total_colors;
  177422. }
  177423. /*
  177424. * Create the color index table.
  177425. */
  177426. LOCAL(void)
  177427. create_colorindex (j_decompress_ptr cinfo)
  177428. {
  177429. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177430. JSAMPROW indexptr;
  177431. int i,j,k, nci, blksize, val, pad;
  177432. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177433. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177434. * This is not necessary in the other dithering modes. However, we
  177435. * flag whether it was done in case user changes dithering mode.
  177436. */
  177437. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177438. pad = MAXJSAMPLE*2;
  177439. cquantize->is_padded = TRUE;
  177440. } else {
  177441. pad = 0;
  177442. cquantize->is_padded = FALSE;
  177443. }
  177444. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177445. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177446. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177447. (JDIMENSION) cinfo->out_color_components);
  177448. /* blksize is number of adjacent repeated entries for a component */
  177449. blksize = cquantize->sv_actual;
  177450. for (i = 0; i < cinfo->out_color_components; i++) {
  177451. /* fill in colorindex entries for i'th color component */
  177452. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177453. blksize = blksize / nci;
  177454. /* adjust colorindex pointers to provide padding at negative indexes. */
  177455. if (pad)
  177456. cquantize->colorindex[i] += MAXJSAMPLE;
  177457. /* in loop, val = index of current output value, */
  177458. /* and k = largest j that maps to current val */
  177459. indexptr = cquantize->colorindex[i];
  177460. val = 0;
  177461. k = largest_input_value(cinfo, i, 0, nci-1);
  177462. for (j = 0; j <= MAXJSAMPLE; j++) {
  177463. while (j > k) /* advance val if past boundary */
  177464. k = largest_input_value(cinfo, i, ++val, nci-1);
  177465. /* premultiply so that no multiplication needed in main processing */
  177466. indexptr[j] = (JSAMPLE) (val * blksize);
  177467. }
  177468. /* Pad at both ends if necessary */
  177469. if (pad)
  177470. for (j = 1; j <= MAXJSAMPLE; j++) {
  177471. indexptr[-j] = indexptr[0];
  177472. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177473. }
  177474. }
  177475. }
  177476. /*
  177477. * Create an ordered-dither array for a component having ncolors
  177478. * distinct output values.
  177479. */
  177480. LOCAL(ODITHER_MATRIX_PTR)
  177481. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177482. {
  177483. ODITHER_MATRIX_PTR odither;
  177484. int j,k;
  177485. INT32 num,den;
  177486. odither = (ODITHER_MATRIX_PTR)
  177487. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177488. SIZEOF(ODITHER_MATRIX));
  177489. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177490. * Hence the dither value for the matrix cell with fill order f
  177491. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177492. * On 16-bit-int machine, be careful to avoid overflow.
  177493. */
  177494. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177495. for (j = 0; j < ODITHER_SIZE; j++) {
  177496. for (k = 0; k < ODITHER_SIZE; k++) {
  177497. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177498. * MAXJSAMPLE;
  177499. /* Ensure round towards zero despite C's lack of consistency
  177500. * about rounding negative values in integer division...
  177501. */
  177502. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177503. }
  177504. }
  177505. return odither;
  177506. }
  177507. /*
  177508. * Create the ordered-dither tables.
  177509. * Components having the same number of representative colors may
  177510. * share a dither table.
  177511. */
  177512. LOCAL(void)
  177513. create_odither_tables (j_decompress_ptr cinfo)
  177514. {
  177515. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177516. ODITHER_MATRIX_PTR odither;
  177517. int i, j, nci;
  177518. for (i = 0; i < cinfo->out_color_components; i++) {
  177519. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177520. odither = NULL; /* search for matching prior component */
  177521. for (j = 0; j < i; j++) {
  177522. if (nci == cquantize->Ncolors[j]) {
  177523. odither = cquantize->odither[j];
  177524. break;
  177525. }
  177526. }
  177527. if (odither == NULL) /* need a new table? */
  177528. odither = make_odither_array(cinfo, nci);
  177529. cquantize->odither[i] = odither;
  177530. }
  177531. }
  177532. /*
  177533. * Map some rows of pixels to the output colormapped representation.
  177534. */
  177535. METHODDEF(void)
  177536. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177537. JSAMPARRAY output_buf, int num_rows)
  177538. /* General case, no dithering */
  177539. {
  177540. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177541. JSAMPARRAY colorindex = cquantize->colorindex;
  177542. register int pixcode, ci;
  177543. register JSAMPROW ptrin, ptrout;
  177544. int row;
  177545. JDIMENSION col;
  177546. JDIMENSION width = cinfo->output_width;
  177547. register int nc = cinfo->out_color_components;
  177548. for (row = 0; row < num_rows; row++) {
  177549. ptrin = input_buf[row];
  177550. ptrout = output_buf[row];
  177551. for (col = width; col > 0; col--) {
  177552. pixcode = 0;
  177553. for (ci = 0; ci < nc; ci++) {
  177554. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177555. }
  177556. *ptrout++ = (JSAMPLE) pixcode;
  177557. }
  177558. }
  177559. }
  177560. METHODDEF(void)
  177561. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177562. JSAMPARRAY output_buf, int num_rows)
  177563. /* Fast path for out_color_components==3, no dithering */
  177564. {
  177565. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177566. register int pixcode;
  177567. register JSAMPROW ptrin, ptrout;
  177568. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177569. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177570. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177571. int row;
  177572. JDIMENSION col;
  177573. JDIMENSION width = cinfo->output_width;
  177574. for (row = 0; row < num_rows; row++) {
  177575. ptrin = input_buf[row];
  177576. ptrout = output_buf[row];
  177577. for (col = width; col > 0; col--) {
  177578. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177579. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177580. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177581. *ptrout++ = (JSAMPLE) pixcode;
  177582. }
  177583. }
  177584. }
  177585. METHODDEF(void)
  177586. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177587. JSAMPARRAY output_buf, int num_rows)
  177588. /* General case, with ordered dithering */
  177589. {
  177590. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177591. register JSAMPROW input_ptr;
  177592. register JSAMPROW output_ptr;
  177593. JSAMPROW colorindex_ci;
  177594. int * dither; /* points to active row of dither matrix */
  177595. int row_index, col_index; /* current indexes into dither matrix */
  177596. int nc = cinfo->out_color_components;
  177597. int ci;
  177598. int row;
  177599. JDIMENSION col;
  177600. JDIMENSION width = cinfo->output_width;
  177601. for (row = 0; row < num_rows; row++) {
  177602. /* Initialize output values to 0 so can process components separately */
  177603. jzero_far((void FAR *) output_buf[row],
  177604. (size_t) (width * SIZEOF(JSAMPLE)));
  177605. row_index = cquantize->row_index;
  177606. for (ci = 0; ci < nc; ci++) {
  177607. input_ptr = input_buf[row] + ci;
  177608. output_ptr = output_buf[row];
  177609. colorindex_ci = cquantize->colorindex[ci];
  177610. dither = cquantize->odither[ci][row_index];
  177611. col_index = 0;
  177612. for (col = width; col > 0; col--) {
  177613. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177614. * select output value, accumulate into output code for this pixel.
  177615. * Range-limiting need not be done explicitly, as we have extended
  177616. * the colorindex table to produce the right answers for out-of-range
  177617. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177618. * required amount of padding.
  177619. */
  177620. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177621. input_ptr += nc;
  177622. output_ptr++;
  177623. col_index = (col_index + 1) & ODITHER_MASK;
  177624. }
  177625. }
  177626. /* Advance row index for next row */
  177627. row_index = (row_index + 1) & ODITHER_MASK;
  177628. cquantize->row_index = row_index;
  177629. }
  177630. }
  177631. METHODDEF(void)
  177632. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177633. JSAMPARRAY output_buf, int num_rows)
  177634. /* Fast path for out_color_components==3, with ordered dithering */
  177635. {
  177636. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177637. register int pixcode;
  177638. register JSAMPROW input_ptr;
  177639. register JSAMPROW output_ptr;
  177640. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177641. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177642. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177643. int * dither0; /* points to active row of dither matrix */
  177644. int * dither1;
  177645. int * dither2;
  177646. int row_index, col_index; /* current indexes into dither matrix */
  177647. int row;
  177648. JDIMENSION col;
  177649. JDIMENSION width = cinfo->output_width;
  177650. for (row = 0; row < num_rows; row++) {
  177651. row_index = cquantize->row_index;
  177652. input_ptr = input_buf[row];
  177653. output_ptr = output_buf[row];
  177654. dither0 = cquantize->odither[0][row_index];
  177655. dither1 = cquantize->odither[1][row_index];
  177656. dither2 = cquantize->odither[2][row_index];
  177657. col_index = 0;
  177658. for (col = width; col > 0; col--) {
  177659. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177660. dither0[col_index]]);
  177661. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177662. dither1[col_index]]);
  177663. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177664. dither2[col_index]]);
  177665. *output_ptr++ = (JSAMPLE) pixcode;
  177666. col_index = (col_index + 1) & ODITHER_MASK;
  177667. }
  177668. row_index = (row_index + 1) & ODITHER_MASK;
  177669. cquantize->row_index = row_index;
  177670. }
  177671. }
  177672. METHODDEF(void)
  177673. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177674. JSAMPARRAY output_buf, int num_rows)
  177675. /* General case, with Floyd-Steinberg dithering */
  177676. {
  177677. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177678. register LOCFSERROR cur; /* current error or pixel value */
  177679. LOCFSERROR belowerr; /* error for pixel below cur */
  177680. LOCFSERROR bpreverr; /* error for below/prev col */
  177681. LOCFSERROR bnexterr; /* error for below/next col */
  177682. LOCFSERROR delta;
  177683. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177684. register JSAMPROW input_ptr;
  177685. register JSAMPROW output_ptr;
  177686. JSAMPROW colorindex_ci;
  177687. JSAMPROW colormap_ci;
  177688. int pixcode;
  177689. int nc = cinfo->out_color_components;
  177690. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177691. int dirnc; /* dir * nc */
  177692. int ci;
  177693. int row;
  177694. JDIMENSION col;
  177695. JDIMENSION width = cinfo->output_width;
  177696. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177697. SHIFT_TEMPS
  177698. for (row = 0; row < num_rows; row++) {
  177699. /* Initialize output values to 0 so can process components separately */
  177700. jzero_far((void FAR *) output_buf[row],
  177701. (size_t) (width * SIZEOF(JSAMPLE)));
  177702. for (ci = 0; ci < nc; ci++) {
  177703. input_ptr = input_buf[row] + ci;
  177704. output_ptr = output_buf[row];
  177705. if (cquantize->on_odd_row) {
  177706. /* work right to left in this row */
  177707. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177708. output_ptr += width-1;
  177709. dir = -1;
  177710. dirnc = -nc;
  177711. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177712. } else {
  177713. /* work left to right in this row */
  177714. dir = 1;
  177715. dirnc = nc;
  177716. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177717. }
  177718. colorindex_ci = cquantize->colorindex[ci];
  177719. colormap_ci = cquantize->sv_colormap[ci];
  177720. /* Preset error values: no error propagated to first pixel from left */
  177721. cur = 0;
  177722. /* and no error propagated to row below yet */
  177723. belowerr = bpreverr = 0;
  177724. for (col = width; col > 0; col--) {
  177725. /* cur holds the error propagated from the previous pixel on the
  177726. * current line. Add the error propagated from the previous line
  177727. * to form the complete error correction term for this pixel, and
  177728. * round the error term (which is expressed * 16) to an integer.
  177729. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177730. * for either sign of the error value.
  177731. * Note: errorptr points to *previous* column's array entry.
  177732. */
  177733. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177734. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177735. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177736. * of the range_limit array.
  177737. */
  177738. cur += GETJSAMPLE(*input_ptr);
  177739. cur = GETJSAMPLE(range_limit[cur]);
  177740. /* Select output value, accumulate into output code for this pixel */
  177741. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177742. *output_ptr += (JSAMPLE) pixcode;
  177743. /* Compute actual representation error at this pixel */
  177744. /* Note: we can do this even though we don't have the final */
  177745. /* pixel code, because the colormap is orthogonal. */
  177746. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177747. /* Compute error fractions to be propagated to adjacent pixels.
  177748. * Add these into the running sums, and simultaneously shift the
  177749. * next-line error sums left by 1 column.
  177750. */
  177751. bnexterr = cur;
  177752. delta = cur * 2;
  177753. cur += delta; /* form error * 3 */
  177754. errorptr[0] = (FSERROR) (bpreverr + cur);
  177755. cur += delta; /* form error * 5 */
  177756. bpreverr = belowerr + cur;
  177757. belowerr = bnexterr;
  177758. cur += delta; /* form error * 7 */
  177759. /* At this point cur contains the 7/16 error value to be propagated
  177760. * to the next pixel on the current line, and all the errors for the
  177761. * next line have been shifted over. We are therefore ready to move on.
  177762. */
  177763. input_ptr += dirnc; /* advance input ptr to next column */
  177764. output_ptr += dir; /* advance output ptr to next column */
  177765. errorptr += dir; /* advance errorptr to current column */
  177766. }
  177767. /* Post-loop cleanup: we must unload the final error value into the
  177768. * final fserrors[] entry. Note we need not unload belowerr because
  177769. * it is for the dummy column before or after the actual array.
  177770. */
  177771. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177772. }
  177773. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177774. }
  177775. }
  177776. /*
  177777. * Allocate workspace for Floyd-Steinberg errors.
  177778. */
  177779. LOCAL(void)
  177780. alloc_fs_workspace (j_decompress_ptr cinfo)
  177781. {
  177782. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177783. size_t arraysize;
  177784. int i;
  177785. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177786. for (i = 0; i < cinfo->out_color_components; i++) {
  177787. cquantize->fserrors[i] = (FSERRPTR)
  177788. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177789. }
  177790. }
  177791. /*
  177792. * Initialize for one-pass color quantization.
  177793. */
  177794. METHODDEF(void)
  177795. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177796. {
  177797. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177798. size_t arraysize;
  177799. int i;
  177800. /* Install my colormap. */
  177801. cinfo->colormap = cquantize->sv_colormap;
  177802. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177803. /* Initialize for desired dithering mode. */
  177804. switch (cinfo->dither_mode) {
  177805. case JDITHER_NONE:
  177806. if (cinfo->out_color_components == 3)
  177807. cquantize->pub.color_quantize = color_quantize3;
  177808. else
  177809. cquantize->pub.color_quantize = color_quantize;
  177810. break;
  177811. case JDITHER_ORDERED:
  177812. if (cinfo->out_color_components == 3)
  177813. cquantize->pub.color_quantize = quantize3_ord_dither;
  177814. else
  177815. cquantize->pub.color_quantize = quantize_ord_dither;
  177816. cquantize->row_index = 0; /* initialize state for ordered dither */
  177817. /* If user changed to ordered dither from another mode,
  177818. * we must recreate the color index table with padding.
  177819. * This will cost extra space, but probably isn't very likely.
  177820. */
  177821. if (! cquantize->is_padded)
  177822. create_colorindex(cinfo);
  177823. /* Create ordered-dither tables if we didn't already. */
  177824. if (cquantize->odither[0] == NULL)
  177825. create_odither_tables(cinfo);
  177826. break;
  177827. case JDITHER_FS:
  177828. cquantize->pub.color_quantize = quantize_fs_dither;
  177829. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177830. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177831. if (cquantize->fserrors[0] == NULL)
  177832. alloc_fs_workspace(cinfo);
  177833. /* Initialize the propagated errors to zero. */
  177834. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177835. for (i = 0; i < cinfo->out_color_components; i++)
  177836. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177837. break;
  177838. default:
  177839. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177840. break;
  177841. }
  177842. }
  177843. /*
  177844. * Finish up at the end of the pass.
  177845. */
  177846. METHODDEF(void)
  177847. finish_pass_1_quant (j_decompress_ptr)
  177848. {
  177849. /* no work in 1-pass case */
  177850. }
  177851. /*
  177852. * Switch to a new external colormap between output passes.
  177853. * Shouldn't get to this module!
  177854. */
  177855. METHODDEF(void)
  177856. new_color_map_1_quant (j_decompress_ptr cinfo)
  177857. {
  177858. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177859. }
  177860. /*
  177861. * Module initialization routine for 1-pass color quantization.
  177862. */
  177863. GLOBAL(void)
  177864. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177865. {
  177866. my_cquantize_ptr cquantize;
  177867. cquantize = (my_cquantize_ptr)
  177868. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177869. SIZEOF(my_cquantizer));
  177870. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177871. cquantize->pub.start_pass = start_pass_1_quant;
  177872. cquantize->pub.finish_pass = finish_pass_1_quant;
  177873. cquantize->pub.new_color_map = new_color_map_1_quant;
  177874. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177875. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177876. /* Make sure my internal arrays won't overflow */
  177877. if (cinfo->out_color_components > MAX_Q_COMPS)
  177878. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177879. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177880. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177881. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177882. /* Create the colormap and color index table. */
  177883. create_colormap(cinfo);
  177884. create_colorindex(cinfo);
  177885. /* Allocate Floyd-Steinberg workspace now if requested.
  177886. * We do this now since it is FAR storage and may affect the memory
  177887. * manager's space calculations. If the user changes to FS dither
  177888. * mode in a later pass, we will allocate the space then, and will
  177889. * possibly overrun the max_memory_to_use setting.
  177890. */
  177891. if (cinfo->dither_mode == JDITHER_FS)
  177892. alloc_fs_workspace(cinfo);
  177893. }
  177894. #endif /* QUANT_1PASS_SUPPORTED */
  177895. /*** End of inlined file: jquant1.c ***/
  177896. /*** Start of inlined file: jquant2.c ***/
  177897. #define JPEG_INTERNALS
  177898. #ifdef QUANT_2PASS_SUPPORTED
  177899. /*
  177900. * This module implements the well-known Heckbert paradigm for color
  177901. * quantization. Most of the ideas used here can be traced back to
  177902. * Heckbert's seminal paper
  177903. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177904. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177905. *
  177906. * In the first pass over the image, we accumulate a histogram showing the
  177907. * usage count of each possible color. To keep the histogram to a reasonable
  177908. * size, we reduce the precision of the input; typical practice is to retain
  177909. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177910. * in the same histogram cell.
  177911. *
  177912. * Next, the color-selection step begins with a box representing the whole
  177913. * color space, and repeatedly splits the "largest" remaining box until we
  177914. * have as many boxes as desired colors. Then the mean color in each
  177915. * remaining box becomes one of the possible output colors.
  177916. *
  177917. * The second pass over the image maps each input pixel to the closest output
  177918. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177919. * This mapping is logically trivial, but making it go fast enough requires
  177920. * considerable care.
  177921. *
  177922. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177923. * the "largest" box and deciding where to cut it. The particular policies
  177924. * used here have proved out well in experimental comparisons, but better ones
  177925. * may yet be found.
  177926. *
  177927. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177928. * space, processing the raw upsampled data without a color conversion step.
  177929. * This allowed the color conversion math to be done only once per colormap
  177930. * entry, not once per pixel. However, that optimization precluded other
  177931. * useful optimizations (such as merging color conversion with upsampling)
  177932. * and it also interfered with desired capabilities such as quantizing to an
  177933. * externally-supplied colormap. We have therefore abandoned that approach.
  177934. * The present code works in the post-conversion color space, typically RGB.
  177935. *
  177936. * To improve the visual quality of the results, we actually work in scaled
  177937. * RGB space, giving G distances more weight than R, and R in turn more than
  177938. * B. To do everything in integer math, we must use integer scale factors.
  177939. * The 2/3/1 scale factors used here correspond loosely to the relative
  177940. * weights of the colors in the NTSC grayscale equation.
  177941. * If you want to use this code to quantize a non-RGB color space, you'll
  177942. * probably need to change these scale factors.
  177943. */
  177944. #define R_SCALE 2 /* scale R distances by this much */
  177945. #define G_SCALE 3 /* scale G distances by this much */
  177946. #define B_SCALE 1 /* and B by this much */
  177947. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177948. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177949. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177950. * you'll get compile errors until you extend this logic. In that case
  177951. * you'll probably want to tweak the histogram sizes too.
  177952. */
  177953. #if RGB_RED == 0
  177954. #define C0_SCALE R_SCALE
  177955. #endif
  177956. #if RGB_BLUE == 0
  177957. #define C0_SCALE B_SCALE
  177958. #endif
  177959. #if RGB_GREEN == 1
  177960. #define C1_SCALE G_SCALE
  177961. #endif
  177962. #if RGB_RED == 2
  177963. #define C2_SCALE R_SCALE
  177964. #endif
  177965. #if RGB_BLUE == 2
  177966. #define C2_SCALE B_SCALE
  177967. #endif
  177968. /*
  177969. * First we have the histogram data structure and routines for creating it.
  177970. *
  177971. * The number of bits of precision can be adjusted by changing these symbols.
  177972. * We recommend keeping 6 bits for G and 5 each for R and B.
  177973. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177974. * better results; if you are short of memory, 5 bits all around will save
  177975. * some space but degrade the results.
  177976. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177977. * (preferably unsigned long) for each cell. In practice this is overkill;
  177978. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177979. * and clamping those that do overflow to the maximum value will give close-
  177980. * enough results. This reduces the recommended histogram size from 256Kb
  177981. * to 128Kb, which is a useful savings on PC-class machines.
  177982. * (In the second pass the histogram space is re-used for pixel mapping data;
  177983. * in that capacity, each cell must be able to store zero to the number of
  177984. * desired colors. 16 bits/cell is plenty for that too.)
  177985. * Since the JPEG code is intended to run in small memory model on 80x86
  177986. * machines, we can't just allocate the histogram in one chunk. Instead
  177987. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177988. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177989. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177990. * on 80x86 machines, the pointer row is in near memory but the actual
  177991. * arrays are in far memory (same arrangement as we use for image arrays).
  177992. */
  177993. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177994. /* These will do the right thing for either R,G,B or B,G,R color order,
  177995. * but you may not like the results for other color orders.
  177996. */
  177997. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177998. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177999. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178000. /* Number of elements along histogram axes. */
  178001. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178002. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178003. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178004. /* These are the amounts to shift an input value to get a histogram index. */
  178005. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178006. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178007. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178008. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178009. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178010. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178011. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178012. typedef hist2d * hist3d; /* type for top-level pointer */
  178013. /* Declarations for Floyd-Steinberg dithering.
  178014. *
  178015. * Errors are accumulated into the array fserrors[], at a resolution of
  178016. * 1/16th of a pixel count. The error at a given pixel is propagated
  178017. * to its not-yet-processed neighbors using the standard F-S fractions,
  178018. * ... (here) 7/16
  178019. * 3/16 5/16 1/16
  178020. * We work left-to-right on even rows, right-to-left on odd rows.
  178021. *
  178022. * We can get away with a single array (holding one row's worth of errors)
  178023. * by using it to store the current row's errors at pixel columns not yet
  178024. * processed, but the next row's errors at columns already processed. We
  178025. * need only a few extra variables to hold the errors immediately around the
  178026. * current column. (If we are lucky, those variables are in registers, but
  178027. * even if not, they're probably cheaper to access than array elements are.)
  178028. *
  178029. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178030. * each end saves us from special-casing the first and last pixels.
  178031. * Each entry is three values long, one value for each color component.
  178032. *
  178033. * Note: on a wide image, we might not have enough room in a PC's near data
  178034. * segment to hold the error array; so it is allocated with alloc_large.
  178035. */
  178036. #if BITS_IN_JSAMPLE == 8
  178037. typedef INT16 FSERROR; /* 16 bits should be enough */
  178038. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178039. #else
  178040. typedef INT32 FSERROR; /* may need more than 16 bits */
  178041. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178042. #endif
  178043. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178044. /* Private subobject */
  178045. typedef struct {
  178046. struct jpeg_color_quantizer pub; /* public fields */
  178047. /* Space for the eventually created colormap is stashed here */
  178048. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178049. int desired; /* desired # of colors = size of colormap */
  178050. /* Variables for accumulating image statistics */
  178051. hist3d histogram; /* pointer to the histogram */
  178052. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178053. /* Variables for Floyd-Steinberg dithering */
  178054. FSERRPTR fserrors; /* accumulated errors */
  178055. boolean on_odd_row; /* flag to remember which row we are on */
  178056. int * error_limiter; /* table for clamping the applied error */
  178057. } my_cquantizer2;
  178058. typedef my_cquantizer2 * my_cquantize_ptr2;
  178059. /*
  178060. * Prescan some rows of pixels.
  178061. * In this module the prescan simply updates the histogram, which has been
  178062. * initialized to zeroes by start_pass.
  178063. * An output_buf parameter is required by the method signature, but no data
  178064. * is actually output (in fact the buffer controller is probably passing a
  178065. * NULL pointer).
  178066. */
  178067. METHODDEF(void)
  178068. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178069. JSAMPARRAY, int num_rows)
  178070. {
  178071. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178072. register JSAMPROW ptr;
  178073. register histptr histp;
  178074. register hist3d histogram = cquantize->histogram;
  178075. int row;
  178076. JDIMENSION col;
  178077. JDIMENSION width = cinfo->output_width;
  178078. for (row = 0; row < num_rows; row++) {
  178079. ptr = input_buf[row];
  178080. for (col = width; col > 0; col--) {
  178081. /* get pixel value and index into the histogram */
  178082. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178083. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178084. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178085. /* increment, check for overflow and undo increment if so. */
  178086. if (++(*histp) <= 0)
  178087. (*histp)--;
  178088. ptr += 3;
  178089. }
  178090. }
  178091. }
  178092. /*
  178093. * Next we have the really interesting routines: selection of a colormap
  178094. * given the completed histogram.
  178095. * These routines work with a list of "boxes", each representing a rectangular
  178096. * subset of the input color space (to histogram precision).
  178097. */
  178098. typedef struct {
  178099. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178100. int c0min, c0max;
  178101. int c1min, c1max;
  178102. int c2min, c2max;
  178103. /* The volume (actually 2-norm) of the box */
  178104. INT32 volume;
  178105. /* The number of nonzero histogram cells within this box */
  178106. long colorcount;
  178107. } box;
  178108. typedef box * boxptr;
  178109. LOCAL(boxptr)
  178110. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178111. /* Find the splittable box with the largest color population */
  178112. /* Returns NULL if no splittable boxes remain */
  178113. {
  178114. register boxptr boxp;
  178115. register int i;
  178116. register long maxc = 0;
  178117. boxptr which = NULL;
  178118. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178119. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178120. which = boxp;
  178121. maxc = boxp->colorcount;
  178122. }
  178123. }
  178124. return which;
  178125. }
  178126. LOCAL(boxptr)
  178127. find_biggest_volume (boxptr boxlist, int numboxes)
  178128. /* Find the splittable box with the largest (scaled) volume */
  178129. /* Returns NULL if no splittable boxes remain */
  178130. {
  178131. register boxptr boxp;
  178132. register int i;
  178133. register INT32 maxv = 0;
  178134. boxptr which = NULL;
  178135. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178136. if (boxp->volume > maxv) {
  178137. which = boxp;
  178138. maxv = boxp->volume;
  178139. }
  178140. }
  178141. return which;
  178142. }
  178143. LOCAL(void)
  178144. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178145. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178146. /* and recompute its volume and population */
  178147. {
  178148. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178149. hist3d histogram = cquantize->histogram;
  178150. histptr histp;
  178151. int c0,c1,c2;
  178152. int c0min,c0max,c1min,c1max,c2min,c2max;
  178153. INT32 dist0,dist1,dist2;
  178154. long ccount;
  178155. c0min = boxp->c0min; c0max = boxp->c0max;
  178156. c1min = boxp->c1min; c1max = boxp->c1max;
  178157. c2min = boxp->c2min; c2max = boxp->c2max;
  178158. if (c0max > c0min)
  178159. for (c0 = c0min; c0 <= c0max; c0++)
  178160. for (c1 = c1min; c1 <= c1max; c1++) {
  178161. histp = & histogram[c0][c1][c2min];
  178162. for (c2 = c2min; c2 <= c2max; c2++)
  178163. if (*histp++ != 0) {
  178164. boxp->c0min = c0min = c0;
  178165. goto have_c0min;
  178166. }
  178167. }
  178168. have_c0min:
  178169. if (c0max > c0min)
  178170. for (c0 = c0max; c0 >= c0min; c0--)
  178171. for (c1 = c1min; c1 <= c1max; c1++) {
  178172. histp = & histogram[c0][c1][c2min];
  178173. for (c2 = c2min; c2 <= c2max; c2++)
  178174. if (*histp++ != 0) {
  178175. boxp->c0max = c0max = c0;
  178176. goto have_c0max;
  178177. }
  178178. }
  178179. have_c0max:
  178180. if (c1max > c1min)
  178181. for (c1 = c1min; c1 <= c1max; c1++)
  178182. for (c0 = c0min; c0 <= c0max; c0++) {
  178183. histp = & histogram[c0][c1][c2min];
  178184. for (c2 = c2min; c2 <= c2max; c2++)
  178185. if (*histp++ != 0) {
  178186. boxp->c1min = c1min = c1;
  178187. goto have_c1min;
  178188. }
  178189. }
  178190. have_c1min:
  178191. if (c1max > c1min)
  178192. for (c1 = c1max; c1 >= c1min; c1--)
  178193. for (c0 = c0min; c0 <= c0max; c0++) {
  178194. histp = & histogram[c0][c1][c2min];
  178195. for (c2 = c2min; c2 <= c2max; c2++)
  178196. if (*histp++ != 0) {
  178197. boxp->c1max = c1max = c1;
  178198. goto have_c1max;
  178199. }
  178200. }
  178201. have_c1max:
  178202. if (c2max > c2min)
  178203. for (c2 = c2min; c2 <= c2max; c2++)
  178204. for (c0 = c0min; c0 <= c0max; c0++) {
  178205. histp = & histogram[c0][c1min][c2];
  178206. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178207. if (*histp != 0) {
  178208. boxp->c2min = c2min = c2;
  178209. goto have_c2min;
  178210. }
  178211. }
  178212. have_c2min:
  178213. if (c2max > c2min)
  178214. for (c2 = c2max; c2 >= c2min; c2--)
  178215. for (c0 = c0min; c0 <= c0max; c0++) {
  178216. histp = & histogram[c0][c1min][c2];
  178217. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178218. if (*histp != 0) {
  178219. boxp->c2max = c2max = c2;
  178220. goto have_c2max;
  178221. }
  178222. }
  178223. have_c2max:
  178224. /* Update box volume.
  178225. * We use 2-norm rather than real volume here; this biases the method
  178226. * against making long narrow boxes, and it has the side benefit that
  178227. * a box is splittable iff norm > 0.
  178228. * Since the differences are expressed in histogram-cell units,
  178229. * we have to shift back to JSAMPLE units to get consistent distances;
  178230. * after which, we scale according to the selected distance scale factors.
  178231. */
  178232. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178233. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178234. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178235. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178236. /* Now scan remaining volume of box and compute population */
  178237. ccount = 0;
  178238. for (c0 = c0min; c0 <= c0max; c0++)
  178239. for (c1 = c1min; c1 <= c1max; c1++) {
  178240. histp = & histogram[c0][c1][c2min];
  178241. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178242. if (*histp != 0) {
  178243. ccount++;
  178244. }
  178245. }
  178246. boxp->colorcount = ccount;
  178247. }
  178248. LOCAL(int)
  178249. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178250. int desired_colors)
  178251. /* Repeatedly select and split the largest box until we have enough boxes */
  178252. {
  178253. int n,lb;
  178254. int c0,c1,c2,cmax;
  178255. register boxptr b1,b2;
  178256. while (numboxes < desired_colors) {
  178257. /* Select box to split.
  178258. * Current algorithm: by population for first half, then by volume.
  178259. */
  178260. if (numboxes*2 <= desired_colors) {
  178261. b1 = find_biggest_color_pop(boxlist, numboxes);
  178262. } else {
  178263. b1 = find_biggest_volume(boxlist, numboxes);
  178264. }
  178265. if (b1 == NULL) /* no splittable boxes left! */
  178266. break;
  178267. b2 = &boxlist[numboxes]; /* where new box will go */
  178268. /* Copy the color bounds to the new box. */
  178269. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178270. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178271. /* Choose which axis to split the box on.
  178272. * Current algorithm: longest scaled axis.
  178273. * See notes in update_box about scaling distances.
  178274. */
  178275. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178276. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178277. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178278. /* We want to break any ties in favor of green, then red, blue last.
  178279. * This code does the right thing for R,G,B or B,G,R color orders only.
  178280. */
  178281. #if RGB_RED == 0
  178282. cmax = c1; n = 1;
  178283. if (c0 > cmax) { cmax = c0; n = 0; }
  178284. if (c2 > cmax) { n = 2; }
  178285. #else
  178286. cmax = c1; n = 1;
  178287. if (c2 > cmax) { cmax = c2; n = 2; }
  178288. if (c0 > cmax) { n = 0; }
  178289. #endif
  178290. /* Choose split point along selected axis, and update box bounds.
  178291. * Current algorithm: split at halfway point.
  178292. * (Since the box has been shrunk to minimum volume,
  178293. * any split will produce two nonempty subboxes.)
  178294. * Note that lb value is max for lower box, so must be < old max.
  178295. */
  178296. switch (n) {
  178297. case 0:
  178298. lb = (b1->c0max + b1->c0min) / 2;
  178299. b1->c0max = lb;
  178300. b2->c0min = lb+1;
  178301. break;
  178302. case 1:
  178303. lb = (b1->c1max + b1->c1min) / 2;
  178304. b1->c1max = lb;
  178305. b2->c1min = lb+1;
  178306. break;
  178307. case 2:
  178308. lb = (b1->c2max + b1->c2min) / 2;
  178309. b1->c2max = lb;
  178310. b2->c2min = lb+1;
  178311. break;
  178312. }
  178313. /* Update stats for boxes */
  178314. update_box(cinfo, b1);
  178315. update_box(cinfo, b2);
  178316. numboxes++;
  178317. }
  178318. return numboxes;
  178319. }
  178320. LOCAL(void)
  178321. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178322. /* Compute representative color for a box, put it in colormap[icolor] */
  178323. {
  178324. /* Current algorithm: mean weighted by pixels (not colors) */
  178325. /* Note it is important to get the rounding correct! */
  178326. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178327. hist3d histogram = cquantize->histogram;
  178328. histptr histp;
  178329. int c0,c1,c2;
  178330. int c0min,c0max,c1min,c1max,c2min,c2max;
  178331. long count;
  178332. long total = 0;
  178333. long c0total = 0;
  178334. long c1total = 0;
  178335. long c2total = 0;
  178336. c0min = boxp->c0min; c0max = boxp->c0max;
  178337. c1min = boxp->c1min; c1max = boxp->c1max;
  178338. c2min = boxp->c2min; c2max = boxp->c2max;
  178339. for (c0 = c0min; c0 <= c0max; c0++)
  178340. for (c1 = c1min; c1 <= c1max; c1++) {
  178341. histp = & histogram[c0][c1][c2min];
  178342. for (c2 = c2min; c2 <= c2max; c2++) {
  178343. if ((count = *histp++) != 0) {
  178344. total += count;
  178345. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178346. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178347. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178348. }
  178349. }
  178350. }
  178351. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178352. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178353. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178354. }
  178355. LOCAL(void)
  178356. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178357. /* Master routine for color selection */
  178358. {
  178359. boxptr boxlist;
  178360. int numboxes;
  178361. int i;
  178362. /* Allocate workspace for box list */
  178363. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178364. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178365. /* Initialize one box containing whole space */
  178366. numboxes = 1;
  178367. boxlist[0].c0min = 0;
  178368. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178369. boxlist[0].c1min = 0;
  178370. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178371. boxlist[0].c2min = 0;
  178372. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178373. /* Shrink it to actually-used volume and set its statistics */
  178374. update_box(cinfo, & boxlist[0]);
  178375. /* Perform median-cut to produce final box list */
  178376. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178377. /* Compute the representative color for each box, fill colormap */
  178378. for (i = 0; i < numboxes; i++)
  178379. compute_color(cinfo, & boxlist[i], i);
  178380. cinfo->actual_number_of_colors = numboxes;
  178381. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178382. }
  178383. /*
  178384. * These routines are concerned with the time-critical task of mapping input
  178385. * colors to the nearest color in the selected colormap.
  178386. *
  178387. * We re-use the histogram space as an "inverse color map", essentially a
  178388. * cache for the results of nearest-color searches. All colors within a
  178389. * histogram cell will be mapped to the same colormap entry, namely the one
  178390. * closest to the cell's center. This may not be quite the closest entry to
  178391. * the actual input color, but it's almost as good. A zero in the cache
  178392. * indicates we haven't found the nearest color for that cell yet; the array
  178393. * is cleared to zeroes before starting the mapping pass. When we find the
  178394. * nearest color for a cell, its colormap index plus one is recorded in the
  178395. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178396. * when they need to use an unfilled entry in the cache.
  178397. *
  178398. * Our method of efficiently finding nearest colors is based on the "locally
  178399. * sorted search" idea described by Heckbert and on the incremental distance
  178400. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178401. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178402. * the distances from a given colormap entry to each cell of the histogram can
  178403. * be computed quickly using an incremental method: the differences between
  178404. * distances to adjacent cells themselves differ by a constant. This allows a
  178405. * fairly fast implementation of the "brute force" approach of computing the
  178406. * distance from every colormap entry to every histogram cell. Unfortunately,
  178407. * it needs a work array to hold the best-distance-so-far for each histogram
  178408. * cell (because the inner loop has to be over cells, not colormap entries).
  178409. * The work array elements have to be INT32s, so the work array would need
  178410. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178411. *
  178412. * To get around these problems, we apply Thomas' method to compute the
  178413. * nearest colors for only the cells within a small subbox of the histogram.
  178414. * The work array need be only as big as the subbox, so the memory usage
  178415. * problem is solved. Furthermore, we need not fill subboxes that are never
  178416. * referenced in pass2; many images use only part of the color gamut, so a
  178417. * fair amount of work is saved. An additional advantage of this
  178418. * approach is that we can apply Heckbert's locality criterion to quickly
  178419. * eliminate colormap entries that are far away from the subbox; typically
  178420. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178421. * and we need not compute their distances to individual cells in the subbox.
  178422. * The speed of this approach is heavily influenced by the subbox size: too
  178423. * small means too much overhead, too big loses because Heckbert's criterion
  178424. * can't eliminate as many colormap entries. Empirically the best subbox
  178425. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178426. *
  178427. * Thomas' article also describes a refined method which is asymptotically
  178428. * faster than the brute-force method, but it is also far more complex and
  178429. * cannot efficiently be applied to small subboxes. It is therefore not
  178430. * useful for programs intended to be portable to DOS machines. On machines
  178431. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178432. * refined method might be faster than the present code --- but then again,
  178433. * it might not be any faster, and it's certainly more complicated.
  178434. */
  178435. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178436. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178437. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178438. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178439. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178440. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178441. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178442. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178443. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178444. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178445. /*
  178446. * The next three routines implement inverse colormap filling. They could
  178447. * all be folded into one big routine, but splitting them up this way saves
  178448. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178449. * and may allow some compilers to produce better code by registerizing more
  178450. * inner-loop variables.
  178451. */
  178452. LOCAL(int)
  178453. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178454. JSAMPLE colorlist[])
  178455. /* Locate the colormap entries close enough to an update box to be candidates
  178456. * for the nearest entry to some cell(s) in the update box. The update box
  178457. * is specified by the center coordinates of its first cell. The number of
  178458. * candidate colormap entries is returned, and their colormap indexes are
  178459. * placed in colorlist[].
  178460. * This routine uses Heckbert's "locally sorted search" criterion to select
  178461. * the colors that need further consideration.
  178462. */
  178463. {
  178464. int numcolors = cinfo->actual_number_of_colors;
  178465. int maxc0, maxc1, maxc2;
  178466. int centerc0, centerc1, centerc2;
  178467. int i, x, ncolors;
  178468. INT32 minmaxdist, min_dist, max_dist, tdist;
  178469. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178470. /* Compute true coordinates of update box's upper corner and center.
  178471. * Actually we compute the coordinates of the center of the upper-corner
  178472. * histogram cell, which are the upper bounds of the volume we care about.
  178473. * Note that since ">>" rounds down, the "center" values may be closer to
  178474. * min than to max; hence comparisons to them must be "<=", not "<".
  178475. */
  178476. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178477. centerc0 = (minc0 + maxc0) >> 1;
  178478. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178479. centerc1 = (minc1 + maxc1) >> 1;
  178480. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178481. centerc2 = (minc2 + maxc2) >> 1;
  178482. /* For each color in colormap, find:
  178483. * 1. its minimum squared-distance to any point in the update box
  178484. * (zero if color is within update box);
  178485. * 2. its maximum squared-distance to any point in the update box.
  178486. * Both of these can be found by considering only the corners of the box.
  178487. * We save the minimum distance for each color in mindist[];
  178488. * only the smallest maximum distance is of interest.
  178489. */
  178490. minmaxdist = 0x7FFFFFFFL;
  178491. for (i = 0; i < numcolors; i++) {
  178492. /* We compute the squared-c0-distance term, then add in the other two. */
  178493. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178494. if (x < minc0) {
  178495. tdist = (x - minc0) * C0_SCALE;
  178496. min_dist = tdist*tdist;
  178497. tdist = (x - maxc0) * C0_SCALE;
  178498. max_dist = tdist*tdist;
  178499. } else if (x > maxc0) {
  178500. tdist = (x - maxc0) * C0_SCALE;
  178501. min_dist = tdist*tdist;
  178502. tdist = (x - minc0) * C0_SCALE;
  178503. max_dist = tdist*tdist;
  178504. } else {
  178505. /* within cell range so no contribution to min_dist */
  178506. min_dist = 0;
  178507. if (x <= centerc0) {
  178508. tdist = (x - maxc0) * C0_SCALE;
  178509. max_dist = tdist*tdist;
  178510. } else {
  178511. tdist = (x - minc0) * C0_SCALE;
  178512. max_dist = tdist*tdist;
  178513. }
  178514. }
  178515. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178516. if (x < minc1) {
  178517. tdist = (x - minc1) * C1_SCALE;
  178518. min_dist += tdist*tdist;
  178519. tdist = (x - maxc1) * C1_SCALE;
  178520. max_dist += tdist*tdist;
  178521. } else if (x > maxc1) {
  178522. tdist = (x - maxc1) * C1_SCALE;
  178523. min_dist += tdist*tdist;
  178524. tdist = (x - minc1) * C1_SCALE;
  178525. max_dist += tdist*tdist;
  178526. } else {
  178527. /* within cell range so no contribution to min_dist */
  178528. if (x <= centerc1) {
  178529. tdist = (x - maxc1) * C1_SCALE;
  178530. max_dist += tdist*tdist;
  178531. } else {
  178532. tdist = (x - minc1) * C1_SCALE;
  178533. max_dist += tdist*tdist;
  178534. }
  178535. }
  178536. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178537. if (x < minc2) {
  178538. tdist = (x - minc2) * C2_SCALE;
  178539. min_dist += tdist*tdist;
  178540. tdist = (x - maxc2) * C2_SCALE;
  178541. max_dist += tdist*tdist;
  178542. } else if (x > maxc2) {
  178543. tdist = (x - maxc2) * C2_SCALE;
  178544. min_dist += tdist*tdist;
  178545. tdist = (x - minc2) * C2_SCALE;
  178546. max_dist += tdist*tdist;
  178547. } else {
  178548. /* within cell range so no contribution to min_dist */
  178549. if (x <= centerc2) {
  178550. tdist = (x - maxc2) * C2_SCALE;
  178551. max_dist += tdist*tdist;
  178552. } else {
  178553. tdist = (x - minc2) * C2_SCALE;
  178554. max_dist += tdist*tdist;
  178555. }
  178556. }
  178557. mindist[i] = min_dist; /* save away the results */
  178558. if (max_dist < minmaxdist)
  178559. minmaxdist = max_dist;
  178560. }
  178561. /* Now we know that no cell in the update box is more than minmaxdist
  178562. * away from some colormap entry. Therefore, only colors that are
  178563. * within minmaxdist of some part of the box need be considered.
  178564. */
  178565. ncolors = 0;
  178566. for (i = 0; i < numcolors; i++) {
  178567. if (mindist[i] <= minmaxdist)
  178568. colorlist[ncolors++] = (JSAMPLE) i;
  178569. }
  178570. return ncolors;
  178571. }
  178572. LOCAL(void)
  178573. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178574. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178575. /* Find the closest colormap entry for each cell in the update box,
  178576. * given the list of candidate colors prepared by find_nearby_colors.
  178577. * Return the indexes of the closest entries in the bestcolor[] array.
  178578. * This routine uses Thomas' incremental distance calculation method to
  178579. * find the distance from a colormap entry to successive cells in the box.
  178580. */
  178581. {
  178582. int ic0, ic1, ic2;
  178583. int i, icolor;
  178584. register INT32 * bptr; /* pointer into bestdist[] array */
  178585. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178586. INT32 dist0, dist1; /* initial distance values */
  178587. register INT32 dist2; /* current distance in inner loop */
  178588. INT32 xx0, xx1; /* distance increments */
  178589. register INT32 xx2;
  178590. INT32 inc0, inc1, inc2; /* initial values for increments */
  178591. /* This array holds the distance to the nearest-so-far color for each cell */
  178592. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178593. /* Initialize best-distance for each cell of the update box */
  178594. bptr = bestdist;
  178595. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178596. *bptr++ = 0x7FFFFFFFL;
  178597. /* For each color selected by find_nearby_colors,
  178598. * compute its distance to the center of each cell in the box.
  178599. * If that's less than best-so-far, update best distance and color number.
  178600. */
  178601. /* Nominal steps between cell centers ("x" in Thomas article) */
  178602. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178603. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178604. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178605. for (i = 0; i < numcolors; i++) {
  178606. icolor = GETJSAMPLE(colorlist[i]);
  178607. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178608. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178609. dist0 = inc0*inc0;
  178610. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178611. dist0 += inc1*inc1;
  178612. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178613. dist0 += inc2*inc2;
  178614. /* Form the initial difference increments */
  178615. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178616. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178617. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178618. /* Now loop over all cells in box, updating distance per Thomas method */
  178619. bptr = bestdist;
  178620. cptr = bestcolor;
  178621. xx0 = inc0;
  178622. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178623. dist1 = dist0;
  178624. xx1 = inc1;
  178625. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178626. dist2 = dist1;
  178627. xx2 = inc2;
  178628. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178629. if (dist2 < *bptr) {
  178630. *bptr = dist2;
  178631. *cptr = (JSAMPLE) icolor;
  178632. }
  178633. dist2 += xx2;
  178634. xx2 += 2 * STEP_C2 * STEP_C2;
  178635. bptr++;
  178636. cptr++;
  178637. }
  178638. dist1 += xx1;
  178639. xx1 += 2 * STEP_C1 * STEP_C1;
  178640. }
  178641. dist0 += xx0;
  178642. xx0 += 2 * STEP_C0 * STEP_C0;
  178643. }
  178644. }
  178645. }
  178646. LOCAL(void)
  178647. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178648. /* Fill the inverse-colormap entries in the update box that contains */
  178649. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178650. /* we can fill as many others as we wish.) */
  178651. {
  178652. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178653. hist3d histogram = cquantize->histogram;
  178654. int minc0, minc1, minc2; /* lower left corner of update box */
  178655. int ic0, ic1, ic2;
  178656. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178657. register histptr cachep; /* pointer into main cache array */
  178658. /* This array lists the candidate colormap indexes. */
  178659. JSAMPLE colorlist[MAXNUMCOLORS];
  178660. int numcolors; /* number of candidate colors */
  178661. /* This array holds the actually closest colormap index for each cell. */
  178662. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178663. /* Convert cell coordinates to update box ID */
  178664. c0 >>= BOX_C0_LOG;
  178665. c1 >>= BOX_C1_LOG;
  178666. c2 >>= BOX_C2_LOG;
  178667. /* Compute true coordinates of update box's origin corner.
  178668. * Actually we compute the coordinates of the center of the corner
  178669. * histogram cell, which are the lower bounds of the volume we care about.
  178670. */
  178671. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178672. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178673. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178674. /* Determine which colormap entries are close enough to be candidates
  178675. * for the nearest entry to some cell in the update box.
  178676. */
  178677. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178678. /* Determine the actually nearest colors. */
  178679. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178680. bestcolor);
  178681. /* Save the best color numbers (plus 1) in the main cache array */
  178682. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178683. c1 <<= BOX_C1_LOG;
  178684. c2 <<= BOX_C2_LOG;
  178685. cptr = bestcolor;
  178686. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178687. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178688. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178689. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178690. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178691. }
  178692. }
  178693. }
  178694. }
  178695. /*
  178696. * Map some rows of pixels to the output colormapped representation.
  178697. */
  178698. METHODDEF(void)
  178699. pass2_no_dither (j_decompress_ptr cinfo,
  178700. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178701. /* This version performs no dithering */
  178702. {
  178703. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178704. hist3d histogram = cquantize->histogram;
  178705. register JSAMPROW inptr, outptr;
  178706. register histptr cachep;
  178707. register int c0, c1, c2;
  178708. int row;
  178709. JDIMENSION col;
  178710. JDIMENSION width = cinfo->output_width;
  178711. for (row = 0; row < num_rows; row++) {
  178712. inptr = input_buf[row];
  178713. outptr = output_buf[row];
  178714. for (col = width; col > 0; col--) {
  178715. /* get pixel value and index into the cache */
  178716. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178717. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178718. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178719. cachep = & histogram[c0][c1][c2];
  178720. /* If we have not seen this color before, find nearest colormap entry */
  178721. /* and update the cache */
  178722. if (*cachep == 0)
  178723. fill_inverse_cmap(cinfo, c0,c1,c2);
  178724. /* Now emit the colormap index for this cell */
  178725. *outptr++ = (JSAMPLE) (*cachep - 1);
  178726. }
  178727. }
  178728. }
  178729. METHODDEF(void)
  178730. pass2_fs_dither (j_decompress_ptr cinfo,
  178731. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178732. /* This version performs Floyd-Steinberg dithering */
  178733. {
  178734. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178735. hist3d histogram = cquantize->histogram;
  178736. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178737. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178738. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178739. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178740. JSAMPROW inptr; /* => current input pixel */
  178741. JSAMPROW outptr; /* => current output pixel */
  178742. histptr cachep;
  178743. int dir; /* +1 or -1 depending on direction */
  178744. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178745. int row;
  178746. JDIMENSION col;
  178747. JDIMENSION width = cinfo->output_width;
  178748. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178749. int *error_limit = cquantize->error_limiter;
  178750. JSAMPROW colormap0 = cinfo->colormap[0];
  178751. JSAMPROW colormap1 = cinfo->colormap[1];
  178752. JSAMPROW colormap2 = cinfo->colormap[2];
  178753. SHIFT_TEMPS
  178754. for (row = 0; row < num_rows; row++) {
  178755. inptr = input_buf[row];
  178756. outptr = output_buf[row];
  178757. if (cquantize->on_odd_row) {
  178758. /* work right to left in this row */
  178759. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178760. outptr += width-1;
  178761. dir = -1;
  178762. dir3 = -3;
  178763. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178764. cquantize->on_odd_row = FALSE; /* flip for next time */
  178765. } else {
  178766. /* work left to right in this row */
  178767. dir = 1;
  178768. dir3 = 3;
  178769. errorptr = cquantize->fserrors; /* => entry before first real column */
  178770. cquantize->on_odd_row = TRUE; /* flip for next time */
  178771. }
  178772. /* Preset error values: no error propagated to first pixel from left */
  178773. cur0 = cur1 = cur2 = 0;
  178774. /* and no error propagated to row below yet */
  178775. belowerr0 = belowerr1 = belowerr2 = 0;
  178776. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178777. for (col = width; col > 0; col--) {
  178778. /* curN holds the error propagated from the previous pixel on the
  178779. * current line. Add the error propagated from the previous line
  178780. * to form the complete error correction term for this pixel, and
  178781. * round the error term (which is expressed * 16) to an integer.
  178782. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178783. * for either sign of the error value.
  178784. * Note: errorptr points to *previous* column's array entry.
  178785. */
  178786. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178787. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178788. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178789. /* Limit the error using transfer function set by init_error_limit.
  178790. * See comments with init_error_limit for rationale.
  178791. */
  178792. cur0 = error_limit[cur0];
  178793. cur1 = error_limit[cur1];
  178794. cur2 = error_limit[cur2];
  178795. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178796. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178797. * this sets the required size of the range_limit array.
  178798. */
  178799. cur0 += GETJSAMPLE(inptr[0]);
  178800. cur1 += GETJSAMPLE(inptr[1]);
  178801. cur2 += GETJSAMPLE(inptr[2]);
  178802. cur0 = GETJSAMPLE(range_limit[cur0]);
  178803. cur1 = GETJSAMPLE(range_limit[cur1]);
  178804. cur2 = GETJSAMPLE(range_limit[cur2]);
  178805. /* Index into the cache with adjusted pixel value */
  178806. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178807. /* If we have not seen this color before, find nearest colormap */
  178808. /* entry and update the cache */
  178809. if (*cachep == 0)
  178810. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178811. /* Now emit the colormap index for this cell */
  178812. { register int pixcode = *cachep - 1;
  178813. *outptr = (JSAMPLE) pixcode;
  178814. /* Compute representation error for this pixel */
  178815. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178816. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178817. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178818. }
  178819. /* Compute error fractions to be propagated to adjacent pixels.
  178820. * Add these into the running sums, and simultaneously shift the
  178821. * next-line error sums left by 1 column.
  178822. */
  178823. { register LOCFSERROR bnexterr, delta;
  178824. bnexterr = cur0; /* Process component 0 */
  178825. delta = cur0 * 2;
  178826. cur0 += delta; /* form error * 3 */
  178827. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178828. cur0 += delta; /* form error * 5 */
  178829. bpreverr0 = belowerr0 + cur0;
  178830. belowerr0 = bnexterr;
  178831. cur0 += delta; /* form error * 7 */
  178832. bnexterr = cur1; /* Process component 1 */
  178833. delta = cur1 * 2;
  178834. cur1 += delta; /* form error * 3 */
  178835. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178836. cur1 += delta; /* form error * 5 */
  178837. bpreverr1 = belowerr1 + cur1;
  178838. belowerr1 = bnexterr;
  178839. cur1 += delta; /* form error * 7 */
  178840. bnexterr = cur2; /* Process component 2 */
  178841. delta = cur2 * 2;
  178842. cur2 += delta; /* form error * 3 */
  178843. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178844. cur2 += delta; /* form error * 5 */
  178845. bpreverr2 = belowerr2 + cur2;
  178846. belowerr2 = bnexterr;
  178847. cur2 += delta; /* form error * 7 */
  178848. }
  178849. /* At this point curN contains the 7/16 error value to be propagated
  178850. * to the next pixel on the current line, and all the errors for the
  178851. * next line have been shifted over. We are therefore ready to move on.
  178852. */
  178853. inptr += dir3; /* Advance pixel pointers to next column */
  178854. outptr += dir;
  178855. errorptr += dir3; /* advance errorptr to current column */
  178856. }
  178857. /* Post-loop cleanup: we must unload the final error values into the
  178858. * final fserrors[] entry. Note we need not unload belowerrN because
  178859. * it is for the dummy column before or after the actual array.
  178860. */
  178861. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178862. errorptr[1] = (FSERROR) bpreverr1;
  178863. errorptr[2] = (FSERROR) bpreverr2;
  178864. }
  178865. }
  178866. /*
  178867. * Initialize the error-limiting transfer function (lookup table).
  178868. * The raw F-S error computation can potentially compute error values of up to
  178869. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178870. * much less, otherwise obviously wrong pixels will be created. (Typical
  178871. * effects include weird fringes at color-area boundaries, isolated bright
  178872. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178873. * is to ensure that the "corners" of the color cube are allocated as output
  178874. * colors; then repeated errors in the same direction cannot cause cascading
  178875. * error buildup. However, that only prevents the error from getting
  178876. * completely out of hand; Aaron Giles reports that error limiting improves
  178877. * the results even with corner colors allocated.
  178878. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178879. * well, but the smoother transfer function used below is even better. Thanks
  178880. * to Aaron Giles for this idea.
  178881. */
  178882. LOCAL(void)
  178883. init_error_limit (j_decompress_ptr cinfo)
  178884. /* Allocate and fill in the error_limiter table */
  178885. {
  178886. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178887. int * table;
  178888. int in, out;
  178889. table = (int *) (*cinfo->mem->alloc_small)
  178890. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178891. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178892. cquantize->error_limiter = table;
  178893. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178894. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178895. out = 0;
  178896. for (in = 0; in < STEPSIZE; in++, out++) {
  178897. table[in] = out; table[-in] = -out;
  178898. }
  178899. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178900. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178901. table[in] = out; table[-in] = -out;
  178902. }
  178903. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178904. for (; in <= MAXJSAMPLE; in++) {
  178905. table[in] = out; table[-in] = -out;
  178906. }
  178907. #undef STEPSIZE
  178908. }
  178909. /*
  178910. * Finish up at the end of each pass.
  178911. */
  178912. METHODDEF(void)
  178913. finish_pass1 (j_decompress_ptr cinfo)
  178914. {
  178915. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178916. /* Select the representative colors and fill in cinfo->colormap */
  178917. cinfo->colormap = cquantize->sv_colormap;
  178918. select_colors(cinfo, cquantize->desired);
  178919. /* Force next pass to zero the color index table */
  178920. cquantize->needs_zeroed = TRUE;
  178921. }
  178922. METHODDEF(void)
  178923. finish_pass2 (j_decompress_ptr)
  178924. {
  178925. /* no work */
  178926. }
  178927. /*
  178928. * Initialize for each processing pass.
  178929. */
  178930. METHODDEF(void)
  178931. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178932. {
  178933. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178934. hist3d histogram = cquantize->histogram;
  178935. int i;
  178936. /* Only F-S dithering or no dithering is supported. */
  178937. /* If user asks for ordered dither, give him F-S. */
  178938. if (cinfo->dither_mode != JDITHER_NONE)
  178939. cinfo->dither_mode = JDITHER_FS;
  178940. if (is_pre_scan) {
  178941. /* Set up method pointers */
  178942. cquantize->pub.color_quantize = prescan_quantize;
  178943. cquantize->pub.finish_pass = finish_pass1;
  178944. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178945. } else {
  178946. /* Set up method pointers */
  178947. if (cinfo->dither_mode == JDITHER_FS)
  178948. cquantize->pub.color_quantize = pass2_fs_dither;
  178949. else
  178950. cquantize->pub.color_quantize = pass2_no_dither;
  178951. cquantize->pub.finish_pass = finish_pass2;
  178952. /* Make sure color count is acceptable */
  178953. i = cinfo->actual_number_of_colors;
  178954. if (i < 1)
  178955. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178956. if (i > MAXNUMCOLORS)
  178957. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178958. if (cinfo->dither_mode == JDITHER_FS) {
  178959. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178960. (3 * SIZEOF(FSERROR)));
  178961. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178962. if (cquantize->fserrors == NULL)
  178963. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178964. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178965. /* Initialize the propagated errors to zero. */
  178966. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178967. /* Make the error-limit table if we didn't already. */
  178968. if (cquantize->error_limiter == NULL)
  178969. init_error_limit(cinfo);
  178970. cquantize->on_odd_row = FALSE;
  178971. }
  178972. }
  178973. /* Zero the histogram or inverse color map, if necessary */
  178974. if (cquantize->needs_zeroed) {
  178975. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178976. jzero_far((void FAR *) histogram[i],
  178977. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178978. }
  178979. cquantize->needs_zeroed = FALSE;
  178980. }
  178981. }
  178982. /*
  178983. * Switch to a new external colormap between output passes.
  178984. */
  178985. METHODDEF(void)
  178986. new_color_map_2_quant (j_decompress_ptr cinfo)
  178987. {
  178988. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178989. /* Reset the inverse color map */
  178990. cquantize->needs_zeroed = TRUE;
  178991. }
  178992. /*
  178993. * Module initialization routine for 2-pass color quantization.
  178994. */
  178995. GLOBAL(void)
  178996. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178997. {
  178998. my_cquantize_ptr2 cquantize;
  178999. int i;
  179000. cquantize = (my_cquantize_ptr2)
  179001. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179002. SIZEOF(my_cquantizer2));
  179003. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179004. cquantize->pub.start_pass = start_pass_2_quant;
  179005. cquantize->pub.new_color_map = new_color_map_2_quant;
  179006. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179007. cquantize->error_limiter = NULL;
  179008. /* Make sure jdmaster didn't give me a case I can't handle */
  179009. if (cinfo->out_color_components != 3)
  179010. ERREXIT(cinfo, JERR_NOTIMPL);
  179011. /* Allocate the histogram/inverse colormap storage */
  179012. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179013. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179014. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179015. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179016. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179017. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179018. }
  179019. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179020. /* Allocate storage for the completed colormap, if required.
  179021. * We do this now since it is FAR storage and may affect
  179022. * the memory manager's space calculations.
  179023. */
  179024. if (cinfo->enable_2pass_quant) {
  179025. /* Make sure color count is acceptable */
  179026. int desired = cinfo->desired_number_of_colors;
  179027. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179028. if (desired < 8)
  179029. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179030. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179031. if (desired > MAXNUMCOLORS)
  179032. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179033. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179034. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179035. cquantize->desired = desired;
  179036. } else
  179037. cquantize->sv_colormap = NULL;
  179038. /* Only F-S dithering or no dithering is supported. */
  179039. /* If user asks for ordered dither, give him F-S. */
  179040. if (cinfo->dither_mode != JDITHER_NONE)
  179041. cinfo->dither_mode = JDITHER_FS;
  179042. /* Allocate Floyd-Steinberg workspace if necessary.
  179043. * This isn't really needed until pass 2, but again it is FAR storage.
  179044. * Although we will cope with a later change in dither_mode,
  179045. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179046. */
  179047. if (cinfo->dither_mode == JDITHER_FS) {
  179048. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179049. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179050. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179051. /* Might as well create the error-limiting table too. */
  179052. init_error_limit(cinfo);
  179053. }
  179054. }
  179055. #endif /* QUANT_2PASS_SUPPORTED */
  179056. /*** End of inlined file: jquant2.c ***/
  179057. /*** Start of inlined file: jutils.c ***/
  179058. #define JPEG_INTERNALS
  179059. /*
  179060. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179061. * of a DCT block read in natural order (left to right, top to bottom).
  179062. */
  179063. #if 0 /* This table is not actually needed in v6a */
  179064. const int jpeg_zigzag_order[DCTSIZE2] = {
  179065. 0, 1, 5, 6, 14, 15, 27, 28,
  179066. 2, 4, 7, 13, 16, 26, 29, 42,
  179067. 3, 8, 12, 17, 25, 30, 41, 43,
  179068. 9, 11, 18, 24, 31, 40, 44, 53,
  179069. 10, 19, 23, 32, 39, 45, 52, 54,
  179070. 20, 22, 33, 38, 46, 51, 55, 60,
  179071. 21, 34, 37, 47, 50, 56, 59, 61,
  179072. 35, 36, 48, 49, 57, 58, 62, 63
  179073. };
  179074. #endif
  179075. /*
  179076. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179077. * of zigzag order.
  179078. *
  179079. * When reading corrupted data, the Huffman decoders could attempt
  179080. * to reference an entry beyond the end of this array (if the decoded
  179081. * zero run length reaches past the end of the block). To prevent
  179082. * wild stores without adding an inner-loop test, we put some extra
  179083. * "63"s after the real entries. This will cause the extra coefficient
  179084. * to be stored in location 63 of the block, not somewhere random.
  179085. * The worst case would be a run-length of 15, which means we need 16
  179086. * fake entries.
  179087. */
  179088. const int jpeg_natural_order[DCTSIZE2+16] = {
  179089. 0, 1, 8, 16, 9, 2, 3, 10,
  179090. 17, 24, 32, 25, 18, 11, 4, 5,
  179091. 12, 19, 26, 33, 40, 48, 41, 34,
  179092. 27, 20, 13, 6, 7, 14, 21, 28,
  179093. 35, 42, 49, 56, 57, 50, 43, 36,
  179094. 29, 22, 15, 23, 30, 37, 44, 51,
  179095. 58, 59, 52, 45, 38, 31, 39, 46,
  179096. 53, 60, 61, 54, 47, 55, 62, 63,
  179097. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179098. 63, 63, 63, 63, 63, 63, 63, 63
  179099. };
  179100. /*
  179101. * Arithmetic utilities
  179102. */
  179103. GLOBAL(long)
  179104. jdiv_round_up (long a, long b)
  179105. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179106. /* Assumes a >= 0, b > 0 */
  179107. {
  179108. return (a + b - 1L) / b;
  179109. }
  179110. GLOBAL(long)
  179111. jround_up (long a, long b)
  179112. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179113. /* Assumes a >= 0, b > 0 */
  179114. {
  179115. a += b - 1L;
  179116. return a - (a % b);
  179117. }
  179118. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179119. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179120. * are FAR and we're assuming a small-pointer memory model. However, some
  179121. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179122. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179123. * Otherwise, the routines below do it the hard way. (The performance cost
  179124. * is not all that great, because these routines aren't very heavily used.)
  179125. */
  179126. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179127. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179128. #define FMEMZERO(target,size) MEMZERO(target,size)
  179129. #else /* 80x86 case, define if we can */
  179130. #ifdef USE_FMEM
  179131. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179132. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179133. #endif
  179134. #endif
  179135. GLOBAL(void)
  179136. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179137. JSAMPARRAY output_array, int dest_row,
  179138. int num_rows, JDIMENSION num_cols)
  179139. /* Copy some rows of samples from one place to another.
  179140. * num_rows rows are copied from input_array[source_row++]
  179141. * to output_array[dest_row++]; these areas may overlap for duplication.
  179142. * The source and destination arrays must be at least as wide as num_cols.
  179143. */
  179144. {
  179145. register JSAMPROW inptr, outptr;
  179146. #ifdef FMEMCOPY
  179147. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179148. #else
  179149. register JDIMENSION count;
  179150. #endif
  179151. register int row;
  179152. input_array += source_row;
  179153. output_array += dest_row;
  179154. for (row = num_rows; row > 0; row--) {
  179155. inptr = *input_array++;
  179156. outptr = *output_array++;
  179157. #ifdef FMEMCOPY
  179158. FMEMCOPY(outptr, inptr, count);
  179159. #else
  179160. for (count = num_cols; count > 0; count--)
  179161. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179162. #endif
  179163. }
  179164. }
  179165. GLOBAL(void)
  179166. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179167. JDIMENSION num_blocks)
  179168. /* Copy a row of coefficient blocks from one place to another. */
  179169. {
  179170. #ifdef FMEMCOPY
  179171. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179172. #else
  179173. register JCOEFPTR inptr, outptr;
  179174. register long count;
  179175. inptr = (JCOEFPTR) input_row;
  179176. outptr = (JCOEFPTR) output_row;
  179177. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179178. *outptr++ = *inptr++;
  179179. }
  179180. #endif
  179181. }
  179182. GLOBAL(void)
  179183. jzero_far (void FAR * target, size_t bytestozero)
  179184. /* Zero out a chunk of FAR memory. */
  179185. /* This might be sample-array data, block-array data, or alloc_large data. */
  179186. {
  179187. #ifdef FMEMZERO
  179188. FMEMZERO(target, bytestozero);
  179189. #else
  179190. register char FAR * ptr = (char FAR *) target;
  179191. register size_t count;
  179192. for (count = bytestozero; count > 0; count--) {
  179193. *ptr++ = 0;
  179194. }
  179195. #endif
  179196. }
  179197. /*** End of inlined file: jutils.c ***/
  179198. /*** Start of inlined file: transupp.c ***/
  179199. /* Although this file really shouldn't have access to the library internals,
  179200. * it's helpful to let it call jround_up() and jcopy_block_row().
  179201. */
  179202. #define JPEG_INTERNALS
  179203. /*** Start of inlined file: transupp.h ***/
  179204. /* If you happen not to want the image transform support, disable it here */
  179205. #ifndef TRANSFORMS_SUPPORTED
  179206. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179207. #endif
  179208. /* Short forms of external names for systems with brain-damaged linkers. */
  179209. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179210. #define jtransform_request_workspace jTrRequest
  179211. #define jtransform_adjust_parameters jTrAdjust
  179212. #define jtransform_execute_transformation jTrExec
  179213. #define jcopy_markers_setup jCMrkSetup
  179214. #define jcopy_markers_execute jCMrkExec
  179215. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179216. /*
  179217. * Codes for supported types of image transformations.
  179218. */
  179219. typedef enum {
  179220. JXFORM_NONE, /* no transformation */
  179221. JXFORM_FLIP_H, /* horizontal flip */
  179222. JXFORM_FLIP_V, /* vertical flip */
  179223. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179224. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179225. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179226. JXFORM_ROT_180, /* 180-degree rotation */
  179227. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179228. } JXFORM_CODE;
  179229. /*
  179230. * Although rotating and flipping data expressed as DCT coefficients is not
  179231. * hard, there is an asymmetry in the JPEG format specification for images
  179232. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179233. * image edges are padded out to the next iMCU boundary with junk data; but
  179234. * no padding is possible at the top and left edges. If we were to flip
  179235. * the whole image including the pad data, then pad garbage would become
  179236. * visible at the top and/or left, and real pixels would disappear into the
  179237. * pad margins --- perhaps permanently, since encoders & decoders may not
  179238. * bother to preserve DCT blocks that appear to be completely outside the
  179239. * nominal image area. So, we have to exclude any partial iMCUs from the
  179240. * basic transformation.
  179241. *
  179242. * Transpose is the only transformation that can handle partial iMCUs at the
  179243. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179244. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179245. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179246. * The other transforms are defined as combinations of these basic transforms
  179247. * and process edge blocks in a way that preserves the equivalence.
  179248. *
  179249. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179250. * this is not strictly lossless, but it usually gives the best-looking
  179251. * result for odd-size images. Note that when this option is active,
  179252. * the expected mathematical equivalences between the transforms may not hold.
  179253. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179254. * followed by -rot 180 -trim trims both edges.)
  179255. *
  179256. * We also offer a "force to grayscale" option, which simply discards the
  179257. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179258. * the luminance channel is preserved exactly. It's not the same kind of
  179259. * thing as the rotate/flip transformations, but it's convenient to handle it
  179260. * as part of this package, mainly because the transformation routines have to
  179261. * be aware of the option to know how many components to work on.
  179262. */
  179263. typedef struct {
  179264. /* Options: set by caller */
  179265. JXFORM_CODE transform; /* image transform operator */
  179266. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179267. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179268. /* Internal workspace: caller should not touch these */
  179269. int num_components; /* # of components in workspace */
  179270. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179271. } jpeg_transform_info;
  179272. #if TRANSFORMS_SUPPORTED
  179273. /* Request any required workspace */
  179274. EXTERN(void) jtransform_request_workspace
  179275. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179276. /* Adjust output image parameters */
  179277. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179278. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179279. jvirt_barray_ptr *src_coef_arrays,
  179280. jpeg_transform_info *info));
  179281. /* Execute the actual transformation, if any */
  179282. EXTERN(void) jtransform_execute_transformation
  179283. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179284. jvirt_barray_ptr *src_coef_arrays,
  179285. jpeg_transform_info *info));
  179286. #endif /* TRANSFORMS_SUPPORTED */
  179287. /*
  179288. * Support for copying optional markers from source to destination file.
  179289. */
  179290. typedef enum {
  179291. JCOPYOPT_NONE, /* copy no optional markers */
  179292. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179293. JCOPYOPT_ALL /* copy all optional markers */
  179294. } JCOPY_OPTION;
  179295. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179296. /* Setup decompression object to save desired markers in memory */
  179297. EXTERN(void) jcopy_markers_setup
  179298. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179299. /* Copy markers saved in the given source object to the destination object */
  179300. EXTERN(void) jcopy_markers_execute
  179301. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179302. JCOPY_OPTION option));
  179303. /*** End of inlined file: transupp.h ***/
  179304. /* My own external interface */
  179305. #if TRANSFORMS_SUPPORTED
  179306. /*
  179307. * Lossless image transformation routines. These routines work on DCT
  179308. * coefficient arrays and thus do not require any lossy decompression
  179309. * or recompression of the image.
  179310. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179311. *
  179312. * Horizontal flipping is done in-place, using a single top-to-bottom
  179313. * pass through the virtual source array. It will thus be much the
  179314. * fastest option for images larger than main memory.
  179315. *
  179316. * The other routines require a set of destination virtual arrays, so they
  179317. * need twice as much memory as jpegtran normally does. The destination
  179318. * arrays are always written in normal scan order (top to bottom) because
  179319. * the virtual array manager expects this. The source arrays will be scanned
  179320. * in the corresponding order, which means multiple passes through the source
  179321. * arrays for most of the transforms. That could result in much thrashing
  179322. * if the image is larger than main memory.
  179323. *
  179324. * Some notes about the operating environment of the individual transform
  179325. * routines:
  179326. * 1. Both the source and destination virtual arrays are allocated from the
  179327. * source JPEG object, and therefore should be manipulated by calling the
  179328. * source's memory manager.
  179329. * 2. The destination's component count should be used. It may be smaller
  179330. * than the source's when forcing to grayscale.
  179331. * 3. Likewise the destination's sampling factors should be used. When
  179332. * forcing to grayscale the destination's sampling factors will be all 1,
  179333. * and we may as well take that as the effective iMCU size.
  179334. * 4. When "trim" is in effect, the destination's dimensions will be the
  179335. * trimmed values but the source's will be untrimmed.
  179336. * 5. All the routines assume that the source and destination buffers are
  179337. * padded out to a full iMCU boundary. This is true, although for the
  179338. * source buffer it is an undocumented property of jdcoefct.c.
  179339. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179340. * dimensions and ignore the source's.
  179341. */
  179342. LOCAL(void)
  179343. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179344. jvirt_barray_ptr *src_coef_arrays)
  179345. /* Horizontal flip; done in-place, so no separate dest array is required */
  179346. {
  179347. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179348. int ci, k, offset_y;
  179349. JBLOCKARRAY buffer;
  179350. JCOEFPTR ptr1, ptr2;
  179351. JCOEF temp1, temp2;
  179352. jpeg_component_info *compptr;
  179353. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179354. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179355. * mirroring by changing the signs of odd-numbered columns.
  179356. * Partial iMCUs at the right edge are left untouched.
  179357. */
  179358. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179359. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179360. compptr = dstinfo->comp_info + ci;
  179361. comp_width = MCU_cols * compptr->h_samp_factor;
  179362. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179363. blk_y += compptr->v_samp_factor) {
  179364. buffer = (*srcinfo->mem->access_virt_barray)
  179365. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179366. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179367. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179368. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179369. ptr1 = buffer[offset_y][blk_x];
  179370. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179371. /* this unrolled loop doesn't need to know which row it's on... */
  179372. for (k = 0; k < DCTSIZE2; k += 2) {
  179373. temp1 = *ptr1; /* swap even column */
  179374. temp2 = *ptr2;
  179375. *ptr1++ = temp2;
  179376. *ptr2++ = temp1;
  179377. temp1 = *ptr1; /* swap odd column with sign change */
  179378. temp2 = *ptr2;
  179379. *ptr1++ = -temp2;
  179380. *ptr2++ = -temp1;
  179381. }
  179382. }
  179383. }
  179384. }
  179385. }
  179386. }
  179387. LOCAL(void)
  179388. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179389. jvirt_barray_ptr *src_coef_arrays,
  179390. jvirt_barray_ptr *dst_coef_arrays)
  179391. /* Vertical flip */
  179392. {
  179393. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179394. int ci, i, j, offset_y;
  179395. JBLOCKARRAY src_buffer, dst_buffer;
  179396. JBLOCKROW src_row_ptr, dst_row_ptr;
  179397. JCOEFPTR src_ptr, dst_ptr;
  179398. jpeg_component_info *compptr;
  179399. /* We output into a separate array because we can't touch different
  179400. * rows of the source virtual array simultaneously. Otherwise, this
  179401. * is a pretty straightforward analog of horizontal flip.
  179402. * Within a DCT block, vertical mirroring is done by changing the signs
  179403. * of odd-numbered rows.
  179404. * Partial iMCUs at the bottom edge are copied verbatim.
  179405. */
  179406. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179407. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179408. compptr = dstinfo->comp_info + ci;
  179409. comp_height = MCU_rows * compptr->v_samp_factor;
  179410. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179411. dst_blk_y += compptr->v_samp_factor) {
  179412. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179413. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179414. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179415. if (dst_blk_y < comp_height) {
  179416. /* Row is within the mirrorable area. */
  179417. src_buffer = (*srcinfo->mem->access_virt_barray)
  179418. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179419. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179420. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179421. } else {
  179422. /* Bottom-edge blocks will be copied verbatim. */
  179423. src_buffer = (*srcinfo->mem->access_virt_barray)
  179424. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179425. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179426. }
  179427. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179428. if (dst_blk_y < comp_height) {
  179429. /* Row is within the mirrorable area. */
  179430. dst_row_ptr = dst_buffer[offset_y];
  179431. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179432. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179433. dst_blk_x++) {
  179434. dst_ptr = dst_row_ptr[dst_blk_x];
  179435. src_ptr = src_row_ptr[dst_blk_x];
  179436. for (i = 0; i < DCTSIZE; i += 2) {
  179437. /* copy even row */
  179438. for (j = 0; j < DCTSIZE; j++)
  179439. *dst_ptr++ = *src_ptr++;
  179440. /* copy odd row with sign change */
  179441. for (j = 0; j < DCTSIZE; j++)
  179442. *dst_ptr++ = - *src_ptr++;
  179443. }
  179444. }
  179445. } else {
  179446. /* Just copy row verbatim. */
  179447. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179448. compptr->width_in_blocks);
  179449. }
  179450. }
  179451. }
  179452. }
  179453. }
  179454. LOCAL(void)
  179455. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179456. jvirt_barray_ptr *src_coef_arrays,
  179457. jvirt_barray_ptr *dst_coef_arrays)
  179458. /* Transpose source into destination */
  179459. {
  179460. JDIMENSION dst_blk_x, dst_blk_y;
  179461. int ci, i, j, offset_x, offset_y;
  179462. JBLOCKARRAY src_buffer, dst_buffer;
  179463. JCOEFPTR src_ptr, dst_ptr;
  179464. jpeg_component_info *compptr;
  179465. /* Transposing pixels within a block just requires transposing the
  179466. * DCT coefficients.
  179467. * Partial iMCUs at the edges require no special treatment; we simply
  179468. * process all the available DCT blocks for every component.
  179469. */
  179470. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179471. compptr = dstinfo->comp_info + ci;
  179472. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179473. dst_blk_y += compptr->v_samp_factor) {
  179474. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179475. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179476. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179477. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179478. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179479. dst_blk_x += compptr->h_samp_factor) {
  179480. src_buffer = (*srcinfo->mem->access_virt_barray)
  179481. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179482. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179483. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179484. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179485. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179486. for (i = 0; i < DCTSIZE; i++)
  179487. for (j = 0; j < DCTSIZE; j++)
  179488. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179489. }
  179490. }
  179491. }
  179492. }
  179493. }
  179494. }
  179495. LOCAL(void)
  179496. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179497. jvirt_barray_ptr *src_coef_arrays,
  179498. jvirt_barray_ptr *dst_coef_arrays)
  179499. /* 90 degree rotation is equivalent to
  179500. * 1. Transposing the image;
  179501. * 2. Horizontal mirroring.
  179502. * These two steps are merged into a single processing routine.
  179503. */
  179504. {
  179505. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179506. int ci, i, j, offset_x, offset_y;
  179507. JBLOCKARRAY src_buffer, dst_buffer;
  179508. JCOEFPTR src_ptr, dst_ptr;
  179509. jpeg_component_info *compptr;
  179510. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179511. * at the (output) right edge properly. They just get transposed and
  179512. * not mirrored.
  179513. */
  179514. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179515. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179516. compptr = dstinfo->comp_info + ci;
  179517. comp_width = MCU_cols * compptr->h_samp_factor;
  179518. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179519. dst_blk_y += compptr->v_samp_factor) {
  179520. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179521. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179522. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179523. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179524. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179525. dst_blk_x += compptr->h_samp_factor) {
  179526. src_buffer = (*srcinfo->mem->access_virt_barray)
  179527. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179528. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179529. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179530. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179531. if (dst_blk_x < comp_width) {
  179532. /* Block is within the mirrorable area. */
  179533. dst_ptr = dst_buffer[offset_y]
  179534. [comp_width - dst_blk_x - offset_x - 1];
  179535. for (i = 0; i < DCTSIZE; i++) {
  179536. for (j = 0; j < DCTSIZE; j++)
  179537. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179538. i++;
  179539. for (j = 0; j < DCTSIZE; j++)
  179540. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179541. }
  179542. } else {
  179543. /* Edge blocks are transposed but not mirrored. */
  179544. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179545. for (i = 0; i < DCTSIZE; i++)
  179546. for (j = 0; j < DCTSIZE; j++)
  179547. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179548. }
  179549. }
  179550. }
  179551. }
  179552. }
  179553. }
  179554. }
  179555. LOCAL(void)
  179556. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179557. jvirt_barray_ptr *src_coef_arrays,
  179558. jvirt_barray_ptr *dst_coef_arrays)
  179559. /* 270 degree rotation is equivalent to
  179560. * 1. Horizontal mirroring;
  179561. * 2. Transposing the image.
  179562. * These two steps are merged into a single processing routine.
  179563. */
  179564. {
  179565. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179566. int ci, i, j, offset_x, offset_y;
  179567. JBLOCKARRAY src_buffer, dst_buffer;
  179568. JCOEFPTR src_ptr, dst_ptr;
  179569. jpeg_component_info *compptr;
  179570. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179571. * at the (output) bottom edge properly. They just get transposed and
  179572. * not mirrored.
  179573. */
  179574. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179575. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179576. compptr = dstinfo->comp_info + ci;
  179577. comp_height = MCU_rows * compptr->v_samp_factor;
  179578. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179579. dst_blk_y += compptr->v_samp_factor) {
  179580. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179581. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179582. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179583. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179584. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179585. dst_blk_x += compptr->h_samp_factor) {
  179586. src_buffer = (*srcinfo->mem->access_virt_barray)
  179587. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179588. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179589. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179590. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179591. if (dst_blk_y < comp_height) {
  179592. /* Block is within the mirrorable area. */
  179593. src_ptr = src_buffer[offset_x]
  179594. [comp_height - dst_blk_y - offset_y - 1];
  179595. for (i = 0; i < DCTSIZE; i++) {
  179596. for (j = 0; j < DCTSIZE; j++) {
  179597. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179598. j++;
  179599. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179600. }
  179601. }
  179602. } else {
  179603. /* Edge blocks are transposed but not mirrored. */
  179604. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179605. for (i = 0; i < DCTSIZE; i++)
  179606. for (j = 0; j < DCTSIZE; j++)
  179607. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179608. }
  179609. }
  179610. }
  179611. }
  179612. }
  179613. }
  179614. }
  179615. LOCAL(void)
  179616. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179617. jvirt_barray_ptr *src_coef_arrays,
  179618. jvirt_barray_ptr *dst_coef_arrays)
  179619. /* 180 degree rotation is equivalent to
  179620. * 1. Vertical mirroring;
  179621. * 2. Horizontal mirroring.
  179622. * These two steps are merged into a single processing routine.
  179623. */
  179624. {
  179625. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179626. int ci, i, j, offset_y;
  179627. JBLOCKARRAY src_buffer, dst_buffer;
  179628. JBLOCKROW src_row_ptr, dst_row_ptr;
  179629. JCOEFPTR src_ptr, dst_ptr;
  179630. jpeg_component_info *compptr;
  179631. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179632. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179633. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179634. compptr = dstinfo->comp_info + ci;
  179635. comp_width = MCU_cols * compptr->h_samp_factor;
  179636. comp_height = MCU_rows * compptr->v_samp_factor;
  179637. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179638. dst_blk_y += compptr->v_samp_factor) {
  179639. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179640. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179641. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179642. if (dst_blk_y < comp_height) {
  179643. /* Row is within the vertically mirrorable area. */
  179644. src_buffer = (*srcinfo->mem->access_virt_barray)
  179645. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179646. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179647. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179648. } else {
  179649. /* Bottom-edge rows are only mirrored horizontally. */
  179650. src_buffer = (*srcinfo->mem->access_virt_barray)
  179651. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179652. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179653. }
  179654. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179655. if (dst_blk_y < comp_height) {
  179656. /* Row is within the mirrorable area. */
  179657. dst_row_ptr = dst_buffer[offset_y];
  179658. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179659. /* Process the blocks that can be mirrored both ways. */
  179660. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179661. dst_ptr = dst_row_ptr[dst_blk_x];
  179662. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179663. for (i = 0; i < DCTSIZE; i += 2) {
  179664. /* For even row, negate every odd column. */
  179665. for (j = 0; j < DCTSIZE; j += 2) {
  179666. *dst_ptr++ = *src_ptr++;
  179667. *dst_ptr++ = - *src_ptr++;
  179668. }
  179669. /* For odd row, negate every even column. */
  179670. for (j = 0; j < DCTSIZE; j += 2) {
  179671. *dst_ptr++ = - *src_ptr++;
  179672. *dst_ptr++ = *src_ptr++;
  179673. }
  179674. }
  179675. }
  179676. /* Any remaining right-edge blocks are only mirrored vertically. */
  179677. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179678. dst_ptr = dst_row_ptr[dst_blk_x];
  179679. src_ptr = src_row_ptr[dst_blk_x];
  179680. for (i = 0; i < DCTSIZE; i += 2) {
  179681. for (j = 0; j < DCTSIZE; j++)
  179682. *dst_ptr++ = *src_ptr++;
  179683. for (j = 0; j < DCTSIZE; j++)
  179684. *dst_ptr++ = - *src_ptr++;
  179685. }
  179686. }
  179687. } else {
  179688. /* Remaining rows are just mirrored horizontally. */
  179689. dst_row_ptr = dst_buffer[offset_y];
  179690. src_row_ptr = src_buffer[offset_y];
  179691. /* Process the blocks that can be mirrored. */
  179692. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179693. dst_ptr = dst_row_ptr[dst_blk_x];
  179694. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179695. for (i = 0; i < DCTSIZE2; i += 2) {
  179696. *dst_ptr++ = *src_ptr++;
  179697. *dst_ptr++ = - *src_ptr++;
  179698. }
  179699. }
  179700. /* Any remaining right-edge blocks are only copied. */
  179701. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179702. dst_ptr = dst_row_ptr[dst_blk_x];
  179703. src_ptr = src_row_ptr[dst_blk_x];
  179704. for (i = 0; i < DCTSIZE2; i++)
  179705. *dst_ptr++ = *src_ptr++;
  179706. }
  179707. }
  179708. }
  179709. }
  179710. }
  179711. }
  179712. LOCAL(void)
  179713. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179714. jvirt_barray_ptr *src_coef_arrays,
  179715. jvirt_barray_ptr *dst_coef_arrays)
  179716. /* Transverse transpose is equivalent to
  179717. * 1. 180 degree rotation;
  179718. * 2. Transposition;
  179719. * or
  179720. * 1. Horizontal mirroring;
  179721. * 2. Transposition;
  179722. * 3. Horizontal mirroring.
  179723. * These steps are merged into a single processing routine.
  179724. */
  179725. {
  179726. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179727. int ci, i, j, offset_x, offset_y;
  179728. JBLOCKARRAY src_buffer, dst_buffer;
  179729. JCOEFPTR src_ptr, dst_ptr;
  179730. jpeg_component_info *compptr;
  179731. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179732. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179733. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179734. compptr = dstinfo->comp_info + ci;
  179735. comp_width = MCU_cols * compptr->h_samp_factor;
  179736. comp_height = MCU_rows * compptr->v_samp_factor;
  179737. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179738. dst_blk_y += compptr->v_samp_factor) {
  179739. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179740. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179741. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179742. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179743. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179744. dst_blk_x += compptr->h_samp_factor) {
  179745. src_buffer = (*srcinfo->mem->access_virt_barray)
  179746. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179747. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179748. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179749. if (dst_blk_y < comp_height) {
  179750. src_ptr = src_buffer[offset_x]
  179751. [comp_height - dst_blk_y - offset_y - 1];
  179752. if (dst_blk_x < comp_width) {
  179753. /* Block is within the mirrorable area. */
  179754. dst_ptr = dst_buffer[offset_y]
  179755. [comp_width - dst_blk_x - offset_x - 1];
  179756. for (i = 0; i < DCTSIZE; i++) {
  179757. for (j = 0; j < DCTSIZE; j++) {
  179758. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179759. j++;
  179760. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179761. }
  179762. i++;
  179763. for (j = 0; j < DCTSIZE; j++) {
  179764. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179765. j++;
  179766. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179767. }
  179768. }
  179769. } else {
  179770. /* Right-edge blocks are mirrored in y only */
  179771. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179772. for (i = 0; i < DCTSIZE; i++) {
  179773. for (j = 0; j < DCTSIZE; j++) {
  179774. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179775. j++;
  179776. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179777. }
  179778. }
  179779. }
  179780. } else {
  179781. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179782. if (dst_blk_x < comp_width) {
  179783. /* Bottom-edge blocks are mirrored in x only */
  179784. dst_ptr = dst_buffer[offset_y]
  179785. [comp_width - dst_blk_x - offset_x - 1];
  179786. for (i = 0; i < DCTSIZE; i++) {
  179787. for (j = 0; j < DCTSIZE; j++)
  179788. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179789. i++;
  179790. for (j = 0; j < DCTSIZE; j++)
  179791. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179792. }
  179793. } else {
  179794. /* At lower right corner, just transpose, no mirroring */
  179795. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179796. for (i = 0; i < DCTSIZE; i++)
  179797. for (j = 0; j < DCTSIZE; j++)
  179798. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179799. }
  179800. }
  179801. }
  179802. }
  179803. }
  179804. }
  179805. }
  179806. }
  179807. /* Request any required workspace.
  179808. *
  179809. * We allocate the workspace virtual arrays from the source decompression
  179810. * object, so that all the arrays (both the original data and the workspace)
  179811. * will be taken into account while making memory management decisions.
  179812. * Hence, this routine must be called after jpeg_read_header (which reads
  179813. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179814. * the source's virtual arrays).
  179815. */
  179816. GLOBAL(void)
  179817. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179818. jpeg_transform_info *info)
  179819. {
  179820. jvirt_barray_ptr *coef_arrays = NULL;
  179821. jpeg_component_info *compptr;
  179822. int ci;
  179823. if (info->force_grayscale &&
  179824. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179825. srcinfo->num_components == 3) {
  179826. /* We'll only process the first component */
  179827. info->num_components = 1;
  179828. } else {
  179829. /* Process all the components */
  179830. info->num_components = srcinfo->num_components;
  179831. }
  179832. switch (info->transform) {
  179833. case JXFORM_NONE:
  179834. case JXFORM_FLIP_H:
  179835. /* Don't need a workspace array */
  179836. break;
  179837. case JXFORM_FLIP_V:
  179838. case JXFORM_ROT_180:
  179839. /* Need workspace arrays having same dimensions as source image.
  179840. * Note that we allocate arrays padded out to the next iMCU boundary,
  179841. * so that transform routines need not worry about missing edge blocks.
  179842. */
  179843. coef_arrays = (jvirt_barray_ptr *)
  179844. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179845. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179846. for (ci = 0; ci < info->num_components; ci++) {
  179847. compptr = srcinfo->comp_info + ci;
  179848. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179849. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179850. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179851. (long) compptr->h_samp_factor),
  179852. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179853. (long) compptr->v_samp_factor),
  179854. (JDIMENSION) compptr->v_samp_factor);
  179855. }
  179856. break;
  179857. case JXFORM_TRANSPOSE:
  179858. case JXFORM_TRANSVERSE:
  179859. case JXFORM_ROT_90:
  179860. case JXFORM_ROT_270:
  179861. /* Need workspace arrays having transposed dimensions.
  179862. * Note that we allocate arrays padded out to the next iMCU boundary,
  179863. * so that transform routines need not worry about missing edge blocks.
  179864. */
  179865. coef_arrays = (jvirt_barray_ptr *)
  179866. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179867. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179868. for (ci = 0; ci < info->num_components; ci++) {
  179869. compptr = srcinfo->comp_info + ci;
  179870. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179871. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179872. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179873. (long) compptr->v_samp_factor),
  179874. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179875. (long) compptr->h_samp_factor),
  179876. (JDIMENSION) compptr->h_samp_factor);
  179877. }
  179878. break;
  179879. }
  179880. info->workspace_coef_arrays = coef_arrays;
  179881. }
  179882. /* Transpose destination image parameters */
  179883. LOCAL(void)
  179884. transpose_critical_parameters (j_compress_ptr dstinfo)
  179885. {
  179886. int tblno, i, j, ci, itemp;
  179887. jpeg_component_info *compptr;
  179888. JQUANT_TBL *qtblptr;
  179889. JDIMENSION dtemp;
  179890. UINT16 qtemp;
  179891. /* Transpose basic image dimensions */
  179892. dtemp = dstinfo->image_width;
  179893. dstinfo->image_width = dstinfo->image_height;
  179894. dstinfo->image_height = dtemp;
  179895. /* Transpose sampling factors */
  179896. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179897. compptr = dstinfo->comp_info + ci;
  179898. itemp = compptr->h_samp_factor;
  179899. compptr->h_samp_factor = compptr->v_samp_factor;
  179900. compptr->v_samp_factor = itemp;
  179901. }
  179902. /* Transpose quantization tables */
  179903. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179904. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179905. if (qtblptr != NULL) {
  179906. for (i = 0; i < DCTSIZE; i++) {
  179907. for (j = 0; j < i; j++) {
  179908. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179909. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179910. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179911. }
  179912. }
  179913. }
  179914. }
  179915. }
  179916. /* Trim off any partial iMCUs on the indicated destination edge */
  179917. LOCAL(void)
  179918. trim_right_edge (j_compress_ptr dstinfo)
  179919. {
  179920. int ci, max_h_samp_factor;
  179921. JDIMENSION MCU_cols;
  179922. /* We have to compute max_h_samp_factor ourselves,
  179923. * because it hasn't been set yet in the destination
  179924. * (and we don't want to use the source's value).
  179925. */
  179926. max_h_samp_factor = 1;
  179927. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179928. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179929. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179930. }
  179931. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179932. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179933. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179934. }
  179935. LOCAL(void)
  179936. trim_bottom_edge (j_compress_ptr dstinfo)
  179937. {
  179938. int ci, max_v_samp_factor;
  179939. JDIMENSION MCU_rows;
  179940. /* We have to compute max_v_samp_factor ourselves,
  179941. * because it hasn't been set yet in the destination
  179942. * (and we don't want to use the source's value).
  179943. */
  179944. max_v_samp_factor = 1;
  179945. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179946. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179947. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179948. }
  179949. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179950. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179951. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179952. }
  179953. /* Adjust output image parameters as needed.
  179954. *
  179955. * This must be called after jpeg_copy_critical_parameters()
  179956. * and before jpeg_write_coefficients().
  179957. *
  179958. * The return value is the set of virtual coefficient arrays to be written
  179959. * (either the ones allocated by jtransform_request_workspace, or the
  179960. * original source data arrays). The caller will need to pass this value
  179961. * to jpeg_write_coefficients().
  179962. */
  179963. GLOBAL(jvirt_barray_ptr *)
  179964. jtransform_adjust_parameters (j_decompress_ptr,
  179965. j_compress_ptr dstinfo,
  179966. jvirt_barray_ptr *src_coef_arrays,
  179967. jpeg_transform_info *info)
  179968. {
  179969. /* If force-to-grayscale is requested, adjust destination parameters */
  179970. if (info->force_grayscale) {
  179971. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179972. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179973. * will get set to 1, which typically won't match the source.
  179974. * In fact we do this even if the source is already grayscale; that
  179975. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179976. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179977. */
  179978. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179979. dstinfo->num_components == 3) ||
  179980. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179981. dstinfo->num_components == 1)) {
  179982. /* We have to preserve the source's quantization table number. */
  179983. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179984. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179985. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179986. } else {
  179987. /* Sorry, can't do it */
  179988. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179989. }
  179990. }
  179991. /* Correct the destination's image dimensions etc if necessary */
  179992. switch (info->transform) {
  179993. case JXFORM_NONE:
  179994. /* Nothing to do */
  179995. break;
  179996. case JXFORM_FLIP_H:
  179997. if (info->trim)
  179998. trim_right_edge(dstinfo);
  179999. break;
  180000. case JXFORM_FLIP_V:
  180001. if (info->trim)
  180002. trim_bottom_edge(dstinfo);
  180003. break;
  180004. case JXFORM_TRANSPOSE:
  180005. transpose_critical_parameters(dstinfo);
  180006. /* transpose does NOT have to trim anything */
  180007. break;
  180008. case JXFORM_TRANSVERSE:
  180009. transpose_critical_parameters(dstinfo);
  180010. if (info->trim) {
  180011. trim_right_edge(dstinfo);
  180012. trim_bottom_edge(dstinfo);
  180013. }
  180014. break;
  180015. case JXFORM_ROT_90:
  180016. transpose_critical_parameters(dstinfo);
  180017. if (info->trim)
  180018. trim_right_edge(dstinfo);
  180019. break;
  180020. case JXFORM_ROT_180:
  180021. if (info->trim) {
  180022. trim_right_edge(dstinfo);
  180023. trim_bottom_edge(dstinfo);
  180024. }
  180025. break;
  180026. case JXFORM_ROT_270:
  180027. transpose_critical_parameters(dstinfo);
  180028. if (info->trim)
  180029. trim_bottom_edge(dstinfo);
  180030. break;
  180031. }
  180032. /* Return the appropriate output data set */
  180033. if (info->workspace_coef_arrays != NULL)
  180034. return info->workspace_coef_arrays;
  180035. return src_coef_arrays;
  180036. }
  180037. /* Execute the actual transformation, if any.
  180038. *
  180039. * This must be called *after* jpeg_write_coefficients, because it depends
  180040. * on jpeg_write_coefficients to have computed subsidiary values such as
  180041. * the per-component width and height fields in the destination object.
  180042. *
  180043. * Note that some transformations will modify the source data arrays!
  180044. */
  180045. GLOBAL(void)
  180046. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180047. j_compress_ptr dstinfo,
  180048. jvirt_barray_ptr *src_coef_arrays,
  180049. jpeg_transform_info *info)
  180050. {
  180051. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180052. switch (info->transform) {
  180053. case JXFORM_NONE:
  180054. break;
  180055. case JXFORM_FLIP_H:
  180056. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180057. break;
  180058. case JXFORM_FLIP_V:
  180059. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180060. break;
  180061. case JXFORM_TRANSPOSE:
  180062. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180063. break;
  180064. case JXFORM_TRANSVERSE:
  180065. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180066. break;
  180067. case JXFORM_ROT_90:
  180068. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180069. break;
  180070. case JXFORM_ROT_180:
  180071. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180072. break;
  180073. case JXFORM_ROT_270:
  180074. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180075. break;
  180076. }
  180077. }
  180078. #endif /* TRANSFORMS_SUPPORTED */
  180079. /* Setup decompression object to save desired markers in memory.
  180080. * This must be called before jpeg_read_header() to have the desired effect.
  180081. */
  180082. GLOBAL(void)
  180083. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180084. {
  180085. #ifdef SAVE_MARKERS_SUPPORTED
  180086. int m;
  180087. /* Save comments except under NONE option */
  180088. if (option != JCOPYOPT_NONE) {
  180089. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180090. }
  180091. /* Save all types of APPn markers iff ALL option */
  180092. if (option == JCOPYOPT_ALL) {
  180093. for (m = 0; m < 16; m++)
  180094. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180095. }
  180096. #endif /* SAVE_MARKERS_SUPPORTED */
  180097. }
  180098. /* Copy markers saved in the given source object to the destination object.
  180099. * This should be called just after jpeg_start_compress() or
  180100. * jpeg_write_coefficients().
  180101. * Note that those routines will have written the SOI, and also the
  180102. * JFIF APP0 or Adobe APP14 markers if selected.
  180103. */
  180104. GLOBAL(void)
  180105. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180106. JCOPY_OPTION)
  180107. {
  180108. jpeg_saved_marker_ptr marker;
  180109. /* In the current implementation, we don't actually need to examine the
  180110. * option flag here; we just copy everything that got saved.
  180111. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180112. * if the encoder library already wrote one.
  180113. */
  180114. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180115. if (dstinfo->write_JFIF_header &&
  180116. marker->marker == JPEG_APP0 &&
  180117. marker->data_length >= 5 &&
  180118. GETJOCTET(marker->data[0]) == 0x4A &&
  180119. GETJOCTET(marker->data[1]) == 0x46 &&
  180120. GETJOCTET(marker->data[2]) == 0x49 &&
  180121. GETJOCTET(marker->data[3]) == 0x46 &&
  180122. GETJOCTET(marker->data[4]) == 0)
  180123. continue; /* reject duplicate JFIF */
  180124. if (dstinfo->write_Adobe_marker &&
  180125. marker->marker == JPEG_APP0+14 &&
  180126. marker->data_length >= 5 &&
  180127. GETJOCTET(marker->data[0]) == 0x41 &&
  180128. GETJOCTET(marker->data[1]) == 0x64 &&
  180129. GETJOCTET(marker->data[2]) == 0x6F &&
  180130. GETJOCTET(marker->data[3]) == 0x62 &&
  180131. GETJOCTET(marker->data[4]) == 0x65)
  180132. continue; /* reject duplicate Adobe */
  180133. #ifdef NEED_FAR_POINTERS
  180134. /* We could use jpeg_write_marker if the data weren't FAR... */
  180135. {
  180136. unsigned int i;
  180137. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180138. for (i = 0; i < marker->data_length; i++)
  180139. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180140. }
  180141. #else
  180142. jpeg_write_marker(dstinfo, marker->marker,
  180143. marker->data, marker->data_length);
  180144. #endif
  180145. }
  180146. }
  180147. /*** End of inlined file: transupp.c ***/
  180148. #else
  180149. #define JPEG_INTERNALS
  180150. #undef FAR
  180151. #include <jpeglib.h>
  180152. #endif
  180153. }
  180154. #undef max
  180155. #undef min
  180156. #if JUCE_MSVC
  180157. #pragma warning (pop)
  180158. #endif
  180159. BEGIN_JUCE_NAMESPACE
  180160. namespace JPEGHelpers
  180161. {
  180162. using namespace jpeglibNamespace;
  180163. #if ! JUCE_MSVC
  180164. using jpeglibNamespace::boolean;
  180165. #endif
  180166. struct JPEGDecodingFailure {};
  180167. void fatalErrorHandler (j_common_ptr)
  180168. {
  180169. throw JPEGDecodingFailure();
  180170. }
  180171. void silentErrorCallback1 (j_common_ptr) {}
  180172. void silentErrorCallback2 (j_common_ptr, int) {}
  180173. void silentErrorCallback3 (j_common_ptr, char*) {}
  180174. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180175. {
  180176. zerostruct (err);
  180177. err.error_exit = fatalErrorHandler;
  180178. err.emit_message = silentErrorCallback2;
  180179. err.output_message = silentErrorCallback1;
  180180. err.format_message = silentErrorCallback3;
  180181. err.reset_error_mgr = silentErrorCallback1;
  180182. }
  180183. void dummyCallback1 (j_decompress_ptr)
  180184. {
  180185. }
  180186. void jpegSkip (j_decompress_ptr decompStruct, long num)
  180187. {
  180188. decompStruct->src->next_input_byte += num;
  180189. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180190. decompStruct->src->bytes_in_buffer -= num;
  180191. }
  180192. boolean jpegFill (j_decompress_ptr)
  180193. {
  180194. return 0;
  180195. }
  180196. const int jpegBufferSize = 512;
  180197. struct JuceJpegDest : public jpeg_destination_mgr
  180198. {
  180199. OutputStream* output;
  180200. char* buffer;
  180201. };
  180202. void jpegWriteInit (j_compress_ptr)
  180203. {
  180204. }
  180205. void jpegWriteTerminate (j_compress_ptr cinfo)
  180206. {
  180207. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180208. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180209. dest->output->write (dest->buffer, (int) numToWrite);
  180210. }
  180211. boolean jpegWriteFlush (j_compress_ptr cinfo)
  180212. {
  180213. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180214. const int numToWrite = jpegBufferSize;
  180215. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180216. dest->free_in_buffer = jpegBufferSize;
  180217. return dest->output->write (dest->buffer, numToWrite);
  180218. }
  180219. }
  180220. JPEGImageFormat::JPEGImageFormat()
  180221. : quality (-1.0f)
  180222. {
  180223. }
  180224. JPEGImageFormat::~JPEGImageFormat() {}
  180225. void JPEGImageFormat::setQuality (const float newQuality)
  180226. {
  180227. quality = newQuality;
  180228. }
  180229. const String JPEGImageFormat::getFormatName()
  180230. {
  180231. return "JPEG";
  180232. }
  180233. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180234. {
  180235. const int bytesNeeded = 10;
  180236. uint8 header [bytesNeeded];
  180237. if (in.read (header, bytesNeeded) == bytesNeeded)
  180238. {
  180239. return header[0] == 0xff
  180240. && header[1] == 0xd8
  180241. && header[2] == 0xff
  180242. && (header[3] == 0xe0 || header[3] == 0xe1);
  180243. }
  180244. return false;
  180245. }
  180246. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180247. const Image juce_loadWithCoreImage (InputStream& input);
  180248. #endif
  180249. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180250. {
  180251. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180252. return juce_loadWithCoreImage (in);
  180253. #else
  180254. using namespace jpeglibNamespace;
  180255. using namespace JPEGHelpers;
  180256. MemoryOutputStream mb;
  180257. mb.writeFromInputStream (in, -1);
  180258. Image image;
  180259. if (mb.getDataSize() > 16)
  180260. {
  180261. struct jpeg_decompress_struct jpegDecompStruct;
  180262. struct jpeg_error_mgr jerr;
  180263. setupSilentErrorHandler (jerr);
  180264. jpegDecompStruct.err = &jerr;
  180265. jpeg_create_decompress (&jpegDecompStruct);
  180266. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180267. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180268. jpegDecompStruct.src->init_source = dummyCallback1;
  180269. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180270. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180271. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180272. jpegDecompStruct.src->term_source = dummyCallback1;
  180273. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180274. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180275. try
  180276. {
  180277. jpeg_read_header (&jpegDecompStruct, TRUE);
  180278. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180279. const int width = jpegDecompStruct.output_width;
  180280. const int height = jpegDecompStruct.output_height;
  180281. jpegDecompStruct.out_color_space = JCS_RGB;
  180282. JSAMPARRAY buffer
  180283. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180284. JPOOL_IMAGE,
  180285. width * 3, 1);
  180286. if (jpeg_start_decompress (&jpegDecompStruct))
  180287. {
  180288. image = Image (Image::RGB, width, height, false);
  180289. image.getProperties()->set ("originalImageHadAlpha", false);
  180290. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180291. const Image::BitmapData destData (image, true);
  180292. for (int y = 0; y < height; ++y)
  180293. {
  180294. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180295. const uint8* src = *buffer;
  180296. uint8* dest = destData.getLinePointer (y);
  180297. if (hasAlphaChan)
  180298. {
  180299. for (int i = width; --i >= 0;)
  180300. {
  180301. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180302. ((PixelARGB*) dest)->premultiply();
  180303. dest += destData.pixelStride;
  180304. src += 3;
  180305. }
  180306. }
  180307. else
  180308. {
  180309. for (int i = width; --i >= 0;)
  180310. {
  180311. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180312. dest += destData.pixelStride;
  180313. src += 3;
  180314. }
  180315. }
  180316. }
  180317. jpeg_finish_decompress (&jpegDecompStruct);
  180318. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180319. }
  180320. jpeg_destroy_decompress (&jpegDecompStruct);
  180321. }
  180322. catch (...)
  180323. {}
  180324. }
  180325. return image;
  180326. #endif
  180327. }
  180328. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180329. {
  180330. using namespace jpeglibNamespace;
  180331. using namespace JPEGHelpers;
  180332. if (image.hasAlphaChannel())
  180333. {
  180334. // this method could fill the background in white and still save the image..
  180335. jassertfalse;
  180336. return true;
  180337. }
  180338. struct jpeg_compress_struct jpegCompStruct;
  180339. struct jpeg_error_mgr jerr;
  180340. setupSilentErrorHandler (jerr);
  180341. jpegCompStruct.err = &jerr;
  180342. jpeg_create_compress (&jpegCompStruct);
  180343. JuceJpegDest dest;
  180344. jpegCompStruct.dest = &dest;
  180345. dest.output = &out;
  180346. HeapBlock <char> tempBuffer (jpegBufferSize);
  180347. dest.buffer = tempBuffer;
  180348. dest.next_output_byte = (JOCTET*) dest.buffer;
  180349. dest.free_in_buffer = jpegBufferSize;
  180350. dest.init_destination = jpegWriteInit;
  180351. dest.empty_output_buffer = jpegWriteFlush;
  180352. dest.term_destination = jpegWriteTerminate;
  180353. jpegCompStruct.image_width = image.getWidth();
  180354. jpegCompStruct.image_height = image.getHeight();
  180355. jpegCompStruct.input_components = 3;
  180356. jpegCompStruct.in_color_space = JCS_RGB;
  180357. jpegCompStruct.write_JFIF_header = 1;
  180358. jpegCompStruct.X_density = 72;
  180359. jpegCompStruct.Y_density = 72;
  180360. jpeg_set_defaults (&jpegCompStruct);
  180361. jpegCompStruct.dct_method = JDCT_FLOAT;
  180362. jpegCompStruct.optimize_coding = 1;
  180363. //jpegCompStruct.smoothing_factor = 10;
  180364. if (quality < 0.0f)
  180365. quality = 0.85f;
  180366. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180367. jpeg_start_compress (&jpegCompStruct, TRUE);
  180368. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180369. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180370. JPOOL_IMAGE, strideBytes, 1);
  180371. const Image::BitmapData srcData (image, false);
  180372. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180373. {
  180374. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180375. uint8* dst = *buffer;
  180376. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180377. {
  180378. *dst++ = ((const PixelRGB*) src)->getRed();
  180379. *dst++ = ((const PixelRGB*) src)->getGreen();
  180380. *dst++ = ((const PixelRGB*) src)->getBlue();
  180381. src += srcData.pixelStride;
  180382. }
  180383. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180384. }
  180385. jpeg_finish_compress (&jpegCompStruct);
  180386. jpeg_destroy_compress (&jpegCompStruct);
  180387. out.flush();
  180388. return true;
  180389. }
  180390. END_JUCE_NAMESPACE
  180391. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180392. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180393. #if JUCE_MSVC
  180394. #pragma warning (push)
  180395. #pragma warning (disable: 4390 4611)
  180396. #endif
  180397. namespace zlibNamespace
  180398. {
  180399. #if JUCE_INCLUDE_ZLIB_CODE
  180400. #undef OS_CODE
  180401. #undef fdopen
  180402. #undef OS_CODE
  180403. #else
  180404. #include <zlib.h>
  180405. #endif
  180406. }
  180407. namespace pnglibNamespace
  180408. {
  180409. using namespace zlibNamespace;
  180410. #if JUCE_INCLUDE_PNGLIB_CODE
  180411. #if _MSC_VER != 1310
  180412. using ::calloc; // (causes conflict in VS.NET 2003)
  180413. using ::malloc;
  180414. using ::free;
  180415. #endif
  180416. using ::abs;
  180417. #define PNG_INTERNAL
  180418. #define NO_DUMMY_DECL
  180419. #define PNG_SETJMP_NOT_SUPPORTED
  180420. /*** Start of inlined file: png.h ***/
  180421. /* png.h - header file for PNG reference library
  180422. *
  180423. * libpng version 1.2.21 - October 4, 2007
  180424. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180425. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180426. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180427. *
  180428. * Authors and maintainers:
  180429. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180430. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180431. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180432. * See also "Contributing Authors", below.
  180433. *
  180434. * Note about libpng version numbers:
  180435. *
  180436. * Due to various miscommunications, unforeseen code incompatibilities
  180437. * and occasional factors outside the authors' control, version numbering
  180438. * on the library has not always been consistent and straightforward.
  180439. * The following table summarizes matters since version 0.89c, which was
  180440. * the first widely used release:
  180441. *
  180442. * source png.h png.h shared-lib
  180443. * version string int version
  180444. * ------- ------ ----- ----------
  180445. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180446. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180447. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180448. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180449. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180450. * 0.97c 0.97 97 2.0.97
  180451. * 0.98 0.98 98 2.0.98
  180452. * 0.99 0.99 98 2.0.99
  180453. * 0.99a-m 0.99 99 2.0.99
  180454. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180455. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180456. * 1.0.1 png.h string is 10001 2.1.0
  180457. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180458. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180459. * 1.0.2a-b 10003 version, except as noted.
  180460. * 1.0.3 10003
  180461. * 1.0.3a-d 10004
  180462. * 1.0.4 10004
  180463. * 1.0.4a-f 10005
  180464. * 1.0.5 (+ 2 patches) 10005
  180465. * 1.0.5a-d 10006
  180466. * 1.0.5e-r 10100 (not source compatible)
  180467. * 1.0.5s-v 10006 (not binary compatible)
  180468. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180469. * 1.0.6d-f 10007 (still binary incompatible)
  180470. * 1.0.6g 10007
  180471. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180472. * 1.0.6i 10007 10.6i
  180473. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180474. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180475. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180476. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180477. * 1.0.7 1 10007 (still compatible)
  180478. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180479. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180480. * 1.0.8 1 10008 2.1.0.8
  180481. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180482. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180483. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180484. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180485. * 1.0.9 1 10009 2.1.0.9
  180486. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180487. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180488. * 1.0.10 1 10010 2.1.0.10
  180489. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180490. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180491. * 1.0.11 1 10011 2.1.0.11
  180492. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180493. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180494. * 1.0.12 2 10012 2.1.0.12
  180495. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180496. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180497. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180498. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180499. * 1.2.0 3 10200 3.1.2.0
  180500. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180501. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180502. * 1.2.1 3 10201 3.1.2.1
  180503. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180504. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180505. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180506. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180507. * 1.0.13 10 10013 10.so.0.1.0.13
  180508. * 1.2.2 12 10202 12.so.0.1.2.2
  180509. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180510. * 1.2.3 12 10203 12.so.0.1.2.3
  180511. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180512. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180513. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180514. * 1.0.14 10 10014 10.so.0.1.0.14
  180515. * 1.2.4 13 10204 12.so.0.1.2.4
  180516. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180517. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180518. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180519. * 1.0.15 10 10015 10.so.0.1.0.15
  180520. * 1.2.5 13 10205 12.so.0.1.2.5
  180521. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180522. * 1.0.16 10 10016 10.so.0.1.0.16
  180523. * 1.2.6 13 10206 12.so.0.1.2.6
  180524. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180525. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180526. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180527. * 1.0.17 10 10017 10.so.0.1.0.17
  180528. * 1.2.7 13 10207 12.so.0.1.2.7
  180529. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180530. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180531. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180532. * 1.0.18 10 10018 10.so.0.1.0.18
  180533. * 1.2.8 13 10208 12.so.0.1.2.8
  180534. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180535. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180536. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180537. * 1.2.9 13 10209 12.so.0.9[.0]
  180538. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180539. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180540. * 1.2.10 13 10210 12.so.0.10[.0]
  180541. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180542. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180543. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180544. * 1.0.19 10 10019 10.so.0.19[.0]
  180545. * 1.2.11 13 10211 12.so.0.11[.0]
  180546. * 1.0.20 10 10020 10.so.0.20[.0]
  180547. * 1.2.12 13 10212 12.so.0.12[.0]
  180548. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180549. * 1.0.21 10 10021 10.so.0.21[.0]
  180550. * 1.2.13 13 10213 12.so.0.13[.0]
  180551. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180552. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180553. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180554. * 1.0.22 10 10022 10.so.0.22[.0]
  180555. * 1.2.14 13 10214 12.so.0.14[.0]
  180556. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180557. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180558. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180559. * 1.0.23 10 10023 10.so.0.23[.0]
  180560. * 1.2.15 13 10215 12.so.0.15[.0]
  180561. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180562. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180563. * 1.0.24 10 10024 10.so.0.24[.0]
  180564. * 1.2.16 13 10216 12.so.0.16[.0]
  180565. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180566. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180567. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180568. * 1.0.25 10 10025 10.so.0.25[.0]
  180569. * 1.2.17 13 10217 12.so.0.17[.0]
  180570. * 1.0.26 10 10026 10.so.0.26[.0]
  180571. * 1.2.18 13 10218 12.so.0.18[.0]
  180572. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180573. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180574. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180575. * 1.0.27 10 10027 10.so.0.27[.0]
  180576. * 1.2.19 13 10219 12.so.0.19[.0]
  180577. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180578. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180579. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180580. * 1.0.28 10 10028 10.so.0.28[.0]
  180581. * 1.2.20 13 10220 12.so.0.20[.0]
  180582. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180583. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180584. * 1.0.29 10 10029 10.so.0.29[.0]
  180585. * 1.2.21 13 10221 12.so.0.21[.0]
  180586. *
  180587. * Henceforth the source version will match the shared-library major
  180588. * and minor numbers; the shared-library major version number will be
  180589. * used for changes in backward compatibility, as it is intended. The
  180590. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180591. * for applications, is an unsigned integer of the form xyyzz corresponding
  180592. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180593. * were given the previous public release number plus a letter, until
  180594. * version 1.0.6j; from then on they were given the upcoming public
  180595. * release number plus "betaNN" or "rcN".
  180596. *
  180597. * Binary incompatibility exists only when applications make direct access
  180598. * to the info_ptr or png_ptr members through png.h, and the compiled
  180599. * application is loaded with a different version of the library.
  180600. *
  180601. * DLLNUM will change each time there are forward or backward changes
  180602. * in binary compatibility (e.g., when a new feature is added).
  180603. *
  180604. * See libpng.txt or libpng.3 for more information. The PNG specification
  180605. * is available as a W3C Recommendation and as an ISO Specification,
  180606. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180607. */
  180608. /*
  180609. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180610. *
  180611. * If you modify libpng you may insert additional notices immediately following
  180612. * this sentence.
  180613. *
  180614. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180615. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180616. * distributed according to the same disclaimer and license as libpng-1.2.5
  180617. * with the following individual added to the list of Contributing Authors:
  180618. *
  180619. * Cosmin Truta
  180620. *
  180621. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180622. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180623. * distributed according to the same disclaimer and license as libpng-1.0.6
  180624. * with the following individuals added to the list of Contributing Authors:
  180625. *
  180626. * Simon-Pierre Cadieux
  180627. * Eric S. Raymond
  180628. * Gilles Vollant
  180629. *
  180630. * and with the following additions to the disclaimer:
  180631. *
  180632. * There is no warranty against interference with your enjoyment of the
  180633. * library or against infringement. There is no warranty that our
  180634. * efforts or the library will fulfill any of your particular purposes
  180635. * or needs. This library is provided with all faults, and the entire
  180636. * risk of satisfactory quality, performance, accuracy, and effort is with
  180637. * the user.
  180638. *
  180639. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180640. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180641. * distributed according to the same disclaimer and license as libpng-0.96,
  180642. * with the following individuals added to the list of Contributing Authors:
  180643. *
  180644. * Tom Lane
  180645. * Glenn Randers-Pehrson
  180646. * Willem van Schaik
  180647. *
  180648. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180649. * Copyright (c) 1996, 1997 Andreas Dilger
  180650. * Distributed according to the same disclaimer and license as libpng-0.88,
  180651. * with the following individuals added to the list of Contributing Authors:
  180652. *
  180653. * John Bowler
  180654. * Kevin Bracey
  180655. * Sam Bushell
  180656. * Magnus Holmgren
  180657. * Greg Roelofs
  180658. * Tom Tanner
  180659. *
  180660. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180661. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180662. *
  180663. * For the purposes of this copyright and license, "Contributing Authors"
  180664. * is defined as the following set of individuals:
  180665. *
  180666. * Andreas Dilger
  180667. * Dave Martindale
  180668. * Guy Eric Schalnat
  180669. * Paul Schmidt
  180670. * Tim Wegner
  180671. *
  180672. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180673. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180674. * including, without limitation, the warranties of merchantability and of
  180675. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180676. * assume no liability for direct, indirect, incidental, special, exemplary,
  180677. * or consequential damages, which may result from the use of the PNG
  180678. * Reference Library, even if advised of the possibility of such damage.
  180679. *
  180680. * Permission is hereby granted to use, copy, modify, and distribute this
  180681. * source code, or portions hereof, for any purpose, without fee, subject
  180682. * to the following restrictions:
  180683. *
  180684. * 1. The origin of this source code must not be misrepresented.
  180685. *
  180686. * 2. Altered versions must be plainly marked as such and
  180687. * must not be misrepresented as being the original source.
  180688. *
  180689. * 3. This Copyright notice may not be removed or altered from
  180690. * any source or altered source distribution.
  180691. *
  180692. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180693. * fee, and encourage the use of this source code as a component to
  180694. * supporting the PNG file format in commercial products. If you use this
  180695. * source code in a product, acknowledgment is not required but would be
  180696. * appreciated.
  180697. */
  180698. /*
  180699. * A "png_get_copyright" function is available, for convenient use in "about"
  180700. * boxes and the like:
  180701. *
  180702. * printf("%s",png_get_copyright(NULL));
  180703. *
  180704. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180705. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180706. */
  180707. /*
  180708. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180709. * certification mark of the Open Source Initiative.
  180710. */
  180711. /*
  180712. * The contributing authors would like to thank all those who helped
  180713. * with testing, bug fixes, and patience. This wouldn't have been
  180714. * possible without all of you.
  180715. *
  180716. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180717. */
  180718. /*
  180719. * Y2K compliance in libpng:
  180720. * =========================
  180721. *
  180722. * October 4, 2007
  180723. *
  180724. * Since the PNG Development group is an ad-hoc body, we can't make
  180725. * an official declaration.
  180726. *
  180727. * This is your unofficial assurance that libpng from version 0.71 and
  180728. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180729. * versions were also Y2K compliant.
  180730. *
  180731. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180732. * that will hold years up to 65535. The other two hold the date in text
  180733. * format, and will hold years up to 9999.
  180734. *
  180735. * The integer is
  180736. * "png_uint_16 year" in png_time_struct.
  180737. *
  180738. * The strings are
  180739. * "png_charp time_buffer" in png_struct and
  180740. * "near_time_buffer", which is a local character string in png.c.
  180741. *
  180742. * There are seven time-related functions:
  180743. * png.c: png_convert_to_rfc_1123() in png.c
  180744. * (formerly png_convert_to_rfc_1152() in error)
  180745. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180746. * png_convert_from_time_t() in pngwrite.c
  180747. * png_get_tIME() in pngget.c
  180748. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180749. * png_set_tIME() in pngset.c
  180750. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180751. *
  180752. * All handle dates properly in a Y2K environment. The
  180753. * png_convert_from_time_t() function calls gmtime() to convert from system
  180754. * clock time, which returns (year - 1900), which we properly convert to
  180755. * the full 4-digit year. There is a possibility that applications using
  180756. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180757. * function, or that they are incorrectly passing only a 2-digit year
  180758. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180759. * but this is not under our control. The libpng documentation has always
  180760. * stated that it works with 4-digit years, and the APIs have been
  180761. * documented as such.
  180762. *
  180763. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180764. * integer to hold the year, and can hold years as large as 65535.
  180765. *
  180766. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180767. * no date-related code.
  180768. *
  180769. * Glenn Randers-Pehrson
  180770. * libpng maintainer
  180771. * PNG Development Group
  180772. */
  180773. #ifndef PNG_H
  180774. #define PNG_H
  180775. /* This is not the place to learn how to use libpng. The file libpng.txt
  180776. * describes how to use libpng, and the file example.c summarizes it
  180777. * with some code on which to build. This file is useful for looking
  180778. * at the actual function definitions and structure components.
  180779. */
  180780. /* Version information for png.h - this should match the version in png.c */
  180781. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180782. #define PNG_HEADER_VERSION_STRING \
  180783. " libpng version 1.2.21 - October 4, 2007\n"
  180784. #define PNG_LIBPNG_VER_SONUM 0
  180785. #define PNG_LIBPNG_VER_DLLNUM 13
  180786. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180787. #define PNG_LIBPNG_VER_MAJOR 1
  180788. #define PNG_LIBPNG_VER_MINOR 2
  180789. #define PNG_LIBPNG_VER_RELEASE 21
  180790. /* This should match the numeric part of the final component of
  180791. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180792. #define PNG_LIBPNG_VER_BUILD 0
  180793. /* Release Status */
  180794. #define PNG_LIBPNG_BUILD_ALPHA 1
  180795. #define PNG_LIBPNG_BUILD_BETA 2
  180796. #define PNG_LIBPNG_BUILD_RC 3
  180797. #define PNG_LIBPNG_BUILD_STABLE 4
  180798. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180799. /* Release-Specific Flags */
  180800. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180801. PNG_LIBPNG_BUILD_STABLE only */
  180802. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180803. PNG_LIBPNG_BUILD_SPECIAL */
  180804. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180805. PNG_LIBPNG_BUILD_PRIVATE */
  180806. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180807. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180808. * We must not include leading zeros.
  180809. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180810. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180811. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180812. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180813. #ifndef PNG_VERSION_INFO_ONLY
  180814. /* include the compression library's header */
  180815. #endif
  180816. /* include all user configurable info, including optional assembler routines */
  180817. /*** Start of inlined file: pngconf.h ***/
  180818. /* pngconf.h - machine configurable file for libpng
  180819. *
  180820. * libpng version 1.2.21 - October 4, 2007
  180821. * For conditions of distribution and use, see copyright notice in png.h
  180822. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180823. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180824. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180825. */
  180826. /* Any machine specific code is near the front of this file, so if you
  180827. * are configuring libpng for a machine, you may want to read the section
  180828. * starting here down to where it starts to typedef png_color, png_text,
  180829. * and png_info.
  180830. */
  180831. #ifndef PNGCONF_H
  180832. #define PNGCONF_H
  180833. #define PNG_1_2_X
  180834. // These are some Juce config settings that should remove any unnecessary code bloat..
  180835. #define PNG_NO_STDIO 1
  180836. #define PNG_DEBUG 0
  180837. #define PNG_NO_WARNINGS 1
  180838. #define PNG_NO_ERROR_TEXT 1
  180839. #define PNG_NO_ERROR_NUMBERS 1
  180840. #define PNG_NO_USER_MEM 1
  180841. #define PNG_NO_READ_iCCP 1
  180842. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180843. #define PNG_NO_READ_USER_CHUNKS 1
  180844. #define PNG_NO_READ_iTXt 1
  180845. #define PNG_NO_READ_sCAL 1
  180846. #define PNG_NO_READ_sPLT 1
  180847. #define png_error(a, b) png_err(a)
  180848. #define png_warning(a, b)
  180849. #define png_chunk_error(a, b) png_err(a)
  180850. #define png_chunk_warning(a, b)
  180851. /*
  180852. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180853. * includes the resource compiler for Windows DLL configurations.
  180854. */
  180855. #ifdef PNG_USER_CONFIG
  180856. # ifndef PNG_USER_PRIVATEBUILD
  180857. # define PNG_USER_PRIVATEBUILD
  180858. # endif
  180859. #include "pngusr.h"
  180860. #endif
  180861. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180862. #ifdef PNG_CONFIGURE_LIBPNG
  180863. #ifdef HAVE_CONFIG_H
  180864. #include "config.h"
  180865. #endif
  180866. #endif
  180867. /*
  180868. * Added at libpng-1.2.8
  180869. *
  180870. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180871. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180872. * the DLL was built>
  180873. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180874. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180875. * distinguish your DLL from those of the official release. These
  180876. * correspond to the trailing letters that come after the version
  180877. * number and must match your private DLL name>
  180878. * e.g. // private DLL "libpng13gx.dll"
  180879. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180880. *
  180881. * The following macros are also at your disposal if you want to complete the
  180882. * DLL VERSIONINFO structure.
  180883. * - PNG_USER_VERSIONINFO_COMMENTS
  180884. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180885. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180886. */
  180887. #ifdef __STDC__
  180888. #ifdef SPECIALBUILD
  180889. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180890. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180891. #endif
  180892. #ifdef PRIVATEBUILD
  180893. # pragma message("PRIVATEBUILD is deprecated.\
  180894. Use PNG_USER_PRIVATEBUILD instead.")
  180895. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180896. #endif
  180897. #endif /* __STDC__ */
  180898. #ifndef PNG_VERSION_INFO_ONLY
  180899. /* End of material added to libpng-1.2.8 */
  180900. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180901. Restored at libpng-1.2.21 */
  180902. # define PNG_WARN_UNINITIALIZED_ROW 1
  180903. /* End of material added at libpng-1.2.19/1.2.21 */
  180904. /* This is the size of the compression buffer, and thus the size of
  180905. * an IDAT chunk. Make this whatever size you feel is best for your
  180906. * machine. One of these will be allocated per png_struct. When this
  180907. * is full, it writes the data to the disk, and does some other
  180908. * calculations. Making this an extremely small size will slow
  180909. * the library down, but you may want to experiment to determine
  180910. * where it becomes significant, if you are concerned with memory
  180911. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180912. * this describes the size of the buffer available to read the data in.
  180913. * Unless this gets smaller than the size of a row (compressed),
  180914. * it should not make much difference how big this is.
  180915. */
  180916. #ifndef PNG_ZBUF_SIZE
  180917. # define PNG_ZBUF_SIZE 8192
  180918. #endif
  180919. /* Enable if you want a write-only libpng */
  180920. #ifndef PNG_NO_READ_SUPPORTED
  180921. # define PNG_READ_SUPPORTED
  180922. #endif
  180923. /* Enable if you want a read-only libpng */
  180924. #ifndef PNG_NO_WRITE_SUPPORTED
  180925. # define PNG_WRITE_SUPPORTED
  180926. #endif
  180927. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180928. support PNGs that are embedded in MNG datastreams */
  180929. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180930. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180931. # define PNG_MNG_FEATURES_SUPPORTED
  180932. # endif
  180933. #endif
  180934. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180935. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180936. # define PNG_FLOATING_POINT_SUPPORTED
  180937. # endif
  180938. #endif
  180939. /* If you are running on a machine where you cannot allocate more
  180940. * than 64K of memory at once, uncomment this. While libpng will not
  180941. * normally need that much memory in a chunk (unless you load up a very
  180942. * large file), zlib needs to know how big of a chunk it can use, and
  180943. * libpng thus makes sure to check any memory allocation to verify it
  180944. * will fit into memory.
  180945. #define PNG_MAX_MALLOC_64K
  180946. */
  180947. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180948. # define PNG_MAX_MALLOC_64K
  180949. #endif
  180950. /* Special munging to support doing things the 'cygwin' way:
  180951. * 'Normal' png-on-win32 defines/defaults:
  180952. * PNG_BUILD_DLL -- building dll
  180953. * PNG_USE_DLL -- building an application, linking to dll
  180954. * (no define) -- building static library, or building an
  180955. * application and linking to the static lib
  180956. * 'Cygwin' defines/defaults:
  180957. * PNG_BUILD_DLL -- (ignored) building the dll
  180958. * (no define) -- (ignored) building an application, linking to the dll
  180959. * PNG_STATIC -- (ignored) building the static lib, or building an
  180960. * application that links to the static lib.
  180961. * ALL_STATIC -- (ignored) building various static libs, or building an
  180962. * application that links to the static libs.
  180963. * Thus,
  180964. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180965. * this bit of #ifdefs will define the 'correct' config variables based on
  180966. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180967. * unnecessary.
  180968. *
  180969. * Also, the precedence order is:
  180970. * ALL_STATIC (since we can't #undef something outside our namespace)
  180971. * PNG_BUILD_DLL
  180972. * PNG_STATIC
  180973. * (nothing) == PNG_USE_DLL
  180974. *
  180975. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180976. * of auto-import in binutils, we no longer need to worry about
  180977. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180978. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180979. * to __declspec() stuff. However, we DO need to worry about
  180980. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180981. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180982. */
  180983. #if defined(__CYGWIN__)
  180984. # if defined(ALL_STATIC)
  180985. # if defined(PNG_BUILD_DLL)
  180986. # undef PNG_BUILD_DLL
  180987. # endif
  180988. # if defined(PNG_USE_DLL)
  180989. # undef PNG_USE_DLL
  180990. # endif
  180991. # if defined(PNG_DLL)
  180992. # undef PNG_DLL
  180993. # endif
  180994. # if !defined(PNG_STATIC)
  180995. # define PNG_STATIC
  180996. # endif
  180997. # else
  180998. # if defined (PNG_BUILD_DLL)
  180999. # if defined(PNG_STATIC)
  181000. # undef PNG_STATIC
  181001. # endif
  181002. # if defined(PNG_USE_DLL)
  181003. # undef PNG_USE_DLL
  181004. # endif
  181005. # if !defined(PNG_DLL)
  181006. # define PNG_DLL
  181007. # endif
  181008. # else
  181009. # if defined(PNG_STATIC)
  181010. # if defined(PNG_USE_DLL)
  181011. # undef PNG_USE_DLL
  181012. # endif
  181013. # if defined(PNG_DLL)
  181014. # undef PNG_DLL
  181015. # endif
  181016. # else
  181017. # if !defined(PNG_USE_DLL)
  181018. # define PNG_USE_DLL
  181019. # endif
  181020. # if !defined(PNG_DLL)
  181021. # define PNG_DLL
  181022. # endif
  181023. # endif
  181024. # endif
  181025. # endif
  181026. #endif
  181027. /* This protects us against compilers that run on a windowing system
  181028. * and thus don't have or would rather us not use the stdio types:
  181029. * stdin, stdout, and stderr. The only one currently used is stderr
  181030. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181031. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181032. * will also prevent these, plus will prevent the entire set of stdio
  181033. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181034. * unless (PNG_DEBUG > 0) has been #defined.
  181035. *
  181036. * #define PNG_NO_CONSOLE_IO
  181037. * #define PNG_NO_STDIO
  181038. */
  181039. #if defined(_WIN32_WCE)
  181040. # include <windows.h>
  181041. /* Console I/O functions are not supported on WindowsCE */
  181042. # define PNG_NO_CONSOLE_IO
  181043. # ifdef PNG_DEBUG
  181044. # undef PNG_DEBUG
  181045. # endif
  181046. #endif
  181047. #ifdef PNG_BUILD_DLL
  181048. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181049. # ifndef PNG_NO_CONSOLE_IO
  181050. # define PNG_NO_CONSOLE_IO
  181051. # endif
  181052. # endif
  181053. #endif
  181054. # ifdef PNG_NO_STDIO
  181055. # ifndef PNG_NO_CONSOLE_IO
  181056. # define PNG_NO_CONSOLE_IO
  181057. # endif
  181058. # ifdef PNG_DEBUG
  181059. # if (PNG_DEBUG > 0)
  181060. # include <stdio.h>
  181061. # endif
  181062. # endif
  181063. # else
  181064. # if !defined(_WIN32_WCE)
  181065. /* "stdio.h" functions are not supported on WindowsCE */
  181066. # include <stdio.h>
  181067. # endif
  181068. # endif
  181069. /* This macro protects us against machines that don't have function
  181070. * prototypes (ie K&R style headers). If your compiler does not handle
  181071. * function prototypes, define this macro and use the included ansi2knr.
  181072. * I've always been able to use _NO_PROTO as the indicator, but you may
  181073. * need to drag the empty declaration out in front of here, or change the
  181074. * ifdef to suit your own needs.
  181075. */
  181076. #ifndef PNGARG
  181077. #ifdef OF /* zlib prototype munger */
  181078. # define PNGARG(arglist) OF(arglist)
  181079. #else
  181080. #ifdef _NO_PROTO
  181081. # define PNGARG(arglist) ()
  181082. # ifndef PNG_TYPECAST_NULL
  181083. # define PNG_TYPECAST_NULL
  181084. # endif
  181085. #else
  181086. # define PNGARG(arglist) arglist
  181087. #endif /* _NO_PROTO */
  181088. #endif /* OF */
  181089. #endif /* PNGARG */
  181090. /* Try to determine if we are compiling on a Mac. Note that testing for
  181091. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181092. * on non-Mac platforms.
  181093. */
  181094. #ifndef MACOS
  181095. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181096. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181097. # define MACOS
  181098. # endif
  181099. #endif
  181100. /* enough people need this for various reasons to include it here */
  181101. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181102. # include <sys/types.h>
  181103. #endif
  181104. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181105. # define PNG_SETJMP_SUPPORTED
  181106. #endif
  181107. #ifdef PNG_SETJMP_SUPPORTED
  181108. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181109. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181110. */
  181111. # ifdef __linux__
  181112. # ifdef _BSD_SOURCE
  181113. # define PNG_SAVE_BSD_SOURCE
  181114. # undef _BSD_SOURCE
  181115. # endif
  181116. # ifdef _SETJMP_H
  181117. /* If you encounter a compiler error here, see the explanation
  181118. * near the end of INSTALL.
  181119. */
  181120. __png.h__ already includes setjmp.h;
  181121. __dont__ include it again.;
  181122. # endif
  181123. # endif /* __linux__ */
  181124. /* include setjmp.h for error handling */
  181125. # include <setjmp.h>
  181126. # ifdef __linux__
  181127. # ifdef PNG_SAVE_BSD_SOURCE
  181128. # define _BSD_SOURCE
  181129. # undef PNG_SAVE_BSD_SOURCE
  181130. # endif
  181131. # endif /* __linux__ */
  181132. #endif /* PNG_SETJMP_SUPPORTED */
  181133. #ifdef BSD
  181134. #if ! JUCE_MAC
  181135. # include <strings.h>
  181136. #endif
  181137. #else
  181138. # include <string.h>
  181139. #endif
  181140. /* Other defines for things like memory and the like can go here. */
  181141. #ifdef PNG_INTERNAL
  181142. #include <stdlib.h>
  181143. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181144. * aren't usually used outside the library (as far as I know), so it is
  181145. * debatable if they should be exported at all. In the future, when it is
  181146. * possible to have run-time registry of chunk-handling functions, some of
  181147. * these will be made available again.
  181148. #define PNG_EXTERN extern
  181149. */
  181150. #define PNG_EXTERN
  181151. /* Other defines specific to compilers can go here. Try to keep
  181152. * them inside an appropriate ifdef/endif pair for portability.
  181153. */
  181154. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181155. # if defined(MACOS)
  181156. /* We need to check that <math.h> hasn't already been included earlier
  181157. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181158. * <fp.h> if possible.
  181159. */
  181160. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181161. # include <fp.h>
  181162. # endif
  181163. # else
  181164. # include <math.h>
  181165. # endif
  181166. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181167. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181168. * MATH=68881
  181169. */
  181170. # include <m68881.h>
  181171. # endif
  181172. #endif
  181173. /* Codewarrior on NT has linking problems without this. */
  181174. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181175. # define PNG_ALWAYS_EXTERN
  181176. #endif
  181177. /* This provides the non-ANSI (far) memory allocation routines. */
  181178. #if defined(__TURBOC__) && defined(__MSDOS__)
  181179. # include <mem.h>
  181180. # include <alloc.h>
  181181. #endif
  181182. /* I have no idea why is this necessary... */
  181183. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181184. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181185. # include <malloc.h>
  181186. #endif
  181187. /* This controls how fine the dithering gets. As this allocates
  181188. * a largish chunk of memory (32K), those who are not as concerned
  181189. * with dithering quality can decrease some or all of these.
  181190. */
  181191. #ifndef PNG_DITHER_RED_BITS
  181192. # define PNG_DITHER_RED_BITS 5
  181193. #endif
  181194. #ifndef PNG_DITHER_GREEN_BITS
  181195. # define PNG_DITHER_GREEN_BITS 5
  181196. #endif
  181197. #ifndef PNG_DITHER_BLUE_BITS
  181198. # define PNG_DITHER_BLUE_BITS 5
  181199. #endif
  181200. /* This controls how fine the gamma correction becomes when you
  181201. * are only interested in 8 bits anyway. Increasing this value
  181202. * results in more memory being used, and more pow() functions
  181203. * being called to fill in the gamma tables. Don't set this value
  181204. * less then 8, and even that may not work (I haven't tested it).
  181205. */
  181206. #ifndef PNG_MAX_GAMMA_8
  181207. # define PNG_MAX_GAMMA_8 11
  181208. #endif
  181209. /* This controls how much a difference in gamma we can tolerate before
  181210. * we actually start doing gamma conversion.
  181211. */
  181212. #ifndef PNG_GAMMA_THRESHOLD
  181213. # define PNG_GAMMA_THRESHOLD 0.05
  181214. #endif
  181215. #endif /* PNG_INTERNAL */
  181216. /* The following uses const char * instead of char * for error
  181217. * and warning message functions, so some compilers won't complain.
  181218. * If you do not want to use const, define PNG_NO_CONST here.
  181219. */
  181220. #ifndef PNG_NO_CONST
  181221. # define PNG_CONST const
  181222. #else
  181223. # define PNG_CONST
  181224. #endif
  181225. /* The following defines give you the ability to remove code from the
  181226. * library that you will not be using. I wish I could figure out how to
  181227. * automate this, but I can't do that without making it seriously hard
  181228. * on the users. So if you are not using an ability, change the #define
  181229. * to and #undef, and that part of the library will not be compiled. If
  181230. * your linker can't find a function, you may want to make sure the
  181231. * ability is defined here. Some of these depend upon some others being
  181232. * defined. I haven't figured out all the interactions here, so you may
  181233. * have to experiment awhile to get everything to compile. If you are
  181234. * creating or using a shared library, you probably shouldn't touch this,
  181235. * as it will affect the size of the structures, and this will cause bad
  181236. * things to happen if the library and/or application ever change.
  181237. */
  181238. /* Any features you will not be using can be undef'ed here */
  181239. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181240. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181241. * on the compile line, then pick and choose which ones to define without
  181242. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181243. * if you only want to have a png-compliant reader/writer but don't need
  181244. * any of the extra transformations. This saves about 80 kbytes in a
  181245. * typical installation of the library. (PNG_NO_* form added in version
  181246. * 1.0.1c, for consistency)
  181247. */
  181248. /* The size of the png_text structure changed in libpng-1.0.6 when
  181249. * iTXt support was added. iTXt support was turned off by default through
  181250. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181251. * instead of calling png_set_text() and letting libpng malloc it. It
  181252. * was turned on by default in libpng-1.3.0.
  181253. */
  181254. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181255. # ifndef PNG_NO_iTXt_SUPPORTED
  181256. # define PNG_NO_iTXt_SUPPORTED
  181257. # endif
  181258. # ifndef PNG_NO_READ_iTXt
  181259. # define PNG_NO_READ_iTXt
  181260. # endif
  181261. # ifndef PNG_NO_WRITE_iTXt
  181262. # define PNG_NO_WRITE_iTXt
  181263. # endif
  181264. #endif
  181265. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181266. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181267. # define PNG_READ_iTXt
  181268. # endif
  181269. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181270. # define PNG_WRITE_iTXt
  181271. # endif
  181272. #endif
  181273. /* The following support, added after version 1.0.0, can be turned off here en
  181274. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181275. * with old applications that require the length of png_struct and png_info
  181276. * to remain unchanged.
  181277. */
  181278. #ifdef PNG_LEGACY_SUPPORTED
  181279. # define PNG_NO_FREE_ME
  181280. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181281. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181282. # define PNG_NO_READ_USER_CHUNKS
  181283. # define PNG_NO_READ_iCCP
  181284. # define PNG_NO_WRITE_iCCP
  181285. # define PNG_NO_READ_iTXt
  181286. # define PNG_NO_WRITE_iTXt
  181287. # define PNG_NO_READ_sCAL
  181288. # define PNG_NO_WRITE_sCAL
  181289. # define PNG_NO_READ_sPLT
  181290. # define PNG_NO_WRITE_sPLT
  181291. # define PNG_NO_INFO_IMAGE
  181292. # define PNG_NO_READ_RGB_TO_GRAY
  181293. # define PNG_NO_READ_USER_TRANSFORM
  181294. # define PNG_NO_WRITE_USER_TRANSFORM
  181295. # define PNG_NO_USER_MEM
  181296. # define PNG_NO_READ_EMPTY_PLTE
  181297. # define PNG_NO_MNG_FEATURES
  181298. # define PNG_NO_FIXED_POINT_SUPPORTED
  181299. #endif
  181300. /* Ignore attempt to turn off both floating and fixed point support */
  181301. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181302. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181303. # define PNG_FIXED_POINT_SUPPORTED
  181304. #endif
  181305. #ifndef PNG_NO_FREE_ME
  181306. # define PNG_FREE_ME_SUPPORTED
  181307. #endif
  181308. #if defined(PNG_READ_SUPPORTED)
  181309. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181310. !defined(PNG_NO_READ_TRANSFORMS)
  181311. # define PNG_READ_TRANSFORMS_SUPPORTED
  181312. #endif
  181313. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181314. # ifndef PNG_NO_READ_EXPAND
  181315. # define PNG_READ_EXPAND_SUPPORTED
  181316. # endif
  181317. # ifndef PNG_NO_READ_SHIFT
  181318. # define PNG_READ_SHIFT_SUPPORTED
  181319. # endif
  181320. # ifndef PNG_NO_READ_PACK
  181321. # define PNG_READ_PACK_SUPPORTED
  181322. # endif
  181323. # ifndef PNG_NO_READ_BGR
  181324. # define PNG_READ_BGR_SUPPORTED
  181325. # endif
  181326. # ifndef PNG_NO_READ_SWAP
  181327. # define PNG_READ_SWAP_SUPPORTED
  181328. # endif
  181329. # ifndef PNG_NO_READ_PACKSWAP
  181330. # define PNG_READ_PACKSWAP_SUPPORTED
  181331. # endif
  181332. # ifndef PNG_NO_READ_INVERT
  181333. # define PNG_READ_INVERT_SUPPORTED
  181334. # endif
  181335. # ifndef PNG_NO_READ_DITHER
  181336. # define PNG_READ_DITHER_SUPPORTED
  181337. # endif
  181338. # ifndef PNG_NO_READ_BACKGROUND
  181339. # define PNG_READ_BACKGROUND_SUPPORTED
  181340. # endif
  181341. # ifndef PNG_NO_READ_16_TO_8
  181342. # define PNG_READ_16_TO_8_SUPPORTED
  181343. # endif
  181344. # ifndef PNG_NO_READ_FILLER
  181345. # define PNG_READ_FILLER_SUPPORTED
  181346. # endif
  181347. # ifndef PNG_NO_READ_GAMMA
  181348. # define PNG_READ_GAMMA_SUPPORTED
  181349. # endif
  181350. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181351. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181352. # endif
  181353. # ifndef PNG_NO_READ_SWAP_ALPHA
  181354. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181355. # endif
  181356. # ifndef PNG_NO_READ_INVERT_ALPHA
  181357. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181358. # endif
  181359. # ifndef PNG_NO_READ_STRIP_ALPHA
  181360. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181361. # endif
  181362. # ifndef PNG_NO_READ_USER_TRANSFORM
  181363. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181364. # endif
  181365. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181366. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181367. # endif
  181368. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181369. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181370. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181371. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181372. #endif /* about interlacing capability! You'll */
  181373. /* still have interlacing unless you change the following line: */
  181374. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181375. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181376. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181377. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181378. # endif
  181379. #endif
  181380. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181381. /* Deprecated, will be removed from version 2.0.0.
  181382. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181383. #ifndef PNG_NO_READ_EMPTY_PLTE
  181384. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181385. #endif
  181386. #endif
  181387. #endif /* PNG_READ_SUPPORTED */
  181388. #if defined(PNG_WRITE_SUPPORTED)
  181389. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181390. !defined(PNG_NO_WRITE_TRANSFORMS)
  181391. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181392. #endif
  181393. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181394. # ifndef PNG_NO_WRITE_SHIFT
  181395. # define PNG_WRITE_SHIFT_SUPPORTED
  181396. # endif
  181397. # ifndef PNG_NO_WRITE_PACK
  181398. # define PNG_WRITE_PACK_SUPPORTED
  181399. # endif
  181400. # ifndef PNG_NO_WRITE_BGR
  181401. # define PNG_WRITE_BGR_SUPPORTED
  181402. # endif
  181403. # ifndef PNG_NO_WRITE_SWAP
  181404. # define PNG_WRITE_SWAP_SUPPORTED
  181405. # endif
  181406. # ifndef PNG_NO_WRITE_PACKSWAP
  181407. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181408. # endif
  181409. # ifndef PNG_NO_WRITE_INVERT
  181410. # define PNG_WRITE_INVERT_SUPPORTED
  181411. # endif
  181412. # ifndef PNG_NO_WRITE_FILLER
  181413. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181414. # endif
  181415. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181416. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181417. # endif
  181418. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181419. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181420. # endif
  181421. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181422. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181423. # endif
  181424. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181425. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181426. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181427. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181428. encoders, but can cause trouble
  181429. if left undefined */
  181430. #endif
  181431. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181432. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181433. defined(PNG_FLOATING_POINT_SUPPORTED)
  181434. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181435. #endif
  181436. #ifndef PNG_NO_WRITE_FLUSH
  181437. # define PNG_WRITE_FLUSH_SUPPORTED
  181438. #endif
  181439. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181440. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181441. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181442. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181443. #endif
  181444. #endif
  181445. #endif /* PNG_WRITE_SUPPORTED */
  181446. #ifndef PNG_1_0_X
  181447. # ifndef PNG_NO_ERROR_NUMBERS
  181448. # define PNG_ERROR_NUMBERS_SUPPORTED
  181449. # endif
  181450. #endif /* PNG_1_0_X */
  181451. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181452. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181453. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181454. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181455. # endif
  181456. #endif
  181457. #ifndef PNG_NO_STDIO
  181458. # define PNG_TIME_RFC1123_SUPPORTED
  181459. #endif
  181460. /* This adds extra functions in pngget.c for accessing data from the
  181461. * info pointer (added in version 0.99)
  181462. * png_get_image_width()
  181463. * png_get_image_height()
  181464. * png_get_bit_depth()
  181465. * png_get_color_type()
  181466. * png_get_compression_type()
  181467. * png_get_filter_type()
  181468. * png_get_interlace_type()
  181469. * png_get_pixel_aspect_ratio()
  181470. * png_get_pixels_per_meter()
  181471. * png_get_x_offset_pixels()
  181472. * png_get_y_offset_pixels()
  181473. * png_get_x_offset_microns()
  181474. * png_get_y_offset_microns()
  181475. */
  181476. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181477. # define PNG_EASY_ACCESS_SUPPORTED
  181478. #endif
  181479. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181480. * and removed from version 1.2.20. The following will be removed
  181481. * from libpng-1.4.0
  181482. */
  181483. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181484. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181485. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181486. # endif
  181487. #endif
  181488. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181489. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181490. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181491. # endif
  181492. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181493. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181494. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181495. # define PNG_NO_MMX_CODE
  181496. # endif
  181497. # endif
  181498. # if defined(__APPLE__)
  181499. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181500. # define PNG_NO_MMX_CODE
  181501. # endif
  181502. # endif
  181503. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181504. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181505. # define PNG_NO_MMX_CODE
  181506. # endif
  181507. # endif
  181508. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181509. # define PNG_MMX_CODE_SUPPORTED
  181510. # endif
  181511. #endif
  181512. /* end of obsolete code to be removed from libpng-1.4.0 */
  181513. #if !defined(PNG_1_0_X)
  181514. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181515. # define PNG_USER_MEM_SUPPORTED
  181516. #endif
  181517. #endif /* PNG_1_0_X */
  181518. /* Added at libpng-1.2.6 */
  181519. #if !defined(PNG_1_0_X)
  181520. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181521. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181522. # define PNG_SET_USER_LIMITS_SUPPORTED
  181523. #endif
  181524. #endif
  181525. #endif /* PNG_1_0_X */
  181526. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181527. * how large, set these limits to 0x7fffffffL
  181528. */
  181529. #ifndef PNG_USER_WIDTH_MAX
  181530. # define PNG_USER_WIDTH_MAX 1000000L
  181531. #endif
  181532. #ifndef PNG_USER_HEIGHT_MAX
  181533. # define PNG_USER_HEIGHT_MAX 1000000L
  181534. #endif
  181535. /* These are currently experimental features, define them if you want */
  181536. /* very little testing */
  181537. /*
  181538. #ifdef PNG_READ_SUPPORTED
  181539. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181540. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181541. # endif
  181542. #endif
  181543. */
  181544. /* This is only for PowerPC big-endian and 680x0 systems */
  181545. /* some testing */
  181546. /*
  181547. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181548. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181549. #endif
  181550. */
  181551. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181552. /*
  181553. #define PNG_NO_POINTER_INDEXING
  181554. */
  181555. /* These functions are turned off by default, as they will be phased out. */
  181556. /*
  181557. #define PNG_USELESS_TESTS_SUPPORTED
  181558. #define PNG_CORRECT_PALETTE_SUPPORTED
  181559. */
  181560. /* Any chunks you are not interested in, you can undef here. The
  181561. * ones that allocate memory may be expecially important (hIST,
  181562. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181563. * a bit smaller.
  181564. */
  181565. #if defined(PNG_READ_SUPPORTED) && \
  181566. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181567. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181568. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181569. #endif
  181570. #if defined(PNG_WRITE_SUPPORTED) && \
  181571. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181572. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181573. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181574. #endif
  181575. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181576. #ifdef PNG_NO_READ_TEXT
  181577. # define PNG_NO_READ_iTXt
  181578. # define PNG_NO_READ_tEXt
  181579. # define PNG_NO_READ_zTXt
  181580. #endif
  181581. #ifndef PNG_NO_READ_bKGD
  181582. # define PNG_READ_bKGD_SUPPORTED
  181583. # define PNG_bKGD_SUPPORTED
  181584. #endif
  181585. #ifndef PNG_NO_READ_cHRM
  181586. # define PNG_READ_cHRM_SUPPORTED
  181587. # define PNG_cHRM_SUPPORTED
  181588. #endif
  181589. #ifndef PNG_NO_READ_gAMA
  181590. # define PNG_READ_gAMA_SUPPORTED
  181591. # define PNG_gAMA_SUPPORTED
  181592. #endif
  181593. #ifndef PNG_NO_READ_hIST
  181594. # define PNG_READ_hIST_SUPPORTED
  181595. # define PNG_hIST_SUPPORTED
  181596. #endif
  181597. #ifndef PNG_NO_READ_iCCP
  181598. # define PNG_READ_iCCP_SUPPORTED
  181599. # define PNG_iCCP_SUPPORTED
  181600. #endif
  181601. #ifndef PNG_NO_READ_iTXt
  181602. # ifndef PNG_READ_iTXt_SUPPORTED
  181603. # define PNG_READ_iTXt_SUPPORTED
  181604. # endif
  181605. # ifndef PNG_iTXt_SUPPORTED
  181606. # define PNG_iTXt_SUPPORTED
  181607. # endif
  181608. #endif
  181609. #ifndef PNG_NO_READ_oFFs
  181610. # define PNG_READ_oFFs_SUPPORTED
  181611. # define PNG_oFFs_SUPPORTED
  181612. #endif
  181613. #ifndef PNG_NO_READ_pCAL
  181614. # define PNG_READ_pCAL_SUPPORTED
  181615. # define PNG_pCAL_SUPPORTED
  181616. #endif
  181617. #ifndef PNG_NO_READ_sCAL
  181618. # define PNG_READ_sCAL_SUPPORTED
  181619. # define PNG_sCAL_SUPPORTED
  181620. #endif
  181621. #ifndef PNG_NO_READ_pHYs
  181622. # define PNG_READ_pHYs_SUPPORTED
  181623. # define PNG_pHYs_SUPPORTED
  181624. #endif
  181625. #ifndef PNG_NO_READ_sBIT
  181626. # define PNG_READ_sBIT_SUPPORTED
  181627. # define PNG_sBIT_SUPPORTED
  181628. #endif
  181629. #ifndef PNG_NO_READ_sPLT
  181630. # define PNG_READ_sPLT_SUPPORTED
  181631. # define PNG_sPLT_SUPPORTED
  181632. #endif
  181633. #ifndef PNG_NO_READ_sRGB
  181634. # define PNG_READ_sRGB_SUPPORTED
  181635. # define PNG_sRGB_SUPPORTED
  181636. #endif
  181637. #ifndef PNG_NO_READ_tEXt
  181638. # define PNG_READ_tEXt_SUPPORTED
  181639. # define PNG_tEXt_SUPPORTED
  181640. #endif
  181641. #ifndef PNG_NO_READ_tIME
  181642. # define PNG_READ_tIME_SUPPORTED
  181643. # define PNG_tIME_SUPPORTED
  181644. #endif
  181645. #ifndef PNG_NO_READ_tRNS
  181646. # define PNG_READ_tRNS_SUPPORTED
  181647. # define PNG_tRNS_SUPPORTED
  181648. #endif
  181649. #ifndef PNG_NO_READ_zTXt
  181650. # define PNG_READ_zTXt_SUPPORTED
  181651. # define PNG_zTXt_SUPPORTED
  181652. #endif
  181653. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181654. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181655. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181656. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181657. # endif
  181658. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181659. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181660. # endif
  181661. #endif
  181662. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181663. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181664. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181665. # define PNG_USER_CHUNKS_SUPPORTED
  181666. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181667. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181668. # endif
  181669. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181670. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181671. # endif
  181672. #endif
  181673. #ifndef PNG_NO_READ_OPT_PLTE
  181674. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181675. #endif /* optional PLTE chunk in RGB and RGBA images */
  181676. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181677. defined(PNG_READ_zTXt_SUPPORTED)
  181678. # define PNG_READ_TEXT_SUPPORTED
  181679. # define PNG_TEXT_SUPPORTED
  181680. #endif
  181681. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181682. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181683. #ifdef PNG_NO_WRITE_TEXT
  181684. # define PNG_NO_WRITE_iTXt
  181685. # define PNG_NO_WRITE_tEXt
  181686. # define PNG_NO_WRITE_zTXt
  181687. #endif
  181688. #ifndef PNG_NO_WRITE_bKGD
  181689. # define PNG_WRITE_bKGD_SUPPORTED
  181690. # ifndef PNG_bKGD_SUPPORTED
  181691. # define PNG_bKGD_SUPPORTED
  181692. # endif
  181693. #endif
  181694. #ifndef PNG_NO_WRITE_cHRM
  181695. # define PNG_WRITE_cHRM_SUPPORTED
  181696. # ifndef PNG_cHRM_SUPPORTED
  181697. # define PNG_cHRM_SUPPORTED
  181698. # endif
  181699. #endif
  181700. #ifndef PNG_NO_WRITE_gAMA
  181701. # define PNG_WRITE_gAMA_SUPPORTED
  181702. # ifndef PNG_gAMA_SUPPORTED
  181703. # define PNG_gAMA_SUPPORTED
  181704. # endif
  181705. #endif
  181706. #ifndef PNG_NO_WRITE_hIST
  181707. # define PNG_WRITE_hIST_SUPPORTED
  181708. # ifndef PNG_hIST_SUPPORTED
  181709. # define PNG_hIST_SUPPORTED
  181710. # endif
  181711. #endif
  181712. #ifndef PNG_NO_WRITE_iCCP
  181713. # define PNG_WRITE_iCCP_SUPPORTED
  181714. # ifndef PNG_iCCP_SUPPORTED
  181715. # define PNG_iCCP_SUPPORTED
  181716. # endif
  181717. #endif
  181718. #ifndef PNG_NO_WRITE_iTXt
  181719. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181720. # define PNG_WRITE_iTXt_SUPPORTED
  181721. # endif
  181722. # ifndef PNG_iTXt_SUPPORTED
  181723. # define PNG_iTXt_SUPPORTED
  181724. # endif
  181725. #endif
  181726. #ifndef PNG_NO_WRITE_oFFs
  181727. # define PNG_WRITE_oFFs_SUPPORTED
  181728. # ifndef PNG_oFFs_SUPPORTED
  181729. # define PNG_oFFs_SUPPORTED
  181730. # endif
  181731. #endif
  181732. #ifndef PNG_NO_WRITE_pCAL
  181733. # define PNG_WRITE_pCAL_SUPPORTED
  181734. # ifndef PNG_pCAL_SUPPORTED
  181735. # define PNG_pCAL_SUPPORTED
  181736. # endif
  181737. #endif
  181738. #ifndef PNG_NO_WRITE_sCAL
  181739. # define PNG_WRITE_sCAL_SUPPORTED
  181740. # ifndef PNG_sCAL_SUPPORTED
  181741. # define PNG_sCAL_SUPPORTED
  181742. # endif
  181743. #endif
  181744. #ifndef PNG_NO_WRITE_pHYs
  181745. # define PNG_WRITE_pHYs_SUPPORTED
  181746. # ifndef PNG_pHYs_SUPPORTED
  181747. # define PNG_pHYs_SUPPORTED
  181748. # endif
  181749. #endif
  181750. #ifndef PNG_NO_WRITE_sBIT
  181751. # define PNG_WRITE_sBIT_SUPPORTED
  181752. # ifndef PNG_sBIT_SUPPORTED
  181753. # define PNG_sBIT_SUPPORTED
  181754. # endif
  181755. #endif
  181756. #ifndef PNG_NO_WRITE_sPLT
  181757. # define PNG_WRITE_sPLT_SUPPORTED
  181758. # ifndef PNG_sPLT_SUPPORTED
  181759. # define PNG_sPLT_SUPPORTED
  181760. # endif
  181761. #endif
  181762. #ifndef PNG_NO_WRITE_sRGB
  181763. # define PNG_WRITE_sRGB_SUPPORTED
  181764. # ifndef PNG_sRGB_SUPPORTED
  181765. # define PNG_sRGB_SUPPORTED
  181766. # endif
  181767. #endif
  181768. #ifndef PNG_NO_WRITE_tEXt
  181769. # define PNG_WRITE_tEXt_SUPPORTED
  181770. # ifndef PNG_tEXt_SUPPORTED
  181771. # define PNG_tEXt_SUPPORTED
  181772. # endif
  181773. #endif
  181774. #ifndef PNG_NO_WRITE_tIME
  181775. # define PNG_WRITE_tIME_SUPPORTED
  181776. # ifndef PNG_tIME_SUPPORTED
  181777. # define PNG_tIME_SUPPORTED
  181778. # endif
  181779. #endif
  181780. #ifndef PNG_NO_WRITE_tRNS
  181781. # define PNG_WRITE_tRNS_SUPPORTED
  181782. # ifndef PNG_tRNS_SUPPORTED
  181783. # define PNG_tRNS_SUPPORTED
  181784. # endif
  181785. #endif
  181786. #ifndef PNG_NO_WRITE_zTXt
  181787. # define PNG_WRITE_zTXt_SUPPORTED
  181788. # ifndef PNG_zTXt_SUPPORTED
  181789. # define PNG_zTXt_SUPPORTED
  181790. # endif
  181791. #endif
  181792. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181793. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181794. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181795. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181796. # endif
  181797. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181798. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181799. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181800. # endif
  181801. # endif
  181802. #endif
  181803. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181804. defined(PNG_WRITE_zTXt_SUPPORTED)
  181805. # define PNG_WRITE_TEXT_SUPPORTED
  181806. # ifndef PNG_TEXT_SUPPORTED
  181807. # define PNG_TEXT_SUPPORTED
  181808. # endif
  181809. #endif
  181810. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181811. /* Turn this off to disable png_read_png() and
  181812. * png_write_png() and leave the row_pointers member
  181813. * out of the info structure.
  181814. */
  181815. #ifndef PNG_NO_INFO_IMAGE
  181816. # define PNG_INFO_IMAGE_SUPPORTED
  181817. #endif
  181818. /* need the time information for reading tIME chunks */
  181819. #if defined(PNG_tIME_SUPPORTED)
  181820. # if !defined(_WIN32_WCE)
  181821. /* "time.h" functions are not supported on WindowsCE */
  181822. # include <time.h>
  181823. # endif
  181824. #endif
  181825. /* Some typedefs to get us started. These should be safe on most of the
  181826. * common platforms. The typedefs should be at least as large as the
  181827. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181828. * don't have to be exactly that size. Some compilers dislike passing
  181829. * unsigned shorts as function parameters, so you may be better off using
  181830. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181831. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181832. */
  181833. typedef unsigned long png_uint_32;
  181834. typedef long png_int_32;
  181835. typedef unsigned short png_uint_16;
  181836. typedef short png_int_16;
  181837. typedef unsigned char png_byte;
  181838. /* This is usually size_t. It is typedef'ed just in case you need it to
  181839. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181840. #ifdef PNG_SIZE_T
  181841. typedef PNG_SIZE_T png_size_t;
  181842. # define png_sizeof(x) png_convert_size(sizeof (x))
  181843. #else
  181844. typedef size_t png_size_t;
  181845. # define png_sizeof(x) sizeof (x)
  181846. #endif
  181847. /* The following is needed for medium model support. It cannot be in the
  181848. * PNG_INTERNAL section. Needs modification for other compilers besides
  181849. * MSC. Model independent support declares all arrays and pointers to be
  181850. * large using the far keyword. The zlib version used must also support
  181851. * model independent data. As of version zlib 1.0.4, the necessary changes
  181852. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181853. * changes that are needed. (Tim Wegner)
  181854. */
  181855. /* Separate compiler dependencies (problem here is that zlib.h always
  181856. defines FAR. (SJT) */
  181857. #ifdef __BORLANDC__
  181858. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181859. # define LDATA 1
  181860. # else
  181861. # define LDATA 0
  181862. # endif
  181863. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181864. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181865. # define PNG_MAX_MALLOC_64K
  181866. # if (LDATA != 1)
  181867. # ifndef FAR
  181868. # define FAR __far
  181869. # endif
  181870. # define USE_FAR_KEYWORD
  181871. # endif /* LDATA != 1 */
  181872. /* Possibly useful for moving data out of default segment.
  181873. * Uncomment it if you want. Could also define FARDATA as
  181874. * const if your compiler supports it. (SJT)
  181875. # define FARDATA FAR
  181876. */
  181877. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181878. #endif /* __BORLANDC__ */
  181879. /* Suggest testing for specific compiler first before testing for
  181880. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181881. * making reliance oncertain keywords suspect. (SJT)
  181882. */
  181883. /* MSC Medium model */
  181884. #if defined(FAR)
  181885. # if defined(M_I86MM)
  181886. # define USE_FAR_KEYWORD
  181887. # define FARDATA FAR
  181888. # include <dos.h>
  181889. # endif
  181890. #endif
  181891. /* SJT: default case */
  181892. #ifndef FAR
  181893. # define FAR
  181894. #endif
  181895. /* At this point FAR is always defined */
  181896. #ifndef FARDATA
  181897. # define FARDATA
  181898. #endif
  181899. /* Typedef for floating-point numbers that are converted
  181900. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181901. typedef png_int_32 png_fixed_point;
  181902. /* Add typedefs for pointers */
  181903. typedef void FAR * png_voidp;
  181904. typedef png_byte FAR * png_bytep;
  181905. typedef png_uint_32 FAR * png_uint_32p;
  181906. typedef png_int_32 FAR * png_int_32p;
  181907. typedef png_uint_16 FAR * png_uint_16p;
  181908. typedef png_int_16 FAR * png_int_16p;
  181909. typedef PNG_CONST char FAR * png_const_charp;
  181910. typedef char FAR * png_charp;
  181911. typedef png_fixed_point FAR * png_fixed_point_p;
  181912. #ifndef PNG_NO_STDIO
  181913. #if defined(_WIN32_WCE)
  181914. typedef HANDLE png_FILE_p;
  181915. #else
  181916. typedef FILE * png_FILE_p;
  181917. #endif
  181918. #endif
  181919. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181920. typedef double FAR * png_doublep;
  181921. #endif
  181922. /* Pointers to pointers; i.e. arrays */
  181923. typedef png_byte FAR * FAR * png_bytepp;
  181924. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181925. typedef png_int_32 FAR * FAR * png_int_32pp;
  181926. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181927. typedef png_int_16 FAR * FAR * png_int_16pp;
  181928. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181929. typedef char FAR * FAR * png_charpp;
  181930. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181931. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181932. typedef double FAR * FAR * png_doublepp;
  181933. #endif
  181934. /* Pointers to pointers to pointers; i.e., pointer to array */
  181935. typedef char FAR * FAR * FAR * png_charppp;
  181936. #if 0
  181937. /* SPC - Is this stuff deprecated? */
  181938. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181939. /* libpng typedefs for types in zlib. If zlib changes
  181940. * or another compression library is used, then change these.
  181941. * Eliminates need to change all the source files.
  181942. */
  181943. typedef charf * png_zcharp;
  181944. typedef charf * FAR * png_zcharpp;
  181945. typedef z_stream FAR * png_zstreamp;
  181946. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181947. /*
  181948. * Define PNG_BUILD_DLL if the module being built is a Windows
  181949. * LIBPNG DLL.
  181950. *
  181951. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181952. * It is equivalent to Microsoft predefined macro _DLL that is
  181953. * automatically defined when you compile using the share
  181954. * version of the CRT (C Run-Time library)
  181955. *
  181956. * The cygwin mods make this behavior a little different:
  181957. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181958. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181959. * -or- if you are building an application that you want to link to the
  181960. * static library.
  181961. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181962. * the other flags is defined.
  181963. */
  181964. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181965. # define PNG_DLL
  181966. #endif
  181967. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181968. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181969. * command-line override
  181970. */
  181971. #if defined(__CYGWIN__)
  181972. # if !defined(PNG_STATIC)
  181973. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181974. # undef PNG_USE_GLOBAL_ARRAYS
  181975. # endif
  181976. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181977. # define PNG_USE_LOCAL_ARRAYS
  181978. # endif
  181979. # else
  181980. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181981. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181982. # undef PNG_USE_GLOBAL_ARRAYS
  181983. # endif
  181984. # endif
  181985. # endif
  181986. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181987. # define PNG_USE_LOCAL_ARRAYS
  181988. # endif
  181989. #endif
  181990. /* Do not use global arrays (helps with building DLL's)
  181991. * They are no longer used in libpng itself, since version 1.0.5c,
  181992. * but might be required for some pre-1.0.5c applications.
  181993. */
  181994. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181995. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181996. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181997. # define PNG_USE_LOCAL_ARRAYS
  181998. # else
  181999. # define PNG_USE_GLOBAL_ARRAYS
  182000. # endif
  182001. #endif
  182002. #if defined(__CYGWIN__)
  182003. # undef PNGAPI
  182004. # define PNGAPI __cdecl
  182005. # undef PNG_IMPEXP
  182006. # define PNG_IMPEXP
  182007. #endif
  182008. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182009. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182010. * Don't ignore those warnings; you must also reset the default calling
  182011. * convention in your compiler to match your PNGAPI, and you must build
  182012. * zlib and your applications the same way you build libpng.
  182013. */
  182014. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182015. # ifndef PNG_NO_MODULEDEF
  182016. # define PNG_NO_MODULEDEF
  182017. # endif
  182018. #endif
  182019. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182020. # define PNG_IMPEXP
  182021. #endif
  182022. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182023. (( defined(_Windows) || defined(_WINDOWS) || \
  182024. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182025. # ifndef PNGAPI
  182026. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182027. # define PNGAPI __cdecl
  182028. # else
  182029. # define PNGAPI _cdecl
  182030. # endif
  182031. # endif
  182032. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182033. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182034. # define PNG_IMPEXP
  182035. # endif
  182036. # if !defined(PNG_IMPEXP)
  182037. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182038. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182039. /* Borland/Microsoft */
  182040. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182041. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182042. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182043. # else
  182044. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182045. # if defined(PNG_BUILD_DLL)
  182046. # define PNG_IMPEXP __export
  182047. # else
  182048. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182049. VC++ */
  182050. # endif /* Exists in Borland C++ for
  182051. C++ classes (== huge) */
  182052. # endif
  182053. # endif
  182054. # if !defined(PNG_IMPEXP)
  182055. # if defined(PNG_BUILD_DLL)
  182056. # define PNG_IMPEXP __declspec(dllexport)
  182057. # else
  182058. # define PNG_IMPEXP __declspec(dllimport)
  182059. # endif
  182060. # endif
  182061. # endif /* PNG_IMPEXP */
  182062. #else /* !(DLL || non-cygwin WINDOWS) */
  182063. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182064. # ifndef PNGAPI
  182065. # define PNGAPI _System
  182066. # endif
  182067. # else
  182068. # if 0 /* ... other platforms, with other meanings */
  182069. # endif
  182070. # endif
  182071. #endif
  182072. #ifndef PNGAPI
  182073. # define PNGAPI
  182074. #endif
  182075. #ifndef PNG_IMPEXP
  182076. # define PNG_IMPEXP
  182077. #endif
  182078. #ifdef PNG_BUILDSYMS
  182079. # ifndef PNG_EXPORT
  182080. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182081. # endif
  182082. # ifdef PNG_USE_GLOBAL_ARRAYS
  182083. # ifndef PNG_EXPORT_VAR
  182084. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182085. # endif
  182086. # endif
  182087. #endif
  182088. #ifndef PNG_EXPORT
  182089. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182090. #endif
  182091. #ifdef PNG_USE_GLOBAL_ARRAYS
  182092. # ifndef PNG_EXPORT_VAR
  182093. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182094. # endif
  182095. #endif
  182096. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182097. * functions that are passed far data must be model independent.
  182098. */
  182099. #ifndef PNG_ABORT
  182100. # define PNG_ABORT() abort()
  182101. #endif
  182102. #ifdef PNG_SETJMP_SUPPORTED
  182103. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182104. #else
  182105. # define png_jmpbuf(png_ptr) \
  182106. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182107. #endif
  182108. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182109. /* use this to make far-to-near assignments */
  182110. # define CHECK 1
  182111. # define NOCHECK 0
  182112. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182113. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182114. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182115. # define png_strcpy _fstrcpy
  182116. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182117. # define png_strlen _fstrlen
  182118. # define png_memcmp _fmemcmp /* SJT: added */
  182119. # define png_memcpy _fmemcpy
  182120. # define png_memset _fmemset
  182121. #else /* use the usual functions */
  182122. # define CVT_PTR(ptr) (ptr)
  182123. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182124. # ifndef PNG_NO_SNPRINTF
  182125. # ifdef _MSC_VER
  182126. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182127. # define png_snprintf2 _snprintf
  182128. # define png_snprintf6 _snprintf
  182129. # else
  182130. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182131. # define png_snprintf2 snprintf
  182132. # define png_snprintf6 snprintf
  182133. # endif
  182134. # else
  182135. /* You don't have or don't want to use snprintf(). Caution: Using
  182136. * sprintf instead of snprintf exposes your application to accidental
  182137. * or malevolent buffer overflows. If you don't have snprintf()
  182138. * as a general rule you should provide one (you can get one from
  182139. * Portable OpenSSH). */
  182140. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182141. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182142. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182143. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182144. # endif
  182145. # define png_strcpy strcpy
  182146. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182147. # define png_strlen strlen
  182148. # define png_memcmp memcmp /* SJT: added */
  182149. # define png_memcpy memcpy
  182150. # define png_memset memset
  182151. #endif
  182152. /* End of memory model independent support */
  182153. /* Just a little check that someone hasn't tried to define something
  182154. * contradictory.
  182155. */
  182156. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182157. # undef PNG_ZBUF_SIZE
  182158. # define PNG_ZBUF_SIZE 65536L
  182159. #endif
  182160. /* Added at libpng-1.2.8 */
  182161. #endif /* PNG_VERSION_INFO_ONLY */
  182162. #endif /* PNGCONF_H */
  182163. /*** End of inlined file: pngconf.h ***/
  182164. #ifdef _MSC_VER
  182165. #pragma warning (disable: 4996 4100)
  182166. #endif
  182167. /*
  182168. * Added at libpng-1.2.8 */
  182169. /* Ref MSDN: Private as priority over Special
  182170. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182171. * procedures. If this value is given, the StringFileInfo block must
  182172. * contain a PrivateBuild string.
  182173. *
  182174. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182175. * standard release procedures but is a variation of the standard
  182176. * file of the same version number. If this value is given, the
  182177. * StringFileInfo block must contain a SpecialBuild string.
  182178. */
  182179. #if defined(PNG_USER_PRIVATEBUILD)
  182180. # define PNG_LIBPNG_BUILD_TYPE \
  182181. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182182. #else
  182183. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182184. # define PNG_LIBPNG_BUILD_TYPE \
  182185. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182186. # else
  182187. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182188. # endif
  182189. #endif
  182190. #ifndef PNG_VERSION_INFO_ONLY
  182191. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182192. #ifdef __cplusplus
  182193. //extern "C" {
  182194. #endif /* __cplusplus */
  182195. /* This file is arranged in several sections. The first section contains
  182196. * structure and type definitions. The second section contains the external
  182197. * library functions, while the third has the internal library functions,
  182198. * which applications aren't expected to use directly.
  182199. */
  182200. #ifndef PNG_NO_TYPECAST_NULL
  182201. #define int_p_NULL (int *)NULL
  182202. #define png_bytep_NULL (png_bytep)NULL
  182203. #define png_bytepp_NULL (png_bytepp)NULL
  182204. #define png_doublep_NULL (png_doublep)NULL
  182205. #define png_error_ptr_NULL (png_error_ptr)NULL
  182206. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182207. #define png_free_ptr_NULL (png_free_ptr)NULL
  182208. #define png_infopp_NULL (png_infopp)NULL
  182209. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182210. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182211. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182212. #define png_structp_NULL (png_structp)NULL
  182213. #define png_uint_16p_NULL (png_uint_16p)NULL
  182214. #define png_voidp_NULL (png_voidp)NULL
  182215. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182216. #else
  182217. #define int_p_NULL NULL
  182218. #define png_bytep_NULL NULL
  182219. #define png_bytepp_NULL NULL
  182220. #define png_doublep_NULL NULL
  182221. #define png_error_ptr_NULL NULL
  182222. #define png_flush_ptr_NULL NULL
  182223. #define png_free_ptr_NULL NULL
  182224. #define png_infopp_NULL NULL
  182225. #define png_malloc_ptr_NULL NULL
  182226. #define png_read_status_ptr_NULL NULL
  182227. #define png_rw_ptr_NULL NULL
  182228. #define png_structp_NULL NULL
  182229. #define png_uint_16p_NULL NULL
  182230. #define png_voidp_NULL NULL
  182231. #define png_write_status_ptr_NULL NULL
  182232. #endif
  182233. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182234. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182235. /* Version information for C files, stored in png.c. This had better match
  182236. * the version above.
  182237. */
  182238. #ifdef PNG_USE_GLOBAL_ARRAYS
  182239. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182240. /* need room for 99.99.99beta99z */
  182241. #else
  182242. #define png_libpng_ver png_get_header_ver(NULL)
  182243. #endif
  182244. #ifdef PNG_USE_GLOBAL_ARRAYS
  182245. /* This was removed in version 1.0.5c */
  182246. /* Structures to facilitate easy interlacing. See png.c for more details */
  182247. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182248. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182249. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182250. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182251. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182252. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182253. /* This isn't currently used. If you need it, see png.c for more details.
  182254. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182255. */
  182256. #endif
  182257. #endif /* PNG_NO_EXTERN */
  182258. /* Three color definitions. The order of the red, green, and blue, (and the
  182259. * exact size) is not important, although the size of the fields need to
  182260. * be png_byte or png_uint_16 (as defined below).
  182261. */
  182262. typedef struct png_color_struct
  182263. {
  182264. png_byte red;
  182265. png_byte green;
  182266. png_byte blue;
  182267. } png_color;
  182268. typedef png_color FAR * png_colorp;
  182269. typedef png_color FAR * FAR * png_colorpp;
  182270. typedef struct png_color_16_struct
  182271. {
  182272. png_byte index; /* used for palette files */
  182273. png_uint_16 red; /* for use in red green blue files */
  182274. png_uint_16 green;
  182275. png_uint_16 blue;
  182276. png_uint_16 gray; /* for use in grayscale files */
  182277. } png_color_16;
  182278. typedef png_color_16 FAR * png_color_16p;
  182279. typedef png_color_16 FAR * FAR * png_color_16pp;
  182280. typedef struct png_color_8_struct
  182281. {
  182282. png_byte red; /* for use in red green blue files */
  182283. png_byte green;
  182284. png_byte blue;
  182285. png_byte gray; /* for use in grayscale files */
  182286. png_byte alpha; /* for alpha channel files */
  182287. } png_color_8;
  182288. typedef png_color_8 FAR * png_color_8p;
  182289. typedef png_color_8 FAR * FAR * png_color_8pp;
  182290. /*
  182291. * The following two structures are used for the in-core representation
  182292. * of sPLT chunks.
  182293. */
  182294. typedef struct png_sPLT_entry_struct
  182295. {
  182296. png_uint_16 red;
  182297. png_uint_16 green;
  182298. png_uint_16 blue;
  182299. png_uint_16 alpha;
  182300. png_uint_16 frequency;
  182301. } png_sPLT_entry;
  182302. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182303. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182304. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182305. * occupy the LSB of their respective members, and the MSB of each member
  182306. * is zero-filled. The frequency member always occupies the full 16 bits.
  182307. */
  182308. typedef struct png_sPLT_struct
  182309. {
  182310. png_charp name; /* palette name */
  182311. png_byte depth; /* depth of palette samples */
  182312. png_sPLT_entryp entries; /* palette entries */
  182313. png_int_32 nentries; /* number of palette entries */
  182314. } png_sPLT_t;
  182315. typedef png_sPLT_t FAR * png_sPLT_tp;
  182316. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182317. #ifdef PNG_TEXT_SUPPORTED
  182318. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182319. * and whether that contents is compressed or not. The "key" field
  182320. * points to a regular zero-terminated C string. The "text", "lang", and
  182321. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182322. * However, the * structure returned by png_get_text() will always contain
  182323. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182324. * so they can be safely used in printf() and other string-handling functions.
  182325. */
  182326. typedef struct png_text_struct
  182327. {
  182328. int compression; /* compression value:
  182329. -1: tEXt, none
  182330. 0: zTXt, deflate
  182331. 1: iTXt, none
  182332. 2: iTXt, deflate */
  182333. png_charp key; /* keyword, 1-79 character description of "text" */
  182334. png_charp text; /* comment, may be an empty string (ie "")
  182335. or a NULL pointer */
  182336. png_size_t text_length; /* length of the text string */
  182337. #ifdef PNG_iTXt_SUPPORTED
  182338. png_size_t itxt_length; /* length of the itxt string */
  182339. png_charp lang; /* language code, 0-79 characters
  182340. or a NULL pointer */
  182341. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182342. chars or a NULL pointer */
  182343. #endif
  182344. } png_text;
  182345. typedef png_text FAR * png_textp;
  182346. typedef png_text FAR * FAR * png_textpp;
  182347. #endif
  182348. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182349. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182350. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182351. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182352. #define PNG_TEXT_COMPRESSION_NONE -1
  182353. #define PNG_TEXT_COMPRESSION_zTXt 0
  182354. #define PNG_ITXT_COMPRESSION_NONE 1
  182355. #define PNG_ITXT_COMPRESSION_zTXt 2
  182356. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182357. /* png_time is a way to hold the time in an machine independent way.
  182358. * Two conversions are provided, both from time_t and struct tm. There
  182359. * is no portable way to convert to either of these structures, as far
  182360. * as I know. If you know of a portable way, send it to me. As a side
  182361. * note - PNG has always been Year 2000 compliant!
  182362. */
  182363. typedef struct png_time_struct
  182364. {
  182365. png_uint_16 year; /* full year, as in, 1995 */
  182366. png_byte month; /* month of year, 1 - 12 */
  182367. png_byte day; /* day of month, 1 - 31 */
  182368. png_byte hour; /* hour of day, 0 - 23 */
  182369. png_byte minute; /* minute of hour, 0 - 59 */
  182370. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182371. } png_time;
  182372. typedef png_time FAR * png_timep;
  182373. typedef png_time FAR * FAR * png_timepp;
  182374. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182375. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182376. * no specific support. The idea is that we can use this to queue
  182377. * up private chunks for output even though the library doesn't actually
  182378. * know about their semantics.
  182379. */
  182380. typedef struct png_unknown_chunk_t
  182381. {
  182382. png_byte name[5];
  182383. png_byte *data;
  182384. png_size_t size;
  182385. /* libpng-using applications should NOT directly modify this byte. */
  182386. png_byte location; /* mode of operation at read time */
  182387. }
  182388. png_unknown_chunk;
  182389. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182390. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182391. #endif
  182392. /* png_info is a structure that holds the information in a PNG file so
  182393. * that the application can find out the characteristics of the image.
  182394. * If you are reading the file, this structure will tell you what is
  182395. * in the PNG file. If you are writing the file, fill in the information
  182396. * you want to put into the PNG file, then call png_write_info().
  182397. * The names chosen should be very close to the PNG specification, so
  182398. * consult that document for information about the meaning of each field.
  182399. *
  182400. * With libpng < 0.95, it was only possible to directly set and read the
  182401. * the values in the png_info_struct, which meant that the contents and
  182402. * order of the values had to remain fixed. With libpng 0.95 and later,
  182403. * however, there are now functions that abstract the contents of
  182404. * png_info_struct from the application, so this makes it easier to use
  182405. * libpng with dynamic libraries, and even makes it possible to use
  182406. * libraries that don't have all of the libpng ancillary chunk-handing
  182407. * functionality.
  182408. *
  182409. * In any case, the order of the parameters in png_info_struct should NOT
  182410. * be changed for as long as possible to keep compatibility with applications
  182411. * that use the old direct-access method with png_info_struct.
  182412. *
  182413. * The following members may have allocated storage attached that should be
  182414. * cleaned up before the structure is discarded: palette, trans, text,
  182415. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182416. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182417. * are automatically freed when the info structure is deallocated, if they were
  182418. * allocated internally by libpng. This behavior can be changed by means
  182419. * of the png_data_freer() function.
  182420. *
  182421. * More allocation details: all the chunk-reading functions that
  182422. * change these members go through the corresponding png_set_*
  182423. * functions. A function to clear these members is available: see
  182424. * png_free_data(). The png_set_* functions do not depend on being
  182425. * able to point info structure members to any of the storage they are
  182426. * passed (they make their own copies), EXCEPT that the png_set_text
  182427. * functions use the same storage passed to them in the text_ptr or
  182428. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182429. * functions do not make their own copies.
  182430. */
  182431. typedef struct png_info_struct
  182432. {
  182433. /* the following are necessary for every PNG file */
  182434. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182435. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182436. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182437. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182438. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182439. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182440. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182441. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182442. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182443. /* The following three should have been named *_method not *_type */
  182444. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182445. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182446. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182447. /* The following is informational only on read, and not used on writes. */
  182448. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182449. png_byte pixel_depth; /* number of bits per pixel */
  182450. png_byte spare_byte; /* to align the data, and for future use */
  182451. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182452. /* The rest of the data is optional. If you are reading, check the
  182453. * valid field to see if the information in these are valid. If you
  182454. * are writing, set the valid field to those chunks you want written,
  182455. * and initialize the appropriate fields below.
  182456. */
  182457. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182458. /* The gAMA chunk describes the gamma characteristics of the system
  182459. * on which the image was created, normally in the range [1.0, 2.5].
  182460. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182461. */
  182462. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182463. #endif
  182464. #if defined(PNG_sRGB_SUPPORTED)
  182465. /* GR-P, 0.96a */
  182466. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182467. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182468. #endif
  182469. #if defined(PNG_TEXT_SUPPORTED)
  182470. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182471. * uncompressed, compressed, and optionally compressed forms, respectively.
  182472. * The data in "text" is an array of pointers to uncompressed,
  182473. * null-terminated C strings. Each chunk has a keyword that describes the
  182474. * textual data contained in that chunk. Keywords are not required to be
  182475. * unique, and the text string may be empty. Any number of text chunks may
  182476. * be in an image.
  182477. */
  182478. int num_text; /* number of comments read/to write */
  182479. int max_text; /* current size of text array */
  182480. png_textp text; /* array of comments read/to write */
  182481. #endif /* PNG_TEXT_SUPPORTED */
  182482. #if defined(PNG_tIME_SUPPORTED)
  182483. /* The tIME chunk holds the last time the displayed image data was
  182484. * modified. See the png_time struct for the contents of this struct.
  182485. */
  182486. png_time mod_time;
  182487. #endif
  182488. #if defined(PNG_sBIT_SUPPORTED)
  182489. /* The sBIT chunk specifies the number of significant high-order bits
  182490. * in the pixel data. Values are in the range [1, bit_depth], and are
  182491. * only specified for the channels in the pixel data. The contents of
  182492. * the low-order bits is not specified. Data is valid if
  182493. * (valid & PNG_INFO_sBIT) is non-zero.
  182494. */
  182495. png_color_8 sig_bit; /* significant bits in color channels */
  182496. #endif
  182497. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182498. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182499. /* The tRNS chunk supplies transparency data for paletted images and
  182500. * other image types that don't need a full alpha channel. There are
  182501. * "num_trans" transparency values for a paletted image, stored in the
  182502. * same order as the palette colors, starting from index 0. Values
  182503. * for the data are in the range [0, 255], ranging from fully transparent
  182504. * to fully opaque, respectively. For non-paletted images, there is a
  182505. * single color specified that should be treated as fully transparent.
  182506. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182507. */
  182508. png_bytep trans; /* transparent values for paletted image */
  182509. png_color_16 trans_values; /* transparent color for non-palette image */
  182510. #endif
  182511. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182512. /* The bKGD chunk gives the suggested image background color if the
  182513. * display program does not have its own background color and the image
  182514. * is needs to composited onto a background before display. The colors
  182515. * in "background" are normally in the same color space/depth as the
  182516. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182517. */
  182518. png_color_16 background;
  182519. #endif
  182520. #if defined(PNG_oFFs_SUPPORTED)
  182521. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182522. * and downwards from the top-left corner of the display, page, or other
  182523. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182524. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182525. */
  182526. png_int_32 x_offset; /* x offset on page */
  182527. png_int_32 y_offset; /* y offset on page */
  182528. png_byte offset_unit_type; /* offset units type */
  182529. #endif
  182530. #if defined(PNG_pHYs_SUPPORTED)
  182531. /* The pHYs chunk gives the physical pixel density of the image for
  182532. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182533. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182534. */
  182535. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182536. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182537. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182538. #endif
  182539. #if defined(PNG_hIST_SUPPORTED)
  182540. /* The hIST chunk contains the relative frequency or importance of the
  182541. * various palette entries, so that a viewer can intelligently select a
  182542. * reduced-color palette, if required. Data is an array of "num_palette"
  182543. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182544. * is non-zero.
  182545. */
  182546. png_uint_16p hist;
  182547. #endif
  182548. #ifdef PNG_cHRM_SUPPORTED
  182549. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182550. * on which the PNG was created. This data allows the viewer to do gamut
  182551. * mapping of the input image to ensure that the viewer sees the same
  182552. * colors in the image as the creator. Values are in the range
  182553. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182554. */
  182555. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182556. float x_white;
  182557. float y_white;
  182558. float x_red;
  182559. float y_red;
  182560. float x_green;
  182561. float y_green;
  182562. float x_blue;
  182563. float y_blue;
  182564. #endif
  182565. #endif
  182566. #if defined(PNG_pCAL_SUPPORTED)
  182567. /* The pCAL chunk describes a transformation between the stored pixel
  182568. * values and original physical data values used to create the image.
  182569. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182570. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182571. * (possibly non-linear) transformation function given by "pcal_type"
  182572. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182573. * defines below, and the PNG-Group's PNG extensions document for a
  182574. * complete description of the transformations and how they should be
  182575. * implemented, and for a description of the ASCII parameter strings.
  182576. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182577. */
  182578. png_charp pcal_purpose; /* pCAL chunk description string */
  182579. png_int_32 pcal_X0; /* minimum value */
  182580. png_int_32 pcal_X1; /* maximum value */
  182581. png_charp pcal_units; /* Latin-1 string giving physical units */
  182582. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182583. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182584. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182585. #endif
  182586. /* New members added in libpng-1.0.6 */
  182587. #ifdef PNG_FREE_ME_SUPPORTED
  182588. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182589. #endif
  182590. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182591. /* storage for unknown chunks that the library doesn't recognize. */
  182592. png_unknown_chunkp unknown_chunks;
  182593. png_size_t unknown_chunks_num;
  182594. #endif
  182595. #if defined(PNG_iCCP_SUPPORTED)
  182596. /* iCCP chunk data. */
  182597. png_charp iccp_name; /* profile name */
  182598. png_charp iccp_profile; /* International Color Consortium profile data */
  182599. /* Note to maintainer: should be png_bytep */
  182600. png_uint_32 iccp_proflen; /* ICC profile data length */
  182601. png_byte iccp_compression; /* Always zero */
  182602. #endif
  182603. #if defined(PNG_sPLT_SUPPORTED)
  182604. /* data on sPLT chunks (there may be more than one). */
  182605. png_sPLT_tp splt_palettes;
  182606. png_uint_32 splt_palettes_num;
  182607. #endif
  182608. #if defined(PNG_sCAL_SUPPORTED)
  182609. /* The sCAL chunk describes the actual physical dimensions of the
  182610. * subject matter of the graphic. The chunk contains a unit specification
  182611. * a byte value, and two ASCII strings representing floating-point
  182612. * values. The values are width and height corresponsing to one pixel
  182613. * in the image. This external representation is converted to double
  182614. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182615. */
  182616. png_byte scal_unit; /* unit of physical scale */
  182617. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182618. double scal_pixel_width; /* width of one pixel */
  182619. double scal_pixel_height; /* height of one pixel */
  182620. #endif
  182621. #ifdef PNG_FIXED_POINT_SUPPORTED
  182622. png_charp scal_s_width; /* string containing height */
  182623. png_charp scal_s_height; /* string containing width */
  182624. #endif
  182625. #endif
  182626. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182627. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182628. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182629. png_bytepp row_pointers; /* the image bits */
  182630. #endif
  182631. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182632. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182633. #endif
  182634. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182635. png_fixed_point int_x_white;
  182636. png_fixed_point int_y_white;
  182637. png_fixed_point int_x_red;
  182638. png_fixed_point int_y_red;
  182639. png_fixed_point int_x_green;
  182640. png_fixed_point int_y_green;
  182641. png_fixed_point int_x_blue;
  182642. png_fixed_point int_y_blue;
  182643. #endif
  182644. } png_info;
  182645. typedef png_info FAR * png_infop;
  182646. typedef png_info FAR * FAR * png_infopp;
  182647. /* Maximum positive integer used in PNG is (2^31)-1 */
  182648. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182649. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182650. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182651. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182652. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182653. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182654. #endif
  182655. /* These describe the color_type field in png_info. */
  182656. /* color type masks */
  182657. #define PNG_COLOR_MASK_PALETTE 1
  182658. #define PNG_COLOR_MASK_COLOR 2
  182659. #define PNG_COLOR_MASK_ALPHA 4
  182660. /* color types. Note that not all combinations are legal */
  182661. #define PNG_COLOR_TYPE_GRAY 0
  182662. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182663. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182664. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182665. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182666. /* aliases */
  182667. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182668. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182669. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182670. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182671. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182672. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182673. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182674. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182675. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182676. /* These are for the interlacing type. These values should NOT be changed. */
  182677. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182678. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182679. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182680. /* These are for the oFFs chunk. These values should NOT be changed. */
  182681. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182682. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182683. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182684. /* These are for the pCAL chunk. These values should NOT be changed. */
  182685. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182686. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182687. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182688. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182689. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182690. /* These are for the sCAL chunk. These values should NOT be changed. */
  182691. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182692. #define PNG_SCALE_METER 1 /* meters per pixel */
  182693. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182694. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182695. /* These are for the pHYs chunk. These values should NOT be changed. */
  182696. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182697. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182698. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182699. /* These are for the sRGB chunk. These values should NOT be changed. */
  182700. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182701. #define PNG_sRGB_INTENT_RELATIVE 1
  182702. #define PNG_sRGB_INTENT_SATURATION 2
  182703. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182704. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182705. /* This is for text chunks */
  182706. #define PNG_KEYWORD_MAX_LENGTH 79
  182707. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182708. #define PNG_MAX_PALETTE_LENGTH 256
  182709. /* These determine if an ancillary chunk's data has been successfully read
  182710. * from the PNG header, or if the application has filled in the corresponding
  182711. * data in the info_struct to be written into the output file. The values
  182712. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182713. */
  182714. #define PNG_INFO_gAMA 0x0001
  182715. #define PNG_INFO_sBIT 0x0002
  182716. #define PNG_INFO_cHRM 0x0004
  182717. #define PNG_INFO_PLTE 0x0008
  182718. #define PNG_INFO_tRNS 0x0010
  182719. #define PNG_INFO_bKGD 0x0020
  182720. #define PNG_INFO_hIST 0x0040
  182721. #define PNG_INFO_pHYs 0x0080
  182722. #define PNG_INFO_oFFs 0x0100
  182723. #define PNG_INFO_tIME 0x0200
  182724. #define PNG_INFO_pCAL 0x0400
  182725. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182726. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182727. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182728. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182729. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182730. /* This is used for the transformation routines, as some of them
  182731. * change these values for the row. It also should enable using
  182732. * the routines for other purposes.
  182733. */
  182734. typedef struct png_row_info_struct
  182735. {
  182736. png_uint_32 width; /* width of row */
  182737. png_uint_32 rowbytes; /* number of bytes in row */
  182738. png_byte color_type; /* color type of row */
  182739. png_byte bit_depth; /* bit depth of row */
  182740. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182741. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182742. } png_row_info;
  182743. typedef png_row_info FAR * png_row_infop;
  182744. typedef png_row_info FAR * FAR * png_row_infopp;
  182745. /* These are the function types for the I/O functions and for the functions
  182746. * that allow the user to override the default I/O functions with his or her
  182747. * own. The png_error_ptr type should match that of user-supplied warning
  182748. * and error functions, while the png_rw_ptr type should match that of the
  182749. * user read/write data functions.
  182750. */
  182751. typedef struct png_struct_def png_struct;
  182752. typedef png_struct FAR * png_structp;
  182753. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182754. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182755. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182756. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182757. int));
  182758. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182759. int));
  182760. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182761. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182762. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182763. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182764. png_uint_32, int));
  182765. #endif
  182766. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182767. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182768. defined(PNG_LEGACY_SUPPORTED)
  182769. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182770. png_row_infop, png_bytep));
  182771. #endif
  182772. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182773. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182774. #endif
  182775. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182776. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182777. #endif
  182778. /* Transform masks for the high-level interface */
  182779. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182780. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182781. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182782. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182783. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182784. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182785. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182786. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182787. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182788. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182789. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182790. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182791. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182792. /* Flags for MNG supported features */
  182793. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182794. #define PNG_FLAG_MNG_FILTER_64 0x04
  182795. #define PNG_ALL_MNG_FEATURES 0x05
  182796. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182797. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182798. /* The structure that holds the information to read and write PNG files.
  182799. * The only people who need to care about what is inside of this are the
  182800. * people who will be modifying the library for their own special needs.
  182801. * It should NOT be accessed directly by an application, except to store
  182802. * the jmp_buf.
  182803. */
  182804. struct png_struct_def
  182805. {
  182806. #ifdef PNG_SETJMP_SUPPORTED
  182807. jmp_buf jmpbuf; /* used in png_error */
  182808. #endif
  182809. png_error_ptr error_fn; /* function for printing errors and aborting */
  182810. png_error_ptr warning_fn; /* function for printing warnings */
  182811. png_voidp error_ptr; /* user supplied struct for error functions */
  182812. png_rw_ptr write_data_fn; /* function for writing output data */
  182813. png_rw_ptr read_data_fn; /* function for reading input data */
  182814. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182815. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182816. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182817. #endif
  182818. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182819. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182820. #endif
  182821. /* These were added in libpng-1.0.2 */
  182822. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182823. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182824. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182825. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182826. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182827. png_byte user_transform_channels; /* channels in user transformed pixels */
  182828. #endif
  182829. #endif
  182830. png_uint_32 mode; /* tells us where we are in the PNG file */
  182831. png_uint_32 flags; /* flags indicating various things to libpng */
  182832. png_uint_32 transformations; /* which transformations to perform */
  182833. z_stream zstream; /* pointer to decompression structure (below) */
  182834. png_bytep zbuf; /* buffer for zlib */
  182835. png_size_t zbuf_size; /* size of zbuf */
  182836. int zlib_level; /* holds zlib compression level */
  182837. int zlib_method; /* holds zlib compression method */
  182838. int zlib_window_bits; /* holds zlib compression window bits */
  182839. int zlib_mem_level; /* holds zlib compression memory level */
  182840. int zlib_strategy; /* holds zlib compression strategy */
  182841. png_uint_32 width; /* width of image in pixels */
  182842. png_uint_32 height; /* height of image in pixels */
  182843. png_uint_32 num_rows; /* number of rows in current pass */
  182844. png_uint_32 usr_width; /* width of row at start of write */
  182845. png_uint_32 rowbytes; /* size of row in bytes */
  182846. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182847. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182848. png_uint_32 row_number; /* current row in interlace pass */
  182849. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182850. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182851. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182852. png_bytep up_row; /* buffer to save "up" row when filtering */
  182853. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182854. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182855. png_row_info row_info; /* used for transformation routines */
  182856. png_uint_32 idat_size; /* current IDAT size for read */
  182857. png_uint_32 crc; /* current chunk CRC value */
  182858. png_colorp palette; /* palette from the input file */
  182859. png_uint_16 num_palette; /* number of color entries in palette */
  182860. png_uint_16 num_trans; /* number of transparency values */
  182861. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182862. png_byte compression; /* file compression type (always 0) */
  182863. png_byte filter; /* file filter type (always 0) */
  182864. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182865. png_byte pass; /* current interlace pass (0 - 6) */
  182866. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182867. png_byte color_type; /* color type of file */
  182868. png_byte bit_depth; /* bit depth of file */
  182869. png_byte usr_bit_depth; /* bit depth of users row */
  182870. png_byte pixel_depth; /* number of bits per pixel */
  182871. png_byte channels; /* number of channels in file */
  182872. png_byte usr_channels; /* channels at start of write */
  182873. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182874. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182875. #ifdef PNG_LEGACY_SUPPORTED
  182876. png_byte filler; /* filler byte for pixel expansion */
  182877. #else
  182878. png_uint_16 filler; /* filler bytes for pixel expansion */
  182879. #endif
  182880. #endif
  182881. #if defined(PNG_bKGD_SUPPORTED)
  182882. png_byte background_gamma_type;
  182883. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182884. float background_gamma;
  182885. # endif
  182886. png_color_16 background; /* background color in screen gamma space */
  182887. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182888. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182889. #endif
  182890. #endif /* PNG_bKGD_SUPPORTED */
  182891. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182892. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182893. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182894. png_uint_32 flush_rows; /* number of rows written since last flush */
  182895. #endif
  182896. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182897. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182898. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182899. float gamma; /* file gamma value */
  182900. float screen_gamma; /* screen gamma value (display_exponent) */
  182901. #endif
  182902. #endif
  182903. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182904. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182905. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182906. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182907. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182908. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182909. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182910. #endif
  182911. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182912. png_color_8 sig_bit; /* significant bits in each available channel */
  182913. #endif
  182914. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182915. png_color_8 shift; /* shift for significant bit tranformation */
  182916. #endif
  182917. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182918. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182919. png_bytep trans; /* transparency values for paletted files */
  182920. png_color_16 trans_values; /* transparency values for non-paletted files */
  182921. #endif
  182922. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182923. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182924. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182925. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182926. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182927. png_progressive_end_ptr end_fn; /* called after image is complete */
  182928. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182929. png_bytep save_buffer; /* buffer for previously read data */
  182930. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182931. png_bytep current_buffer; /* buffer for recently used data */
  182932. png_uint_32 push_length; /* size of current input chunk */
  182933. png_uint_32 skip_length; /* bytes to skip in input data */
  182934. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182935. png_size_t save_buffer_max; /* total size of save_buffer */
  182936. png_size_t buffer_size; /* total amount of available input data */
  182937. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182938. int process_mode; /* what push library is currently doing */
  182939. int cur_palette; /* current push library palette index */
  182940. # if defined(PNG_TEXT_SUPPORTED)
  182941. png_size_t current_text_size; /* current size of text input data */
  182942. png_size_t current_text_left; /* how much text left to read in input */
  182943. png_charp current_text; /* current text chunk buffer */
  182944. png_charp current_text_ptr; /* current location in current_text */
  182945. # endif /* PNG_TEXT_SUPPORTED */
  182946. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182947. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182948. /* for the Borland special 64K segment handler */
  182949. png_bytepp offset_table_ptr;
  182950. png_bytep offset_table;
  182951. png_uint_16 offset_table_number;
  182952. png_uint_16 offset_table_count;
  182953. png_uint_16 offset_table_count_free;
  182954. #endif
  182955. #if defined(PNG_READ_DITHER_SUPPORTED)
  182956. png_bytep palette_lookup; /* lookup table for dithering */
  182957. png_bytep dither_index; /* index translation for palette files */
  182958. #endif
  182959. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182960. png_uint_16p hist; /* histogram */
  182961. #endif
  182962. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182963. png_byte heuristic_method; /* heuristic for row filter selection */
  182964. png_byte num_prev_filters; /* number of weights for previous rows */
  182965. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182966. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182967. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182968. png_uint_16p filter_costs; /* relative filter calculation cost */
  182969. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182970. #endif
  182971. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182972. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182973. #endif
  182974. /* New members added in libpng-1.0.6 */
  182975. #ifdef PNG_FREE_ME_SUPPORTED
  182976. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182977. #endif
  182978. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182979. png_voidp user_chunk_ptr;
  182980. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182981. #endif
  182982. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182983. int num_chunk_list;
  182984. png_bytep chunk_list;
  182985. #endif
  182986. /* New members added in libpng-1.0.3 */
  182987. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182988. png_byte rgb_to_gray_status;
  182989. /* These were changed from png_byte in libpng-1.0.6 */
  182990. png_uint_16 rgb_to_gray_red_coeff;
  182991. png_uint_16 rgb_to_gray_green_coeff;
  182992. png_uint_16 rgb_to_gray_blue_coeff;
  182993. #endif
  182994. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182995. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182996. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182997. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182998. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182999. #ifdef PNG_1_0_X
  183000. png_byte mng_features_permitted;
  183001. #else
  183002. png_uint_32 mng_features_permitted;
  183003. #endif /* PNG_1_0_X */
  183004. #endif
  183005. /* New member added in libpng-1.0.7 */
  183006. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183007. png_fixed_point int_gamma;
  183008. #endif
  183009. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183010. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183011. png_byte filter_type;
  183012. #endif
  183013. #if defined(PNG_1_0_X)
  183014. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183015. png_uint_32 row_buf_size;
  183016. #endif
  183017. /* New members added in libpng-1.2.0 */
  183018. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183019. # if !defined(PNG_1_0_X)
  183020. # if defined(PNG_MMX_CODE_SUPPORTED)
  183021. png_byte mmx_bitdepth_threshold;
  183022. png_uint_32 mmx_rowbytes_threshold;
  183023. # endif
  183024. png_uint_32 asm_flags;
  183025. # endif
  183026. #endif
  183027. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183028. #ifdef PNG_USER_MEM_SUPPORTED
  183029. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183030. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183031. png_free_ptr free_fn; /* function for freeing memory */
  183032. #endif
  183033. /* New member added in libpng-1.0.13 and 1.2.0 */
  183034. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183035. #if defined(PNG_READ_DITHER_SUPPORTED)
  183036. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183037. png_bytep dither_sort; /* working sort array */
  183038. png_bytep index_to_palette; /* where the original index currently is */
  183039. /* in the palette */
  183040. png_bytep palette_to_index; /* which original index points to this */
  183041. /* palette color */
  183042. #endif
  183043. /* New members added in libpng-1.0.16 and 1.2.6 */
  183044. png_byte compression_type;
  183045. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183046. png_uint_32 user_width_max;
  183047. png_uint_32 user_height_max;
  183048. #endif
  183049. /* New member added in libpng-1.0.25 and 1.2.17 */
  183050. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183051. /* storage for unknown chunk that the library doesn't recognize. */
  183052. png_unknown_chunk unknown_chunk;
  183053. #endif
  183054. };
  183055. /* This triggers a compiler error in png.c, if png.c and png.h
  183056. * do not agree upon the version number.
  183057. */
  183058. typedef png_structp version_1_2_21;
  183059. typedef png_struct FAR * FAR * png_structpp;
  183060. /* Here are the function definitions most commonly used. This is not
  183061. * the place to find out how to use libpng. See libpng.txt for the
  183062. * full explanation, see example.c for the summary. This just provides
  183063. * a simple one line description of the use of each function.
  183064. */
  183065. /* Returns the version number of the library */
  183066. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183067. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183068. * Handling more than 8 bytes from the beginning of the file is an error.
  183069. */
  183070. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183071. int num_bytes));
  183072. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183073. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183074. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183075. * start > 7 will always fail (ie return non-zero).
  183076. */
  183077. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183078. png_size_t num_to_check));
  183079. /* Simple signature checking function. This is the same as calling
  183080. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183081. */
  183082. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183083. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183084. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183085. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183086. png_error_ptr error_fn, png_error_ptr warn_fn));
  183087. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183088. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183089. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183090. png_error_ptr error_fn, png_error_ptr warn_fn));
  183091. #ifdef PNG_WRITE_SUPPORTED
  183092. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183093. PNGARG((png_structp png_ptr));
  183094. #endif
  183095. #ifdef PNG_WRITE_SUPPORTED
  183096. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183097. PNGARG((png_structp png_ptr, png_uint_32 size));
  183098. #endif
  183099. /* Reset the compression stream */
  183100. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183101. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183102. #ifdef PNG_USER_MEM_SUPPORTED
  183103. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183104. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183105. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183106. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183107. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183108. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183109. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183110. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183111. #endif
  183112. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183113. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183114. png_bytep chunk_name, png_bytep data, png_size_t length));
  183115. /* Write the start of a PNG chunk - length and chunk name. */
  183116. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183117. png_bytep chunk_name, png_uint_32 length));
  183118. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183119. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183120. png_bytep data, png_size_t length));
  183121. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183122. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183123. /* Allocate and initialize the info structure */
  183124. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183125. PNGARG((png_structp png_ptr));
  183126. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183127. /* Initialize the info structure (old interface - DEPRECATED) */
  183128. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183129. #undef png_info_init
  183130. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183131. png_sizeof(png_info));
  183132. #endif
  183133. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183134. png_size_t png_info_struct_size));
  183135. /* Writes all the PNG information before the image. */
  183136. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183137. png_infop info_ptr));
  183138. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183139. png_infop info_ptr));
  183140. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183141. /* read the information before the actual image data. */
  183142. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183143. png_infop info_ptr));
  183144. #endif
  183145. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183146. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183147. PNGARG((png_structp png_ptr, png_timep ptime));
  183148. #endif
  183149. #if !defined(_WIN32_WCE)
  183150. /* "time.h" functions are not supported on WindowsCE */
  183151. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183152. /* convert from a struct tm to png_time */
  183153. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183154. struct tm FAR * ttime));
  183155. /* convert from time_t to png_time. Uses gmtime() */
  183156. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183157. time_t ttime));
  183158. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183159. #endif /* _WIN32_WCE */
  183160. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183161. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183162. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183163. #if !defined(PNG_1_0_X)
  183164. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183165. png_ptr));
  183166. #endif
  183167. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183168. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183169. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183170. /* Deprecated */
  183171. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183172. #endif
  183173. #endif
  183174. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183175. /* Use blue, green, red order for pixels. */
  183176. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183177. #endif
  183178. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183179. /* Expand the grayscale to 24-bit RGB if necessary. */
  183180. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183181. #endif
  183182. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183183. /* Reduce RGB to grayscale. */
  183184. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183185. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183186. int error_action, double red, double green ));
  183187. #endif
  183188. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183189. int error_action, png_fixed_point red, png_fixed_point green ));
  183190. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183191. png_ptr));
  183192. #endif
  183193. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183194. png_colorp palette));
  183195. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183196. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183197. #endif
  183198. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183199. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183200. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183201. #endif
  183202. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183203. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183204. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183205. #endif
  183206. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183207. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183208. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183209. png_uint_32 filler, int flags));
  183210. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183211. #define PNG_FILLER_BEFORE 0
  183212. #define PNG_FILLER_AFTER 1
  183213. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183214. #if !defined(PNG_1_0_X)
  183215. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183216. png_uint_32 filler, int flags));
  183217. #endif
  183218. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183219. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183220. /* Swap bytes in 16-bit depth files. */
  183221. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183222. #endif
  183223. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183224. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183225. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183226. #endif
  183227. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183228. /* Swap packing order of pixels in bytes. */
  183229. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183230. #endif
  183231. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183232. /* Converts files to legal bit depths. */
  183233. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183234. png_color_8p true_bits));
  183235. #endif
  183236. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183237. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183238. /* Have the code handle the interlacing. Returns the number of passes. */
  183239. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183240. #endif
  183241. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183242. /* Invert monochrome files */
  183243. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183244. #endif
  183245. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183246. /* Handle alpha and tRNS by replacing with a background color. */
  183247. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183248. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183249. png_color_16p background_color, int background_gamma_code,
  183250. int need_expand, double background_gamma));
  183251. #endif
  183252. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183253. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183254. #define PNG_BACKGROUND_GAMMA_FILE 2
  183255. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183256. #endif
  183257. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183258. /* strip the second byte of information from a 16-bit depth file. */
  183259. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183260. #endif
  183261. #if defined(PNG_READ_DITHER_SUPPORTED)
  183262. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183263. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183264. png_colorp palette, int num_palette, int maximum_colors,
  183265. png_uint_16p histogram, int full_dither));
  183266. #endif
  183267. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183268. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183269. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183270. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183271. double screen_gamma, double default_file_gamma));
  183272. #endif
  183273. #endif
  183274. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183275. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183276. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183277. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183278. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183279. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183280. int empty_plte_permitted));
  183281. #endif
  183282. #endif
  183283. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183284. /* Set how many lines between output flushes - 0 for no flushing */
  183285. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183286. /* Flush the current PNG output buffer */
  183287. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183288. #endif
  183289. /* optional update palette with requested transformations */
  183290. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183291. /* optional call to update the users info structure */
  183292. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183293. png_infop info_ptr));
  183294. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183295. /* read one or more rows of image data. */
  183296. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183297. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183298. #endif
  183299. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183300. /* read a row of data. */
  183301. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183302. png_bytep row,
  183303. png_bytep display_row));
  183304. #endif
  183305. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183306. /* read the whole image into memory at once. */
  183307. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183308. png_bytepp image));
  183309. #endif
  183310. /* write a row of image data */
  183311. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183312. png_bytep row));
  183313. /* write a few rows of image data */
  183314. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183315. png_bytepp row, png_uint_32 num_rows));
  183316. /* write the image data */
  183317. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183318. png_bytepp image));
  183319. /* writes the end of the PNG file. */
  183320. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183321. png_infop info_ptr));
  183322. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183323. /* read the end of the PNG file. */
  183324. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183325. png_infop info_ptr));
  183326. #endif
  183327. /* free any memory associated with the png_info_struct */
  183328. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183329. png_infopp info_ptr_ptr));
  183330. /* free any memory associated with the png_struct and the png_info_structs */
  183331. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183332. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183333. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183334. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183335. png_infop end_info_ptr));
  183336. /* free any memory associated with the png_struct and the png_info_structs */
  183337. extern PNG_EXPORT(void,png_destroy_write_struct)
  183338. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183339. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183340. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183341. /* set the libpng method of handling chunk CRC errors */
  183342. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183343. int crit_action, int ancil_action));
  183344. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183345. * ancillary and critical chunks, and whether to use the data contained
  183346. * therein. Note that it is impossible to "discard" data in a critical
  183347. * chunk. For versions prior to 0.90, the action was always error/quit,
  183348. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183349. * chunks is warn/discard. These values should NOT be changed.
  183350. *
  183351. * value action:critical action:ancillary
  183352. */
  183353. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183354. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183355. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183356. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183357. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183358. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183359. /* These functions give the user control over the scan-line filtering in
  183360. * libpng and the compression methods used by zlib. These functions are
  183361. * mainly useful for testing, as the defaults should work with most users.
  183362. * Those users who are tight on memory or want faster performance at the
  183363. * expense of compression can modify them. See the compression library
  183364. * header file (zlib.h) for an explination of the compression functions.
  183365. */
  183366. /* set the filtering method(s) used by libpng. Currently, the only valid
  183367. * value for "method" is 0.
  183368. */
  183369. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183370. int filters));
  183371. /* Flags for png_set_filter() to say which filters to use. The flags
  183372. * are chosen so that they don't conflict with real filter types
  183373. * below, in case they are supplied instead of the #defined constants.
  183374. * These values should NOT be changed.
  183375. */
  183376. #define PNG_NO_FILTERS 0x00
  183377. #define PNG_FILTER_NONE 0x08
  183378. #define PNG_FILTER_SUB 0x10
  183379. #define PNG_FILTER_UP 0x20
  183380. #define PNG_FILTER_AVG 0x40
  183381. #define PNG_FILTER_PAETH 0x80
  183382. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183383. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183384. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183385. * These defines should NOT be changed.
  183386. */
  183387. #define PNG_FILTER_VALUE_NONE 0
  183388. #define PNG_FILTER_VALUE_SUB 1
  183389. #define PNG_FILTER_VALUE_UP 2
  183390. #define PNG_FILTER_VALUE_AVG 3
  183391. #define PNG_FILTER_VALUE_PAETH 4
  183392. #define PNG_FILTER_VALUE_LAST 5
  183393. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183394. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183395. * defines, either the default (minimum-sum-of-absolute-differences), or
  183396. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183397. *
  183398. * Weights are factors >= 1.0, indicating how important it is to keep the
  183399. * filter type consistent between rows. Larger numbers mean the current
  183400. * filter is that many times as likely to be the same as the "num_weights"
  183401. * previous filters. This is cumulative for each previous row with a weight.
  183402. * There needs to be "num_weights" values in "filter_weights", or it can be
  183403. * NULL if the weights aren't being specified. Weights have no influence on
  183404. * the selection of the first row filter. Well chosen weights can (in theory)
  183405. * improve the compression for a given image.
  183406. *
  183407. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183408. * filter type. Higher costs indicate more decoding expense, and are
  183409. * therefore less likely to be selected over a filter with lower computational
  183410. * costs. There needs to be a value in "filter_costs" for each valid filter
  183411. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183412. * setting the costs. Costs try to improve the speed of decompression without
  183413. * unduly increasing the compressed image size.
  183414. *
  183415. * A negative weight or cost indicates the default value is to be used, and
  183416. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183417. * The default values for both weights and costs are currently 1.0, but may
  183418. * change if good general weighting/cost heuristics can be found. If both
  183419. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183420. * to the UNWEIGHTED method, but with added encoding time/computation.
  183421. */
  183422. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183423. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183424. int heuristic_method, int num_weights, png_doublep filter_weights,
  183425. png_doublep filter_costs));
  183426. #endif
  183427. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183428. /* Heuristic used for row filter selection. These defines should NOT be
  183429. * changed.
  183430. */
  183431. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183432. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183433. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183434. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183435. /* Set the library compression level. Currently, valid values range from
  183436. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183437. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183438. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183439. * for PNG images, and do considerably fewer caclulations. In the future,
  183440. * these values may not correspond directly to the zlib compression levels.
  183441. */
  183442. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183443. int level));
  183444. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183445. PNGARG((png_structp png_ptr, int mem_level));
  183446. extern PNG_EXPORT(void,png_set_compression_strategy)
  183447. PNGARG((png_structp png_ptr, int strategy));
  183448. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183449. PNGARG((png_structp png_ptr, int window_bits));
  183450. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183451. int method));
  183452. /* These next functions are called for input/output, memory, and error
  183453. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183454. * and call standard C I/O routines such as fread(), fwrite(), and
  183455. * fprintf(). These functions can be made to use other I/O routines
  183456. * at run time for those applications that need to handle I/O in a
  183457. * different manner by calling png_set_???_fn(). See libpng.txt for
  183458. * more information.
  183459. */
  183460. #if !defined(PNG_NO_STDIO)
  183461. /* Initialize the input/output for the PNG file to the default functions. */
  183462. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183463. #endif
  183464. /* Replace the (error and abort), and warning functions with user
  183465. * supplied functions. If no messages are to be printed you must still
  183466. * write and use replacement functions. The replacement error_fn should
  183467. * still do a longjmp to the last setjmp location if you are using this
  183468. * method of error handling. If error_fn or warning_fn is NULL, the
  183469. * default function will be used.
  183470. */
  183471. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183472. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183473. /* Return the user pointer associated with the error functions */
  183474. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183475. /* Replace the default data output functions with a user supplied one(s).
  183476. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183477. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183478. * output_flush_fn will be ignored (and thus can be NULL).
  183479. */
  183480. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183481. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183482. /* Replace the default data input function with a user supplied one. */
  183483. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183484. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183485. /* Return the user pointer associated with the I/O functions */
  183486. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183487. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183488. png_read_status_ptr read_row_fn));
  183489. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183490. png_write_status_ptr write_row_fn));
  183491. #ifdef PNG_USER_MEM_SUPPORTED
  183492. /* Replace the default memory allocation functions with user supplied one(s). */
  183493. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183494. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183495. /* Return the user pointer associated with the memory functions */
  183496. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183497. #endif
  183498. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183499. defined(PNG_LEGACY_SUPPORTED)
  183500. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183501. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183502. #endif
  183503. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183504. defined(PNG_LEGACY_SUPPORTED)
  183505. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183506. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183507. #endif
  183508. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183509. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183510. defined(PNG_LEGACY_SUPPORTED)
  183511. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183512. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183513. int user_transform_channels));
  183514. /* Return the user pointer associated with the user transform functions */
  183515. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183516. PNGARG((png_structp png_ptr));
  183517. #endif
  183518. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183519. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183520. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183521. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183522. png_ptr));
  183523. #endif
  183524. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183525. /* Sets the function callbacks for the push reader, and a pointer to a
  183526. * user-defined structure available to the callback functions.
  183527. */
  183528. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183529. png_voidp progressive_ptr,
  183530. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183531. png_progressive_end_ptr end_fn));
  183532. /* returns the user pointer associated with the push read functions */
  183533. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183534. PNGARG((png_structp png_ptr));
  183535. /* function to be called when data becomes available */
  183536. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183537. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183538. /* function that combines rows. Not very much different than the
  183539. * png_combine_row() call. Is this even used?????
  183540. */
  183541. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183542. png_bytep old_row, png_bytep new_row));
  183543. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183544. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183545. png_uint_32 size));
  183546. #if defined(PNG_1_0_X)
  183547. # define png_malloc_warn png_malloc
  183548. #else
  183549. /* Added at libpng version 1.2.4 */
  183550. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183551. png_uint_32 size));
  183552. #endif
  183553. /* frees a pointer allocated by png_malloc() */
  183554. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183555. #if defined(PNG_1_0_X)
  183556. /* Function to allocate memory for zlib. */
  183557. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183558. uInt size));
  183559. /* Function to free memory for zlib */
  183560. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183561. #endif
  183562. /* Free data that was allocated internally */
  183563. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183564. png_infop info_ptr, png_uint_32 free_me, int num));
  183565. #ifdef PNG_FREE_ME_SUPPORTED
  183566. /* Reassign responsibility for freeing existing data, whether allocated
  183567. * by libpng or by the application */
  183568. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183569. png_infop info_ptr, int freer, png_uint_32 mask));
  183570. #endif
  183571. /* assignments for png_data_freer */
  183572. #define PNG_DESTROY_WILL_FREE_DATA 1
  183573. #define PNG_SET_WILL_FREE_DATA 1
  183574. #define PNG_USER_WILL_FREE_DATA 2
  183575. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183576. #define PNG_FREE_HIST 0x0008
  183577. #define PNG_FREE_ICCP 0x0010
  183578. #define PNG_FREE_SPLT 0x0020
  183579. #define PNG_FREE_ROWS 0x0040
  183580. #define PNG_FREE_PCAL 0x0080
  183581. #define PNG_FREE_SCAL 0x0100
  183582. #define PNG_FREE_UNKN 0x0200
  183583. #define PNG_FREE_LIST 0x0400
  183584. #define PNG_FREE_PLTE 0x1000
  183585. #define PNG_FREE_TRNS 0x2000
  183586. #define PNG_FREE_TEXT 0x4000
  183587. #define PNG_FREE_ALL 0x7fff
  183588. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183589. #ifdef PNG_USER_MEM_SUPPORTED
  183590. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183591. png_uint_32 size));
  183592. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183593. png_voidp ptr));
  183594. #endif
  183595. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183596. png_voidp s1, png_voidp s2, png_uint_32 size));
  183597. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183598. png_voidp s1, int value, png_uint_32 size));
  183599. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183600. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183601. int check));
  183602. #endif /* USE_FAR_KEYWORD */
  183603. #ifndef PNG_NO_ERROR_TEXT
  183604. /* Fatal error in PNG image of libpng - can't continue */
  183605. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183606. png_const_charp error_message));
  183607. /* The same, but the chunk name is prepended to the error string. */
  183608. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183609. png_const_charp error_message));
  183610. #else
  183611. /* Fatal error in PNG image of libpng - can't continue */
  183612. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183613. #endif
  183614. #ifndef PNG_NO_WARNINGS
  183615. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183616. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183617. png_const_charp warning_message));
  183618. #ifdef PNG_READ_SUPPORTED
  183619. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183620. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183621. png_const_charp warning_message));
  183622. #endif /* PNG_READ_SUPPORTED */
  183623. #endif /* PNG_NO_WARNINGS */
  183624. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183625. * Similarly, the png_get_<chunk> calls are used to read values from the
  183626. * png_info_struct, either storing the parameters in the passed variables, or
  183627. * setting pointers into the png_info_struct where the data is stored. The
  183628. * png_get_<chunk> functions return a non-zero value if the data was available
  183629. * in info_ptr, or return zero and do not change any of the parameters if the
  183630. * data was not available.
  183631. *
  183632. * These functions should be used instead of directly accessing png_info
  183633. * to avoid problems with future changes in the size and internal layout of
  183634. * png_info_struct.
  183635. */
  183636. /* Returns "flag" if chunk data is valid in info_ptr. */
  183637. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183638. png_infop info_ptr, png_uint_32 flag));
  183639. /* Returns number of bytes needed to hold a transformed row. */
  183640. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183641. png_infop info_ptr));
  183642. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183643. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183644. returned from png_read_png(). */
  183645. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183646. png_infop info_ptr));
  183647. /* Set row_pointers, which is an array of pointers to scanlines for use
  183648. by png_write_png(). */
  183649. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183650. png_infop info_ptr, png_bytepp row_pointers));
  183651. #endif
  183652. /* Returns number of color channels in image. */
  183653. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183654. png_infop info_ptr));
  183655. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183656. /* Returns image width in pixels. */
  183657. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183658. png_ptr, png_infop info_ptr));
  183659. /* Returns image height in pixels. */
  183660. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183661. png_ptr, png_infop info_ptr));
  183662. /* Returns image bit_depth. */
  183663. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183664. png_ptr, png_infop info_ptr));
  183665. /* Returns image color_type. */
  183666. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183667. png_ptr, png_infop info_ptr));
  183668. /* Returns image filter_type. */
  183669. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183670. png_ptr, png_infop info_ptr));
  183671. /* Returns image interlace_type. */
  183672. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183673. png_ptr, png_infop info_ptr));
  183674. /* Returns image compression_type. */
  183675. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183676. png_ptr, png_infop info_ptr));
  183677. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183678. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183679. png_ptr, png_infop info_ptr));
  183680. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183681. png_ptr, png_infop info_ptr));
  183682. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183683. png_ptr, png_infop info_ptr));
  183684. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183685. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183686. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183687. png_ptr, png_infop info_ptr));
  183688. #endif
  183689. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183690. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183691. png_ptr, png_infop info_ptr));
  183692. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183693. png_ptr, png_infop info_ptr));
  183694. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183695. png_ptr, png_infop info_ptr));
  183696. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183697. png_ptr, png_infop info_ptr));
  183698. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183699. /* Returns pointer to signature string read from PNG header */
  183700. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183701. png_infop info_ptr));
  183702. #if defined(PNG_bKGD_SUPPORTED)
  183703. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183704. png_infop info_ptr, png_color_16p *background));
  183705. #endif
  183706. #if defined(PNG_bKGD_SUPPORTED)
  183707. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183708. png_infop info_ptr, png_color_16p background));
  183709. #endif
  183710. #if defined(PNG_cHRM_SUPPORTED)
  183711. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183712. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183713. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183714. double *red_y, double *green_x, double *green_y, double *blue_x,
  183715. double *blue_y));
  183716. #endif
  183717. #ifdef PNG_FIXED_POINT_SUPPORTED
  183718. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183719. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183720. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183721. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183722. *int_blue_x, png_fixed_point *int_blue_y));
  183723. #endif
  183724. #endif
  183725. #if defined(PNG_cHRM_SUPPORTED)
  183726. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183727. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183728. png_infop info_ptr, double white_x, double white_y, double red_x,
  183729. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183730. #endif
  183731. #ifdef PNG_FIXED_POINT_SUPPORTED
  183732. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183733. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183734. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183735. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183736. png_fixed_point int_blue_y));
  183737. #endif
  183738. #endif
  183739. #if defined(PNG_gAMA_SUPPORTED)
  183740. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183741. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183742. png_infop info_ptr, double *file_gamma));
  183743. #endif
  183744. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183745. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183746. #endif
  183747. #if defined(PNG_gAMA_SUPPORTED)
  183748. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183749. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183750. png_infop info_ptr, double file_gamma));
  183751. #endif
  183752. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183753. png_infop info_ptr, png_fixed_point int_file_gamma));
  183754. #endif
  183755. #if defined(PNG_hIST_SUPPORTED)
  183756. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183757. png_infop info_ptr, png_uint_16p *hist));
  183758. #endif
  183759. #if defined(PNG_hIST_SUPPORTED)
  183760. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183761. png_infop info_ptr, png_uint_16p hist));
  183762. #endif
  183763. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183764. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183765. int *bit_depth, int *color_type, int *interlace_method,
  183766. int *compression_method, int *filter_method));
  183767. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183768. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183769. int color_type, int interlace_method, int compression_method,
  183770. int filter_method));
  183771. #if defined(PNG_oFFs_SUPPORTED)
  183772. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183773. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183774. int *unit_type));
  183775. #endif
  183776. #if defined(PNG_oFFs_SUPPORTED)
  183777. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183778. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183779. int unit_type));
  183780. #endif
  183781. #if defined(PNG_pCAL_SUPPORTED)
  183782. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183783. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183784. int *type, int *nparams, png_charp *units, png_charpp *params));
  183785. #endif
  183786. #if defined(PNG_pCAL_SUPPORTED)
  183787. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183788. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183789. int type, int nparams, png_charp units, png_charpp params));
  183790. #endif
  183791. #if defined(PNG_pHYs_SUPPORTED)
  183792. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183793. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183794. #endif
  183795. #if defined(PNG_pHYs_SUPPORTED)
  183796. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183797. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183798. #endif
  183799. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183800. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183801. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183802. png_infop info_ptr, png_colorp palette, int num_palette));
  183803. #if defined(PNG_sBIT_SUPPORTED)
  183804. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183805. png_infop info_ptr, png_color_8p *sig_bit));
  183806. #endif
  183807. #if defined(PNG_sBIT_SUPPORTED)
  183808. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183809. png_infop info_ptr, png_color_8p sig_bit));
  183810. #endif
  183811. #if defined(PNG_sRGB_SUPPORTED)
  183812. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183813. png_infop info_ptr, int *intent));
  183814. #endif
  183815. #if defined(PNG_sRGB_SUPPORTED)
  183816. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183817. png_infop info_ptr, int intent));
  183818. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183819. png_infop info_ptr, int intent));
  183820. #endif
  183821. #if defined(PNG_iCCP_SUPPORTED)
  183822. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183823. png_infop info_ptr, png_charpp name, int *compression_type,
  183824. png_charpp profile, png_uint_32 *proflen));
  183825. /* Note to maintainer: profile should be png_bytepp */
  183826. #endif
  183827. #if defined(PNG_iCCP_SUPPORTED)
  183828. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183829. png_infop info_ptr, png_charp name, int compression_type,
  183830. png_charp profile, png_uint_32 proflen));
  183831. /* Note to maintainer: profile should be png_bytep */
  183832. #endif
  183833. #if defined(PNG_sPLT_SUPPORTED)
  183834. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183835. png_infop info_ptr, png_sPLT_tpp entries));
  183836. #endif
  183837. #if defined(PNG_sPLT_SUPPORTED)
  183838. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183839. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183840. #endif
  183841. #if defined(PNG_TEXT_SUPPORTED)
  183842. /* png_get_text also returns the number of text chunks in *num_text */
  183843. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183844. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183845. #endif
  183846. /*
  183847. * Note while png_set_text() will accept a structure whose text,
  183848. * language, and translated keywords are NULL pointers, the structure
  183849. * returned by png_get_text will always contain regular
  183850. * zero-terminated C strings. They might be empty strings but
  183851. * they will never be NULL pointers.
  183852. */
  183853. #if defined(PNG_TEXT_SUPPORTED)
  183854. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183855. png_infop info_ptr, png_textp text_ptr, int num_text));
  183856. #endif
  183857. #if defined(PNG_tIME_SUPPORTED)
  183858. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183859. png_infop info_ptr, png_timep *mod_time));
  183860. #endif
  183861. #if defined(PNG_tIME_SUPPORTED)
  183862. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183863. png_infop info_ptr, png_timep mod_time));
  183864. #endif
  183865. #if defined(PNG_tRNS_SUPPORTED)
  183866. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183867. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183868. png_color_16p *trans_values));
  183869. #endif
  183870. #if defined(PNG_tRNS_SUPPORTED)
  183871. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183872. png_infop info_ptr, png_bytep trans, int num_trans,
  183873. png_color_16p trans_values));
  183874. #endif
  183875. #if defined(PNG_tRNS_SUPPORTED)
  183876. #endif
  183877. #if defined(PNG_sCAL_SUPPORTED)
  183878. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183879. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183880. png_infop info_ptr, int *unit, double *width, double *height));
  183881. #else
  183882. #ifdef PNG_FIXED_POINT_SUPPORTED
  183883. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183884. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183885. #endif
  183886. #endif
  183887. #endif /* PNG_sCAL_SUPPORTED */
  183888. #if defined(PNG_sCAL_SUPPORTED)
  183889. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183890. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183891. png_infop info_ptr, int unit, double width, double height));
  183892. #else
  183893. #ifdef PNG_FIXED_POINT_SUPPORTED
  183894. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183895. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183896. #endif
  183897. #endif
  183898. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183899. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183900. /* provide a list of chunks and how they are to be handled, if the built-in
  183901. handling or default unknown chunk handling is not desired. Any chunks not
  183902. listed will be handled in the default manner. The IHDR and IEND chunks
  183903. must not be listed.
  183904. keep = 0: follow default behaviour
  183905. = 1: do not keep
  183906. = 2: keep only if safe-to-copy
  183907. = 3: keep even if unsafe-to-copy
  183908. */
  183909. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183910. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183911. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183912. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183913. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183914. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183915. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183916. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183917. #endif
  183918. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183919. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183920. chunk_name));
  183921. #endif
  183922. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183923. If you need to turn it off for a chunk that your application has freed,
  183924. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183925. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183926. png_infop info_ptr, int mask));
  183927. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183928. /* The "params" pointer is currently not used and is for future expansion. */
  183929. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183930. png_infop info_ptr,
  183931. int transforms,
  183932. png_voidp params));
  183933. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183934. png_infop info_ptr,
  183935. int transforms,
  183936. png_voidp params));
  183937. #endif
  183938. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183939. * numbers for PNG_DEBUG mean more debugging information. This has
  183940. * only been added since version 0.95 so it is not implemented throughout
  183941. * libpng yet, but more support will be added as needed.
  183942. */
  183943. #ifdef PNG_DEBUG
  183944. #if (PNG_DEBUG > 0)
  183945. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183946. #include <crtdbg.h>
  183947. #if (PNG_DEBUG > 1)
  183948. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183949. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183950. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183951. #endif
  183952. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183953. #ifndef PNG_DEBUG_FILE
  183954. #define PNG_DEBUG_FILE stderr
  183955. #endif /* PNG_DEBUG_FILE */
  183956. #if (PNG_DEBUG > 1)
  183957. #define png_debug(l,m) \
  183958. { \
  183959. int num_tabs=l; \
  183960. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183961. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183962. }
  183963. #define png_debug1(l,m,p1) \
  183964. { \
  183965. int num_tabs=l; \
  183966. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183967. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183968. }
  183969. #define png_debug2(l,m,p1,p2) \
  183970. { \
  183971. int num_tabs=l; \
  183972. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183973. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183974. }
  183975. #endif /* (PNG_DEBUG > 1) */
  183976. #endif /* _MSC_VER */
  183977. #endif /* (PNG_DEBUG > 0) */
  183978. #endif /* PNG_DEBUG */
  183979. #ifndef png_debug
  183980. #define png_debug(l, m)
  183981. #endif
  183982. #ifndef png_debug1
  183983. #define png_debug1(l, m, p1)
  183984. #endif
  183985. #ifndef png_debug2
  183986. #define png_debug2(l, m, p1, p2)
  183987. #endif
  183988. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183989. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183990. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183991. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183992. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183993. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183994. png_ptr, png_uint_32 mng_features_permitted));
  183995. #endif
  183996. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183997. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183998. #define PNG_HANDLE_CHUNK_NEVER 1
  183999. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184000. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184001. /* Added to version 1.2.0 */
  184002. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184003. #if defined(PNG_MMX_CODE_SUPPORTED)
  184004. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184005. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184006. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184007. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184008. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184009. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184010. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184011. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184012. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184013. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184014. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184015. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184016. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184017. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184018. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184019. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184020. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184021. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184022. | PNG_MMX_READ_FLAGS \
  184023. | PNG_MMX_WRITE_FLAGS )
  184024. #define PNG_SELECT_READ 1
  184025. #define PNG_SELECT_WRITE 2
  184026. #endif /* PNG_MMX_CODE_SUPPORTED */
  184027. #if !defined(PNG_1_0_X)
  184028. /* pngget.c */
  184029. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184030. PNGARG((int flag_select, int *compilerID));
  184031. /* pngget.c */
  184032. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184033. PNGARG((int flag_select));
  184034. /* pngget.c */
  184035. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184036. PNGARG((png_structp png_ptr));
  184037. /* pngget.c */
  184038. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184039. PNGARG((png_structp png_ptr));
  184040. /* pngget.c */
  184041. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184042. PNGARG((png_structp png_ptr));
  184043. /* pngset.c */
  184044. extern PNG_EXPORT(void,png_set_asm_flags)
  184045. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184046. /* pngset.c */
  184047. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184048. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184049. png_uint_32 mmx_rowbytes_threshold));
  184050. #endif /* PNG_1_0_X */
  184051. #if !defined(PNG_1_0_X)
  184052. /* png.c, pnggccrd.c, or pngvcrd.c */
  184053. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184054. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184055. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184056. * messages before passing them to the error or warning handler. */
  184057. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184058. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184059. png_ptr, png_uint_32 strip_mode));
  184060. #endif
  184061. #endif /* PNG_1_0_X */
  184062. /* Added at libpng-1.2.6 */
  184063. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184064. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184065. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184066. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184067. png_ptr));
  184068. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184069. png_ptr));
  184070. #endif
  184071. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184072. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184073. /* With these routines we avoid an integer divide, which will be slower on
  184074. * most machines. However, it does take more operations than the corresponding
  184075. * divide method, so it may be slower on a few RISC systems. There are two
  184076. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184077. *
  184078. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184079. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184080. * standard method.
  184081. *
  184082. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184083. */
  184084. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184085. # define png_composite(composite, fg, alpha, bg) \
  184086. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184087. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184088. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184089. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184090. # define png_composite_16(composite, fg, alpha, bg) \
  184091. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184092. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184093. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184094. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184095. #else /* standard method using integer division */
  184096. # define png_composite(composite, fg, alpha, bg) \
  184097. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184098. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184099. (png_uint_16)127) / 255)
  184100. # define png_composite_16(composite, fg, alpha, bg) \
  184101. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184102. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184103. (png_uint_32)32767) / (png_uint_32)65535L)
  184104. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184105. /* Inline macros to do direct reads of bytes from the input buffer. These
  184106. * require that you are using an architecture that uses PNG byte ordering
  184107. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184108. * in big-endian mode and 680x0 are the only ones that will support this.
  184109. * The x86 line of processors definitely do not. The png_get_int_32()
  184110. * routine also assumes we are using two's complement format for negative
  184111. * values, which is almost certainly true.
  184112. */
  184113. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184114. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184115. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184116. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184117. #else
  184118. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184119. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184120. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184121. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184122. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184123. PNGARG((png_structp png_ptr, png_bytep buf));
  184124. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184125. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184126. */
  184127. extern PNG_EXPORT(void,png_save_uint_32)
  184128. PNGARG((png_bytep buf, png_uint_32 i));
  184129. extern PNG_EXPORT(void,png_save_int_32)
  184130. PNGARG((png_bytep buf, png_int_32 i));
  184131. /* Place a 16-bit number into a buffer in PNG byte order.
  184132. * The parameter is declared unsigned int, not png_uint_16,
  184133. * just to avoid potential problems on pre-ANSI C compilers.
  184134. */
  184135. extern PNG_EXPORT(void,png_save_uint_16)
  184136. PNGARG((png_bytep buf, unsigned int i));
  184137. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184138. /* ************************************************************************* */
  184139. /* These next functions are used internally in the code. They generally
  184140. * shouldn't be used unless you are writing code to add or replace some
  184141. * functionality in libpng. More information about most functions can
  184142. * be found in the files where the functions are located.
  184143. */
  184144. /* Various modes of operation, that are visible to applications because
  184145. * they are used for unknown chunk location.
  184146. */
  184147. #define PNG_HAVE_IHDR 0x01
  184148. #define PNG_HAVE_PLTE 0x02
  184149. #define PNG_HAVE_IDAT 0x04
  184150. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184151. #define PNG_HAVE_IEND 0x10
  184152. #if defined(PNG_INTERNAL)
  184153. /* More modes of operation. Note that after an init, mode is set to
  184154. * zero automatically when the structure is created.
  184155. */
  184156. #define PNG_HAVE_gAMA 0x20
  184157. #define PNG_HAVE_cHRM 0x40
  184158. #define PNG_HAVE_sRGB 0x80
  184159. #define PNG_HAVE_CHUNK_HEADER 0x100
  184160. #define PNG_WROTE_tIME 0x200
  184161. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184162. #define PNG_BACKGROUND_IS_GRAY 0x800
  184163. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184164. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184165. /* flags for the transformations the PNG library does on the image data */
  184166. #define PNG_BGR 0x0001
  184167. #define PNG_INTERLACE 0x0002
  184168. #define PNG_PACK 0x0004
  184169. #define PNG_SHIFT 0x0008
  184170. #define PNG_SWAP_BYTES 0x0010
  184171. #define PNG_INVERT_MONO 0x0020
  184172. #define PNG_DITHER 0x0040
  184173. #define PNG_BACKGROUND 0x0080
  184174. #define PNG_BACKGROUND_EXPAND 0x0100
  184175. /* 0x0200 unused */
  184176. #define PNG_16_TO_8 0x0400
  184177. #define PNG_RGBA 0x0800
  184178. #define PNG_EXPAND 0x1000
  184179. #define PNG_GAMMA 0x2000
  184180. #define PNG_GRAY_TO_RGB 0x4000
  184181. #define PNG_FILLER 0x8000L
  184182. #define PNG_PACKSWAP 0x10000L
  184183. #define PNG_SWAP_ALPHA 0x20000L
  184184. #define PNG_STRIP_ALPHA 0x40000L
  184185. #define PNG_INVERT_ALPHA 0x80000L
  184186. #define PNG_USER_TRANSFORM 0x100000L
  184187. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184188. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184189. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184190. /* 0x800000L Unused */
  184191. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184192. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184193. /* 0x4000000L unused */
  184194. /* 0x8000000L unused */
  184195. /* 0x10000000L unused */
  184196. /* 0x20000000L unused */
  184197. /* 0x40000000L unused */
  184198. /* flags for png_create_struct */
  184199. #define PNG_STRUCT_PNG 0x0001
  184200. #define PNG_STRUCT_INFO 0x0002
  184201. /* Scaling factor for filter heuristic weighting calculations */
  184202. #define PNG_WEIGHT_SHIFT 8
  184203. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184204. #define PNG_COST_SHIFT 3
  184205. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184206. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184207. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184208. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184209. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184210. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184211. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184212. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184213. #define PNG_FLAG_ROW_INIT 0x0040
  184214. #define PNG_FLAG_FILLER_AFTER 0x0080
  184215. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184216. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184217. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184218. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184219. #define PNG_FLAG_FREE_PLTE 0x1000
  184220. #define PNG_FLAG_FREE_TRNS 0x2000
  184221. #define PNG_FLAG_FREE_HIST 0x4000
  184222. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184223. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184224. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184225. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184226. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184227. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184228. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184229. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184230. /* 0x800000L unused */
  184231. /* 0x1000000L unused */
  184232. /* 0x2000000L unused */
  184233. /* 0x4000000L unused */
  184234. /* 0x8000000L unused */
  184235. /* 0x10000000L unused */
  184236. /* 0x20000000L unused */
  184237. /* 0x40000000L unused */
  184238. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184239. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184240. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184241. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184242. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184243. PNG_FLAG_CRC_CRITICAL_MASK)
  184244. /* save typing and make code easier to understand */
  184245. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184246. abs((int)((c1).green) - (int)((c2).green)) + \
  184247. abs((int)((c1).blue) - (int)((c2).blue)))
  184248. /* Added to libpng-1.2.6 JB */
  184249. #define PNG_ROWBYTES(pixel_bits, width) \
  184250. ((pixel_bits) >= 8 ? \
  184251. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184252. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184253. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184254. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184255. "ideal" and "delta" should be constants, normally simple
  184256. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184257. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184258. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184259. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184260. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184261. /* place to hold the signature string for a PNG file. */
  184262. #ifdef PNG_USE_GLOBAL_ARRAYS
  184263. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184264. #else
  184265. #endif
  184266. #endif /* PNG_NO_EXTERN */
  184267. /* Constant strings for known chunk types. If you need to add a chunk,
  184268. * define the name here, and add an invocation of the macro in png.c and
  184269. * wherever it's needed.
  184270. */
  184271. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184272. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184273. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184274. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184275. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184276. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184277. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184278. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184279. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184280. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184281. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184282. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184283. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184284. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184285. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184286. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184287. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184288. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184289. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184290. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184291. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184292. #ifdef PNG_USE_GLOBAL_ARRAYS
  184293. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184294. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184295. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184296. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184297. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184298. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184299. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184300. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184301. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184302. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184303. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184304. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184305. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184306. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184307. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184308. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184309. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184310. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184311. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184312. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184313. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184314. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184315. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184316. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184317. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184318. */
  184319. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184320. #undef png_read_init
  184321. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184322. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184323. #endif
  184324. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184325. png_const_charp user_png_ver, png_size_t png_struct_size));
  184326. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184327. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184328. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184329. png_info_size));
  184330. #endif
  184331. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184332. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184333. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184334. */
  184335. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184336. #undef png_write_init
  184337. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184338. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184339. #endif
  184340. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184341. png_const_charp user_png_ver, png_size_t png_struct_size));
  184342. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184343. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184344. png_info_size));
  184345. /* Allocate memory for an internal libpng struct */
  184346. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184347. /* Free memory from internal libpng struct */
  184348. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184349. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184350. malloc_fn, png_voidp mem_ptr));
  184351. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184352. png_free_ptr free_fn, png_voidp mem_ptr));
  184353. /* Free any memory that info_ptr points to and reset struct. */
  184354. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184355. png_infop info_ptr));
  184356. #ifndef PNG_1_0_X
  184357. /* Function to allocate memory for zlib. */
  184358. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184359. /* Function to free memory for zlib */
  184360. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184361. #ifdef PNG_SIZE_T
  184362. /* Function to convert a sizeof an item to png_sizeof item */
  184363. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184364. #endif
  184365. /* Next four functions are used internally as callbacks. PNGAPI is required
  184366. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184367. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184368. png_bytep data, png_size_t length));
  184369. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184370. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184371. png_bytep buffer, png_size_t length));
  184372. #endif
  184373. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184374. png_bytep data, png_size_t length));
  184375. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184376. #if !defined(PNG_NO_STDIO)
  184377. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184378. #endif
  184379. #endif
  184380. #else /* PNG_1_0_X */
  184381. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184382. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184383. png_bytep buffer, png_size_t length));
  184384. #endif
  184385. #endif /* PNG_1_0_X */
  184386. /* Reset the CRC variable */
  184387. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184388. /* Write the "data" buffer to whatever output you are using. */
  184389. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184390. png_size_t length));
  184391. /* Read data from whatever input you are using into the "data" buffer */
  184392. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184393. png_size_t length));
  184394. /* Read bytes into buf, and update png_ptr->crc */
  184395. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184396. png_size_t length));
  184397. /* Decompress data in a chunk that uses compression */
  184398. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184399. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184400. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184401. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184402. png_size_t prefix_length, png_size_t *data_length));
  184403. #endif
  184404. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184405. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184406. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184407. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184408. /* Calculate the CRC over a section of data. Note that we are only
  184409. * passing a maximum of 64K on systems that have this as a memory limit,
  184410. * since this is the maximum buffer size we can specify.
  184411. */
  184412. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184413. png_size_t length));
  184414. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184415. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184416. #endif
  184417. /* simple function to write the signature */
  184418. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184419. /* write various chunks */
  184420. /* Write the IHDR chunk, and update the png_struct with the necessary
  184421. * information.
  184422. */
  184423. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184424. png_uint_32 height,
  184425. int bit_depth, int color_type, int compression_method, int filter_method,
  184426. int interlace_method));
  184427. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184428. png_uint_32 num_pal));
  184429. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184430. png_size_t length));
  184431. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184432. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184433. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184434. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184435. #endif
  184436. #ifdef PNG_FIXED_POINT_SUPPORTED
  184437. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184438. file_gamma));
  184439. #endif
  184440. #endif
  184441. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184442. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184443. int color_type));
  184444. #endif
  184445. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184446. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184447. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184448. double white_x, double white_y,
  184449. double red_x, double red_y, double green_x, double green_y,
  184450. double blue_x, double blue_y));
  184451. #endif
  184452. #ifdef PNG_FIXED_POINT_SUPPORTED
  184453. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184454. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184455. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184456. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184457. png_fixed_point int_blue_y));
  184458. #endif
  184459. #endif
  184460. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184461. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184462. int intent));
  184463. #endif
  184464. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184465. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184466. png_charp name, int compression_type,
  184467. png_charp profile, int proflen));
  184468. /* Note to maintainer: profile should be png_bytep */
  184469. #endif
  184470. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184471. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184472. png_sPLT_tp palette));
  184473. #endif
  184474. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184475. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184476. png_color_16p values, int number, int color_type));
  184477. #endif
  184478. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184479. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184480. png_color_16p values, int color_type));
  184481. #endif
  184482. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184483. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184484. int num_hist));
  184485. #endif
  184486. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184487. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184488. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184489. png_charp key, png_charpp new_key));
  184490. #endif
  184491. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184492. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184493. png_charp text, png_size_t text_len));
  184494. #endif
  184495. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184496. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184497. png_charp text, png_size_t text_len, int compression));
  184498. #endif
  184499. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184500. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184501. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184502. png_charp text));
  184503. #endif
  184504. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184505. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184506. png_infop info_ptr, png_textp text_ptr, int num_text));
  184507. #endif
  184508. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184509. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184510. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184511. #endif
  184512. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184513. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184514. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184515. png_charp units, png_charpp params));
  184516. #endif
  184517. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184518. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184519. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184520. int unit_type));
  184521. #endif
  184522. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184523. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184524. png_timep mod_time));
  184525. #endif
  184526. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184527. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184528. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184529. int unit, double width, double height));
  184530. #else
  184531. #ifdef PNG_FIXED_POINT_SUPPORTED
  184532. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184533. int unit, png_charp width, png_charp height));
  184534. #endif
  184535. #endif
  184536. #endif
  184537. /* Called when finished processing a row of data */
  184538. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184539. /* Internal use only. Called before first row of data */
  184540. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184541. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184542. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184543. #endif
  184544. /* combine a row of data, dealing with alpha, etc. if requested */
  184545. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184546. int mask));
  184547. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184548. /* expand an interlaced row */
  184549. /* OLD pre-1.0.9 interface:
  184550. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184551. png_bytep row, int pass, png_uint_32 transformations));
  184552. */
  184553. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184554. #endif
  184555. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184556. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184557. /* grab pixels out of a row for an interlaced pass */
  184558. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184559. png_bytep row, int pass));
  184560. #endif
  184561. /* unfilter a row */
  184562. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184563. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184564. /* Choose the best filter to use and filter the row data */
  184565. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184566. png_row_infop row_info));
  184567. /* Write out the filtered row. */
  184568. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184569. png_bytep filtered_row));
  184570. /* finish a row while reading, dealing with interlacing passes, etc. */
  184571. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184572. /* initialize the row buffers, etc. */
  184573. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184574. /* optional call to update the users info structure */
  184575. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184576. png_infop info_ptr));
  184577. /* these are the functions that do the transformations */
  184578. #if defined(PNG_READ_FILLER_SUPPORTED)
  184579. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184580. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184581. #endif
  184582. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184583. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184584. png_bytep row));
  184585. #endif
  184586. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184587. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184588. png_bytep row));
  184589. #endif
  184590. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184591. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184592. png_bytep row));
  184593. #endif
  184594. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184595. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184596. png_bytep row));
  184597. #endif
  184598. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184599. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184600. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184601. png_bytep row, png_uint_32 flags));
  184602. #endif
  184603. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184604. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184605. #endif
  184606. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184607. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184608. #endif
  184609. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184610. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184611. row_info, png_bytep row));
  184612. #endif
  184613. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184614. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184615. png_bytep row));
  184616. #endif
  184617. #if defined(PNG_READ_PACK_SUPPORTED)
  184618. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184619. #endif
  184620. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184621. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184622. png_color_8p sig_bits));
  184623. #endif
  184624. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184625. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184626. #endif
  184627. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184628. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184629. #endif
  184630. #if defined(PNG_READ_DITHER_SUPPORTED)
  184631. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184632. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184633. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184634. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184635. png_colorp palette, int num_palette));
  184636. # endif
  184637. #endif
  184638. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184639. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184640. #endif
  184641. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184642. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184643. png_bytep row, png_uint_32 bit_depth));
  184644. #endif
  184645. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184646. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184647. png_color_8p bit_depth));
  184648. #endif
  184649. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184650. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184651. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184652. png_color_16p trans_values, png_color_16p background,
  184653. png_color_16p background_1,
  184654. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184655. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184656. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184657. #else
  184658. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184659. png_color_16p trans_values, png_color_16p background));
  184660. #endif
  184661. #endif
  184662. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184663. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184664. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184665. int gamma_shift));
  184666. #endif
  184667. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184668. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184669. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184670. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184671. png_bytep row, png_color_16p trans_value));
  184672. #endif
  184673. /* The following decodes the appropriate chunks, and does error correction,
  184674. * then calls the appropriate callback for the chunk if it is valid.
  184675. */
  184676. /* decode the IHDR chunk */
  184677. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184678. png_uint_32 length));
  184679. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184680. png_uint_32 length));
  184681. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184682. png_uint_32 length));
  184683. #if defined(PNG_READ_bKGD_SUPPORTED)
  184684. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184685. png_uint_32 length));
  184686. #endif
  184687. #if defined(PNG_READ_cHRM_SUPPORTED)
  184688. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184689. png_uint_32 length));
  184690. #endif
  184691. #if defined(PNG_READ_gAMA_SUPPORTED)
  184692. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184693. png_uint_32 length));
  184694. #endif
  184695. #if defined(PNG_READ_hIST_SUPPORTED)
  184696. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184697. png_uint_32 length));
  184698. #endif
  184699. #if defined(PNG_READ_iCCP_SUPPORTED)
  184700. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184701. png_uint_32 length));
  184702. #endif /* PNG_READ_iCCP_SUPPORTED */
  184703. #if defined(PNG_READ_iTXt_SUPPORTED)
  184704. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184705. png_uint_32 length));
  184706. #endif
  184707. #if defined(PNG_READ_oFFs_SUPPORTED)
  184708. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184709. png_uint_32 length));
  184710. #endif
  184711. #if defined(PNG_READ_pCAL_SUPPORTED)
  184712. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184713. png_uint_32 length));
  184714. #endif
  184715. #if defined(PNG_READ_pHYs_SUPPORTED)
  184716. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184717. png_uint_32 length));
  184718. #endif
  184719. #if defined(PNG_READ_sBIT_SUPPORTED)
  184720. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184721. png_uint_32 length));
  184722. #endif
  184723. #if defined(PNG_READ_sCAL_SUPPORTED)
  184724. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184725. png_uint_32 length));
  184726. #endif
  184727. #if defined(PNG_READ_sPLT_SUPPORTED)
  184728. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184729. png_uint_32 length));
  184730. #endif /* PNG_READ_sPLT_SUPPORTED */
  184731. #if defined(PNG_READ_sRGB_SUPPORTED)
  184732. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184733. png_uint_32 length));
  184734. #endif
  184735. #if defined(PNG_READ_tEXt_SUPPORTED)
  184736. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184737. png_uint_32 length));
  184738. #endif
  184739. #if defined(PNG_READ_tIME_SUPPORTED)
  184740. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184741. png_uint_32 length));
  184742. #endif
  184743. #if defined(PNG_READ_tRNS_SUPPORTED)
  184744. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184745. png_uint_32 length));
  184746. #endif
  184747. #if defined(PNG_READ_zTXt_SUPPORTED)
  184748. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184749. png_uint_32 length));
  184750. #endif
  184751. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184752. png_infop info_ptr, png_uint_32 length));
  184753. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184754. png_bytep chunk_name));
  184755. /* handle the transformations for reading and writing */
  184756. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184757. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184758. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184759. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184760. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184761. png_infop info_ptr));
  184762. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184763. png_infop info_ptr));
  184764. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184765. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184766. png_uint_32 length));
  184767. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184768. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184769. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184770. png_bytep buffer, png_size_t buffer_length));
  184771. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184772. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184773. png_bytep buffer, png_size_t buffer_length));
  184774. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184775. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184776. png_infop info_ptr, png_uint_32 length));
  184777. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184778. png_infop info_ptr));
  184779. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184780. png_infop info_ptr));
  184781. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184782. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184783. png_infop info_ptr));
  184784. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184785. png_infop info_ptr));
  184786. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184787. #if defined(PNG_READ_tEXt_SUPPORTED)
  184788. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184789. png_infop info_ptr, png_uint_32 length));
  184790. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184791. png_infop info_ptr));
  184792. #endif
  184793. #if defined(PNG_READ_zTXt_SUPPORTED)
  184794. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184795. png_infop info_ptr, png_uint_32 length));
  184796. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184797. png_infop info_ptr));
  184798. #endif
  184799. #if defined(PNG_READ_iTXt_SUPPORTED)
  184800. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184801. png_infop info_ptr, png_uint_32 length));
  184802. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184803. png_infop info_ptr));
  184804. #endif
  184805. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184806. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184807. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184808. png_bytep row));
  184809. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184810. png_bytep row));
  184811. #endif
  184812. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184813. #if defined(PNG_MMX_CODE_SUPPORTED)
  184814. /* png.c */ /* PRIVATE */
  184815. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184816. #endif
  184817. #endif
  184818. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184819. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184820. png_infop info_ptr));
  184821. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184822. png_infop info_ptr));
  184823. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184824. png_infop info_ptr));
  184825. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184826. png_infop info_ptr));
  184827. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184828. png_infop info_ptr));
  184829. #if defined(PNG_pHYs_SUPPORTED)
  184830. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184831. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184832. #endif /* PNG_pHYs_SUPPORTED */
  184833. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184834. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184835. #endif /* PNG_INTERNAL */
  184836. #ifdef __cplusplus
  184837. //}
  184838. #endif
  184839. #endif /* PNG_VERSION_INFO_ONLY */
  184840. /* do not put anything past this line */
  184841. #endif /* PNG_H */
  184842. /*** End of inlined file: png.h ***/
  184843. #define PNG_NO_EXTERN
  184844. /*** Start of inlined file: png.c ***/
  184845. /* png.c - location for general purpose libpng functions
  184846. *
  184847. * Last changed in libpng 1.2.21 [October 4, 2007]
  184848. * For conditions of distribution and use, see copyright notice in png.h
  184849. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184850. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184851. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184852. */
  184853. #define PNG_INTERNAL
  184854. #define PNG_NO_EXTERN
  184855. /* Generate a compiler error if there is an old png.h in the search path. */
  184856. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184857. /* Version information for C files. This had better match the version
  184858. * string defined in png.h. */
  184859. #ifdef PNG_USE_GLOBAL_ARRAYS
  184860. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184861. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184862. #ifdef PNG_READ_SUPPORTED
  184863. /* png_sig was changed to a function in version 1.0.5c */
  184864. /* Place to hold the signature string for a PNG file. */
  184865. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184866. #endif /* PNG_READ_SUPPORTED */
  184867. /* Invoke global declarations for constant strings for known chunk types */
  184868. PNG_IHDR;
  184869. PNG_IDAT;
  184870. PNG_IEND;
  184871. PNG_PLTE;
  184872. PNG_bKGD;
  184873. PNG_cHRM;
  184874. PNG_gAMA;
  184875. PNG_hIST;
  184876. PNG_iCCP;
  184877. PNG_iTXt;
  184878. PNG_oFFs;
  184879. PNG_pCAL;
  184880. PNG_sCAL;
  184881. PNG_pHYs;
  184882. PNG_sBIT;
  184883. PNG_sPLT;
  184884. PNG_sRGB;
  184885. PNG_tEXt;
  184886. PNG_tIME;
  184887. PNG_tRNS;
  184888. PNG_zTXt;
  184889. #ifdef PNG_READ_SUPPORTED
  184890. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184891. /* start of interlace block */
  184892. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184893. /* offset to next interlace block */
  184894. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184895. /* start of interlace block in the y direction */
  184896. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184897. /* offset to next interlace block in the y direction */
  184898. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184899. /* Height of interlace block. This is not currently used - if you need
  184900. * it, uncomment it here and in png.h
  184901. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184902. */
  184903. /* Mask to determine which pixels are valid in a pass */
  184904. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184905. /* Mask to determine which pixels to overwrite while displaying */
  184906. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184907. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184908. #endif /* PNG_READ_SUPPORTED */
  184909. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184910. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184911. * of the PNG file signature. If the PNG data is embedded into another
  184912. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184913. * or write any of the magic bytes before it starts on the IHDR.
  184914. */
  184915. #ifdef PNG_READ_SUPPORTED
  184916. void PNGAPI
  184917. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184918. {
  184919. if(png_ptr == NULL) return;
  184920. png_debug(1, "in png_set_sig_bytes\n");
  184921. if (num_bytes > 8)
  184922. png_error(png_ptr, "Too many bytes for PNG signature.");
  184923. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184924. }
  184925. /* Checks whether the supplied bytes match the PNG signature. We allow
  184926. * checking less than the full 8-byte signature so that those apps that
  184927. * already read the first few bytes of a file to determine the file type
  184928. * can simply check the remaining bytes for extra assurance. Returns
  184929. * an integer less than, equal to, or greater than zero if sig is found,
  184930. * respectively, to be less than, to match, or be greater than the correct
  184931. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184932. */
  184933. int PNGAPI
  184934. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184935. {
  184936. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184937. if (num_to_check > 8)
  184938. num_to_check = 8;
  184939. else if (num_to_check < 1)
  184940. return (-1);
  184941. if (start > 7)
  184942. return (-1);
  184943. if (start + num_to_check > 8)
  184944. num_to_check = 8 - start;
  184945. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184946. }
  184947. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184948. /* (Obsolete) function to check signature bytes. It does not allow one
  184949. * to check a partial signature. This function might be removed in the
  184950. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184951. */
  184952. int PNGAPI
  184953. png_check_sig(png_bytep sig, int num)
  184954. {
  184955. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184956. }
  184957. #endif
  184958. #endif /* PNG_READ_SUPPORTED */
  184959. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184960. /* Function to allocate memory for zlib and clear it to 0. */
  184961. #ifdef PNG_1_0_X
  184962. voidpf PNGAPI
  184963. #else
  184964. voidpf /* private */
  184965. #endif
  184966. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184967. {
  184968. png_voidp ptr;
  184969. png_structp p=(png_structp)png_ptr;
  184970. png_uint_32 save_flags=p->flags;
  184971. png_uint_32 num_bytes;
  184972. if(png_ptr == NULL) return (NULL);
  184973. if (items > PNG_UINT_32_MAX/size)
  184974. {
  184975. png_warning (p, "Potential overflow in png_zalloc()");
  184976. return (NULL);
  184977. }
  184978. num_bytes = (png_uint_32)items * size;
  184979. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184980. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184981. p->flags=save_flags;
  184982. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184983. if (ptr == NULL)
  184984. return ((voidpf)ptr);
  184985. if (num_bytes > (png_uint_32)0x8000L)
  184986. {
  184987. png_memset(ptr, 0, (png_size_t)0x8000L);
  184988. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184989. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184990. }
  184991. else
  184992. {
  184993. png_memset(ptr, 0, (png_size_t)num_bytes);
  184994. }
  184995. #endif
  184996. return ((voidpf)ptr);
  184997. }
  184998. /* function to free memory for zlib */
  184999. #ifdef PNG_1_0_X
  185000. void PNGAPI
  185001. #else
  185002. void /* private */
  185003. #endif
  185004. png_zfree(voidpf png_ptr, voidpf ptr)
  185005. {
  185006. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185007. }
  185008. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185009. * in case CRC is > 32 bits to leave the top bits 0.
  185010. */
  185011. void /* PRIVATE */
  185012. png_reset_crc(png_structp png_ptr)
  185013. {
  185014. png_ptr->crc = crc32(0, Z_NULL, 0);
  185015. }
  185016. /* Calculate the CRC over a section of data. We can only pass as
  185017. * much data to this routine as the largest single buffer size. We
  185018. * also check that this data will actually be used before going to the
  185019. * trouble of calculating it.
  185020. */
  185021. void /* PRIVATE */
  185022. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185023. {
  185024. int need_crc = 1;
  185025. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185026. {
  185027. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185028. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185029. need_crc = 0;
  185030. }
  185031. else /* critical */
  185032. {
  185033. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185034. need_crc = 0;
  185035. }
  185036. if (need_crc)
  185037. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185038. }
  185039. /* Allocate the memory for an info_struct for the application. We don't
  185040. * really need the png_ptr, but it could potentially be useful in the
  185041. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185042. * and png_info_init() so that applications that want to use a shared
  185043. * libpng don't have to be recompiled if png_info changes size.
  185044. */
  185045. png_infop PNGAPI
  185046. png_create_info_struct(png_structp png_ptr)
  185047. {
  185048. png_infop info_ptr;
  185049. png_debug(1, "in png_create_info_struct\n");
  185050. if(png_ptr == NULL) return (NULL);
  185051. #ifdef PNG_USER_MEM_SUPPORTED
  185052. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185053. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185054. #else
  185055. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185056. #endif
  185057. if (info_ptr != NULL)
  185058. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185059. return (info_ptr);
  185060. }
  185061. /* This function frees the memory associated with a single info struct.
  185062. * Normally, one would use either png_destroy_read_struct() or
  185063. * png_destroy_write_struct() to free an info struct, but this may be
  185064. * useful for some applications.
  185065. */
  185066. void PNGAPI
  185067. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185068. {
  185069. png_infop info_ptr = NULL;
  185070. if(png_ptr == NULL) return;
  185071. png_debug(1, "in png_destroy_info_struct\n");
  185072. if (info_ptr_ptr != NULL)
  185073. info_ptr = *info_ptr_ptr;
  185074. if (info_ptr != NULL)
  185075. {
  185076. png_info_destroy(png_ptr, info_ptr);
  185077. #ifdef PNG_USER_MEM_SUPPORTED
  185078. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185079. png_ptr->mem_ptr);
  185080. #else
  185081. png_destroy_struct((png_voidp)info_ptr);
  185082. #endif
  185083. *info_ptr_ptr = NULL;
  185084. }
  185085. }
  185086. /* Initialize the info structure. This is now an internal function (0.89)
  185087. * and applications using it are urged to use png_create_info_struct()
  185088. * instead.
  185089. */
  185090. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185091. #undef png_info_init
  185092. void PNGAPI
  185093. png_info_init(png_infop info_ptr)
  185094. {
  185095. /* We only come here via pre-1.0.12-compiled applications */
  185096. png_info_init_3(&info_ptr, 0);
  185097. }
  185098. #endif
  185099. void PNGAPI
  185100. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185101. {
  185102. png_infop info_ptr = *ptr_ptr;
  185103. if(info_ptr == NULL) return;
  185104. png_debug(1, "in png_info_init_3\n");
  185105. if(png_sizeof(png_info) > png_info_struct_size)
  185106. {
  185107. png_destroy_struct(info_ptr);
  185108. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185109. *ptr_ptr = info_ptr;
  185110. }
  185111. /* set everything to 0 */
  185112. png_memset(info_ptr, 0, png_sizeof (png_info));
  185113. }
  185114. #ifdef PNG_FREE_ME_SUPPORTED
  185115. void PNGAPI
  185116. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185117. int freer, png_uint_32 mask)
  185118. {
  185119. png_debug(1, "in png_data_freer\n");
  185120. if (png_ptr == NULL || info_ptr == NULL)
  185121. return;
  185122. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185123. info_ptr->free_me |= mask;
  185124. else if(freer == PNG_USER_WILL_FREE_DATA)
  185125. info_ptr->free_me &= ~mask;
  185126. else
  185127. png_warning(png_ptr,
  185128. "Unknown freer parameter in png_data_freer.");
  185129. }
  185130. #endif
  185131. void PNGAPI
  185132. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185133. int num)
  185134. {
  185135. png_debug(1, "in png_free_data\n");
  185136. if (png_ptr == NULL || info_ptr == NULL)
  185137. return;
  185138. #if defined(PNG_TEXT_SUPPORTED)
  185139. /* free text item num or (if num == -1) all text items */
  185140. #ifdef PNG_FREE_ME_SUPPORTED
  185141. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185142. #else
  185143. if (mask & PNG_FREE_TEXT)
  185144. #endif
  185145. {
  185146. if (num != -1)
  185147. {
  185148. if (info_ptr->text && info_ptr->text[num].key)
  185149. {
  185150. png_free(png_ptr, info_ptr->text[num].key);
  185151. info_ptr->text[num].key = NULL;
  185152. }
  185153. }
  185154. else
  185155. {
  185156. int i;
  185157. for (i = 0; i < info_ptr->num_text; i++)
  185158. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185159. png_free(png_ptr, info_ptr->text);
  185160. info_ptr->text = NULL;
  185161. info_ptr->num_text=0;
  185162. }
  185163. }
  185164. #endif
  185165. #if defined(PNG_tRNS_SUPPORTED)
  185166. /* free any tRNS entry */
  185167. #ifdef PNG_FREE_ME_SUPPORTED
  185168. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185169. #else
  185170. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185171. #endif
  185172. {
  185173. png_free(png_ptr, info_ptr->trans);
  185174. info_ptr->valid &= ~PNG_INFO_tRNS;
  185175. #ifndef PNG_FREE_ME_SUPPORTED
  185176. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185177. #endif
  185178. info_ptr->trans = NULL;
  185179. }
  185180. #endif
  185181. #if defined(PNG_sCAL_SUPPORTED)
  185182. /* free any sCAL entry */
  185183. #ifdef PNG_FREE_ME_SUPPORTED
  185184. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185185. #else
  185186. if (mask & PNG_FREE_SCAL)
  185187. #endif
  185188. {
  185189. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185190. png_free(png_ptr, info_ptr->scal_s_width);
  185191. png_free(png_ptr, info_ptr->scal_s_height);
  185192. info_ptr->scal_s_width = NULL;
  185193. info_ptr->scal_s_height = NULL;
  185194. #endif
  185195. info_ptr->valid &= ~PNG_INFO_sCAL;
  185196. }
  185197. #endif
  185198. #if defined(PNG_pCAL_SUPPORTED)
  185199. /* free any pCAL entry */
  185200. #ifdef PNG_FREE_ME_SUPPORTED
  185201. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185202. #else
  185203. if (mask & PNG_FREE_PCAL)
  185204. #endif
  185205. {
  185206. png_free(png_ptr, info_ptr->pcal_purpose);
  185207. png_free(png_ptr, info_ptr->pcal_units);
  185208. info_ptr->pcal_purpose = NULL;
  185209. info_ptr->pcal_units = NULL;
  185210. if (info_ptr->pcal_params != NULL)
  185211. {
  185212. int i;
  185213. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185214. {
  185215. png_free(png_ptr, info_ptr->pcal_params[i]);
  185216. info_ptr->pcal_params[i]=NULL;
  185217. }
  185218. png_free(png_ptr, info_ptr->pcal_params);
  185219. info_ptr->pcal_params = NULL;
  185220. }
  185221. info_ptr->valid &= ~PNG_INFO_pCAL;
  185222. }
  185223. #endif
  185224. #if defined(PNG_iCCP_SUPPORTED)
  185225. /* free any iCCP entry */
  185226. #ifdef PNG_FREE_ME_SUPPORTED
  185227. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185228. #else
  185229. if (mask & PNG_FREE_ICCP)
  185230. #endif
  185231. {
  185232. png_free(png_ptr, info_ptr->iccp_name);
  185233. png_free(png_ptr, info_ptr->iccp_profile);
  185234. info_ptr->iccp_name = NULL;
  185235. info_ptr->iccp_profile = NULL;
  185236. info_ptr->valid &= ~PNG_INFO_iCCP;
  185237. }
  185238. #endif
  185239. #if defined(PNG_sPLT_SUPPORTED)
  185240. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185241. #ifdef PNG_FREE_ME_SUPPORTED
  185242. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185243. #else
  185244. if (mask & PNG_FREE_SPLT)
  185245. #endif
  185246. {
  185247. if (num != -1)
  185248. {
  185249. if(info_ptr->splt_palettes)
  185250. {
  185251. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185252. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185253. info_ptr->splt_palettes[num].name = NULL;
  185254. info_ptr->splt_palettes[num].entries = NULL;
  185255. }
  185256. }
  185257. else
  185258. {
  185259. if(info_ptr->splt_palettes_num)
  185260. {
  185261. int i;
  185262. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185263. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185264. png_free(png_ptr, info_ptr->splt_palettes);
  185265. info_ptr->splt_palettes = NULL;
  185266. info_ptr->splt_palettes_num = 0;
  185267. }
  185268. info_ptr->valid &= ~PNG_INFO_sPLT;
  185269. }
  185270. }
  185271. #endif
  185272. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185273. if(png_ptr->unknown_chunk.data)
  185274. {
  185275. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185276. png_ptr->unknown_chunk.data = NULL;
  185277. }
  185278. #ifdef PNG_FREE_ME_SUPPORTED
  185279. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185280. #else
  185281. if (mask & PNG_FREE_UNKN)
  185282. #endif
  185283. {
  185284. if (num != -1)
  185285. {
  185286. if(info_ptr->unknown_chunks)
  185287. {
  185288. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185289. info_ptr->unknown_chunks[num].data = NULL;
  185290. }
  185291. }
  185292. else
  185293. {
  185294. int i;
  185295. if(info_ptr->unknown_chunks_num)
  185296. {
  185297. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185298. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185299. png_free(png_ptr, info_ptr->unknown_chunks);
  185300. info_ptr->unknown_chunks = NULL;
  185301. info_ptr->unknown_chunks_num = 0;
  185302. }
  185303. }
  185304. }
  185305. #endif
  185306. #if defined(PNG_hIST_SUPPORTED)
  185307. /* free any hIST entry */
  185308. #ifdef PNG_FREE_ME_SUPPORTED
  185309. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185310. #else
  185311. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185312. #endif
  185313. {
  185314. png_free(png_ptr, info_ptr->hist);
  185315. info_ptr->hist = NULL;
  185316. info_ptr->valid &= ~PNG_INFO_hIST;
  185317. #ifndef PNG_FREE_ME_SUPPORTED
  185318. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185319. #endif
  185320. }
  185321. #endif
  185322. /* free any PLTE entry that was internally allocated */
  185323. #ifdef PNG_FREE_ME_SUPPORTED
  185324. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185325. #else
  185326. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185327. #endif
  185328. {
  185329. png_zfree(png_ptr, info_ptr->palette);
  185330. info_ptr->palette = NULL;
  185331. info_ptr->valid &= ~PNG_INFO_PLTE;
  185332. #ifndef PNG_FREE_ME_SUPPORTED
  185333. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185334. #endif
  185335. info_ptr->num_palette = 0;
  185336. }
  185337. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185338. /* free any image bits attached to the info structure */
  185339. #ifdef PNG_FREE_ME_SUPPORTED
  185340. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185341. #else
  185342. if (mask & PNG_FREE_ROWS)
  185343. #endif
  185344. {
  185345. if(info_ptr->row_pointers)
  185346. {
  185347. int row;
  185348. for (row = 0; row < (int)info_ptr->height; row++)
  185349. {
  185350. png_free(png_ptr, info_ptr->row_pointers[row]);
  185351. info_ptr->row_pointers[row]=NULL;
  185352. }
  185353. png_free(png_ptr, info_ptr->row_pointers);
  185354. info_ptr->row_pointers=NULL;
  185355. }
  185356. info_ptr->valid &= ~PNG_INFO_IDAT;
  185357. }
  185358. #endif
  185359. #ifdef PNG_FREE_ME_SUPPORTED
  185360. if(num == -1)
  185361. info_ptr->free_me &= ~mask;
  185362. else
  185363. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185364. #endif
  185365. }
  185366. /* This is an internal routine to free any memory that the info struct is
  185367. * pointing to before re-using it or freeing the struct itself. Recall
  185368. * that png_free() checks for NULL pointers for us.
  185369. */
  185370. void /* PRIVATE */
  185371. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185372. {
  185373. png_debug(1, "in png_info_destroy\n");
  185374. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185375. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185376. if (png_ptr->num_chunk_list)
  185377. {
  185378. png_free(png_ptr, png_ptr->chunk_list);
  185379. png_ptr->chunk_list=NULL;
  185380. png_ptr->num_chunk_list=0;
  185381. }
  185382. #endif
  185383. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185384. }
  185385. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185386. /* This function returns a pointer to the io_ptr associated with the user
  185387. * functions. The application should free any memory associated with this
  185388. * pointer before png_write_destroy() or png_read_destroy() are called.
  185389. */
  185390. png_voidp PNGAPI
  185391. png_get_io_ptr(png_structp png_ptr)
  185392. {
  185393. if(png_ptr == NULL) return (NULL);
  185394. return (png_ptr->io_ptr);
  185395. }
  185396. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185397. #if !defined(PNG_NO_STDIO)
  185398. /* Initialize the default input/output functions for the PNG file. If you
  185399. * use your own read or write routines, you can call either png_set_read_fn()
  185400. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185401. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185402. * necessarily available.
  185403. */
  185404. void PNGAPI
  185405. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185406. {
  185407. png_debug(1, "in png_init_io\n");
  185408. if(png_ptr == NULL) return;
  185409. png_ptr->io_ptr = (png_voidp)fp;
  185410. }
  185411. #endif
  185412. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185413. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185414. * a "Creation Time" or other text-based time string.
  185415. */
  185416. png_charp PNGAPI
  185417. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185418. {
  185419. static PNG_CONST char short_months[12][4] =
  185420. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185421. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185422. if(png_ptr == NULL) return (NULL);
  185423. if (png_ptr->time_buffer == NULL)
  185424. {
  185425. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185426. png_sizeof(char)));
  185427. }
  185428. #if defined(_WIN32_WCE)
  185429. {
  185430. wchar_t time_buf[29];
  185431. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185432. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185433. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185434. ptime->second % 61);
  185435. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185436. NULL, NULL);
  185437. }
  185438. #else
  185439. #ifdef USE_FAR_KEYWORD
  185440. {
  185441. char near_time_buf[29];
  185442. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185443. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185444. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185445. ptime->second % 61);
  185446. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185447. 29*png_sizeof(char));
  185448. }
  185449. #else
  185450. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185451. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185452. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185453. ptime->second % 61);
  185454. #endif
  185455. #endif /* _WIN32_WCE */
  185456. return ((png_charp)png_ptr->time_buffer);
  185457. }
  185458. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185459. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185460. png_charp PNGAPI
  185461. png_get_copyright(png_structp png_ptr)
  185462. {
  185463. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185464. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185465. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185466. Copyright (c) 1996-1997 Andreas Dilger\n\
  185467. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185468. }
  185469. /* The following return the library version as a short string in the
  185470. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185471. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185472. * is defined in png.h.
  185473. * Note: now there is no difference between png_get_libpng_ver() and
  185474. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185475. * it is guaranteed that png.c uses the correct version of png.h.
  185476. */
  185477. png_charp PNGAPI
  185478. png_get_libpng_ver(png_structp png_ptr)
  185479. {
  185480. /* Version of *.c files used when building libpng */
  185481. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185482. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185483. }
  185484. png_charp PNGAPI
  185485. png_get_header_ver(png_structp png_ptr)
  185486. {
  185487. /* Version of *.h files used when building libpng */
  185488. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185489. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185490. }
  185491. png_charp PNGAPI
  185492. png_get_header_version(png_structp png_ptr)
  185493. {
  185494. /* Returns longer string containing both version and date */
  185495. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185496. return ((png_charp) PNG_HEADER_VERSION_STRING
  185497. #ifndef PNG_READ_SUPPORTED
  185498. " (NO READ SUPPORT)"
  185499. #endif
  185500. "\n");
  185501. }
  185502. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185503. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185504. int PNGAPI
  185505. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185506. {
  185507. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185508. int i;
  185509. png_bytep p;
  185510. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185511. return 0;
  185512. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185513. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185514. if (!png_memcmp(chunk_name, p, 4))
  185515. return ((int)*(p+4));
  185516. return 0;
  185517. }
  185518. #endif
  185519. /* This function, added to libpng-1.0.6g, is untested. */
  185520. int PNGAPI
  185521. png_reset_zstream(png_structp png_ptr)
  185522. {
  185523. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185524. return (inflateReset(&png_ptr->zstream));
  185525. }
  185526. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185527. /* This function was added to libpng-1.0.7 */
  185528. png_uint_32 PNGAPI
  185529. png_access_version_number(void)
  185530. {
  185531. /* Version of *.c files used when building libpng */
  185532. return((png_uint_32) PNG_LIBPNG_VER);
  185533. }
  185534. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185535. #if !defined(PNG_1_0_X)
  185536. /* this function was added to libpng 1.2.0 */
  185537. int PNGAPI
  185538. png_mmx_support(void)
  185539. {
  185540. /* obsolete, to be removed from libpng-1.4.0 */
  185541. return -1;
  185542. }
  185543. #endif /* PNG_1_0_X */
  185544. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185545. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185546. #ifdef PNG_SIZE_T
  185547. /* Added at libpng version 1.2.6 */
  185548. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185549. png_size_t PNGAPI
  185550. png_convert_size(size_t size)
  185551. {
  185552. if (size > (png_size_t)-1)
  185553. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185554. return ((png_size_t)size);
  185555. }
  185556. #endif /* PNG_SIZE_T */
  185557. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185558. /*** End of inlined file: png.c ***/
  185559. /*** Start of inlined file: pngerror.c ***/
  185560. /* pngerror.c - stub functions for i/o and memory allocation
  185561. *
  185562. * Last changed in libpng 1.2.20 October 4, 2007
  185563. * For conditions of distribution and use, see copyright notice in png.h
  185564. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185565. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185566. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185567. *
  185568. * This file provides a location for all error handling. Users who
  185569. * need special error handling are expected to write replacement functions
  185570. * and use png_set_error_fn() to use those functions. See the instructions
  185571. * at each function.
  185572. */
  185573. #define PNG_INTERNAL
  185574. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185575. static void /* PRIVATE */
  185576. png_default_error PNGARG((png_structp png_ptr,
  185577. png_const_charp error_message));
  185578. #ifndef PNG_NO_WARNINGS
  185579. static void /* PRIVATE */
  185580. png_default_warning PNGARG((png_structp png_ptr,
  185581. png_const_charp warning_message));
  185582. #endif /* PNG_NO_WARNINGS */
  185583. /* This function is called whenever there is a fatal error. This function
  185584. * should not be changed. If there is a need to handle errors differently,
  185585. * you should supply a replacement error function and use png_set_error_fn()
  185586. * to replace the error function at run-time.
  185587. */
  185588. #ifndef PNG_NO_ERROR_TEXT
  185589. void PNGAPI
  185590. png_error(png_structp png_ptr, png_const_charp error_message)
  185591. {
  185592. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185593. char msg[16];
  185594. if (png_ptr != NULL)
  185595. {
  185596. if (png_ptr->flags&
  185597. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185598. {
  185599. if (*error_message == '#')
  185600. {
  185601. int offset;
  185602. for (offset=1; offset<15; offset++)
  185603. if (*(error_message+offset) == ' ')
  185604. break;
  185605. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185606. {
  185607. int i;
  185608. for (i=0; i<offset-1; i++)
  185609. msg[i]=error_message[i+1];
  185610. msg[i]='\0';
  185611. error_message=msg;
  185612. }
  185613. else
  185614. error_message+=offset;
  185615. }
  185616. else
  185617. {
  185618. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185619. {
  185620. msg[0]='0';
  185621. msg[1]='\0';
  185622. error_message=msg;
  185623. }
  185624. }
  185625. }
  185626. }
  185627. #endif
  185628. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185629. (*(png_ptr->error_fn))(png_ptr, error_message);
  185630. /* If the custom handler doesn't exist, or if it returns,
  185631. use the default handler, which will not return. */
  185632. png_default_error(png_ptr, error_message);
  185633. }
  185634. #else
  185635. void PNGAPI
  185636. png_err(png_structp png_ptr)
  185637. {
  185638. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185639. (*(png_ptr->error_fn))(png_ptr, '\0');
  185640. /* If the custom handler doesn't exist, or if it returns,
  185641. use the default handler, which will not return. */
  185642. png_default_error(png_ptr, '\0');
  185643. }
  185644. #endif /* PNG_NO_ERROR_TEXT */
  185645. #ifndef PNG_NO_WARNINGS
  185646. /* This function is called whenever there is a non-fatal error. This function
  185647. * should not be changed. If there is a need to handle warnings differently,
  185648. * you should supply a replacement warning function and use
  185649. * png_set_error_fn() to replace the warning function at run-time.
  185650. */
  185651. void PNGAPI
  185652. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185653. {
  185654. int offset = 0;
  185655. if (png_ptr != NULL)
  185656. {
  185657. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185658. if (png_ptr->flags&
  185659. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185660. #endif
  185661. {
  185662. if (*warning_message == '#')
  185663. {
  185664. for (offset=1; offset<15; offset++)
  185665. if (*(warning_message+offset) == ' ')
  185666. break;
  185667. }
  185668. }
  185669. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185670. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185671. }
  185672. else
  185673. png_default_warning(png_ptr, warning_message+offset);
  185674. }
  185675. #endif /* PNG_NO_WARNINGS */
  185676. /* These utilities are used internally to build an error message that relates
  185677. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185678. * this is used to prefix the message. The message is limited in length
  185679. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185680. * if the character is invalid.
  185681. */
  185682. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185683. /*static PNG_CONST char png_digit[16] = {
  185684. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185685. 'A', 'B', 'C', 'D', 'E', 'F'
  185686. };*/
  185687. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185688. static void /* PRIVATE */
  185689. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185690. error_message)
  185691. {
  185692. int iout = 0, iin = 0;
  185693. while (iin < 4)
  185694. {
  185695. int c = png_ptr->chunk_name[iin++];
  185696. if (isnonalpha(c))
  185697. {
  185698. buffer[iout++] = '[';
  185699. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185700. buffer[iout++] = png_digit[c & 0x0f];
  185701. buffer[iout++] = ']';
  185702. }
  185703. else
  185704. {
  185705. buffer[iout++] = (png_byte)c;
  185706. }
  185707. }
  185708. if (error_message == NULL)
  185709. buffer[iout] = 0;
  185710. else
  185711. {
  185712. buffer[iout++] = ':';
  185713. buffer[iout++] = ' ';
  185714. png_strncpy(buffer+iout, error_message, 63);
  185715. buffer[iout+63] = 0;
  185716. }
  185717. }
  185718. #ifdef PNG_READ_SUPPORTED
  185719. void PNGAPI
  185720. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185721. {
  185722. char msg[18+64];
  185723. if (png_ptr == NULL)
  185724. png_error(png_ptr, error_message);
  185725. else
  185726. {
  185727. png_format_buffer(png_ptr, msg, error_message);
  185728. png_error(png_ptr, msg);
  185729. }
  185730. }
  185731. #endif /* PNG_READ_SUPPORTED */
  185732. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185733. #ifndef PNG_NO_WARNINGS
  185734. void PNGAPI
  185735. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185736. {
  185737. char msg[18+64];
  185738. if (png_ptr == NULL)
  185739. png_warning(png_ptr, warning_message);
  185740. else
  185741. {
  185742. png_format_buffer(png_ptr, msg, warning_message);
  185743. png_warning(png_ptr, msg);
  185744. }
  185745. }
  185746. #endif /* PNG_NO_WARNINGS */
  185747. /* This is the default error handling function. Note that replacements for
  185748. * this function MUST NOT RETURN, or the program will likely crash. This
  185749. * function is used by default, or if the program supplies NULL for the
  185750. * error function pointer in png_set_error_fn().
  185751. */
  185752. static void /* PRIVATE */
  185753. png_default_error(png_structp, png_const_charp error_message)
  185754. {
  185755. #ifndef PNG_NO_CONSOLE_IO
  185756. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185757. if (*error_message == '#')
  185758. {
  185759. int offset;
  185760. char error_number[16];
  185761. for (offset=0; offset<15; offset++)
  185762. {
  185763. error_number[offset] = *(error_message+offset+1);
  185764. if (*(error_message+offset) == ' ')
  185765. break;
  185766. }
  185767. if((offset > 1) && (offset < 15))
  185768. {
  185769. error_number[offset-1]='\0';
  185770. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185771. error_message+offset);
  185772. }
  185773. else
  185774. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185775. }
  185776. else
  185777. #endif
  185778. fprintf(stderr, "libpng error: %s\n", error_message);
  185779. #endif
  185780. #ifdef PNG_SETJMP_SUPPORTED
  185781. if (png_ptr)
  185782. {
  185783. # ifdef USE_FAR_KEYWORD
  185784. {
  185785. jmp_buf jmpbuf;
  185786. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185787. longjmp(jmpbuf, 1);
  185788. }
  185789. # else
  185790. longjmp(png_ptr->jmpbuf, 1);
  185791. # endif
  185792. }
  185793. #else
  185794. PNG_ABORT();
  185795. #endif
  185796. #ifdef PNG_NO_CONSOLE_IO
  185797. error_message = error_message; /* make compiler happy */
  185798. #endif
  185799. }
  185800. #ifndef PNG_NO_WARNINGS
  185801. /* This function is called when there is a warning, but the library thinks
  185802. * it can continue anyway. Replacement functions don't have to do anything
  185803. * here if you don't want them to. In the default configuration, png_ptr is
  185804. * not used, but it is passed in case it may be useful.
  185805. */
  185806. static void /* PRIVATE */
  185807. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185808. {
  185809. #ifndef PNG_NO_CONSOLE_IO
  185810. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185811. if (*warning_message == '#')
  185812. {
  185813. int offset;
  185814. char warning_number[16];
  185815. for (offset=0; offset<15; offset++)
  185816. {
  185817. warning_number[offset]=*(warning_message+offset+1);
  185818. if (*(warning_message+offset) == ' ')
  185819. break;
  185820. }
  185821. if((offset > 1) && (offset < 15))
  185822. {
  185823. warning_number[offset-1]='\0';
  185824. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185825. warning_message+offset);
  185826. }
  185827. else
  185828. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185829. }
  185830. else
  185831. # endif
  185832. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185833. #else
  185834. warning_message = warning_message; /* make compiler happy */
  185835. #endif
  185836. png_ptr = png_ptr; /* make compiler happy */
  185837. }
  185838. #endif /* PNG_NO_WARNINGS */
  185839. /* This function is called when the application wants to use another method
  185840. * of handling errors and warnings. Note that the error function MUST NOT
  185841. * return to the calling routine or serious problems will occur. The return
  185842. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185843. */
  185844. void PNGAPI
  185845. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185846. png_error_ptr error_fn, png_error_ptr warning_fn)
  185847. {
  185848. if (png_ptr == NULL)
  185849. return;
  185850. png_ptr->error_ptr = error_ptr;
  185851. png_ptr->error_fn = error_fn;
  185852. png_ptr->warning_fn = warning_fn;
  185853. }
  185854. /* This function returns a pointer to the error_ptr associated with the user
  185855. * functions. The application should free any memory associated with this
  185856. * pointer before png_write_destroy and png_read_destroy are called.
  185857. */
  185858. png_voidp PNGAPI
  185859. png_get_error_ptr(png_structp png_ptr)
  185860. {
  185861. if (png_ptr == NULL)
  185862. return NULL;
  185863. return ((png_voidp)png_ptr->error_ptr);
  185864. }
  185865. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185866. void PNGAPI
  185867. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185868. {
  185869. if(png_ptr != NULL)
  185870. {
  185871. png_ptr->flags &=
  185872. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185873. }
  185874. }
  185875. #endif
  185876. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185877. /*** End of inlined file: pngerror.c ***/
  185878. /*** Start of inlined file: pngget.c ***/
  185879. /* pngget.c - retrieval of values from info struct
  185880. *
  185881. * Last changed in libpng 1.2.15 January 5, 2007
  185882. * For conditions of distribution and use, see copyright notice in png.h
  185883. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185884. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185885. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185886. */
  185887. #define PNG_INTERNAL
  185888. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185889. png_uint_32 PNGAPI
  185890. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185891. {
  185892. if (png_ptr != NULL && info_ptr != NULL)
  185893. return(info_ptr->valid & flag);
  185894. else
  185895. return(0);
  185896. }
  185897. png_uint_32 PNGAPI
  185898. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185899. {
  185900. if (png_ptr != NULL && info_ptr != NULL)
  185901. return(info_ptr->rowbytes);
  185902. else
  185903. return(0);
  185904. }
  185905. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185906. png_bytepp PNGAPI
  185907. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185908. {
  185909. if (png_ptr != NULL && info_ptr != NULL)
  185910. return(info_ptr->row_pointers);
  185911. else
  185912. return(0);
  185913. }
  185914. #endif
  185915. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185916. /* easy access to info, added in libpng-0.99 */
  185917. png_uint_32 PNGAPI
  185918. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185919. {
  185920. if (png_ptr != NULL && info_ptr != NULL)
  185921. {
  185922. return info_ptr->width;
  185923. }
  185924. return (0);
  185925. }
  185926. png_uint_32 PNGAPI
  185927. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185928. {
  185929. if (png_ptr != NULL && info_ptr != NULL)
  185930. {
  185931. return info_ptr->height;
  185932. }
  185933. return (0);
  185934. }
  185935. png_byte PNGAPI
  185936. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185937. {
  185938. if (png_ptr != NULL && info_ptr != NULL)
  185939. {
  185940. return info_ptr->bit_depth;
  185941. }
  185942. return (0);
  185943. }
  185944. png_byte PNGAPI
  185945. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185946. {
  185947. if (png_ptr != NULL && info_ptr != NULL)
  185948. {
  185949. return info_ptr->color_type;
  185950. }
  185951. return (0);
  185952. }
  185953. png_byte PNGAPI
  185954. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185955. {
  185956. if (png_ptr != NULL && info_ptr != NULL)
  185957. {
  185958. return info_ptr->filter_type;
  185959. }
  185960. return (0);
  185961. }
  185962. png_byte PNGAPI
  185963. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185964. {
  185965. if (png_ptr != NULL && info_ptr != NULL)
  185966. {
  185967. return info_ptr->interlace_type;
  185968. }
  185969. return (0);
  185970. }
  185971. png_byte PNGAPI
  185972. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185973. {
  185974. if (png_ptr != NULL && info_ptr != NULL)
  185975. {
  185976. return info_ptr->compression_type;
  185977. }
  185978. return (0);
  185979. }
  185980. png_uint_32 PNGAPI
  185981. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185982. {
  185983. if (png_ptr != NULL && info_ptr != NULL)
  185984. #if defined(PNG_pHYs_SUPPORTED)
  185985. if (info_ptr->valid & PNG_INFO_pHYs)
  185986. {
  185987. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185988. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185989. return (0);
  185990. else return (info_ptr->x_pixels_per_unit);
  185991. }
  185992. #else
  185993. return (0);
  185994. #endif
  185995. return (0);
  185996. }
  185997. png_uint_32 PNGAPI
  185998. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185999. {
  186000. if (png_ptr != NULL && info_ptr != NULL)
  186001. #if defined(PNG_pHYs_SUPPORTED)
  186002. if (info_ptr->valid & PNG_INFO_pHYs)
  186003. {
  186004. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186005. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186006. return (0);
  186007. else return (info_ptr->y_pixels_per_unit);
  186008. }
  186009. #else
  186010. return (0);
  186011. #endif
  186012. return (0);
  186013. }
  186014. png_uint_32 PNGAPI
  186015. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186016. {
  186017. if (png_ptr != NULL && info_ptr != NULL)
  186018. #if defined(PNG_pHYs_SUPPORTED)
  186019. if (info_ptr->valid & PNG_INFO_pHYs)
  186020. {
  186021. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186022. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186023. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186024. return (0);
  186025. else return (info_ptr->x_pixels_per_unit);
  186026. }
  186027. #else
  186028. return (0);
  186029. #endif
  186030. return (0);
  186031. }
  186032. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186033. float PNGAPI
  186034. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186035. {
  186036. if (png_ptr != NULL && info_ptr != NULL)
  186037. #if defined(PNG_pHYs_SUPPORTED)
  186038. if (info_ptr->valid & PNG_INFO_pHYs)
  186039. {
  186040. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186041. if (info_ptr->x_pixels_per_unit == 0)
  186042. return ((float)0.0);
  186043. else
  186044. return ((float)((float)info_ptr->y_pixels_per_unit
  186045. /(float)info_ptr->x_pixels_per_unit));
  186046. }
  186047. #else
  186048. return (0.0);
  186049. #endif
  186050. return ((float)0.0);
  186051. }
  186052. #endif
  186053. png_int_32 PNGAPI
  186054. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186055. {
  186056. if (png_ptr != NULL && info_ptr != NULL)
  186057. #if defined(PNG_oFFs_SUPPORTED)
  186058. if (info_ptr->valid & PNG_INFO_oFFs)
  186059. {
  186060. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186061. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186062. return (0);
  186063. else return (info_ptr->x_offset);
  186064. }
  186065. #else
  186066. return (0);
  186067. #endif
  186068. return (0);
  186069. }
  186070. png_int_32 PNGAPI
  186071. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186072. {
  186073. if (png_ptr != NULL && info_ptr != NULL)
  186074. #if defined(PNG_oFFs_SUPPORTED)
  186075. if (info_ptr->valid & PNG_INFO_oFFs)
  186076. {
  186077. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186078. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186079. return (0);
  186080. else return (info_ptr->y_offset);
  186081. }
  186082. #else
  186083. return (0);
  186084. #endif
  186085. return (0);
  186086. }
  186087. png_int_32 PNGAPI
  186088. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186089. {
  186090. if (png_ptr != NULL && info_ptr != NULL)
  186091. #if defined(PNG_oFFs_SUPPORTED)
  186092. if (info_ptr->valid & PNG_INFO_oFFs)
  186093. {
  186094. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186095. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186096. return (0);
  186097. else return (info_ptr->x_offset);
  186098. }
  186099. #else
  186100. return (0);
  186101. #endif
  186102. return (0);
  186103. }
  186104. png_int_32 PNGAPI
  186105. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186106. {
  186107. if (png_ptr != NULL && info_ptr != NULL)
  186108. #if defined(PNG_oFFs_SUPPORTED)
  186109. if (info_ptr->valid & PNG_INFO_oFFs)
  186110. {
  186111. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186112. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186113. return (0);
  186114. else return (info_ptr->y_offset);
  186115. }
  186116. #else
  186117. return (0);
  186118. #endif
  186119. return (0);
  186120. }
  186121. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186122. png_uint_32 PNGAPI
  186123. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186124. {
  186125. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186126. *.0254 +.5));
  186127. }
  186128. png_uint_32 PNGAPI
  186129. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186130. {
  186131. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186132. *.0254 +.5));
  186133. }
  186134. png_uint_32 PNGAPI
  186135. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186136. {
  186137. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186138. *.0254 +.5));
  186139. }
  186140. float PNGAPI
  186141. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186142. {
  186143. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186144. *.00003937);
  186145. }
  186146. float PNGAPI
  186147. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186148. {
  186149. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186150. *.00003937);
  186151. }
  186152. #if defined(PNG_pHYs_SUPPORTED)
  186153. png_uint_32 PNGAPI
  186154. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186155. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186156. {
  186157. png_uint_32 retval = 0;
  186158. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186159. {
  186160. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186161. if (res_x != NULL)
  186162. {
  186163. *res_x = info_ptr->x_pixels_per_unit;
  186164. retval |= PNG_INFO_pHYs;
  186165. }
  186166. if (res_y != NULL)
  186167. {
  186168. *res_y = info_ptr->y_pixels_per_unit;
  186169. retval |= PNG_INFO_pHYs;
  186170. }
  186171. if (unit_type != NULL)
  186172. {
  186173. *unit_type = (int)info_ptr->phys_unit_type;
  186174. retval |= PNG_INFO_pHYs;
  186175. if(*unit_type == 1)
  186176. {
  186177. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186178. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186179. }
  186180. }
  186181. }
  186182. return (retval);
  186183. }
  186184. #endif /* PNG_pHYs_SUPPORTED */
  186185. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186186. /* png_get_channels really belongs in here, too, but it's been around longer */
  186187. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186188. png_byte PNGAPI
  186189. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186190. {
  186191. if (png_ptr != NULL && info_ptr != NULL)
  186192. return(info_ptr->channels);
  186193. else
  186194. return (0);
  186195. }
  186196. png_bytep PNGAPI
  186197. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186198. {
  186199. if (png_ptr != NULL && info_ptr != NULL)
  186200. return(info_ptr->signature);
  186201. else
  186202. return (NULL);
  186203. }
  186204. #if defined(PNG_bKGD_SUPPORTED)
  186205. png_uint_32 PNGAPI
  186206. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186207. png_color_16p *background)
  186208. {
  186209. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186210. && background != NULL)
  186211. {
  186212. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186213. *background = &(info_ptr->background);
  186214. return (PNG_INFO_bKGD);
  186215. }
  186216. return (0);
  186217. }
  186218. #endif
  186219. #if defined(PNG_cHRM_SUPPORTED)
  186220. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186221. png_uint_32 PNGAPI
  186222. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186223. double *white_x, double *white_y, double *red_x, double *red_y,
  186224. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186225. {
  186226. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186227. {
  186228. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186229. if (white_x != NULL)
  186230. *white_x = (double)info_ptr->x_white;
  186231. if (white_y != NULL)
  186232. *white_y = (double)info_ptr->y_white;
  186233. if (red_x != NULL)
  186234. *red_x = (double)info_ptr->x_red;
  186235. if (red_y != NULL)
  186236. *red_y = (double)info_ptr->y_red;
  186237. if (green_x != NULL)
  186238. *green_x = (double)info_ptr->x_green;
  186239. if (green_y != NULL)
  186240. *green_y = (double)info_ptr->y_green;
  186241. if (blue_x != NULL)
  186242. *blue_x = (double)info_ptr->x_blue;
  186243. if (blue_y != NULL)
  186244. *blue_y = (double)info_ptr->y_blue;
  186245. return (PNG_INFO_cHRM);
  186246. }
  186247. return (0);
  186248. }
  186249. #endif
  186250. #ifdef PNG_FIXED_POINT_SUPPORTED
  186251. png_uint_32 PNGAPI
  186252. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186253. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186254. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186255. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186256. {
  186257. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186258. {
  186259. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186260. if (white_x != NULL)
  186261. *white_x = info_ptr->int_x_white;
  186262. if (white_y != NULL)
  186263. *white_y = info_ptr->int_y_white;
  186264. if (red_x != NULL)
  186265. *red_x = info_ptr->int_x_red;
  186266. if (red_y != NULL)
  186267. *red_y = info_ptr->int_y_red;
  186268. if (green_x != NULL)
  186269. *green_x = info_ptr->int_x_green;
  186270. if (green_y != NULL)
  186271. *green_y = info_ptr->int_y_green;
  186272. if (blue_x != NULL)
  186273. *blue_x = info_ptr->int_x_blue;
  186274. if (blue_y != NULL)
  186275. *blue_y = info_ptr->int_y_blue;
  186276. return (PNG_INFO_cHRM);
  186277. }
  186278. return (0);
  186279. }
  186280. #endif
  186281. #endif
  186282. #if defined(PNG_gAMA_SUPPORTED)
  186283. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186284. png_uint_32 PNGAPI
  186285. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186286. {
  186287. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186288. && file_gamma != NULL)
  186289. {
  186290. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186291. *file_gamma = (double)info_ptr->gamma;
  186292. return (PNG_INFO_gAMA);
  186293. }
  186294. return (0);
  186295. }
  186296. #endif
  186297. #ifdef PNG_FIXED_POINT_SUPPORTED
  186298. png_uint_32 PNGAPI
  186299. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186300. png_fixed_point *int_file_gamma)
  186301. {
  186302. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186303. && int_file_gamma != NULL)
  186304. {
  186305. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186306. *int_file_gamma = info_ptr->int_gamma;
  186307. return (PNG_INFO_gAMA);
  186308. }
  186309. return (0);
  186310. }
  186311. #endif
  186312. #endif
  186313. #if defined(PNG_sRGB_SUPPORTED)
  186314. png_uint_32 PNGAPI
  186315. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186316. {
  186317. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186318. && file_srgb_intent != NULL)
  186319. {
  186320. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186321. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186322. return (PNG_INFO_sRGB);
  186323. }
  186324. return (0);
  186325. }
  186326. #endif
  186327. #if defined(PNG_iCCP_SUPPORTED)
  186328. png_uint_32 PNGAPI
  186329. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186330. png_charpp name, int *compression_type,
  186331. png_charpp profile, png_uint_32 *proflen)
  186332. {
  186333. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186334. && name != NULL && profile != NULL && proflen != NULL)
  186335. {
  186336. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186337. *name = info_ptr->iccp_name;
  186338. *profile = info_ptr->iccp_profile;
  186339. /* compression_type is a dummy so the API won't have to change
  186340. if we introduce multiple compression types later. */
  186341. *proflen = (int)info_ptr->iccp_proflen;
  186342. *compression_type = (int)info_ptr->iccp_compression;
  186343. return (PNG_INFO_iCCP);
  186344. }
  186345. return (0);
  186346. }
  186347. #endif
  186348. #if defined(PNG_sPLT_SUPPORTED)
  186349. png_uint_32 PNGAPI
  186350. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186351. png_sPLT_tpp spalettes)
  186352. {
  186353. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186354. {
  186355. *spalettes = info_ptr->splt_palettes;
  186356. return ((png_uint_32)info_ptr->splt_palettes_num);
  186357. }
  186358. return (0);
  186359. }
  186360. #endif
  186361. #if defined(PNG_hIST_SUPPORTED)
  186362. png_uint_32 PNGAPI
  186363. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186364. {
  186365. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186366. && hist != NULL)
  186367. {
  186368. png_debug1(1, "in %s retrieval function\n", "hIST");
  186369. *hist = info_ptr->hist;
  186370. return (PNG_INFO_hIST);
  186371. }
  186372. return (0);
  186373. }
  186374. #endif
  186375. png_uint_32 PNGAPI
  186376. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186377. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186378. int *color_type, int *interlace_type, int *compression_type,
  186379. int *filter_type)
  186380. {
  186381. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186382. bit_depth != NULL && color_type != NULL)
  186383. {
  186384. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186385. *width = info_ptr->width;
  186386. *height = info_ptr->height;
  186387. *bit_depth = info_ptr->bit_depth;
  186388. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186389. png_error(png_ptr, "Invalid bit depth");
  186390. *color_type = info_ptr->color_type;
  186391. if (info_ptr->color_type > 6)
  186392. png_error(png_ptr, "Invalid color type");
  186393. if (compression_type != NULL)
  186394. *compression_type = info_ptr->compression_type;
  186395. if (filter_type != NULL)
  186396. *filter_type = info_ptr->filter_type;
  186397. if (interlace_type != NULL)
  186398. *interlace_type = info_ptr->interlace_type;
  186399. /* check for potential overflow of rowbytes */
  186400. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186401. png_error(png_ptr, "Invalid image width");
  186402. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186403. png_error(png_ptr, "Invalid image height");
  186404. if (info_ptr->width > (PNG_UINT_32_MAX
  186405. >> 3) /* 8-byte RGBA pixels */
  186406. - 64 /* bigrowbuf hack */
  186407. - 1 /* filter byte */
  186408. - 7*8 /* rounding of width to multiple of 8 pixels */
  186409. - 8) /* extra max_pixel_depth pad */
  186410. {
  186411. png_warning(png_ptr,
  186412. "Width too large for libpng to process image data.");
  186413. }
  186414. return (1);
  186415. }
  186416. return (0);
  186417. }
  186418. #if defined(PNG_oFFs_SUPPORTED)
  186419. png_uint_32 PNGAPI
  186420. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186421. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186422. {
  186423. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186424. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186425. {
  186426. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186427. *offset_x = info_ptr->x_offset;
  186428. *offset_y = info_ptr->y_offset;
  186429. *unit_type = (int)info_ptr->offset_unit_type;
  186430. return (PNG_INFO_oFFs);
  186431. }
  186432. return (0);
  186433. }
  186434. #endif
  186435. #if defined(PNG_pCAL_SUPPORTED)
  186436. png_uint_32 PNGAPI
  186437. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186438. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186439. png_charp *units, png_charpp *params)
  186440. {
  186441. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186442. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186443. nparams != NULL && units != NULL && params != NULL)
  186444. {
  186445. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186446. *purpose = info_ptr->pcal_purpose;
  186447. *X0 = info_ptr->pcal_X0;
  186448. *X1 = info_ptr->pcal_X1;
  186449. *type = (int)info_ptr->pcal_type;
  186450. *nparams = (int)info_ptr->pcal_nparams;
  186451. *units = info_ptr->pcal_units;
  186452. *params = info_ptr->pcal_params;
  186453. return (PNG_INFO_pCAL);
  186454. }
  186455. return (0);
  186456. }
  186457. #endif
  186458. #if defined(PNG_sCAL_SUPPORTED)
  186459. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186460. png_uint_32 PNGAPI
  186461. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186462. int *unit, double *width, double *height)
  186463. {
  186464. if (png_ptr != NULL && info_ptr != NULL &&
  186465. (info_ptr->valid & PNG_INFO_sCAL))
  186466. {
  186467. *unit = info_ptr->scal_unit;
  186468. *width = info_ptr->scal_pixel_width;
  186469. *height = info_ptr->scal_pixel_height;
  186470. return (PNG_INFO_sCAL);
  186471. }
  186472. return(0);
  186473. }
  186474. #else
  186475. #ifdef PNG_FIXED_POINT_SUPPORTED
  186476. png_uint_32 PNGAPI
  186477. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186478. int *unit, png_charpp width, png_charpp height)
  186479. {
  186480. if (png_ptr != NULL && info_ptr != NULL &&
  186481. (info_ptr->valid & PNG_INFO_sCAL))
  186482. {
  186483. *unit = info_ptr->scal_unit;
  186484. *width = info_ptr->scal_s_width;
  186485. *height = info_ptr->scal_s_height;
  186486. return (PNG_INFO_sCAL);
  186487. }
  186488. return(0);
  186489. }
  186490. #endif
  186491. #endif
  186492. #endif
  186493. #if defined(PNG_pHYs_SUPPORTED)
  186494. png_uint_32 PNGAPI
  186495. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186496. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186497. {
  186498. png_uint_32 retval = 0;
  186499. if (png_ptr != NULL && info_ptr != NULL &&
  186500. (info_ptr->valid & PNG_INFO_pHYs))
  186501. {
  186502. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186503. if (res_x != NULL)
  186504. {
  186505. *res_x = info_ptr->x_pixels_per_unit;
  186506. retval |= PNG_INFO_pHYs;
  186507. }
  186508. if (res_y != NULL)
  186509. {
  186510. *res_y = info_ptr->y_pixels_per_unit;
  186511. retval |= PNG_INFO_pHYs;
  186512. }
  186513. if (unit_type != NULL)
  186514. {
  186515. *unit_type = (int)info_ptr->phys_unit_type;
  186516. retval |= PNG_INFO_pHYs;
  186517. }
  186518. }
  186519. return (retval);
  186520. }
  186521. #endif
  186522. png_uint_32 PNGAPI
  186523. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186524. int *num_palette)
  186525. {
  186526. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186527. && palette != NULL)
  186528. {
  186529. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186530. *palette = info_ptr->palette;
  186531. *num_palette = info_ptr->num_palette;
  186532. png_debug1(3, "num_palette = %d\n", *num_palette);
  186533. return (PNG_INFO_PLTE);
  186534. }
  186535. return (0);
  186536. }
  186537. #if defined(PNG_sBIT_SUPPORTED)
  186538. png_uint_32 PNGAPI
  186539. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186540. {
  186541. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186542. && sig_bit != NULL)
  186543. {
  186544. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186545. *sig_bit = &(info_ptr->sig_bit);
  186546. return (PNG_INFO_sBIT);
  186547. }
  186548. return (0);
  186549. }
  186550. #endif
  186551. #if defined(PNG_TEXT_SUPPORTED)
  186552. png_uint_32 PNGAPI
  186553. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186554. int *num_text)
  186555. {
  186556. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186557. {
  186558. png_debug1(1, "in %s retrieval function\n",
  186559. (png_ptr->chunk_name[0] == '\0' ? "text"
  186560. : (png_const_charp)png_ptr->chunk_name));
  186561. if (text_ptr != NULL)
  186562. *text_ptr = info_ptr->text;
  186563. if (num_text != NULL)
  186564. *num_text = info_ptr->num_text;
  186565. return ((png_uint_32)info_ptr->num_text);
  186566. }
  186567. if (num_text != NULL)
  186568. *num_text = 0;
  186569. return(0);
  186570. }
  186571. #endif
  186572. #if defined(PNG_tIME_SUPPORTED)
  186573. png_uint_32 PNGAPI
  186574. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186575. {
  186576. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186577. && mod_time != NULL)
  186578. {
  186579. png_debug1(1, "in %s retrieval function\n", "tIME");
  186580. *mod_time = &(info_ptr->mod_time);
  186581. return (PNG_INFO_tIME);
  186582. }
  186583. return (0);
  186584. }
  186585. #endif
  186586. #if defined(PNG_tRNS_SUPPORTED)
  186587. png_uint_32 PNGAPI
  186588. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186589. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186590. {
  186591. png_uint_32 retval = 0;
  186592. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186593. {
  186594. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186595. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186596. {
  186597. if (trans != NULL)
  186598. {
  186599. *trans = info_ptr->trans;
  186600. retval |= PNG_INFO_tRNS;
  186601. }
  186602. if (trans_values != NULL)
  186603. *trans_values = &(info_ptr->trans_values);
  186604. }
  186605. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186606. {
  186607. if (trans_values != NULL)
  186608. {
  186609. *trans_values = &(info_ptr->trans_values);
  186610. retval |= PNG_INFO_tRNS;
  186611. }
  186612. if(trans != NULL)
  186613. *trans = NULL;
  186614. }
  186615. if(num_trans != NULL)
  186616. {
  186617. *num_trans = info_ptr->num_trans;
  186618. retval |= PNG_INFO_tRNS;
  186619. }
  186620. }
  186621. return (retval);
  186622. }
  186623. #endif
  186624. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186625. png_uint_32 PNGAPI
  186626. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186627. png_unknown_chunkpp unknowns)
  186628. {
  186629. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186630. {
  186631. *unknowns = info_ptr->unknown_chunks;
  186632. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186633. }
  186634. return (0);
  186635. }
  186636. #endif
  186637. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186638. png_byte PNGAPI
  186639. png_get_rgb_to_gray_status (png_structp png_ptr)
  186640. {
  186641. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186642. }
  186643. #endif
  186644. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186645. png_voidp PNGAPI
  186646. png_get_user_chunk_ptr(png_structp png_ptr)
  186647. {
  186648. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186649. }
  186650. #endif
  186651. #ifdef PNG_WRITE_SUPPORTED
  186652. png_uint_32 PNGAPI
  186653. png_get_compression_buffer_size(png_structp png_ptr)
  186654. {
  186655. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186656. }
  186657. #endif
  186658. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186659. #ifndef PNG_1_0_X
  186660. /* this function was added to libpng 1.2.0 and should exist by default */
  186661. png_uint_32 PNGAPI
  186662. png_get_asm_flags (png_structp png_ptr)
  186663. {
  186664. /* obsolete, to be removed from libpng-1.4.0 */
  186665. return (png_ptr? 0L: 0L);
  186666. }
  186667. /* this function was added to libpng 1.2.0 and should exist by default */
  186668. png_uint_32 PNGAPI
  186669. png_get_asm_flagmask (int flag_select)
  186670. {
  186671. /* obsolete, to be removed from libpng-1.4.0 */
  186672. flag_select=flag_select;
  186673. return 0L;
  186674. }
  186675. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186676. /* this function was added to libpng 1.2.0 */
  186677. png_uint_32 PNGAPI
  186678. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186679. {
  186680. /* obsolete, to be removed from libpng-1.4.0 */
  186681. flag_select=flag_select;
  186682. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186683. return 0L;
  186684. }
  186685. /* this function was added to libpng 1.2.0 */
  186686. png_byte PNGAPI
  186687. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186688. {
  186689. /* obsolete, to be removed from libpng-1.4.0 */
  186690. return (png_ptr? 0: 0);
  186691. }
  186692. /* this function was added to libpng 1.2.0 */
  186693. png_uint_32 PNGAPI
  186694. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186695. {
  186696. /* obsolete, to be removed from libpng-1.4.0 */
  186697. return (png_ptr? 0L: 0L);
  186698. }
  186699. #endif /* ?PNG_1_0_X */
  186700. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186701. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186702. /* these functions were added to libpng 1.2.6 */
  186703. png_uint_32 PNGAPI
  186704. png_get_user_width_max (png_structp png_ptr)
  186705. {
  186706. return (png_ptr? png_ptr->user_width_max : 0);
  186707. }
  186708. png_uint_32 PNGAPI
  186709. png_get_user_height_max (png_structp png_ptr)
  186710. {
  186711. return (png_ptr? png_ptr->user_height_max : 0);
  186712. }
  186713. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186714. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186715. /*** End of inlined file: pngget.c ***/
  186716. /*** Start of inlined file: pngmem.c ***/
  186717. /* pngmem.c - stub functions for memory allocation
  186718. *
  186719. * Last changed in libpng 1.2.13 November 13, 2006
  186720. * For conditions of distribution and use, see copyright notice in png.h
  186721. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186722. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186723. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186724. *
  186725. * This file provides a location for all memory allocation. Users who
  186726. * need special memory handling are expected to supply replacement
  186727. * functions for png_malloc() and png_free(), and to use
  186728. * png_create_read_struct_2() and png_create_write_struct_2() to
  186729. * identify the replacement functions.
  186730. */
  186731. #define PNG_INTERNAL
  186732. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186733. /* Borland DOS special memory handler */
  186734. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186735. /* if you change this, be sure to change the one in png.h also */
  186736. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186737. by a single call to calloc() if this is thought to improve performance. */
  186738. png_voidp /* PRIVATE */
  186739. png_create_struct(int type)
  186740. {
  186741. #ifdef PNG_USER_MEM_SUPPORTED
  186742. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186743. }
  186744. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186745. png_voidp /* PRIVATE */
  186746. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186747. {
  186748. #endif /* PNG_USER_MEM_SUPPORTED */
  186749. png_size_t size;
  186750. png_voidp struct_ptr;
  186751. if (type == PNG_STRUCT_INFO)
  186752. size = png_sizeof(png_info);
  186753. else if (type == PNG_STRUCT_PNG)
  186754. size = png_sizeof(png_struct);
  186755. else
  186756. return (png_get_copyright(NULL));
  186757. #ifdef PNG_USER_MEM_SUPPORTED
  186758. if(malloc_fn != NULL)
  186759. {
  186760. png_struct dummy_struct;
  186761. png_structp png_ptr = &dummy_struct;
  186762. png_ptr->mem_ptr=mem_ptr;
  186763. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186764. }
  186765. else
  186766. #endif /* PNG_USER_MEM_SUPPORTED */
  186767. struct_ptr = (png_voidp)farmalloc(size);
  186768. if (struct_ptr != NULL)
  186769. png_memset(struct_ptr, 0, size);
  186770. return (struct_ptr);
  186771. }
  186772. /* Free memory allocated by a png_create_struct() call */
  186773. void /* PRIVATE */
  186774. png_destroy_struct(png_voidp struct_ptr)
  186775. {
  186776. #ifdef PNG_USER_MEM_SUPPORTED
  186777. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186778. }
  186779. /* Free memory allocated by a png_create_struct() call */
  186780. void /* PRIVATE */
  186781. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186782. png_voidp mem_ptr)
  186783. {
  186784. #endif
  186785. if (struct_ptr != NULL)
  186786. {
  186787. #ifdef PNG_USER_MEM_SUPPORTED
  186788. if(free_fn != NULL)
  186789. {
  186790. png_struct dummy_struct;
  186791. png_structp png_ptr = &dummy_struct;
  186792. png_ptr->mem_ptr=mem_ptr;
  186793. (*(free_fn))(png_ptr, struct_ptr);
  186794. return;
  186795. }
  186796. #endif /* PNG_USER_MEM_SUPPORTED */
  186797. farfree (struct_ptr);
  186798. }
  186799. }
  186800. /* Allocate memory. For reasonable files, size should never exceed
  186801. * 64K. However, zlib may allocate more then 64K if you don't tell
  186802. * it not to. See zconf.h and png.h for more information. zlib does
  186803. * need to allocate exactly 64K, so whatever you call here must
  186804. * have the ability to do that.
  186805. *
  186806. * Borland seems to have a problem in DOS mode for exactly 64K.
  186807. * It gives you a segment with an offset of 8 (perhaps to store its
  186808. * memory stuff). zlib doesn't like this at all, so we have to
  186809. * detect and deal with it. This code should not be needed in
  186810. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186811. * been updated by Alexander Lehmann for version 0.89 to waste less
  186812. * memory.
  186813. *
  186814. * Note that we can't use png_size_t for the "size" declaration,
  186815. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186816. * result, we would be truncating potentially larger memory requests
  186817. * (which should cause a fatal error) and introducing major problems.
  186818. */
  186819. png_voidp PNGAPI
  186820. png_malloc(png_structp png_ptr, png_uint_32 size)
  186821. {
  186822. png_voidp ret;
  186823. if (png_ptr == NULL || size == 0)
  186824. return (NULL);
  186825. #ifdef PNG_USER_MEM_SUPPORTED
  186826. if(png_ptr->malloc_fn != NULL)
  186827. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186828. else
  186829. ret = (png_malloc_default(png_ptr, size));
  186830. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186831. png_error(png_ptr, "Out of memory!");
  186832. return (ret);
  186833. }
  186834. png_voidp PNGAPI
  186835. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186836. {
  186837. png_voidp ret;
  186838. #endif /* PNG_USER_MEM_SUPPORTED */
  186839. if (png_ptr == NULL || size == 0)
  186840. return (NULL);
  186841. #ifdef PNG_MAX_MALLOC_64K
  186842. if (size > (png_uint_32)65536L)
  186843. {
  186844. png_warning(png_ptr, "Cannot Allocate > 64K");
  186845. ret = NULL;
  186846. }
  186847. else
  186848. #endif
  186849. if (size != (size_t)size)
  186850. ret = NULL;
  186851. else if (size == (png_uint_32)65536L)
  186852. {
  186853. if (png_ptr->offset_table == NULL)
  186854. {
  186855. /* try to see if we need to do any of this fancy stuff */
  186856. ret = farmalloc(size);
  186857. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186858. {
  186859. int num_blocks;
  186860. png_uint_32 total_size;
  186861. png_bytep table;
  186862. int i;
  186863. png_byte huge * hptr;
  186864. if (ret != NULL)
  186865. {
  186866. farfree(ret);
  186867. ret = NULL;
  186868. }
  186869. if(png_ptr->zlib_window_bits > 14)
  186870. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186871. else
  186872. num_blocks = 1;
  186873. if (png_ptr->zlib_mem_level >= 7)
  186874. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186875. else
  186876. num_blocks++;
  186877. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186878. table = farmalloc(total_size);
  186879. if (table == NULL)
  186880. {
  186881. #ifndef PNG_USER_MEM_SUPPORTED
  186882. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186883. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186884. else
  186885. png_warning(png_ptr, "Out Of Memory.");
  186886. #endif
  186887. return (NULL);
  186888. }
  186889. if ((png_size_t)table & 0xfff0)
  186890. {
  186891. #ifndef PNG_USER_MEM_SUPPORTED
  186892. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186893. png_error(png_ptr,
  186894. "Farmalloc didn't return normalized pointer");
  186895. else
  186896. png_warning(png_ptr,
  186897. "Farmalloc didn't return normalized pointer");
  186898. #endif
  186899. return (NULL);
  186900. }
  186901. png_ptr->offset_table = table;
  186902. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186903. png_sizeof (png_bytep));
  186904. if (png_ptr->offset_table_ptr == NULL)
  186905. {
  186906. #ifndef PNG_USER_MEM_SUPPORTED
  186907. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186908. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186909. else
  186910. png_warning(png_ptr, "Out Of memory.");
  186911. #endif
  186912. return (NULL);
  186913. }
  186914. hptr = (png_byte huge *)table;
  186915. if ((png_size_t)hptr & 0xf)
  186916. {
  186917. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186918. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186919. }
  186920. for (i = 0; i < num_blocks; i++)
  186921. {
  186922. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186923. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186924. }
  186925. png_ptr->offset_table_number = num_blocks;
  186926. png_ptr->offset_table_count = 0;
  186927. png_ptr->offset_table_count_free = 0;
  186928. }
  186929. }
  186930. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186931. {
  186932. #ifndef PNG_USER_MEM_SUPPORTED
  186933. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186934. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186935. else
  186936. png_warning(png_ptr, "Out of Memory.");
  186937. #endif
  186938. return (NULL);
  186939. }
  186940. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186941. }
  186942. else
  186943. ret = farmalloc(size);
  186944. #ifndef PNG_USER_MEM_SUPPORTED
  186945. if (ret == NULL)
  186946. {
  186947. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186948. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186949. else
  186950. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186951. }
  186952. #endif
  186953. return (ret);
  186954. }
  186955. /* free a pointer allocated by png_malloc(). In the default
  186956. configuration, png_ptr is not used, but is passed in case it
  186957. is needed. If ptr is NULL, return without taking any action. */
  186958. void PNGAPI
  186959. png_free(png_structp png_ptr, png_voidp ptr)
  186960. {
  186961. if (png_ptr == NULL || ptr == NULL)
  186962. return;
  186963. #ifdef PNG_USER_MEM_SUPPORTED
  186964. if (png_ptr->free_fn != NULL)
  186965. {
  186966. (*(png_ptr->free_fn))(png_ptr, ptr);
  186967. return;
  186968. }
  186969. else png_free_default(png_ptr, ptr);
  186970. }
  186971. void PNGAPI
  186972. png_free_default(png_structp png_ptr, png_voidp ptr)
  186973. {
  186974. #endif /* PNG_USER_MEM_SUPPORTED */
  186975. if(png_ptr == NULL) return;
  186976. if (png_ptr->offset_table != NULL)
  186977. {
  186978. int i;
  186979. for (i = 0; i < png_ptr->offset_table_count; i++)
  186980. {
  186981. if (ptr == png_ptr->offset_table_ptr[i])
  186982. {
  186983. ptr = NULL;
  186984. png_ptr->offset_table_count_free++;
  186985. break;
  186986. }
  186987. }
  186988. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186989. {
  186990. farfree(png_ptr->offset_table);
  186991. farfree(png_ptr->offset_table_ptr);
  186992. png_ptr->offset_table = NULL;
  186993. png_ptr->offset_table_ptr = NULL;
  186994. }
  186995. }
  186996. if (ptr != NULL)
  186997. {
  186998. farfree(ptr);
  186999. }
  187000. }
  187001. #else /* Not the Borland DOS special memory handler */
  187002. /* Allocate memory for a png_struct or a png_info. The malloc and
  187003. memset can be replaced by a single call to calloc() if this is thought
  187004. to improve performance noticably. */
  187005. png_voidp /* PRIVATE */
  187006. png_create_struct(int type)
  187007. {
  187008. #ifdef PNG_USER_MEM_SUPPORTED
  187009. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187010. }
  187011. /* Allocate memory for a png_struct or a png_info. The malloc and
  187012. memset can be replaced by a single call to calloc() if this is thought
  187013. to improve performance noticably. */
  187014. png_voidp /* PRIVATE */
  187015. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187016. {
  187017. #endif /* PNG_USER_MEM_SUPPORTED */
  187018. png_size_t size;
  187019. png_voidp struct_ptr;
  187020. if (type == PNG_STRUCT_INFO)
  187021. size = png_sizeof(png_info);
  187022. else if (type == PNG_STRUCT_PNG)
  187023. size = png_sizeof(png_struct);
  187024. else
  187025. return (NULL);
  187026. #ifdef PNG_USER_MEM_SUPPORTED
  187027. if(malloc_fn != NULL)
  187028. {
  187029. png_struct dummy_struct;
  187030. png_structp png_ptr = &dummy_struct;
  187031. png_ptr->mem_ptr=mem_ptr;
  187032. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187033. if (struct_ptr != NULL)
  187034. png_memset(struct_ptr, 0, size);
  187035. return (struct_ptr);
  187036. }
  187037. #endif /* PNG_USER_MEM_SUPPORTED */
  187038. #if defined(__TURBOC__) && !defined(__FLAT__)
  187039. struct_ptr = (png_voidp)farmalloc(size);
  187040. #else
  187041. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187042. struct_ptr = (png_voidp)halloc(size,1);
  187043. # else
  187044. struct_ptr = (png_voidp)malloc(size);
  187045. # endif
  187046. #endif
  187047. if (struct_ptr != NULL)
  187048. png_memset(struct_ptr, 0, size);
  187049. return (struct_ptr);
  187050. }
  187051. /* Free memory allocated by a png_create_struct() call */
  187052. void /* PRIVATE */
  187053. png_destroy_struct(png_voidp struct_ptr)
  187054. {
  187055. #ifdef PNG_USER_MEM_SUPPORTED
  187056. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187057. }
  187058. /* Free memory allocated by a png_create_struct() call */
  187059. void /* PRIVATE */
  187060. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187061. png_voidp mem_ptr)
  187062. {
  187063. #endif /* PNG_USER_MEM_SUPPORTED */
  187064. if (struct_ptr != NULL)
  187065. {
  187066. #ifdef PNG_USER_MEM_SUPPORTED
  187067. if(free_fn != NULL)
  187068. {
  187069. png_struct dummy_struct;
  187070. png_structp png_ptr = &dummy_struct;
  187071. png_ptr->mem_ptr=mem_ptr;
  187072. (*(free_fn))(png_ptr, struct_ptr);
  187073. return;
  187074. }
  187075. #endif /* PNG_USER_MEM_SUPPORTED */
  187076. #if defined(__TURBOC__) && !defined(__FLAT__)
  187077. farfree(struct_ptr);
  187078. #else
  187079. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187080. hfree(struct_ptr);
  187081. # else
  187082. free(struct_ptr);
  187083. # endif
  187084. #endif
  187085. }
  187086. }
  187087. /* Allocate memory. For reasonable files, size should never exceed
  187088. 64K. However, zlib may allocate more then 64K if you don't tell
  187089. it not to. See zconf.h and png.h for more information. zlib does
  187090. need to allocate exactly 64K, so whatever you call here must
  187091. have the ability to do that. */
  187092. png_voidp PNGAPI
  187093. png_malloc(png_structp png_ptr, png_uint_32 size)
  187094. {
  187095. png_voidp ret;
  187096. #ifdef PNG_USER_MEM_SUPPORTED
  187097. if (png_ptr == NULL || size == 0)
  187098. return (NULL);
  187099. if(png_ptr->malloc_fn != NULL)
  187100. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187101. else
  187102. ret = (png_malloc_default(png_ptr, size));
  187103. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187104. png_error(png_ptr, "Out of Memory!");
  187105. return (ret);
  187106. }
  187107. png_voidp PNGAPI
  187108. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187109. {
  187110. png_voidp ret;
  187111. #endif /* PNG_USER_MEM_SUPPORTED */
  187112. if (png_ptr == NULL || size == 0)
  187113. return (NULL);
  187114. #ifdef PNG_MAX_MALLOC_64K
  187115. if (size > (png_uint_32)65536L)
  187116. {
  187117. #ifndef PNG_USER_MEM_SUPPORTED
  187118. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187119. png_error(png_ptr, "Cannot Allocate > 64K");
  187120. else
  187121. #endif
  187122. return NULL;
  187123. }
  187124. #endif
  187125. /* Check for overflow */
  187126. #if defined(__TURBOC__) && !defined(__FLAT__)
  187127. if (size != (unsigned long)size)
  187128. ret = NULL;
  187129. else
  187130. ret = farmalloc(size);
  187131. #else
  187132. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187133. if (size != (unsigned long)size)
  187134. ret = NULL;
  187135. else
  187136. ret = halloc(size, 1);
  187137. # else
  187138. if (size != (size_t)size)
  187139. ret = NULL;
  187140. else
  187141. ret = malloc((size_t)size);
  187142. # endif
  187143. #endif
  187144. #ifndef PNG_USER_MEM_SUPPORTED
  187145. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187146. png_error(png_ptr, "Out of Memory");
  187147. #endif
  187148. return (ret);
  187149. }
  187150. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187151. without taking any action. */
  187152. void PNGAPI
  187153. png_free(png_structp png_ptr, png_voidp ptr)
  187154. {
  187155. if (png_ptr == NULL || ptr == NULL)
  187156. return;
  187157. #ifdef PNG_USER_MEM_SUPPORTED
  187158. if (png_ptr->free_fn != NULL)
  187159. {
  187160. (*(png_ptr->free_fn))(png_ptr, ptr);
  187161. return;
  187162. }
  187163. else png_free_default(png_ptr, ptr);
  187164. }
  187165. void PNGAPI
  187166. png_free_default(png_structp png_ptr, png_voidp ptr)
  187167. {
  187168. if (png_ptr == NULL || ptr == NULL)
  187169. return;
  187170. #endif /* PNG_USER_MEM_SUPPORTED */
  187171. #if defined(__TURBOC__) && !defined(__FLAT__)
  187172. farfree(ptr);
  187173. #else
  187174. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187175. hfree(ptr);
  187176. # else
  187177. free(ptr);
  187178. # endif
  187179. #endif
  187180. }
  187181. #endif /* Not Borland DOS special memory handler */
  187182. #if defined(PNG_1_0_X)
  187183. # define png_malloc_warn png_malloc
  187184. #else
  187185. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187186. * function will set up png_malloc() to issue a png_warning and return NULL
  187187. * instead of issuing a png_error, if it fails to allocate the requested
  187188. * memory.
  187189. */
  187190. png_voidp PNGAPI
  187191. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187192. {
  187193. png_voidp ptr;
  187194. png_uint_32 save_flags;
  187195. if(png_ptr == NULL) return (NULL);
  187196. save_flags=png_ptr->flags;
  187197. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187198. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187199. png_ptr->flags=save_flags;
  187200. return(ptr);
  187201. }
  187202. #endif
  187203. png_voidp PNGAPI
  187204. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187205. png_uint_32 length)
  187206. {
  187207. png_size_t size;
  187208. size = (png_size_t)length;
  187209. if ((png_uint_32)size != length)
  187210. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187211. return(png_memcpy (s1, s2, size));
  187212. }
  187213. png_voidp PNGAPI
  187214. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187215. png_uint_32 length)
  187216. {
  187217. png_size_t size;
  187218. size = (png_size_t)length;
  187219. if ((png_uint_32)size != length)
  187220. png_error(png_ptr,"Overflow in png_memset_check.");
  187221. return (png_memset (s1, value, size));
  187222. }
  187223. #ifdef PNG_USER_MEM_SUPPORTED
  187224. /* This function is called when the application wants to use another method
  187225. * of allocating and freeing memory.
  187226. */
  187227. void PNGAPI
  187228. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187229. malloc_fn, png_free_ptr free_fn)
  187230. {
  187231. if(png_ptr != NULL) {
  187232. png_ptr->mem_ptr = mem_ptr;
  187233. png_ptr->malloc_fn = malloc_fn;
  187234. png_ptr->free_fn = free_fn;
  187235. }
  187236. }
  187237. /* This function returns a pointer to the mem_ptr associated with the user
  187238. * functions. The application should free any memory associated with this
  187239. * pointer before png_write_destroy and png_read_destroy are called.
  187240. */
  187241. png_voidp PNGAPI
  187242. png_get_mem_ptr(png_structp png_ptr)
  187243. {
  187244. if(png_ptr == NULL) return (NULL);
  187245. return ((png_voidp)png_ptr->mem_ptr);
  187246. }
  187247. #endif /* PNG_USER_MEM_SUPPORTED */
  187248. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187249. /*** End of inlined file: pngmem.c ***/
  187250. /*** Start of inlined file: pngread.c ***/
  187251. /* pngread.c - read a PNG file
  187252. *
  187253. * Last changed in libpng 1.2.20 September 7, 2007
  187254. * For conditions of distribution and use, see copyright notice in png.h
  187255. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187256. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187257. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187258. *
  187259. * This file contains routines that an application calls directly to
  187260. * read a PNG file or stream.
  187261. */
  187262. #define PNG_INTERNAL
  187263. #if defined(PNG_READ_SUPPORTED)
  187264. /* Create a PNG structure for reading, and allocate any memory needed. */
  187265. png_structp PNGAPI
  187266. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187267. png_error_ptr error_fn, png_error_ptr warn_fn)
  187268. {
  187269. #ifdef PNG_USER_MEM_SUPPORTED
  187270. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187271. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187272. }
  187273. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187274. png_structp PNGAPI
  187275. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187276. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187277. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187278. {
  187279. #endif /* PNG_USER_MEM_SUPPORTED */
  187280. png_structp png_ptr;
  187281. #ifdef PNG_SETJMP_SUPPORTED
  187282. #ifdef USE_FAR_KEYWORD
  187283. jmp_buf jmpbuf;
  187284. #endif
  187285. #endif
  187286. int i;
  187287. png_debug(1, "in png_create_read_struct\n");
  187288. #ifdef PNG_USER_MEM_SUPPORTED
  187289. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187290. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187291. #else
  187292. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187293. #endif
  187294. if (png_ptr == NULL)
  187295. return (NULL);
  187296. /* added at libpng-1.2.6 */
  187297. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187298. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187299. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187300. #endif
  187301. #ifdef PNG_SETJMP_SUPPORTED
  187302. #ifdef USE_FAR_KEYWORD
  187303. if (setjmp(jmpbuf))
  187304. #else
  187305. if (setjmp(png_ptr->jmpbuf))
  187306. #endif
  187307. {
  187308. png_free(png_ptr, png_ptr->zbuf);
  187309. png_ptr->zbuf=NULL;
  187310. #ifdef PNG_USER_MEM_SUPPORTED
  187311. png_destroy_struct_2((png_voidp)png_ptr,
  187312. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187313. #else
  187314. png_destroy_struct((png_voidp)png_ptr);
  187315. #endif
  187316. return (NULL);
  187317. }
  187318. #ifdef USE_FAR_KEYWORD
  187319. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187320. #endif
  187321. #endif
  187322. #ifdef PNG_USER_MEM_SUPPORTED
  187323. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187324. #endif
  187325. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187326. i=0;
  187327. do
  187328. {
  187329. if(user_png_ver[i] != png_libpng_ver[i])
  187330. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187331. } while (png_libpng_ver[i++]);
  187332. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187333. {
  187334. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187335. * we must recompile any applications that use any older library version.
  187336. * For versions after libpng 1.0, we will be compatible, so we need
  187337. * only check the first digit.
  187338. */
  187339. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187340. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187341. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187342. {
  187343. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187344. char msg[80];
  187345. if (user_png_ver)
  187346. {
  187347. png_snprintf(msg, 80,
  187348. "Application was compiled with png.h from libpng-%.20s",
  187349. user_png_ver);
  187350. png_warning(png_ptr, msg);
  187351. }
  187352. png_snprintf(msg, 80,
  187353. "Application is running with png.c from libpng-%.20s",
  187354. png_libpng_ver);
  187355. png_warning(png_ptr, msg);
  187356. #endif
  187357. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187358. png_ptr->flags=0;
  187359. #endif
  187360. png_error(png_ptr,
  187361. "Incompatible libpng version in application and library");
  187362. }
  187363. }
  187364. /* initialize zbuf - compression buffer */
  187365. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187366. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187367. (png_uint_32)png_ptr->zbuf_size);
  187368. png_ptr->zstream.zalloc = png_zalloc;
  187369. png_ptr->zstream.zfree = png_zfree;
  187370. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187371. switch (inflateInit(&png_ptr->zstream))
  187372. {
  187373. case Z_OK: /* Do nothing */ break;
  187374. case Z_MEM_ERROR:
  187375. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187376. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187377. default: png_error(png_ptr, "Unknown zlib error");
  187378. }
  187379. png_ptr->zstream.next_out = png_ptr->zbuf;
  187380. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187381. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187382. #ifdef PNG_SETJMP_SUPPORTED
  187383. /* Applications that neglect to set up their own setjmp() and then encounter
  187384. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187385. abort instead of returning. */
  187386. #ifdef USE_FAR_KEYWORD
  187387. if (setjmp(jmpbuf))
  187388. PNG_ABORT();
  187389. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187390. #else
  187391. if (setjmp(png_ptr->jmpbuf))
  187392. PNG_ABORT();
  187393. #endif
  187394. #endif
  187395. return (png_ptr);
  187396. }
  187397. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187398. /* Initialize PNG structure for reading, and allocate any memory needed.
  187399. This interface is deprecated in favour of the png_create_read_struct(),
  187400. and it will disappear as of libpng-1.3.0. */
  187401. #undef png_read_init
  187402. void PNGAPI
  187403. png_read_init(png_structp png_ptr)
  187404. {
  187405. /* We only come here via pre-1.0.7-compiled applications */
  187406. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187407. }
  187408. void PNGAPI
  187409. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187410. png_size_t png_struct_size, png_size_t png_info_size)
  187411. {
  187412. /* We only come here via pre-1.0.12-compiled applications */
  187413. if(png_ptr == NULL) return;
  187414. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187415. if(png_sizeof(png_struct) > png_struct_size ||
  187416. png_sizeof(png_info) > png_info_size)
  187417. {
  187418. char msg[80];
  187419. png_ptr->warning_fn=NULL;
  187420. if (user_png_ver)
  187421. {
  187422. png_snprintf(msg, 80,
  187423. "Application was compiled with png.h from libpng-%.20s",
  187424. user_png_ver);
  187425. png_warning(png_ptr, msg);
  187426. }
  187427. png_snprintf(msg, 80,
  187428. "Application is running with png.c from libpng-%.20s",
  187429. png_libpng_ver);
  187430. png_warning(png_ptr, msg);
  187431. }
  187432. #endif
  187433. if(png_sizeof(png_struct) > png_struct_size)
  187434. {
  187435. png_ptr->error_fn=NULL;
  187436. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187437. png_ptr->flags=0;
  187438. #endif
  187439. png_error(png_ptr,
  187440. "The png struct allocated by the application for reading is too small.");
  187441. }
  187442. if(png_sizeof(png_info) > png_info_size)
  187443. {
  187444. png_ptr->error_fn=NULL;
  187445. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187446. png_ptr->flags=0;
  187447. #endif
  187448. png_error(png_ptr,
  187449. "The info struct allocated by application for reading is too small.");
  187450. }
  187451. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187452. }
  187453. #endif /* PNG_1_0_X || PNG_1_2_X */
  187454. void PNGAPI
  187455. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187456. png_size_t png_struct_size)
  187457. {
  187458. #ifdef PNG_SETJMP_SUPPORTED
  187459. jmp_buf tmp_jmp; /* to save current jump buffer */
  187460. #endif
  187461. int i=0;
  187462. png_structp png_ptr=*ptr_ptr;
  187463. if(png_ptr == NULL) return;
  187464. do
  187465. {
  187466. if(user_png_ver[i] != png_libpng_ver[i])
  187467. {
  187468. #ifdef PNG_LEGACY_SUPPORTED
  187469. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187470. #else
  187471. png_ptr->warning_fn=NULL;
  187472. png_warning(png_ptr,
  187473. "Application uses deprecated png_read_init() and should be recompiled.");
  187474. break;
  187475. #endif
  187476. }
  187477. } while (png_libpng_ver[i++]);
  187478. png_debug(1, "in png_read_init_3\n");
  187479. #ifdef PNG_SETJMP_SUPPORTED
  187480. /* save jump buffer and error functions */
  187481. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187482. #endif
  187483. if(png_sizeof(png_struct) > png_struct_size)
  187484. {
  187485. png_destroy_struct(png_ptr);
  187486. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187487. png_ptr = *ptr_ptr;
  187488. }
  187489. /* reset all variables to 0 */
  187490. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187491. #ifdef PNG_SETJMP_SUPPORTED
  187492. /* restore jump buffer */
  187493. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187494. #endif
  187495. /* added at libpng-1.2.6 */
  187496. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187497. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187498. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187499. #endif
  187500. /* initialize zbuf - compression buffer */
  187501. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187502. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187503. (png_uint_32)png_ptr->zbuf_size);
  187504. png_ptr->zstream.zalloc = png_zalloc;
  187505. png_ptr->zstream.zfree = png_zfree;
  187506. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187507. switch (inflateInit(&png_ptr->zstream))
  187508. {
  187509. case Z_OK: /* Do nothing */ break;
  187510. case Z_MEM_ERROR:
  187511. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187512. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187513. default: png_error(png_ptr, "Unknown zlib error");
  187514. }
  187515. png_ptr->zstream.next_out = png_ptr->zbuf;
  187516. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187517. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187518. }
  187519. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187520. /* Read the information before the actual image data. This has been
  187521. * changed in v0.90 to allow reading a file that already has the magic
  187522. * bytes read from the stream. You can tell libpng how many bytes have
  187523. * been read from the beginning of the stream (up to the maximum of 8)
  187524. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187525. * here. The application can then have access to the signature bytes we
  187526. * read if it is determined that this isn't a valid PNG file.
  187527. */
  187528. void PNGAPI
  187529. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187530. {
  187531. if(png_ptr == NULL) return;
  187532. png_debug(1, "in png_read_info\n");
  187533. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187534. if (png_ptr->sig_bytes < 8)
  187535. {
  187536. png_size_t num_checked = png_ptr->sig_bytes,
  187537. num_to_check = 8 - num_checked;
  187538. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187539. png_ptr->sig_bytes = 8;
  187540. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187541. {
  187542. if (num_checked < 4 &&
  187543. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187544. png_error(png_ptr, "Not a PNG file");
  187545. else
  187546. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187547. }
  187548. if (num_checked < 3)
  187549. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187550. }
  187551. for(;;)
  187552. {
  187553. #ifdef PNG_USE_LOCAL_ARRAYS
  187554. PNG_CONST PNG_IHDR;
  187555. PNG_CONST PNG_IDAT;
  187556. PNG_CONST PNG_IEND;
  187557. PNG_CONST PNG_PLTE;
  187558. #if defined(PNG_READ_bKGD_SUPPORTED)
  187559. PNG_CONST PNG_bKGD;
  187560. #endif
  187561. #if defined(PNG_READ_cHRM_SUPPORTED)
  187562. PNG_CONST PNG_cHRM;
  187563. #endif
  187564. #if defined(PNG_READ_gAMA_SUPPORTED)
  187565. PNG_CONST PNG_gAMA;
  187566. #endif
  187567. #if defined(PNG_READ_hIST_SUPPORTED)
  187568. PNG_CONST PNG_hIST;
  187569. #endif
  187570. #if defined(PNG_READ_iCCP_SUPPORTED)
  187571. PNG_CONST PNG_iCCP;
  187572. #endif
  187573. #if defined(PNG_READ_iTXt_SUPPORTED)
  187574. PNG_CONST PNG_iTXt;
  187575. #endif
  187576. #if defined(PNG_READ_oFFs_SUPPORTED)
  187577. PNG_CONST PNG_oFFs;
  187578. #endif
  187579. #if defined(PNG_READ_pCAL_SUPPORTED)
  187580. PNG_CONST PNG_pCAL;
  187581. #endif
  187582. #if defined(PNG_READ_pHYs_SUPPORTED)
  187583. PNG_CONST PNG_pHYs;
  187584. #endif
  187585. #if defined(PNG_READ_sBIT_SUPPORTED)
  187586. PNG_CONST PNG_sBIT;
  187587. #endif
  187588. #if defined(PNG_READ_sCAL_SUPPORTED)
  187589. PNG_CONST PNG_sCAL;
  187590. #endif
  187591. #if defined(PNG_READ_sPLT_SUPPORTED)
  187592. PNG_CONST PNG_sPLT;
  187593. #endif
  187594. #if defined(PNG_READ_sRGB_SUPPORTED)
  187595. PNG_CONST PNG_sRGB;
  187596. #endif
  187597. #if defined(PNG_READ_tEXt_SUPPORTED)
  187598. PNG_CONST PNG_tEXt;
  187599. #endif
  187600. #if defined(PNG_READ_tIME_SUPPORTED)
  187601. PNG_CONST PNG_tIME;
  187602. #endif
  187603. #if defined(PNG_READ_tRNS_SUPPORTED)
  187604. PNG_CONST PNG_tRNS;
  187605. #endif
  187606. #if defined(PNG_READ_zTXt_SUPPORTED)
  187607. PNG_CONST PNG_zTXt;
  187608. #endif
  187609. #endif /* PNG_USE_LOCAL_ARRAYS */
  187610. png_byte chunk_length[4];
  187611. png_uint_32 length;
  187612. png_read_data(png_ptr, chunk_length, 4);
  187613. length = png_get_uint_31(png_ptr,chunk_length);
  187614. png_reset_crc(png_ptr);
  187615. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187616. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187617. length);
  187618. /* This should be a binary subdivision search or a hash for
  187619. * matching the chunk name rather than a linear search.
  187620. */
  187621. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187622. if(png_ptr->mode & PNG_AFTER_IDAT)
  187623. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187624. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187625. png_handle_IHDR(png_ptr, info_ptr, length);
  187626. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187627. png_handle_IEND(png_ptr, info_ptr, length);
  187628. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187629. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187630. {
  187631. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187632. png_ptr->mode |= PNG_HAVE_IDAT;
  187633. png_handle_unknown(png_ptr, info_ptr, length);
  187634. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187635. png_ptr->mode |= PNG_HAVE_PLTE;
  187636. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187637. {
  187638. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187639. png_error(png_ptr, "Missing IHDR before IDAT");
  187640. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187641. !(png_ptr->mode & PNG_HAVE_PLTE))
  187642. png_error(png_ptr, "Missing PLTE before IDAT");
  187643. break;
  187644. }
  187645. }
  187646. #endif
  187647. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187648. png_handle_PLTE(png_ptr, info_ptr, length);
  187649. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187650. {
  187651. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187652. png_error(png_ptr, "Missing IHDR before IDAT");
  187653. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187654. !(png_ptr->mode & PNG_HAVE_PLTE))
  187655. png_error(png_ptr, "Missing PLTE before IDAT");
  187656. png_ptr->idat_size = length;
  187657. png_ptr->mode |= PNG_HAVE_IDAT;
  187658. break;
  187659. }
  187660. #if defined(PNG_READ_bKGD_SUPPORTED)
  187661. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187662. png_handle_bKGD(png_ptr, info_ptr, length);
  187663. #endif
  187664. #if defined(PNG_READ_cHRM_SUPPORTED)
  187665. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187666. png_handle_cHRM(png_ptr, info_ptr, length);
  187667. #endif
  187668. #if defined(PNG_READ_gAMA_SUPPORTED)
  187669. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187670. png_handle_gAMA(png_ptr, info_ptr, length);
  187671. #endif
  187672. #if defined(PNG_READ_hIST_SUPPORTED)
  187673. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187674. png_handle_hIST(png_ptr, info_ptr, length);
  187675. #endif
  187676. #if defined(PNG_READ_oFFs_SUPPORTED)
  187677. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187678. png_handle_oFFs(png_ptr, info_ptr, length);
  187679. #endif
  187680. #if defined(PNG_READ_pCAL_SUPPORTED)
  187681. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187682. png_handle_pCAL(png_ptr, info_ptr, length);
  187683. #endif
  187684. #if defined(PNG_READ_sCAL_SUPPORTED)
  187685. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187686. png_handle_sCAL(png_ptr, info_ptr, length);
  187687. #endif
  187688. #if defined(PNG_READ_pHYs_SUPPORTED)
  187689. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187690. png_handle_pHYs(png_ptr, info_ptr, length);
  187691. #endif
  187692. #if defined(PNG_READ_sBIT_SUPPORTED)
  187693. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187694. png_handle_sBIT(png_ptr, info_ptr, length);
  187695. #endif
  187696. #if defined(PNG_READ_sRGB_SUPPORTED)
  187697. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187698. png_handle_sRGB(png_ptr, info_ptr, length);
  187699. #endif
  187700. #if defined(PNG_READ_iCCP_SUPPORTED)
  187701. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187702. png_handle_iCCP(png_ptr, info_ptr, length);
  187703. #endif
  187704. #if defined(PNG_READ_sPLT_SUPPORTED)
  187705. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187706. png_handle_sPLT(png_ptr, info_ptr, length);
  187707. #endif
  187708. #if defined(PNG_READ_tEXt_SUPPORTED)
  187709. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187710. png_handle_tEXt(png_ptr, info_ptr, length);
  187711. #endif
  187712. #if defined(PNG_READ_tIME_SUPPORTED)
  187713. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187714. png_handle_tIME(png_ptr, info_ptr, length);
  187715. #endif
  187716. #if defined(PNG_READ_tRNS_SUPPORTED)
  187717. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187718. png_handle_tRNS(png_ptr, info_ptr, length);
  187719. #endif
  187720. #if defined(PNG_READ_zTXt_SUPPORTED)
  187721. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187722. png_handle_zTXt(png_ptr, info_ptr, length);
  187723. #endif
  187724. #if defined(PNG_READ_iTXt_SUPPORTED)
  187725. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187726. png_handle_iTXt(png_ptr, info_ptr, length);
  187727. #endif
  187728. else
  187729. png_handle_unknown(png_ptr, info_ptr, length);
  187730. }
  187731. }
  187732. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187733. /* optional call to update the users info_ptr structure */
  187734. void PNGAPI
  187735. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187736. {
  187737. png_debug(1, "in png_read_update_info\n");
  187738. if(png_ptr == NULL) return;
  187739. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187740. png_read_start_row(png_ptr);
  187741. else
  187742. png_warning(png_ptr,
  187743. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187744. png_read_transform_info(png_ptr, info_ptr);
  187745. }
  187746. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187747. /* Initialize palette, background, etc, after transformations
  187748. * are set, but before any reading takes place. This allows
  187749. * the user to obtain a gamma-corrected palette, for example.
  187750. * If the user doesn't call this, we will do it ourselves.
  187751. */
  187752. void PNGAPI
  187753. png_start_read_image(png_structp png_ptr)
  187754. {
  187755. png_debug(1, "in png_start_read_image\n");
  187756. if(png_ptr == NULL) return;
  187757. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187758. png_read_start_row(png_ptr);
  187759. }
  187760. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187761. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187762. void PNGAPI
  187763. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187764. {
  187765. #ifdef PNG_USE_LOCAL_ARRAYS
  187766. PNG_CONST PNG_IDAT;
  187767. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187768. 0xff};
  187769. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187770. #endif
  187771. int ret;
  187772. if(png_ptr == NULL) return;
  187773. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187774. png_ptr->row_number, png_ptr->pass);
  187775. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187776. png_read_start_row(png_ptr);
  187777. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187778. {
  187779. /* check for transforms that have been set but were defined out */
  187780. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187781. if (png_ptr->transformations & PNG_INVERT_MONO)
  187782. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187783. #endif
  187784. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187785. if (png_ptr->transformations & PNG_FILLER)
  187786. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187787. #endif
  187788. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187789. if (png_ptr->transformations & PNG_PACKSWAP)
  187790. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187791. #endif
  187792. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187793. if (png_ptr->transformations & PNG_PACK)
  187794. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187795. #endif
  187796. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187797. if (png_ptr->transformations & PNG_SHIFT)
  187798. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187799. #endif
  187800. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187801. if (png_ptr->transformations & PNG_BGR)
  187802. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187803. #endif
  187804. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187805. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187806. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187807. #endif
  187808. }
  187809. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187810. /* if interlaced and we do not need a new row, combine row and return */
  187811. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187812. {
  187813. switch (png_ptr->pass)
  187814. {
  187815. case 0:
  187816. if (png_ptr->row_number & 0x07)
  187817. {
  187818. if (dsp_row != NULL)
  187819. png_combine_row(png_ptr, dsp_row,
  187820. png_pass_dsp_mask[png_ptr->pass]);
  187821. png_read_finish_row(png_ptr);
  187822. return;
  187823. }
  187824. break;
  187825. case 1:
  187826. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187827. {
  187828. if (dsp_row != NULL)
  187829. png_combine_row(png_ptr, dsp_row,
  187830. png_pass_dsp_mask[png_ptr->pass]);
  187831. png_read_finish_row(png_ptr);
  187832. return;
  187833. }
  187834. break;
  187835. case 2:
  187836. if ((png_ptr->row_number & 0x07) != 4)
  187837. {
  187838. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187839. png_combine_row(png_ptr, dsp_row,
  187840. png_pass_dsp_mask[png_ptr->pass]);
  187841. png_read_finish_row(png_ptr);
  187842. return;
  187843. }
  187844. break;
  187845. case 3:
  187846. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187847. {
  187848. if (dsp_row != NULL)
  187849. png_combine_row(png_ptr, dsp_row,
  187850. png_pass_dsp_mask[png_ptr->pass]);
  187851. png_read_finish_row(png_ptr);
  187852. return;
  187853. }
  187854. break;
  187855. case 4:
  187856. if ((png_ptr->row_number & 3) != 2)
  187857. {
  187858. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187859. png_combine_row(png_ptr, dsp_row,
  187860. png_pass_dsp_mask[png_ptr->pass]);
  187861. png_read_finish_row(png_ptr);
  187862. return;
  187863. }
  187864. break;
  187865. case 5:
  187866. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187867. {
  187868. if (dsp_row != NULL)
  187869. png_combine_row(png_ptr, dsp_row,
  187870. png_pass_dsp_mask[png_ptr->pass]);
  187871. png_read_finish_row(png_ptr);
  187872. return;
  187873. }
  187874. break;
  187875. case 6:
  187876. if (!(png_ptr->row_number & 1))
  187877. {
  187878. png_read_finish_row(png_ptr);
  187879. return;
  187880. }
  187881. break;
  187882. }
  187883. }
  187884. #endif
  187885. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187886. png_error(png_ptr, "Invalid attempt to read row data");
  187887. png_ptr->zstream.next_out = png_ptr->row_buf;
  187888. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187889. do
  187890. {
  187891. if (!(png_ptr->zstream.avail_in))
  187892. {
  187893. while (!png_ptr->idat_size)
  187894. {
  187895. png_byte chunk_length[4];
  187896. png_crc_finish(png_ptr, 0);
  187897. png_read_data(png_ptr, chunk_length, 4);
  187898. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187899. png_reset_crc(png_ptr);
  187900. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187901. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187902. png_error(png_ptr, "Not enough image data");
  187903. }
  187904. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187905. png_ptr->zstream.next_in = png_ptr->zbuf;
  187906. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187907. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187908. png_crc_read(png_ptr, png_ptr->zbuf,
  187909. (png_size_t)png_ptr->zstream.avail_in);
  187910. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187911. }
  187912. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187913. if (ret == Z_STREAM_END)
  187914. {
  187915. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187916. png_ptr->idat_size)
  187917. png_error(png_ptr, "Extra compressed data");
  187918. png_ptr->mode |= PNG_AFTER_IDAT;
  187919. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187920. break;
  187921. }
  187922. if (ret != Z_OK)
  187923. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187924. "Decompression error");
  187925. } while (png_ptr->zstream.avail_out);
  187926. png_ptr->row_info.color_type = png_ptr->color_type;
  187927. png_ptr->row_info.width = png_ptr->iwidth;
  187928. png_ptr->row_info.channels = png_ptr->channels;
  187929. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187930. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187931. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187932. png_ptr->row_info.width);
  187933. if(png_ptr->row_buf[0])
  187934. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187935. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187936. (int)(png_ptr->row_buf[0]));
  187937. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187938. png_ptr->rowbytes + 1);
  187939. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187940. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187941. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187942. {
  187943. /* Intrapixel differencing */
  187944. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187945. }
  187946. #endif
  187947. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187948. png_do_read_transformations(png_ptr);
  187949. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187950. /* blow up interlaced rows to full size */
  187951. if (png_ptr->interlaced &&
  187952. (png_ptr->transformations & PNG_INTERLACE))
  187953. {
  187954. if (png_ptr->pass < 6)
  187955. /* old interface (pre-1.0.9):
  187956. png_do_read_interlace(&(png_ptr->row_info),
  187957. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187958. */
  187959. png_do_read_interlace(png_ptr);
  187960. if (dsp_row != NULL)
  187961. png_combine_row(png_ptr, dsp_row,
  187962. png_pass_dsp_mask[png_ptr->pass]);
  187963. if (row != NULL)
  187964. png_combine_row(png_ptr, row,
  187965. png_pass_mask[png_ptr->pass]);
  187966. }
  187967. else
  187968. #endif
  187969. {
  187970. if (row != NULL)
  187971. png_combine_row(png_ptr, row, 0xff);
  187972. if (dsp_row != NULL)
  187973. png_combine_row(png_ptr, dsp_row, 0xff);
  187974. }
  187975. png_read_finish_row(png_ptr);
  187976. if (png_ptr->read_row_fn != NULL)
  187977. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187978. }
  187979. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187980. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187981. /* Read one or more rows of image data. If the image is interlaced,
  187982. * and png_set_interlace_handling() has been called, the rows need to
  187983. * contain the contents of the rows from the previous pass. If the
  187984. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187985. * called, the rows contents must be initialized to the contents of the
  187986. * screen.
  187987. *
  187988. * "row" holds the actual image, and pixels are placed in it
  187989. * as they arrive. If the image is displayed after each pass, it will
  187990. * appear to "sparkle" in. "display_row" can be used to display a
  187991. * "chunky" progressive image, with finer detail added as it becomes
  187992. * available. If you do not want this "chunky" display, you may pass
  187993. * NULL for display_row. If you do not want the sparkle display, and
  187994. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187995. * If you have called png_handle_alpha(), and the image has either an
  187996. * alpha channel or a transparency chunk, you must provide a buffer for
  187997. * rows. In this case, you do not have to provide a display_row buffer
  187998. * also, but you may. If the image is not interlaced, or if you have
  187999. * not called png_set_interlace_handling(), the display_row buffer will
  188000. * be ignored, so pass NULL to it.
  188001. *
  188002. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188003. */
  188004. void PNGAPI
  188005. png_read_rows(png_structp png_ptr, png_bytepp row,
  188006. png_bytepp display_row, png_uint_32 num_rows)
  188007. {
  188008. png_uint_32 i;
  188009. png_bytepp rp;
  188010. png_bytepp dp;
  188011. png_debug(1, "in png_read_rows\n");
  188012. if(png_ptr == NULL) return;
  188013. rp = row;
  188014. dp = display_row;
  188015. if (rp != NULL && dp != NULL)
  188016. for (i = 0; i < num_rows; i++)
  188017. {
  188018. png_bytep rptr = *rp++;
  188019. png_bytep dptr = *dp++;
  188020. png_read_row(png_ptr, rptr, dptr);
  188021. }
  188022. else if(rp != NULL)
  188023. for (i = 0; i < num_rows; i++)
  188024. {
  188025. png_bytep rptr = *rp;
  188026. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188027. rp++;
  188028. }
  188029. else if(dp != NULL)
  188030. for (i = 0; i < num_rows; i++)
  188031. {
  188032. png_bytep dptr = *dp;
  188033. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188034. dp++;
  188035. }
  188036. }
  188037. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188038. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188039. /* Read the entire image. If the image has an alpha channel or a tRNS
  188040. * chunk, and you have called png_handle_alpha()[*], you will need to
  188041. * initialize the image to the current image that PNG will be overlaying.
  188042. * We set the num_rows again here, in case it was incorrectly set in
  188043. * png_read_start_row() by a call to png_read_update_info() or
  188044. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188045. * prior to either of these functions like it should have been. You can
  188046. * only call this function once. If you desire to have an image for
  188047. * each pass of a interlaced image, use png_read_rows() instead.
  188048. *
  188049. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188050. */
  188051. void PNGAPI
  188052. png_read_image(png_structp png_ptr, png_bytepp image)
  188053. {
  188054. png_uint_32 i,image_height;
  188055. int pass, j;
  188056. png_bytepp rp;
  188057. png_debug(1, "in png_read_image\n");
  188058. if(png_ptr == NULL) return;
  188059. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188060. pass = png_set_interlace_handling(png_ptr);
  188061. #else
  188062. if (png_ptr->interlaced)
  188063. png_error(png_ptr,
  188064. "Cannot read interlaced image -- interlace handler disabled.");
  188065. pass = 1;
  188066. #endif
  188067. image_height=png_ptr->height;
  188068. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188069. for (j = 0; j < pass; j++)
  188070. {
  188071. rp = image;
  188072. for (i = 0; i < image_height; i++)
  188073. {
  188074. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188075. rp++;
  188076. }
  188077. }
  188078. }
  188079. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188080. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188081. /* Read the end of the PNG file. Will not read past the end of the
  188082. * file, will verify the end is accurate, and will read any comments
  188083. * or time information at the end of the file, if info is not NULL.
  188084. */
  188085. void PNGAPI
  188086. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188087. {
  188088. png_byte chunk_length[4];
  188089. png_uint_32 length;
  188090. png_debug(1, "in png_read_end\n");
  188091. if(png_ptr == NULL) return;
  188092. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188093. do
  188094. {
  188095. #ifdef PNG_USE_LOCAL_ARRAYS
  188096. PNG_CONST PNG_IHDR;
  188097. PNG_CONST PNG_IDAT;
  188098. PNG_CONST PNG_IEND;
  188099. PNG_CONST PNG_PLTE;
  188100. #if defined(PNG_READ_bKGD_SUPPORTED)
  188101. PNG_CONST PNG_bKGD;
  188102. #endif
  188103. #if defined(PNG_READ_cHRM_SUPPORTED)
  188104. PNG_CONST PNG_cHRM;
  188105. #endif
  188106. #if defined(PNG_READ_gAMA_SUPPORTED)
  188107. PNG_CONST PNG_gAMA;
  188108. #endif
  188109. #if defined(PNG_READ_hIST_SUPPORTED)
  188110. PNG_CONST PNG_hIST;
  188111. #endif
  188112. #if defined(PNG_READ_iCCP_SUPPORTED)
  188113. PNG_CONST PNG_iCCP;
  188114. #endif
  188115. #if defined(PNG_READ_iTXt_SUPPORTED)
  188116. PNG_CONST PNG_iTXt;
  188117. #endif
  188118. #if defined(PNG_READ_oFFs_SUPPORTED)
  188119. PNG_CONST PNG_oFFs;
  188120. #endif
  188121. #if defined(PNG_READ_pCAL_SUPPORTED)
  188122. PNG_CONST PNG_pCAL;
  188123. #endif
  188124. #if defined(PNG_READ_pHYs_SUPPORTED)
  188125. PNG_CONST PNG_pHYs;
  188126. #endif
  188127. #if defined(PNG_READ_sBIT_SUPPORTED)
  188128. PNG_CONST PNG_sBIT;
  188129. #endif
  188130. #if defined(PNG_READ_sCAL_SUPPORTED)
  188131. PNG_CONST PNG_sCAL;
  188132. #endif
  188133. #if defined(PNG_READ_sPLT_SUPPORTED)
  188134. PNG_CONST PNG_sPLT;
  188135. #endif
  188136. #if defined(PNG_READ_sRGB_SUPPORTED)
  188137. PNG_CONST PNG_sRGB;
  188138. #endif
  188139. #if defined(PNG_READ_tEXt_SUPPORTED)
  188140. PNG_CONST PNG_tEXt;
  188141. #endif
  188142. #if defined(PNG_READ_tIME_SUPPORTED)
  188143. PNG_CONST PNG_tIME;
  188144. #endif
  188145. #if defined(PNG_READ_tRNS_SUPPORTED)
  188146. PNG_CONST PNG_tRNS;
  188147. #endif
  188148. #if defined(PNG_READ_zTXt_SUPPORTED)
  188149. PNG_CONST PNG_zTXt;
  188150. #endif
  188151. #endif /* PNG_USE_LOCAL_ARRAYS */
  188152. png_read_data(png_ptr, chunk_length, 4);
  188153. length = png_get_uint_31(png_ptr,chunk_length);
  188154. png_reset_crc(png_ptr);
  188155. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188156. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188157. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188158. png_handle_IHDR(png_ptr, info_ptr, length);
  188159. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188160. png_handle_IEND(png_ptr, info_ptr, length);
  188161. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188162. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188163. {
  188164. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188165. {
  188166. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188167. png_error(png_ptr, "Too many IDAT's found");
  188168. }
  188169. png_handle_unknown(png_ptr, info_ptr, length);
  188170. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188171. png_ptr->mode |= PNG_HAVE_PLTE;
  188172. }
  188173. #endif
  188174. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188175. {
  188176. /* Zero length IDATs are legal after the last IDAT has been
  188177. * read, but not after other chunks have been read.
  188178. */
  188179. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188180. png_error(png_ptr, "Too many IDAT's found");
  188181. png_crc_finish(png_ptr, length);
  188182. }
  188183. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188184. png_handle_PLTE(png_ptr, info_ptr, length);
  188185. #if defined(PNG_READ_bKGD_SUPPORTED)
  188186. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188187. png_handle_bKGD(png_ptr, info_ptr, length);
  188188. #endif
  188189. #if defined(PNG_READ_cHRM_SUPPORTED)
  188190. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188191. png_handle_cHRM(png_ptr, info_ptr, length);
  188192. #endif
  188193. #if defined(PNG_READ_gAMA_SUPPORTED)
  188194. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188195. png_handle_gAMA(png_ptr, info_ptr, length);
  188196. #endif
  188197. #if defined(PNG_READ_hIST_SUPPORTED)
  188198. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188199. png_handle_hIST(png_ptr, info_ptr, length);
  188200. #endif
  188201. #if defined(PNG_READ_oFFs_SUPPORTED)
  188202. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188203. png_handle_oFFs(png_ptr, info_ptr, length);
  188204. #endif
  188205. #if defined(PNG_READ_pCAL_SUPPORTED)
  188206. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188207. png_handle_pCAL(png_ptr, info_ptr, length);
  188208. #endif
  188209. #if defined(PNG_READ_sCAL_SUPPORTED)
  188210. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188211. png_handle_sCAL(png_ptr, info_ptr, length);
  188212. #endif
  188213. #if defined(PNG_READ_pHYs_SUPPORTED)
  188214. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188215. png_handle_pHYs(png_ptr, info_ptr, length);
  188216. #endif
  188217. #if defined(PNG_READ_sBIT_SUPPORTED)
  188218. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188219. png_handle_sBIT(png_ptr, info_ptr, length);
  188220. #endif
  188221. #if defined(PNG_READ_sRGB_SUPPORTED)
  188222. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188223. png_handle_sRGB(png_ptr, info_ptr, length);
  188224. #endif
  188225. #if defined(PNG_READ_iCCP_SUPPORTED)
  188226. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188227. png_handle_iCCP(png_ptr, info_ptr, length);
  188228. #endif
  188229. #if defined(PNG_READ_sPLT_SUPPORTED)
  188230. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188231. png_handle_sPLT(png_ptr, info_ptr, length);
  188232. #endif
  188233. #if defined(PNG_READ_tEXt_SUPPORTED)
  188234. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188235. png_handle_tEXt(png_ptr, info_ptr, length);
  188236. #endif
  188237. #if defined(PNG_READ_tIME_SUPPORTED)
  188238. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188239. png_handle_tIME(png_ptr, info_ptr, length);
  188240. #endif
  188241. #if defined(PNG_READ_tRNS_SUPPORTED)
  188242. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188243. png_handle_tRNS(png_ptr, info_ptr, length);
  188244. #endif
  188245. #if defined(PNG_READ_zTXt_SUPPORTED)
  188246. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188247. png_handle_zTXt(png_ptr, info_ptr, length);
  188248. #endif
  188249. #if defined(PNG_READ_iTXt_SUPPORTED)
  188250. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188251. png_handle_iTXt(png_ptr, info_ptr, length);
  188252. #endif
  188253. else
  188254. png_handle_unknown(png_ptr, info_ptr, length);
  188255. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188256. }
  188257. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188258. /* free all memory used by the read */
  188259. void PNGAPI
  188260. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188261. png_infopp end_info_ptr_ptr)
  188262. {
  188263. png_structp png_ptr = NULL;
  188264. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188265. #ifdef PNG_USER_MEM_SUPPORTED
  188266. png_free_ptr free_fn;
  188267. png_voidp mem_ptr;
  188268. #endif
  188269. png_debug(1, "in png_destroy_read_struct\n");
  188270. if (png_ptr_ptr != NULL)
  188271. png_ptr = *png_ptr_ptr;
  188272. if (info_ptr_ptr != NULL)
  188273. info_ptr = *info_ptr_ptr;
  188274. if (end_info_ptr_ptr != NULL)
  188275. end_info_ptr = *end_info_ptr_ptr;
  188276. #ifdef PNG_USER_MEM_SUPPORTED
  188277. free_fn = png_ptr->free_fn;
  188278. mem_ptr = png_ptr->mem_ptr;
  188279. #endif
  188280. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188281. if (info_ptr != NULL)
  188282. {
  188283. #if defined(PNG_TEXT_SUPPORTED)
  188284. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188285. #endif
  188286. #ifdef PNG_USER_MEM_SUPPORTED
  188287. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188288. (png_voidp)mem_ptr);
  188289. #else
  188290. png_destroy_struct((png_voidp)info_ptr);
  188291. #endif
  188292. *info_ptr_ptr = NULL;
  188293. }
  188294. if (end_info_ptr != NULL)
  188295. {
  188296. #if defined(PNG_READ_TEXT_SUPPORTED)
  188297. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188298. #endif
  188299. #ifdef PNG_USER_MEM_SUPPORTED
  188300. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188301. (png_voidp)mem_ptr);
  188302. #else
  188303. png_destroy_struct((png_voidp)end_info_ptr);
  188304. #endif
  188305. *end_info_ptr_ptr = NULL;
  188306. }
  188307. if (png_ptr != NULL)
  188308. {
  188309. #ifdef PNG_USER_MEM_SUPPORTED
  188310. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188311. (png_voidp)mem_ptr);
  188312. #else
  188313. png_destroy_struct((png_voidp)png_ptr);
  188314. #endif
  188315. *png_ptr_ptr = NULL;
  188316. }
  188317. }
  188318. /* free all memory used by the read (old method) */
  188319. void /* PRIVATE */
  188320. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188321. {
  188322. #ifdef PNG_SETJMP_SUPPORTED
  188323. jmp_buf tmp_jmp;
  188324. #endif
  188325. png_error_ptr error_fn;
  188326. png_error_ptr warning_fn;
  188327. png_voidp error_ptr;
  188328. #ifdef PNG_USER_MEM_SUPPORTED
  188329. png_free_ptr free_fn;
  188330. #endif
  188331. png_debug(1, "in png_read_destroy\n");
  188332. if (info_ptr != NULL)
  188333. png_info_destroy(png_ptr, info_ptr);
  188334. if (end_info_ptr != NULL)
  188335. png_info_destroy(png_ptr, end_info_ptr);
  188336. png_free(png_ptr, png_ptr->zbuf);
  188337. png_free(png_ptr, png_ptr->big_row_buf);
  188338. png_free(png_ptr, png_ptr->prev_row);
  188339. #if defined(PNG_READ_DITHER_SUPPORTED)
  188340. png_free(png_ptr, png_ptr->palette_lookup);
  188341. png_free(png_ptr, png_ptr->dither_index);
  188342. #endif
  188343. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188344. png_free(png_ptr, png_ptr->gamma_table);
  188345. #endif
  188346. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188347. png_free(png_ptr, png_ptr->gamma_from_1);
  188348. png_free(png_ptr, png_ptr->gamma_to_1);
  188349. #endif
  188350. #ifdef PNG_FREE_ME_SUPPORTED
  188351. if (png_ptr->free_me & PNG_FREE_PLTE)
  188352. png_zfree(png_ptr, png_ptr->palette);
  188353. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188354. #else
  188355. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188356. png_zfree(png_ptr, png_ptr->palette);
  188357. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188358. #endif
  188359. #if defined(PNG_tRNS_SUPPORTED) || \
  188360. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188361. #ifdef PNG_FREE_ME_SUPPORTED
  188362. if (png_ptr->free_me & PNG_FREE_TRNS)
  188363. png_free(png_ptr, png_ptr->trans);
  188364. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188365. #else
  188366. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188367. png_free(png_ptr, png_ptr->trans);
  188368. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188369. #endif
  188370. #endif
  188371. #if defined(PNG_READ_hIST_SUPPORTED)
  188372. #ifdef PNG_FREE_ME_SUPPORTED
  188373. if (png_ptr->free_me & PNG_FREE_HIST)
  188374. png_free(png_ptr, png_ptr->hist);
  188375. png_ptr->free_me &= ~PNG_FREE_HIST;
  188376. #else
  188377. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188378. png_free(png_ptr, png_ptr->hist);
  188379. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188380. #endif
  188381. #endif
  188382. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188383. if (png_ptr->gamma_16_table != NULL)
  188384. {
  188385. int i;
  188386. int istop = (1 << (8 - png_ptr->gamma_shift));
  188387. for (i = 0; i < istop; i++)
  188388. {
  188389. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188390. }
  188391. png_free(png_ptr, png_ptr->gamma_16_table);
  188392. }
  188393. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188394. if (png_ptr->gamma_16_from_1 != NULL)
  188395. {
  188396. int i;
  188397. int istop = (1 << (8 - png_ptr->gamma_shift));
  188398. for (i = 0; i < istop; i++)
  188399. {
  188400. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188401. }
  188402. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188403. }
  188404. if (png_ptr->gamma_16_to_1 != NULL)
  188405. {
  188406. int i;
  188407. int istop = (1 << (8 - png_ptr->gamma_shift));
  188408. for (i = 0; i < istop; i++)
  188409. {
  188410. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188411. }
  188412. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188413. }
  188414. #endif
  188415. #endif
  188416. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188417. png_free(png_ptr, png_ptr->time_buffer);
  188418. #endif
  188419. inflateEnd(&png_ptr->zstream);
  188420. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188421. png_free(png_ptr, png_ptr->save_buffer);
  188422. #endif
  188423. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188424. #ifdef PNG_TEXT_SUPPORTED
  188425. png_free(png_ptr, png_ptr->current_text);
  188426. #endif /* PNG_TEXT_SUPPORTED */
  188427. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188428. /* Save the important info out of the png_struct, in case it is
  188429. * being used again.
  188430. */
  188431. #ifdef PNG_SETJMP_SUPPORTED
  188432. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188433. #endif
  188434. error_fn = png_ptr->error_fn;
  188435. warning_fn = png_ptr->warning_fn;
  188436. error_ptr = png_ptr->error_ptr;
  188437. #ifdef PNG_USER_MEM_SUPPORTED
  188438. free_fn = png_ptr->free_fn;
  188439. #endif
  188440. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188441. png_ptr->error_fn = error_fn;
  188442. png_ptr->warning_fn = warning_fn;
  188443. png_ptr->error_ptr = error_ptr;
  188444. #ifdef PNG_USER_MEM_SUPPORTED
  188445. png_ptr->free_fn = free_fn;
  188446. #endif
  188447. #ifdef PNG_SETJMP_SUPPORTED
  188448. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188449. #endif
  188450. }
  188451. void PNGAPI
  188452. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188453. {
  188454. if(png_ptr == NULL) return;
  188455. png_ptr->read_row_fn = read_row_fn;
  188456. }
  188457. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188458. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188459. void PNGAPI
  188460. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188461. int transforms,
  188462. voidp params)
  188463. {
  188464. int row;
  188465. if(png_ptr == NULL) return;
  188466. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188467. /* invert the alpha channel from opacity to transparency
  188468. */
  188469. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188470. png_set_invert_alpha(png_ptr);
  188471. #endif
  188472. /* png_read_info() gives us all of the information from the
  188473. * PNG file before the first IDAT (image data chunk).
  188474. */
  188475. png_read_info(png_ptr, info_ptr);
  188476. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188477. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188478. /* -------------- image transformations start here ------------------- */
  188479. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188480. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188481. */
  188482. if (transforms & PNG_TRANSFORM_STRIP_16)
  188483. png_set_strip_16(png_ptr);
  188484. #endif
  188485. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188486. /* Strip alpha bytes from the input data without combining with
  188487. * the background (not recommended).
  188488. */
  188489. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188490. png_set_strip_alpha(png_ptr);
  188491. #endif
  188492. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188493. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188494. * byte into separate bytes (useful for paletted and grayscale images).
  188495. */
  188496. if (transforms & PNG_TRANSFORM_PACKING)
  188497. png_set_packing(png_ptr);
  188498. #endif
  188499. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188500. /* Change the order of packed pixels to least significant bit first
  188501. * (not useful if you are using png_set_packing).
  188502. */
  188503. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188504. png_set_packswap(png_ptr);
  188505. #endif
  188506. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188507. /* Expand paletted colors into true RGB triplets
  188508. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188509. * Expand paletted or RGB images with transparency to full alpha
  188510. * channels so the data will be available as RGBA quartets.
  188511. */
  188512. if (transforms & PNG_TRANSFORM_EXPAND)
  188513. if ((png_ptr->bit_depth < 8) ||
  188514. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188515. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188516. png_set_expand(png_ptr);
  188517. #endif
  188518. /* We don't handle background color or gamma transformation or dithering.
  188519. */
  188520. #if defined(PNG_READ_INVERT_SUPPORTED)
  188521. /* invert monochrome files to have 0 as white and 1 as black
  188522. */
  188523. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188524. png_set_invert_mono(png_ptr);
  188525. #endif
  188526. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188527. /* If you want to shift the pixel values from the range [0,255] or
  188528. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188529. * colors were originally in:
  188530. */
  188531. if ((transforms & PNG_TRANSFORM_SHIFT)
  188532. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188533. {
  188534. png_color_8p sig_bit;
  188535. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188536. png_set_shift(png_ptr, sig_bit);
  188537. }
  188538. #endif
  188539. #if defined(PNG_READ_BGR_SUPPORTED)
  188540. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188541. */
  188542. if (transforms & PNG_TRANSFORM_BGR)
  188543. png_set_bgr(png_ptr);
  188544. #endif
  188545. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188546. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188547. */
  188548. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188549. png_set_swap_alpha(png_ptr);
  188550. #endif
  188551. #if defined(PNG_READ_SWAP_SUPPORTED)
  188552. /* swap bytes of 16 bit files to least significant byte first
  188553. */
  188554. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188555. png_set_swap(png_ptr);
  188556. #endif
  188557. /* We don't handle adding filler bytes */
  188558. /* Optional call to gamma correct and add the background to the palette
  188559. * and update info structure. REQUIRED if you are expecting libpng to
  188560. * update the palette for you (i.e., you selected such a transform above).
  188561. */
  188562. png_read_update_info(png_ptr, info_ptr);
  188563. /* -------------- image transformations end here ------------------- */
  188564. #ifdef PNG_FREE_ME_SUPPORTED
  188565. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188566. #endif
  188567. if(info_ptr->row_pointers == NULL)
  188568. {
  188569. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188570. info_ptr->height * png_sizeof(png_bytep));
  188571. #ifdef PNG_FREE_ME_SUPPORTED
  188572. info_ptr->free_me |= PNG_FREE_ROWS;
  188573. #endif
  188574. for (row = 0; row < (int)info_ptr->height; row++)
  188575. {
  188576. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188577. png_get_rowbytes(png_ptr, info_ptr));
  188578. }
  188579. }
  188580. png_read_image(png_ptr, info_ptr->row_pointers);
  188581. info_ptr->valid |= PNG_INFO_IDAT;
  188582. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188583. png_read_end(png_ptr, info_ptr);
  188584. transforms = transforms; /* quiet compiler warnings */
  188585. params = params;
  188586. }
  188587. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188588. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188589. #endif /* PNG_READ_SUPPORTED */
  188590. /*** End of inlined file: pngread.c ***/
  188591. /*** Start of inlined file: pngpread.c ***/
  188592. /* pngpread.c - read a png file in push mode
  188593. *
  188594. * Last changed in libpng 1.2.21 October 4, 2007
  188595. * For conditions of distribution and use, see copyright notice in png.h
  188596. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188597. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188598. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188599. */
  188600. #define PNG_INTERNAL
  188601. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188602. /* push model modes */
  188603. #define PNG_READ_SIG_MODE 0
  188604. #define PNG_READ_CHUNK_MODE 1
  188605. #define PNG_READ_IDAT_MODE 2
  188606. #define PNG_SKIP_MODE 3
  188607. #define PNG_READ_tEXt_MODE 4
  188608. #define PNG_READ_zTXt_MODE 5
  188609. #define PNG_READ_DONE_MODE 6
  188610. #define PNG_READ_iTXt_MODE 7
  188611. #define PNG_ERROR_MODE 8
  188612. void PNGAPI
  188613. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188614. png_bytep buffer, png_size_t buffer_size)
  188615. {
  188616. if(png_ptr == NULL) return;
  188617. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188618. while (png_ptr->buffer_size)
  188619. {
  188620. png_process_some_data(png_ptr, info_ptr);
  188621. }
  188622. }
  188623. /* What we do with the incoming data depends on what we were previously
  188624. * doing before we ran out of data...
  188625. */
  188626. void /* PRIVATE */
  188627. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188628. {
  188629. if(png_ptr == NULL) return;
  188630. switch (png_ptr->process_mode)
  188631. {
  188632. case PNG_READ_SIG_MODE:
  188633. {
  188634. png_push_read_sig(png_ptr, info_ptr);
  188635. break;
  188636. }
  188637. case PNG_READ_CHUNK_MODE:
  188638. {
  188639. png_push_read_chunk(png_ptr, info_ptr);
  188640. break;
  188641. }
  188642. case PNG_READ_IDAT_MODE:
  188643. {
  188644. png_push_read_IDAT(png_ptr);
  188645. break;
  188646. }
  188647. #if defined(PNG_READ_tEXt_SUPPORTED)
  188648. case PNG_READ_tEXt_MODE:
  188649. {
  188650. png_push_read_tEXt(png_ptr, info_ptr);
  188651. break;
  188652. }
  188653. #endif
  188654. #if defined(PNG_READ_zTXt_SUPPORTED)
  188655. case PNG_READ_zTXt_MODE:
  188656. {
  188657. png_push_read_zTXt(png_ptr, info_ptr);
  188658. break;
  188659. }
  188660. #endif
  188661. #if defined(PNG_READ_iTXt_SUPPORTED)
  188662. case PNG_READ_iTXt_MODE:
  188663. {
  188664. png_push_read_iTXt(png_ptr, info_ptr);
  188665. break;
  188666. }
  188667. #endif
  188668. case PNG_SKIP_MODE:
  188669. {
  188670. png_push_crc_finish(png_ptr);
  188671. break;
  188672. }
  188673. default:
  188674. {
  188675. png_ptr->buffer_size = 0;
  188676. break;
  188677. }
  188678. }
  188679. }
  188680. /* Read any remaining signature bytes from the stream and compare them with
  188681. * the correct PNG signature. It is possible that this routine is called
  188682. * with bytes already read from the signature, either because they have been
  188683. * checked by the calling application, or because of multiple calls to this
  188684. * routine.
  188685. */
  188686. void /* PRIVATE */
  188687. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188688. {
  188689. png_size_t num_checked = png_ptr->sig_bytes,
  188690. num_to_check = 8 - num_checked;
  188691. if (png_ptr->buffer_size < num_to_check)
  188692. {
  188693. num_to_check = png_ptr->buffer_size;
  188694. }
  188695. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188696. num_to_check);
  188697. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188698. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188699. {
  188700. if (num_checked < 4 &&
  188701. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188702. png_error(png_ptr, "Not a PNG file");
  188703. else
  188704. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188705. }
  188706. else
  188707. {
  188708. if (png_ptr->sig_bytes >= 8)
  188709. {
  188710. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188711. }
  188712. }
  188713. }
  188714. void /* PRIVATE */
  188715. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188716. {
  188717. #ifdef PNG_USE_LOCAL_ARRAYS
  188718. PNG_CONST PNG_IHDR;
  188719. PNG_CONST PNG_IDAT;
  188720. PNG_CONST PNG_IEND;
  188721. PNG_CONST PNG_PLTE;
  188722. #if defined(PNG_READ_bKGD_SUPPORTED)
  188723. PNG_CONST PNG_bKGD;
  188724. #endif
  188725. #if defined(PNG_READ_cHRM_SUPPORTED)
  188726. PNG_CONST PNG_cHRM;
  188727. #endif
  188728. #if defined(PNG_READ_gAMA_SUPPORTED)
  188729. PNG_CONST PNG_gAMA;
  188730. #endif
  188731. #if defined(PNG_READ_hIST_SUPPORTED)
  188732. PNG_CONST PNG_hIST;
  188733. #endif
  188734. #if defined(PNG_READ_iCCP_SUPPORTED)
  188735. PNG_CONST PNG_iCCP;
  188736. #endif
  188737. #if defined(PNG_READ_iTXt_SUPPORTED)
  188738. PNG_CONST PNG_iTXt;
  188739. #endif
  188740. #if defined(PNG_READ_oFFs_SUPPORTED)
  188741. PNG_CONST PNG_oFFs;
  188742. #endif
  188743. #if defined(PNG_READ_pCAL_SUPPORTED)
  188744. PNG_CONST PNG_pCAL;
  188745. #endif
  188746. #if defined(PNG_READ_pHYs_SUPPORTED)
  188747. PNG_CONST PNG_pHYs;
  188748. #endif
  188749. #if defined(PNG_READ_sBIT_SUPPORTED)
  188750. PNG_CONST PNG_sBIT;
  188751. #endif
  188752. #if defined(PNG_READ_sCAL_SUPPORTED)
  188753. PNG_CONST PNG_sCAL;
  188754. #endif
  188755. #if defined(PNG_READ_sRGB_SUPPORTED)
  188756. PNG_CONST PNG_sRGB;
  188757. #endif
  188758. #if defined(PNG_READ_sPLT_SUPPORTED)
  188759. PNG_CONST PNG_sPLT;
  188760. #endif
  188761. #if defined(PNG_READ_tEXt_SUPPORTED)
  188762. PNG_CONST PNG_tEXt;
  188763. #endif
  188764. #if defined(PNG_READ_tIME_SUPPORTED)
  188765. PNG_CONST PNG_tIME;
  188766. #endif
  188767. #if defined(PNG_READ_tRNS_SUPPORTED)
  188768. PNG_CONST PNG_tRNS;
  188769. #endif
  188770. #if defined(PNG_READ_zTXt_SUPPORTED)
  188771. PNG_CONST PNG_zTXt;
  188772. #endif
  188773. #endif /* PNG_USE_LOCAL_ARRAYS */
  188774. /* First we make sure we have enough data for the 4 byte chunk name
  188775. * and the 4 byte chunk length before proceeding with decoding the
  188776. * chunk data. To fully decode each of these chunks, we also make
  188777. * sure we have enough data in the buffer for the 4 byte CRC at the
  188778. * end of every chunk (except IDAT, which is handled separately).
  188779. */
  188780. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188781. {
  188782. png_byte chunk_length[4];
  188783. if (png_ptr->buffer_size < 8)
  188784. {
  188785. png_push_save_buffer(png_ptr);
  188786. return;
  188787. }
  188788. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188789. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188790. png_reset_crc(png_ptr);
  188791. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188792. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188793. }
  188794. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188795. if(png_ptr->mode & PNG_AFTER_IDAT)
  188796. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188797. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188798. {
  188799. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188800. {
  188801. png_push_save_buffer(png_ptr);
  188802. return;
  188803. }
  188804. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188805. }
  188806. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188807. {
  188808. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188809. {
  188810. png_push_save_buffer(png_ptr);
  188811. return;
  188812. }
  188813. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188814. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188815. png_push_have_end(png_ptr, info_ptr);
  188816. }
  188817. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188818. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188819. {
  188820. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188821. {
  188822. png_push_save_buffer(png_ptr);
  188823. return;
  188824. }
  188825. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188826. png_ptr->mode |= PNG_HAVE_IDAT;
  188827. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188828. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188829. png_ptr->mode |= PNG_HAVE_PLTE;
  188830. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188831. {
  188832. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188833. png_error(png_ptr, "Missing IHDR before IDAT");
  188834. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188835. !(png_ptr->mode & PNG_HAVE_PLTE))
  188836. png_error(png_ptr, "Missing PLTE before IDAT");
  188837. }
  188838. }
  188839. #endif
  188840. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188841. {
  188842. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188843. {
  188844. png_push_save_buffer(png_ptr);
  188845. return;
  188846. }
  188847. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188848. }
  188849. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188850. {
  188851. /* If we reach an IDAT chunk, this means we have read all of the
  188852. * header chunks, and we can start reading the image (or if this
  188853. * is called after the image has been read - we have an error).
  188854. */
  188855. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188856. png_error(png_ptr, "Missing IHDR before IDAT");
  188857. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188858. !(png_ptr->mode & PNG_HAVE_PLTE))
  188859. png_error(png_ptr, "Missing PLTE before IDAT");
  188860. if (png_ptr->mode & PNG_HAVE_IDAT)
  188861. {
  188862. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188863. if (png_ptr->push_length == 0)
  188864. return;
  188865. if (png_ptr->mode & PNG_AFTER_IDAT)
  188866. png_error(png_ptr, "Too many IDAT's found");
  188867. }
  188868. png_ptr->idat_size = png_ptr->push_length;
  188869. png_ptr->mode |= PNG_HAVE_IDAT;
  188870. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188871. png_push_have_info(png_ptr, info_ptr);
  188872. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188873. png_ptr->zstream.next_out = png_ptr->row_buf;
  188874. return;
  188875. }
  188876. #if defined(PNG_READ_gAMA_SUPPORTED)
  188877. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188878. {
  188879. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188880. {
  188881. png_push_save_buffer(png_ptr);
  188882. return;
  188883. }
  188884. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188885. }
  188886. #endif
  188887. #if defined(PNG_READ_sBIT_SUPPORTED)
  188888. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188889. {
  188890. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188891. {
  188892. png_push_save_buffer(png_ptr);
  188893. return;
  188894. }
  188895. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188896. }
  188897. #endif
  188898. #if defined(PNG_READ_cHRM_SUPPORTED)
  188899. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188900. {
  188901. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188902. {
  188903. png_push_save_buffer(png_ptr);
  188904. return;
  188905. }
  188906. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188907. }
  188908. #endif
  188909. #if defined(PNG_READ_sRGB_SUPPORTED)
  188910. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188911. {
  188912. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188913. {
  188914. png_push_save_buffer(png_ptr);
  188915. return;
  188916. }
  188917. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188918. }
  188919. #endif
  188920. #if defined(PNG_READ_iCCP_SUPPORTED)
  188921. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188922. {
  188923. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188924. {
  188925. png_push_save_buffer(png_ptr);
  188926. return;
  188927. }
  188928. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188929. }
  188930. #endif
  188931. #if defined(PNG_READ_sPLT_SUPPORTED)
  188932. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188933. {
  188934. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188935. {
  188936. png_push_save_buffer(png_ptr);
  188937. return;
  188938. }
  188939. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188940. }
  188941. #endif
  188942. #if defined(PNG_READ_tRNS_SUPPORTED)
  188943. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188944. {
  188945. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188946. {
  188947. png_push_save_buffer(png_ptr);
  188948. return;
  188949. }
  188950. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188951. }
  188952. #endif
  188953. #if defined(PNG_READ_bKGD_SUPPORTED)
  188954. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188955. {
  188956. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188957. {
  188958. png_push_save_buffer(png_ptr);
  188959. return;
  188960. }
  188961. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188962. }
  188963. #endif
  188964. #if defined(PNG_READ_hIST_SUPPORTED)
  188965. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188966. {
  188967. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188968. {
  188969. png_push_save_buffer(png_ptr);
  188970. return;
  188971. }
  188972. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188973. }
  188974. #endif
  188975. #if defined(PNG_READ_pHYs_SUPPORTED)
  188976. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188977. {
  188978. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188979. {
  188980. png_push_save_buffer(png_ptr);
  188981. return;
  188982. }
  188983. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188984. }
  188985. #endif
  188986. #if defined(PNG_READ_oFFs_SUPPORTED)
  188987. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188988. {
  188989. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188990. {
  188991. png_push_save_buffer(png_ptr);
  188992. return;
  188993. }
  188994. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188995. }
  188996. #endif
  188997. #if defined(PNG_READ_pCAL_SUPPORTED)
  188998. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188999. {
  189000. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189001. {
  189002. png_push_save_buffer(png_ptr);
  189003. return;
  189004. }
  189005. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189006. }
  189007. #endif
  189008. #if defined(PNG_READ_sCAL_SUPPORTED)
  189009. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189010. {
  189011. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189012. {
  189013. png_push_save_buffer(png_ptr);
  189014. return;
  189015. }
  189016. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189017. }
  189018. #endif
  189019. #if defined(PNG_READ_tIME_SUPPORTED)
  189020. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189021. {
  189022. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189023. {
  189024. png_push_save_buffer(png_ptr);
  189025. return;
  189026. }
  189027. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189028. }
  189029. #endif
  189030. #if defined(PNG_READ_tEXt_SUPPORTED)
  189031. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189032. {
  189033. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189034. {
  189035. png_push_save_buffer(png_ptr);
  189036. return;
  189037. }
  189038. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189039. }
  189040. #endif
  189041. #if defined(PNG_READ_zTXt_SUPPORTED)
  189042. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189043. {
  189044. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189045. {
  189046. png_push_save_buffer(png_ptr);
  189047. return;
  189048. }
  189049. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189050. }
  189051. #endif
  189052. #if defined(PNG_READ_iTXt_SUPPORTED)
  189053. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189054. {
  189055. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189056. {
  189057. png_push_save_buffer(png_ptr);
  189058. return;
  189059. }
  189060. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189061. }
  189062. #endif
  189063. else
  189064. {
  189065. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189066. {
  189067. png_push_save_buffer(png_ptr);
  189068. return;
  189069. }
  189070. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189071. }
  189072. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189073. }
  189074. void /* PRIVATE */
  189075. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189076. {
  189077. png_ptr->process_mode = PNG_SKIP_MODE;
  189078. png_ptr->skip_length = skip;
  189079. }
  189080. void /* PRIVATE */
  189081. png_push_crc_finish(png_structp png_ptr)
  189082. {
  189083. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189084. {
  189085. png_size_t save_size;
  189086. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189087. save_size = (png_size_t)png_ptr->skip_length;
  189088. else
  189089. save_size = png_ptr->save_buffer_size;
  189090. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189091. png_ptr->skip_length -= save_size;
  189092. png_ptr->buffer_size -= save_size;
  189093. png_ptr->save_buffer_size -= save_size;
  189094. png_ptr->save_buffer_ptr += save_size;
  189095. }
  189096. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189097. {
  189098. png_size_t save_size;
  189099. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189100. save_size = (png_size_t)png_ptr->skip_length;
  189101. else
  189102. save_size = png_ptr->current_buffer_size;
  189103. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189104. png_ptr->skip_length -= save_size;
  189105. png_ptr->buffer_size -= save_size;
  189106. png_ptr->current_buffer_size -= save_size;
  189107. png_ptr->current_buffer_ptr += save_size;
  189108. }
  189109. if (!png_ptr->skip_length)
  189110. {
  189111. if (png_ptr->buffer_size < 4)
  189112. {
  189113. png_push_save_buffer(png_ptr);
  189114. return;
  189115. }
  189116. png_crc_finish(png_ptr, 0);
  189117. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189118. }
  189119. }
  189120. void PNGAPI
  189121. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189122. {
  189123. png_bytep ptr;
  189124. if(png_ptr == NULL) return;
  189125. ptr = buffer;
  189126. if (png_ptr->save_buffer_size)
  189127. {
  189128. png_size_t save_size;
  189129. if (length < png_ptr->save_buffer_size)
  189130. save_size = length;
  189131. else
  189132. save_size = png_ptr->save_buffer_size;
  189133. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189134. length -= save_size;
  189135. ptr += save_size;
  189136. png_ptr->buffer_size -= save_size;
  189137. png_ptr->save_buffer_size -= save_size;
  189138. png_ptr->save_buffer_ptr += save_size;
  189139. }
  189140. if (length && png_ptr->current_buffer_size)
  189141. {
  189142. png_size_t save_size;
  189143. if (length < png_ptr->current_buffer_size)
  189144. save_size = length;
  189145. else
  189146. save_size = png_ptr->current_buffer_size;
  189147. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189148. png_ptr->buffer_size -= save_size;
  189149. png_ptr->current_buffer_size -= save_size;
  189150. png_ptr->current_buffer_ptr += save_size;
  189151. }
  189152. }
  189153. void /* PRIVATE */
  189154. png_push_save_buffer(png_structp png_ptr)
  189155. {
  189156. if (png_ptr->save_buffer_size)
  189157. {
  189158. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189159. {
  189160. png_size_t i,istop;
  189161. png_bytep sp;
  189162. png_bytep dp;
  189163. istop = png_ptr->save_buffer_size;
  189164. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189165. i < istop; i++, sp++, dp++)
  189166. {
  189167. *dp = *sp;
  189168. }
  189169. }
  189170. }
  189171. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189172. png_ptr->save_buffer_max)
  189173. {
  189174. png_size_t new_max;
  189175. png_bytep old_buffer;
  189176. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189177. (png_ptr->current_buffer_size + 256))
  189178. {
  189179. png_error(png_ptr, "Potential overflow of save_buffer");
  189180. }
  189181. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189182. old_buffer = png_ptr->save_buffer;
  189183. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189184. (png_uint_32)new_max);
  189185. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189186. png_free(png_ptr, old_buffer);
  189187. png_ptr->save_buffer_max = new_max;
  189188. }
  189189. if (png_ptr->current_buffer_size)
  189190. {
  189191. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189192. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189193. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189194. png_ptr->current_buffer_size = 0;
  189195. }
  189196. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189197. png_ptr->buffer_size = 0;
  189198. }
  189199. void /* PRIVATE */
  189200. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189201. png_size_t buffer_length)
  189202. {
  189203. png_ptr->current_buffer = buffer;
  189204. png_ptr->current_buffer_size = buffer_length;
  189205. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189206. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189207. }
  189208. void /* PRIVATE */
  189209. png_push_read_IDAT(png_structp png_ptr)
  189210. {
  189211. #ifdef PNG_USE_LOCAL_ARRAYS
  189212. PNG_CONST PNG_IDAT;
  189213. #endif
  189214. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189215. {
  189216. png_byte chunk_length[4];
  189217. if (png_ptr->buffer_size < 8)
  189218. {
  189219. png_push_save_buffer(png_ptr);
  189220. return;
  189221. }
  189222. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189223. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189224. png_reset_crc(png_ptr);
  189225. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189226. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189227. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189228. {
  189229. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189230. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189231. png_error(png_ptr, "Not enough compressed data");
  189232. return;
  189233. }
  189234. png_ptr->idat_size = png_ptr->push_length;
  189235. }
  189236. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189237. {
  189238. png_size_t save_size;
  189239. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189240. {
  189241. save_size = (png_size_t)png_ptr->idat_size;
  189242. /* check for overflow */
  189243. if((png_uint_32)save_size != png_ptr->idat_size)
  189244. png_error(png_ptr, "save_size overflowed in pngpread");
  189245. }
  189246. else
  189247. save_size = png_ptr->save_buffer_size;
  189248. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189249. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189250. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189251. png_ptr->idat_size -= save_size;
  189252. png_ptr->buffer_size -= save_size;
  189253. png_ptr->save_buffer_size -= save_size;
  189254. png_ptr->save_buffer_ptr += save_size;
  189255. }
  189256. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189257. {
  189258. png_size_t save_size;
  189259. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189260. {
  189261. save_size = (png_size_t)png_ptr->idat_size;
  189262. /* check for overflow */
  189263. if((png_uint_32)save_size != png_ptr->idat_size)
  189264. png_error(png_ptr, "save_size overflowed in pngpread");
  189265. }
  189266. else
  189267. save_size = png_ptr->current_buffer_size;
  189268. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189269. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189270. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189271. png_ptr->idat_size -= save_size;
  189272. png_ptr->buffer_size -= save_size;
  189273. png_ptr->current_buffer_size -= save_size;
  189274. png_ptr->current_buffer_ptr += save_size;
  189275. }
  189276. if (!png_ptr->idat_size)
  189277. {
  189278. if (png_ptr->buffer_size < 4)
  189279. {
  189280. png_push_save_buffer(png_ptr);
  189281. return;
  189282. }
  189283. png_crc_finish(png_ptr, 0);
  189284. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189285. png_ptr->mode |= PNG_AFTER_IDAT;
  189286. }
  189287. }
  189288. void /* PRIVATE */
  189289. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189290. png_size_t buffer_length)
  189291. {
  189292. int ret;
  189293. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189294. png_error(png_ptr, "Extra compression data");
  189295. png_ptr->zstream.next_in = buffer;
  189296. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189297. for(;;)
  189298. {
  189299. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189300. if (ret != Z_OK)
  189301. {
  189302. if (ret == Z_STREAM_END)
  189303. {
  189304. if (png_ptr->zstream.avail_in)
  189305. png_error(png_ptr, "Extra compressed data");
  189306. if (!(png_ptr->zstream.avail_out))
  189307. {
  189308. png_push_process_row(png_ptr);
  189309. }
  189310. png_ptr->mode |= PNG_AFTER_IDAT;
  189311. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189312. break;
  189313. }
  189314. else if (ret == Z_BUF_ERROR)
  189315. break;
  189316. else
  189317. png_error(png_ptr, "Decompression Error");
  189318. }
  189319. if (!(png_ptr->zstream.avail_out))
  189320. {
  189321. if ((
  189322. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189323. png_ptr->interlaced && png_ptr->pass > 6) ||
  189324. (!png_ptr->interlaced &&
  189325. #endif
  189326. png_ptr->row_number == png_ptr->num_rows))
  189327. {
  189328. if (png_ptr->zstream.avail_in)
  189329. {
  189330. png_warning(png_ptr, "Too much data in IDAT chunks");
  189331. }
  189332. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189333. break;
  189334. }
  189335. png_push_process_row(png_ptr);
  189336. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189337. png_ptr->zstream.next_out = png_ptr->row_buf;
  189338. }
  189339. else
  189340. break;
  189341. }
  189342. }
  189343. void /* PRIVATE */
  189344. png_push_process_row(png_structp png_ptr)
  189345. {
  189346. png_ptr->row_info.color_type = png_ptr->color_type;
  189347. png_ptr->row_info.width = png_ptr->iwidth;
  189348. png_ptr->row_info.channels = png_ptr->channels;
  189349. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189350. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189351. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189352. png_ptr->row_info.width);
  189353. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189354. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189355. (int)(png_ptr->row_buf[0]));
  189356. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189357. png_ptr->rowbytes + 1);
  189358. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189359. png_do_read_transformations(png_ptr);
  189360. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189361. /* blow up interlaced rows to full size */
  189362. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189363. {
  189364. if (png_ptr->pass < 6)
  189365. /* old interface (pre-1.0.9):
  189366. png_do_read_interlace(&(png_ptr->row_info),
  189367. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189368. */
  189369. png_do_read_interlace(png_ptr);
  189370. switch (png_ptr->pass)
  189371. {
  189372. case 0:
  189373. {
  189374. int i;
  189375. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189376. {
  189377. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189378. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189379. }
  189380. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189381. {
  189382. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189383. {
  189384. png_push_have_row(png_ptr, png_bytep_NULL);
  189385. png_read_push_finish_row(png_ptr);
  189386. }
  189387. }
  189388. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189389. {
  189390. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189391. {
  189392. png_push_have_row(png_ptr, png_bytep_NULL);
  189393. png_read_push_finish_row(png_ptr);
  189394. }
  189395. }
  189396. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189397. {
  189398. png_push_have_row(png_ptr, png_bytep_NULL);
  189399. png_read_push_finish_row(png_ptr);
  189400. }
  189401. break;
  189402. }
  189403. case 1:
  189404. {
  189405. int i;
  189406. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189407. {
  189408. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189409. png_read_push_finish_row(png_ptr);
  189410. }
  189411. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189412. {
  189413. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189414. {
  189415. png_push_have_row(png_ptr, png_bytep_NULL);
  189416. png_read_push_finish_row(png_ptr);
  189417. }
  189418. }
  189419. break;
  189420. }
  189421. case 2:
  189422. {
  189423. int i;
  189424. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189425. {
  189426. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189427. png_read_push_finish_row(png_ptr);
  189428. }
  189429. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189430. {
  189431. png_push_have_row(png_ptr, png_bytep_NULL);
  189432. png_read_push_finish_row(png_ptr);
  189433. }
  189434. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189435. {
  189436. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189437. {
  189438. png_push_have_row(png_ptr, png_bytep_NULL);
  189439. png_read_push_finish_row(png_ptr);
  189440. }
  189441. }
  189442. break;
  189443. }
  189444. case 3:
  189445. {
  189446. int i;
  189447. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189448. {
  189449. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189450. png_read_push_finish_row(png_ptr);
  189451. }
  189452. if (png_ptr->pass == 4) /* skip top two generated rows */
  189453. {
  189454. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189455. {
  189456. png_push_have_row(png_ptr, png_bytep_NULL);
  189457. png_read_push_finish_row(png_ptr);
  189458. }
  189459. }
  189460. break;
  189461. }
  189462. case 4:
  189463. {
  189464. int i;
  189465. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189466. {
  189467. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189468. png_read_push_finish_row(png_ptr);
  189469. }
  189470. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189471. {
  189472. png_push_have_row(png_ptr, png_bytep_NULL);
  189473. png_read_push_finish_row(png_ptr);
  189474. }
  189475. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189476. {
  189477. png_push_have_row(png_ptr, png_bytep_NULL);
  189478. png_read_push_finish_row(png_ptr);
  189479. }
  189480. break;
  189481. }
  189482. case 5:
  189483. {
  189484. int i;
  189485. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189486. {
  189487. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189488. png_read_push_finish_row(png_ptr);
  189489. }
  189490. if (png_ptr->pass == 6) /* skip top generated row */
  189491. {
  189492. png_push_have_row(png_ptr, png_bytep_NULL);
  189493. png_read_push_finish_row(png_ptr);
  189494. }
  189495. break;
  189496. }
  189497. case 6:
  189498. {
  189499. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189500. png_read_push_finish_row(png_ptr);
  189501. if (png_ptr->pass != 6)
  189502. break;
  189503. png_push_have_row(png_ptr, png_bytep_NULL);
  189504. png_read_push_finish_row(png_ptr);
  189505. }
  189506. }
  189507. }
  189508. else
  189509. #endif
  189510. {
  189511. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189512. png_read_push_finish_row(png_ptr);
  189513. }
  189514. }
  189515. void /* PRIVATE */
  189516. png_read_push_finish_row(png_structp png_ptr)
  189517. {
  189518. #ifdef PNG_USE_LOCAL_ARRAYS
  189519. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189520. /* start of interlace block */
  189521. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189522. /* offset to next interlace block */
  189523. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189524. /* start of interlace block in the y direction */
  189525. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189526. /* offset to next interlace block in the y direction */
  189527. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189528. /* Height of interlace block. This is not currently used - if you need
  189529. * it, uncomment it here and in png.h
  189530. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189531. */
  189532. #endif
  189533. png_ptr->row_number++;
  189534. if (png_ptr->row_number < png_ptr->num_rows)
  189535. return;
  189536. if (png_ptr->interlaced)
  189537. {
  189538. png_ptr->row_number = 0;
  189539. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189540. png_ptr->rowbytes + 1);
  189541. do
  189542. {
  189543. png_ptr->pass++;
  189544. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189545. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189546. (png_ptr->pass == 5 && png_ptr->width < 2))
  189547. png_ptr->pass++;
  189548. if (png_ptr->pass > 7)
  189549. png_ptr->pass--;
  189550. if (png_ptr->pass >= 7)
  189551. break;
  189552. png_ptr->iwidth = (png_ptr->width +
  189553. png_pass_inc[png_ptr->pass] - 1 -
  189554. png_pass_start[png_ptr->pass]) /
  189555. png_pass_inc[png_ptr->pass];
  189556. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189557. png_ptr->iwidth) + 1;
  189558. if (png_ptr->transformations & PNG_INTERLACE)
  189559. break;
  189560. png_ptr->num_rows = (png_ptr->height +
  189561. png_pass_yinc[png_ptr->pass] - 1 -
  189562. png_pass_ystart[png_ptr->pass]) /
  189563. png_pass_yinc[png_ptr->pass];
  189564. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189565. }
  189566. }
  189567. #if defined(PNG_READ_tEXt_SUPPORTED)
  189568. void /* PRIVATE */
  189569. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189570. length)
  189571. {
  189572. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189573. {
  189574. png_error(png_ptr, "Out of place tEXt");
  189575. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189576. }
  189577. #ifdef PNG_MAX_MALLOC_64K
  189578. png_ptr->skip_length = 0; /* This may not be necessary */
  189579. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189580. {
  189581. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189582. png_ptr->skip_length = length - (png_uint_32)65535L;
  189583. length = (png_uint_32)65535L;
  189584. }
  189585. #endif
  189586. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189587. (png_uint_32)(length+1));
  189588. png_ptr->current_text[length] = '\0';
  189589. png_ptr->current_text_ptr = png_ptr->current_text;
  189590. png_ptr->current_text_size = (png_size_t)length;
  189591. png_ptr->current_text_left = (png_size_t)length;
  189592. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189593. }
  189594. void /* PRIVATE */
  189595. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189596. {
  189597. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189598. {
  189599. png_size_t text_size;
  189600. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189601. text_size = png_ptr->buffer_size;
  189602. else
  189603. text_size = png_ptr->current_text_left;
  189604. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189605. png_ptr->current_text_left -= text_size;
  189606. png_ptr->current_text_ptr += text_size;
  189607. }
  189608. if (!(png_ptr->current_text_left))
  189609. {
  189610. png_textp text_ptr;
  189611. png_charp text;
  189612. png_charp key;
  189613. int ret;
  189614. if (png_ptr->buffer_size < 4)
  189615. {
  189616. png_push_save_buffer(png_ptr);
  189617. return;
  189618. }
  189619. png_push_crc_finish(png_ptr);
  189620. #if defined(PNG_MAX_MALLOC_64K)
  189621. if (png_ptr->skip_length)
  189622. return;
  189623. #endif
  189624. key = png_ptr->current_text;
  189625. for (text = key; *text; text++)
  189626. /* empty loop */ ;
  189627. if (text < key + png_ptr->current_text_size)
  189628. text++;
  189629. text_ptr = (png_textp)png_malloc(png_ptr,
  189630. (png_uint_32)png_sizeof(png_text));
  189631. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189632. text_ptr->key = key;
  189633. #ifdef PNG_iTXt_SUPPORTED
  189634. text_ptr->lang = NULL;
  189635. text_ptr->lang_key = NULL;
  189636. #endif
  189637. text_ptr->text = text;
  189638. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189639. png_free(png_ptr, key);
  189640. png_free(png_ptr, text_ptr);
  189641. png_ptr->current_text = NULL;
  189642. if (ret)
  189643. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189644. }
  189645. }
  189646. #endif
  189647. #if defined(PNG_READ_zTXt_SUPPORTED)
  189648. void /* PRIVATE */
  189649. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189650. length)
  189651. {
  189652. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189653. {
  189654. png_error(png_ptr, "Out of place zTXt");
  189655. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189656. }
  189657. #ifdef PNG_MAX_MALLOC_64K
  189658. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189659. * to be able to store the uncompressed data. Actually, the threshold
  189660. * is probably around 32K, but it isn't as definite as 64K is.
  189661. */
  189662. if (length > (png_uint_32)65535L)
  189663. {
  189664. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189665. png_push_crc_skip(png_ptr, length);
  189666. return;
  189667. }
  189668. #endif
  189669. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189670. (png_uint_32)(length+1));
  189671. png_ptr->current_text[length] = '\0';
  189672. png_ptr->current_text_ptr = png_ptr->current_text;
  189673. png_ptr->current_text_size = (png_size_t)length;
  189674. png_ptr->current_text_left = (png_size_t)length;
  189675. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189676. }
  189677. void /* PRIVATE */
  189678. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189679. {
  189680. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189681. {
  189682. png_size_t text_size;
  189683. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189684. text_size = png_ptr->buffer_size;
  189685. else
  189686. text_size = png_ptr->current_text_left;
  189687. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189688. png_ptr->current_text_left -= text_size;
  189689. png_ptr->current_text_ptr += text_size;
  189690. }
  189691. if (!(png_ptr->current_text_left))
  189692. {
  189693. png_textp text_ptr;
  189694. png_charp text;
  189695. png_charp key;
  189696. int ret;
  189697. png_size_t text_size, key_size;
  189698. if (png_ptr->buffer_size < 4)
  189699. {
  189700. png_push_save_buffer(png_ptr);
  189701. return;
  189702. }
  189703. png_push_crc_finish(png_ptr);
  189704. key = png_ptr->current_text;
  189705. for (text = key; *text; text++)
  189706. /* empty loop */ ;
  189707. /* zTXt can't have zero text */
  189708. if (text >= key + png_ptr->current_text_size)
  189709. {
  189710. png_ptr->current_text = NULL;
  189711. png_free(png_ptr, key);
  189712. return;
  189713. }
  189714. text++;
  189715. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189716. {
  189717. png_ptr->current_text = NULL;
  189718. png_free(png_ptr, key);
  189719. return;
  189720. }
  189721. text++;
  189722. png_ptr->zstream.next_in = (png_bytep )text;
  189723. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189724. (text - key));
  189725. png_ptr->zstream.next_out = png_ptr->zbuf;
  189726. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189727. key_size = text - key;
  189728. text_size = 0;
  189729. text = NULL;
  189730. ret = Z_STREAM_END;
  189731. while (png_ptr->zstream.avail_in)
  189732. {
  189733. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189734. if (ret != Z_OK && ret != Z_STREAM_END)
  189735. {
  189736. inflateReset(&png_ptr->zstream);
  189737. png_ptr->zstream.avail_in = 0;
  189738. png_ptr->current_text = NULL;
  189739. png_free(png_ptr, key);
  189740. png_free(png_ptr, text);
  189741. return;
  189742. }
  189743. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189744. {
  189745. if (text == NULL)
  189746. {
  189747. text = (png_charp)png_malloc(png_ptr,
  189748. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189749. + key_size + 1));
  189750. png_memcpy(text + key_size, png_ptr->zbuf,
  189751. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189752. png_memcpy(text, key, key_size);
  189753. text_size = key_size + png_ptr->zbuf_size -
  189754. png_ptr->zstream.avail_out;
  189755. *(text + text_size) = '\0';
  189756. }
  189757. else
  189758. {
  189759. png_charp tmp;
  189760. tmp = text;
  189761. text = (png_charp)png_malloc(png_ptr, text_size +
  189762. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189763. + 1));
  189764. png_memcpy(text, tmp, text_size);
  189765. png_free(png_ptr, tmp);
  189766. png_memcpy(text + text_size, png_ptr->zbuf,
  189767. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189768. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189769. *(text + text_size) = '\0';
  189770. }
  189771. if (ret != Z_STREAM_END)
  189772. {
  189773. png_ptr->zstream.next_out = png_ptr->zbuf;
  189774. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189775. }
  189776. }
  189777. else
  189778. {
  189779. break;
  189780. }
  189781. if (ret == Z_STREAM_END)
  189782. break;
  189783. }
  189784. inflateReset(&png_ptr->zstream);
  189785. png_ptr->zstream.avail_in = 0;
  189786. if (ret != Z_STREAM_END)
  189787. {
  189788. png_ptr->current_text = NULL;
  189789. png_free(png_ptr, key);
  189790. png_free(png_ptr, text);
  189791. return;
  189792. }
  189793. png_ptr->current_text = NULL;
  189794. png_free(png_ptr, key);
  189795. key = text;
  189796. text += key_size;
  189797. text_ptr = (png_textp)png_malloc(png_ptr,
  189798. (png_uint_32)png_sizeof(png_text));
  189799. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189800. text_ptr->key = key;
  189801. #ifdef PNG_iTXt_SUPPORTED
  189802. text_ptr->lang = NULL;
  189803. text_ptr->lang_key = NULL;
  189804. #endif
  189805. text_ptr->text = text;
  189806. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189807. png_free(png_ptr, key);
  189808. png_free(png_ptr, text_ptr);
  189809. if (ret)
  189810. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189811. }
  189812. }
  189813. #endif
  189814. #if defined(PNG_READ_iTXt_SUPPORTED)
  189815. void /* PRIVATE */
  189816. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189817. length)
  189818. {
  189819. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189820. {
  189821. png_error(png_ptr, "Out of place iTXt");
  189822. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189823. }
  189824. #ifdef PNG_MAX_MALLOC_64K
  189825. png_ptr->skip_length = 0; /* This may not be necessary */
  189826. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189827. {
  189828. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189829. png_ptr->skip_length = length - (png_uint_32)65535L;
  189830. length = (png_uint_32)65535L;
  189831. }
  189832. #endif
  189833. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189834. (png_uint_32)(length+1));
  189835. png_ptr->current_text[length] = '\0';
  189836. png_ptr->current_text_ptr = png_ptr->current_text;
  189837. png_ptr->current_text_size = (png_size_t)length;
  189838. png_ptr->current_text_left = (png_size_t)length;
  189839. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189840. }
  189841. void /* PRIVATE */
  189842. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189843. {
  189844. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189845. {
  189846. png_size_t text_size;
  189847. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189848. text_size = png_ptr->buffer_size;
  189849. else
  189850. text_size = png_ptr->current_text_left;
  189851. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189852. png_ptr->current_text_left -= text_size;
  189853. png_ptr->current_text_ptr += text_size;
  189854. }
  189855. if (!(png_ptr->current_text_left))
  189856. {
  189857. png_textp text_ptr;
  189858. png_charp key;
  189859. int comp_flag;
  189860. png_charp lang;
  189861. png_charp lang_key;
  189862. png_charp text;
  189863. int ret;
  189864. if (png_ptr->buffer_size < 4)
  189865. {
  189866. png_push_save_buffer(png_ptr);
  189867. return;
  189868. }
  189869. png_push_crc_finish(png_ptr);
  189870. #if defined(PNG_MAX_MALLOC_64K)
  189871. if (png_ptr->skip_length)
  189872. return;
  189873. #endif
  189874. key = png_ptr->current_text;
  189875. for (lang = key; *lang; lang++)
  189876. /* empty loop */ ;
  189877. if (lang < key + png_ptr->current_text_size - 3)
  189878. lang++;
  189879. comp_flag = *lang++;
  189880. lang++; /* skip comp_type, always zero */
  189881. for (lang_key = lang; *lang_key; lang_key++)
  189882. /* empty loop */ ;
  189883. lang_key++; /* skip NUL separator */
  189884. text=lang_key;
  189885. if (lang_key < key + png_ptr->current_text_size - 1)
  189886. {
  189887. for (; *text; text++)
  189888. /* empty loop */ ;
  189889. }
  189890. if (text < key + png_ptr->current_text_size)
  189891. text++;
  189892. text_ptr = (png_textp)png_malloc(png_ptr,
  189893. (png_uint_32)png_sizeof(png_text));
  189894. text_ptr->compression = comp_flag + 2;
  189895. text_ptr->key = key;
  189896. text_ptr->lang = lang;
  189897. text_ptr->lang_key = lang_key;
  189898. text_ptr->text = text;
  189899. text_ptr->text_length = 0;
  189900. text_ptr->itxt_length = png_strlen(text);
  189901. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189902. png_ptr->current_text = NULL;
  189903. png_free(png_ptr, text_ptr);
  189904. if (ret)
  189905. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189906. }
  189907. }
  189908. #endif
  189909. /* This function is called when we haven't found a handler for this
  189910. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189911. * name or a critical chunk), the chunk is (currently) silently ignored.
  189912. */
  189913. void /* PRIVATE */
  189914. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189915. length)
  189916. {
  189917. png_uint_32 skip=0;
  189918. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189919. if (!(png_ptr->chunk_name[0] & 0x20))
  189920. {
  189921. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189922. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189923. PNG_HANDLE_CHUNK_ALWAYS
  189924. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189925. && png_ptr->read_user_chunk_fn == NULL
  189926. #endif
  189927. )
  189928. #endif
  189929. png_chunk_error(png_ptr, "unknown critical chunk");
  189930. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189931. }
  189932. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189933. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189934. {
  189935. #ifdef PNG_MAX_MALLOC_64K
  189936. if (length > (png_uint_32)65535L)
  189937. {
  189938. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189939. skip = length - (png_uint_32)65535L;
  189940. length = (png_uint_32)65535L;
  189941. }
  189942. #endif
  189943. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189944. (png_charp)png_ptr->chunk_name, 5);
  189945. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189946. png_ptr->unknown_chunk.size = (png_size_t)length;
  189947. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189948. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189949. if(png_ptr->read_user_chunk_fn != NULL)
  189950. {
  189951. /* callback to user unknown chunk handler */
  189952. int ret;
  189953. ret = (*(png_ptr->read_user_chunk_fn))
  189954. (png_ptr, &png_ptr->unknown_chunk);
  189955. if (ret < 0)
  189956. png_chunk_error(png_ptr, "error in user chunk");
  189957. if (ret == 0)
  189958. {
  189959. if (!(png_ptr->chunk_name[0] & 0x20))
  189960. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189961. PNG_HANDLE_CHUNK_ALWAYS)
  189962. png_chunk_error(png_ptr, "unknown critical chunk");
  189963. png_set_unknown_chunks(png_ptr, info_ptr,
  189964. &png_ptr->unknown_chunk, 1);
  189965. }
  189966. }
  189967. #else
  189968. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189969. #endif
  189970. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189971. png_ptr->unknown_chunk.data = NULL;
  189972. }
  189973. else
  189974. #endif
  189975. skip=length;
  189976. png_push_crc_skip(png_ptr, skip);
  189977. }
  189978. void /* PRIVATE */
  189979. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189980. {
  189981. if (png_ptr->info_fn != NULL)
  189982. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189983. }
  189984. void /* PRIVATE */
  189985. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189986. {
  189987. if (png_ptr->end_fn != NULL)
  189988. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189989. }
  189990. void /* PRIVATE */
  189991. png_push_have_row(png_structp png_ptr, png_bytep row)
  189992. {
  189993. if (png_ptr->row_fn != NULL)
  189994. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189995. (int)png_ptr->pass);
  189996. }
  189997. void PNGAPI
  189998. png_progressive_combine_row (png_structp png_ptr,
  189999. png_bytep old_row, png_bytep new_row)
  190000. {
  190001. #ifdef PNG_USE_LOCAL_ARRAYS
  190002. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190003. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190004. #endif
  190005. if(png_ptr == NULL) return;
  190006. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190007. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190008. }
  190009. void PNGAPI
  190010. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190011. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190012. png_progressive_end_ptr end_fn)
  190013. {
  190014. if(png_ptr == NULL) return;
  190015. png_ptr->info_fn = info_fn;
  190016. png_ptr->row_fn = row_fn;
  190017. png_ptr->end_fn = end_fn;
  190018. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190019. }
  190020. png_voidp PNGAPI
  190021. png_get_progressive_ptr(png_structp png_ptr)
  190022. {
  190023. if(png_ptr == NULL) return (NULL);
  190024. return png_ptr->io_ptr;
  190025. }
  190026. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190027. /*** End of inlined file: pngpread.c ***/
  190028. /*** Start of inlined file: pngrio.c ***/
  190029. /* pngrio.c - functions for data input
  190030. *
  190031. * Last changed in libpng 1.2.13 November 13, 2006
  190032. * For conditions of distribution and use, see copyright notice in png.h
  190033. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190034. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190035. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190036. *
  190037. * This file provides a location for all input. Users who need
  190038. * special handling are expected to write a function that has the same
  190039. * arguments as this and performs a similar function, but that possibly
  190040. * has a different input method. Note that you shouldn't change this
  190041. * function, but rather write a replacement function and then make
  190042. * libpng use it at run time with png_set_read_fn(...).
  190043. */
  190044. #define PNG_INTERNAL
  190045. #if defined(PNG_READ_SUPPORTED)
  190046. /* Read the data from whatever input you are using. The default routine
  190047. reads from a file pointer. Note that this routine sometimes gets called
  190048. with very small lengths, so you should implement some kind of simple
  190049. buffering if you are using unbuffered reads. This should never be asked
  190050. to read more then 64K on a 16 bit machine. */
  190051. void /* PRIVATE */
  190052. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190053. {
  190054. png_debug1(4,"reading %d bytes\n", (int)length);
  190055. if (png_ptr->read_data_fn != NULL)
  190056. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190057. else
  190058. png_error(png_ptr, "Call to NULL read function");
  190059. }
  190060. #if !defined(PNG_NO_STDIO)
  190061. /* This is the function that does the actual reading of data. If you are
  190062. not reading from a standard C stream, you should create a replacement
  190063. read_data function and use it at run time with png_set_read_fn(), rather
  190064. than changing the library. */
  190065. #ifndef USE_FAR_KEYWORD
  190066. void PNGAPI
  190067. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190068. {
  190069. png_size_t check;
  190070. if(png_ptr == NULL) return;
  190071. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190072. * instead of an int, which is what fread() actually returns.
  190073. */
  190074. #if defined(_WIN32_WCE)
  190075. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190076. check = 0;
  190077. #else
  190078. check = (png_size_t)fread(data, (png_size_t)1, length,
  190079. (png_FILE_p)png_ptr->io_ptr);
  190080. #endif
  190081. if (check != length)
  190082. png_error(png_ptr, "Read Error");
  190083. }
  190084. #else
  190085. /* this is the model-independent version. Since the standard I/O library
  190086. can't handle far buffers in the medium and small models, we have to copy
  190087. the data.
  190088. */
  190089. #define NEAR_BUF_SIZE 1024
  190090. #define MIN(a,b) (a <= b ? a : b)
  190091. static void PNGAPI
  190092. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190093. {
  190094. int check;
  190095. png_byte *n_data;
  190096. png_FILE_p io_ptr;
  190097. if(png_ptr == NULL) return;
  190098. /* Check if data really is near. If so, use usual code. */
  190099. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190100. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190101. if ((png_bytep)n_data == data)
  190102. {
  190103. #if defined(_WIN32_WCE)
  190104. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190105. check = 0;
  190106. #else
  190107. check = fread(n_data, 1, length, io_ptr);
  190108. #endif
  190109. }
  190110. else
  190111. {
  190112. png_byte buf[NEAR_BUF_SIZE];
  190113. png_size_t read, remaining, err;
  190114. check = 0;
  190115. remaining = length;
  190116. do
  190117. {
  190118. read = MIN(NEAR_BUF_SIZE, remaining);
  190119. #if defined(_WIN32_WCE)
  190120. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190121. err = 0;
  190122. #else
  190123. err = fread(buf, (png_size_t)1, read, io_ptr);
  190124. #endif
  190125. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190126. if(err != read)
  190127. break;
  190128. else
  190129. check += err;
  190130. data += read;
  190131. remaining -= read;
  190132. }
  190133. while (remaining != 0);
  190134. }
  190135. if ((png_uint_32)check != (png_uint_32)length)
  190136. png_error(png_ptr, "read Error");
  190137. }
  190138. #endif
  190139. #endif
  190140. /* This function allows the application to supply a new input function
  190141. for libpng if standard C streams aren't being used.
  190142. This function takes as its arguments:
  190143. png_ptr - pointer to a png input data structure
  190144. io_ptr - pointer to user supplied structure containing info about
  190145. the input functions. May be NULL.
  190146. read_data_fn - pointer to a new input function that takes as its
  190147. arguments a pointer to a png_struct, a pointer to
  190148. a location where input data can be stored, and a 32-bit
  190149. unsigned int that is the number of bytes to be read.
  190150. To exit and output any fatal error messages the new write
  190151. function should call png_error(png_ptr, "Error msg"). */
  190152. void PNGAPI
  190153. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190154. png_rw_ptr read_data_fn)
  190155. {
  190156. if(png_ptr == NULL) return;
  190157. png_ptr->io_ptr = io_ptr;
  190158. #if !defined(PNG_NO_STDIO)
  190159. if (read_data_fn != NULL)
  190160. png_ptr->read_data_fn = read_data_fn;
  190161. else
  190162. png_ptr->read_data_fn = png_default_read_data;
  190163. #else
  190164. png_ptr->read_data_fn = read_data_fn;
  190165. #endif
  190166. /* It is an error to write to a read device */
  190167. if (png_ptr->write_data_fn != NULL)
  190168. {
  190169. png_ptr->write_data_fn = NULL;
  190170. png_warning(png_ptr,
  190171. "It's an error to set both read_data_fn and write_data_fn in the ");
  190172. png_warning(png_ptr,
  190173. "same structure. Resetting write_data_fn to NULL.");
  190174. }
  190175. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190176. png_ptr->output_flush_fn = NULL;
  190177. #endif
  190178. }
  190179. #endif /* PNG_READ_SUPPORTED */
  190180. /*** End of inlined file: pngrio.c ***/
  190181. /*** Start of inlined file: pngrtran.c ***/
  190182. /* pngrtran.c - transforms the data in a row for PNG readers
  190183. *
  190184. * Last changed in libpng 1.2.21 [October 4, 2007]
  190185. * For conditions of distribution and use, see copyright notice in png.h
  190186. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190187. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190188. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190189. *
  190190. * This file contains functions optionally called by an application
  190191. * in order to tell libpng how to handle data when reading a PNG.
  190192. * Transformations that are used in both reading and writing are
  190193. * in pngtrans.c.
  190194. */
  190195. #define PNG_INTERNAL
  190196. #if defined(PNG_READ_SUPPORTED)
  190197. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190198. void PNGAPI
  190199. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190200. {
  190201. png_debug(1, "in png_set_crc_action\n");
  190202. /* Tell libpng how we react to CRC errors in critical chunks */
  190203. if(png_ptr == NULL) return;
  190204. switch (crit_action)
  190205. {
  190206. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190207. break;
  190208. case PNG_CRC_WARN_USE: /* warn/use data */
  190209. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190210. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190211. break;
  190212. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190213. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190214. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190215. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190216. break;
  190217. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190218. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190219. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190220. case PNG_CRC_DEFAULT:
  190221. default:
  190222. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190223. break;
  190224. }
  190225. switch (ancil_action)
  190226. {
  190227. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190228. break;
  190229. case PNG_CRC_WARN_USE: /* warn/use data */
  190230. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190231. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190232. break;
  190233. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190234. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190235. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190236. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190237. break;
  190238. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190239. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190240. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190241. break;
  190242. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190243. case PNG_CRC_DEFAULT:
  190244. default:
  190245. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190246. break;
  190247. }
  190248. }
  190249. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190250. defined(PNG_FLOATING_POINT_SUPPORTED)
  190251. /* handle alpha and tRNS via a background color */
  190252. void PNGAPI
  190253. png_set_background(png_structp png_ptr,
  190254. png_color_16p background_color, int background_gamma_code,
  190255. int need_expand, double background_gamma)
  190256. {
  190257. png_debug(1, "in png_set_background\n");
  190258. if(png_ptr == NULL) return;
  190259. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190260. {
  190261. png_warning(png_ptr, "Application must supply a known background gamma");
  190262. return;
  190263. }
  190264. png_ptr->transformations |= PNG_BACKGROUND;
  190265. png_memcpy(&(png_ptr->background), background_color,
  190266. png_sizeof(png_color_16));
  190267. png_ptr->background_gamma = (float)background_gamma;
  190268. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190269. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190270. }
  190271. #endif
  190272. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190273. /* strip 16 bit depth files to 8 bit depth */
  190274. void PNGAPI
  190275. png_set_strip_16(png_structp png_ptr)
  190276. {
  190277. png_debug(1, "in png_set_strip_16\n");
  190278. if(png_ptr == NULL) return;
  190279. png_ptr->transformations |= PNG_16_TO_8;
  190280. }
  190281. #endif
  190282. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190283. void PNGAPI
  190284. png_set_strip_alpha(png_structp png_ptr)
  190285. {
  190286. png_debug(1, "in png_set_strip_alpha\n");
  190287. if(png_ptr == NULL) return;
  190288. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190289. }
  190290. #endif
  190291. #if defined(PNG_READ_DITHER_SUPPORTED)
  190292. /* Dither file to 8 bit. Supply a palette, the current number
  190293. * of elements in the palette, the maximum number of elements
  190294. * allowed, and a histogram if possible. If the current number
  190295. * of colors is greater then the maximum number, the palette will be
  190296. * modified to fit in the maximum number. "full_dither" indicates
  190297. * whether we need a dithering cube set up for RGB images, or if we
  190298. * simply are reducing the number of colors in a paletted image.
  190299. */
  190300. typedef struct png_dsort_struct
  190301. {
  190302. struct png_dsort_struct FAR * next;
  190303. png_byte left;
  190304. png_byte right;
  190305. } png_dsort;
  190306. typedef png_dsort FAR * png_dsortp;
  190307. typedef png_dsort FAR * FAR * png_dsortpp;
  190308. void PNGAPI
  190309. png_set_dither(png_structp png_ptr, png_colorp palette,
  190310. int num_palette, int maximum_colors, png_uint_16p histogram,
  190311. int full_dither)
  190312. {
  190313. png_debug(1, "in png_set_dither\n");
  190314. if(png_ptr == NULL) return;
  190315. png_ptr->transformations |= PNG_DITHER;
  190316. if (!full_dither)
  190317. {
  190318. int i;
  190319. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190320. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190321. for (i = 0; i < num_palette; i++)
  190322. png_ptr->dither_index[i] = (png_byte)i;
  190323. }
  190324. if (num_palette > maximum_colors)
  190325. {
  190326. if (histogram != NULL)
  190327. {
  190328. /* This is easy enough, just throw out the least used colors.
  190329. Perhaps not the best solution, but good enough. */
  190330. int i;
  190331. /* initialize an array to sort colors */
  190332. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190333. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190334. /* initialize the dither_sort array */
  190335. for (i = 0; i < num_palette; i++)
  190336. png_ptr->dither_sort[i] = (png_byte)i;
  190337. /* Find the least used palette entries by starting a
  190338. bubble sort, and running it until we have sorted
  190339. out enough colors. Note that we don't care about
  190340. sorting all the colors, just finding which are
  190341. least used. */
  190342. for (i = num_palette - 1; i >= maximum_colors; i--)
  190343. {
  190344. int done; /* to stop early if the list is pre-sorted */
  190345. int j;
  190346. done = 1;
  190347. for (j = 0; j < i; j++)
  190348. {
  190349. if (histogram[png_ptr->dither_sort[j]]
  190350. < histogram[png_ptr->dither_sort[j + 1]])
  190351. {
  190352. png_byte t;
  190353. t = png_ptr->dither_sort[j];
  190354. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190355. png_ptr->dither_sort[j + 1] = t;
  190356. done = 0;
  190357. }
  190358. }
  190359. if (done)
  190360. break;
  190361. }
  190362. /* swap the palette around, and set up a table, if necessary */
  190363. if (full_dither)
  190364. {
  190365. int j = num_palette;
  190366. /* put all the useful colors within the max, but don't
  190367. move the others */
  190368. for (i = 0; i < maximum_colors; i++)
  190369. {
  190370. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190371. {
  190372. do
  190373. j--;
  190374. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190375. palette[i] = palette[j];
  190376. }
  190377. }
  190378. }
  190379. else
  190380. {
  190381. int j = num_palette;
  190382. /* move all the used colors inside the max limit, and
  190383. develop a translation table */
  190384. for (i = 0; i < maximum_colors; i++)
  190385. {
  190386. /* only move the colors we need to */
  190387. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190388. {
  190389. png_color tmp_color;
  190390. do
  190391. j--;
  190392. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190393. tmp_color = palette[j];
  190394. palette[j] = palette[i];
  190395. palette[i] = tmp_color;
  190396. /* indicate where the color went */
  190397. png_ptr->dither_index[j] = (png_byte)i;
  190398. png_ptr->dither_index[i] = (png_byte)j;
  190399. }
  190400. }
  190401. /* find closest color for those colors we are not using */
  190402. for (i = 0; i < num_palette; i++)
  190403. {
  190404. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190405. {
  190406. int min_d, k, min_k, d_index;
  190407. /* find the closest color to one we threw out */
  190408. d_index = png_ptr->dither_index[i];
  190409. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190410. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190411. {
  190412. int d;
  190413. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190414. if (d < min_d)
  190415. {
  190416. min_d = d;
  190417. min_k = k;
  190418. }
  190419. }
  190420. /* point to closest color */
  190421. png_ptr->dither_index[i] = (png_byte)min_k;
  190422. }
  190423. }
  190424. }
  190425. png_free(png_ptr, png_ptr->dither_sort);
  190426. png_ptr->dither_sort=NULL;
  190427. }
  190428. else
  190429. {
  190430. /* This is much harder to do simply (and quickly). Perhaps
  190431. we need to go through a median cut routine, but those
  190432. don't always behave themselves with only a few colors
  190433. as input. So we will just find the closest two colors,
  190434. and throw out one of them (chosen somewhat randomly).
  190435. [We don't understand this at all, so if someone wants to
  190436. work on improving it, be our guest - AED, GRP]
  190437. */
  190438. int i;
  190439. int max_d;
  190440. int num_new_palette;
  190441. png_dsortp t;
  190442. png_dsortpp hash;
  190443. t=NULL;
  190444. /* initialize palette index arrays */
  190445. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190446. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190447. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190448. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190449. /* initialize the sort array */
  190450. for (i = 0; i < num_palette; i++)
  190451. {
  190452. png_ptr->index_to_palette[i] = (png_byte)i;
  190453. png_ptr->palette_to_index[i] = (png_byte)i;
  190454. }
  190455. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190456. png_sizeof (png_dsortp)));
  190457. for (i = 0; i < 769; i++)
  190458. hash[i] = NULL;
  190459. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190460. num_new_palette = num_palette;
  190461. /* initial wild guess at how far apart the farthest pixel
  190462. pair we will be eliminating will be. Larger
  190463. numbers mean more areas will be allocated, Smaller
  190464. numbers run the risk of not saving enough data, and
  190465. having to do this all over again.
  190466. I have not done extensive checking on this number.
  190467. */
  190468. max_d = 96;
  190469. while (num_new_palette > maximum_colors)
  190470. {
  190471. for (i = 0; i < num_new_palette - 1; i++)
  190472. {
  190473. int j;
  190474. for (j = i + 1; j < num_new_palette; j++)
  190475. {
  190476. int d;
  190477. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190478. if (d <= max_d)
  190479. {
  190480. t = (png_dsortp)png_malloc_warn(png_ptr,
  190481. (png_uint_32)(png_sizeof(png_dsort)));
  190482. if (t == NULL)
  190483. break;
  190484. t->next = hash[d];
  190485. t->left = (png_byte)i;
  190486. t->right = (png_byte)j;
  190487. hash[d] = t;
  190488. }
  190489. }
  190490. if (t == NULL)
  190491. break;
  190492. }
  190493. if (t != NULL)
  190494. for (i = 0; i <= max_d; i++)
  190495. {
  190496. if (hash[i] != NULL)
  190497. {
  190498. png_dsortp p;
  190499. for (p = hash[i]; p; p = p->next)
  190500. {
  190501. if ((int)png_ptr->index_to_palette[p->left]
  190502. < num_new_palette &&
  190503. (int)png_ptr->index_to_palette[p->right]
  190504. < num_new_palette)
  190505. {
  190506. int j, next_j;
  190507. if (num_new_palette & 0x01)
  190508. {
  190509. j = p->left;
  190510. next_j = p->right;
  190511. }
  190512. else
  190513. {
  190514. j = p->right;
  190515. next_j = p->left;
  190516. }
  190517. num_new_palette--;
  190518. palette[png_ptr->index_to_palette[j]]
  190519. = palette[num_new_palette];
  190520. if (!full_dither)
  190521. {
  190522. int k;
  190523. for (k = 0; k < num_palette; k++)
  190524. {
  190525. if (png_ptr->dither_index[k] ==
  190526. png_ptr->index_to_palette[j])
  190527. png_ptr->dither_index[k] =
  190528. png_ptr->index_to_palette[next_j];
  190529. if ((int)png_ptr->dither_index[k] ==
  190530. num_new_palette)
  190531. png_ptr->dither_index[k] =
  190532. png_ptr->index_to_palette[j];
  190533. }
  190534. }
  190535. png_ptr->index_to_palette[png_ptr->palette_to_index
  190536. [num_new_palette]] = png_ptr->index_to_palette[j];
  190537. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190538. = png_ptr->palette_to_index[num_new_palette];
  190539. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190540. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190541. }
  190542. if (num_new_palette <= maximum_colors)
  190543. break;
  190544. }
  190545. if (num_new_palette <= maximum_colors)
  190546. break;
  190547. }
  190548. }
  190549. for (i = 0; i < 769; i++)
  190550. {
  190551. if (hash[i] != NULL)
  190552. {
  190553. png_dsortp p = hash[i];
  190554. while (p)
  190555. {
  190556. t = p->next;
  190557. png_free(png_ptr, p);
  190558. p = t;
  190559. }
  190560. }
  190561. hash[i] = 0;
  190562. }
  190563. max_d += 96;
  190564. }
  190565. png_free(png_ptr, hash);
  190566. png_free(png_ptr, png_ptr->palette_to_index);
  190567. png_free(png_ptr, png_ptr->index_to_palette);
  190568. png_ptr->palette_to_index=NULL;
  190569. png_ptr->index_to_palette=NULL;
  190570. }
  190571. num_palette = maximum_colors;
  190572. }
  190573. if (png_ptr->palette == NULL)
  190574. {
  190575. png_ptr->palette = palette;
  190576. }
  190577. png_ptr->num_palette = (png_uint_16)num_palette;
  190578. if (full_dither)
  190579. {
  190580. int i;
  190581. png_bytep distance;
  190582. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190583. PNG_DITHER_BLUE_BITS;
  190584. int num_red = (1 << PNG_DITHER_RED_BITS);
  190585. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190586. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190587. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190588. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190589. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190590. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190591. png_sizeof (png_byte));
  190592. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190593. png_sizeof(png_byte)));
  190594. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190595. for (i = 0; i < num_palette; i++)
  190596. {
  190597. int ir, ig, ib;
  190598. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190599. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190600. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190601. for (ir = 0; ir < num_red; ir++)
  190602. {
  190603. /* int dr = abs(ir - r); */
  190604. int dr = ((ir > r) ? ir - r : r - ir);
  190605. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190606. for (ig = 0; ig < num_green; ig++)
  190607. {
  190608. /* int dg = abs(ig - g); */
  190609. int dg = ((ig > g) ? ig - g : g - ig);
  190610. int dt = dr + dg;
  190611. int dm = ((dr > dg) ? dr : dg);
  190612. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190613. for (ib = 0; ib < num_blue; ib++)
  190614. {
  190615. int d_index = index_g | ib;
  190616. /* int db = abs(ib - b); */
  190617. int db = ((ib > b) ? ib - b : b - ib);
  190618. int dmax = ((dm > db) ? dm : db);
  190619. int d = dmax + dt + db;
  190620. if (d < (int)distance[d_index])
  190621. {
  190622. distance[d_index] = (png_byte)d;
  190623. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190624. }
  190625. }
  190626. }
  190627. }
  190628. }
  190629. png_free(png_ptr, distance);
  190630. }
  190631. }
  190632. #endif
  190633. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190634. /* Transform the image from the file_gamma to the screen_gamma. We
  190635. * only do transformations on images where the file_gamma and screen_gamma
  190636. * are not close reciprocals, otherwise it slows things down slightly, and
  190637. * also needlessly introduces small errors.
  190638. *
  190639. * We will turn off gamma transformation later if no semitransparent entries
  190640. * are present in the tRNS array for palette images. We can't do it here
  190641. * because we don't necessarily have the tRNS chunk yet.
  190642. */
  190643. void PNGAPI
  190644. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190645. {
  190646. png_debug(1, "in png_set_gamma\n");
  190647. if(png_ptr == NULL) return;
  190648. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190649. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190650. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190651. png_ptr->transformations |= PNG_GAMMA;
  190652. png_ptr->gamma = (float)file_gamma;
  190653. png_ptr->screen_gamma = (float)scrn_gamma;
  190654. }
  190655. #endif
  190656. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190657. /* Expand paletted images to RGB, expand grayscale images of
  190658. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190659. * to alpha channels.
  190660. */
  190661. void PNGAPI
  190662. png_set_expand(png_structp png_ptr)
  190663. {
  190664. png_debug(1, "in png_set_expand\n");
  190665. if(png_ptr == NULL) return;
  190666. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190667. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190668. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190669. #endif
  190670. }
  190671. /* GRR 19990627: the following three functions currently are identical
  190672. * to png_set_expand(). However, it is entirely reasonable that someone
  190673. * might wish to expand an indexed image to RGB but *not* expand a single,
  190674. * fully transparent palette entry to a full alpha channel--perhaps instead
  190675. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190676. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190677. * IOW, a future version of the library may make the transformations flag
  190678. * a bit more fine-grained, with separate bits for each of these three
  190679. * functions.
  190680. *
  190681. * More to the point, these functions make it obvious what libpng will be
  190682. * doing, whereas "expand" can (and does) mean any number of things.
  190683. *
  190684. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190685. * to expand only the sample depth but not to expand the tRNS to alpha.
  190686. */
  190687. /* Expand paletted images to RGB. */
  190688. void PNGAPI
  190689. png_set_palette_to_rgb(png_structp png_ptr)
  190690. {
  190691. png_debug(1, "in png_set_palette_to_rgb\n");
  190692. if(png_ptr == NULL) return;
  190693. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190694. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190695. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190696. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190697. #endif
  190698. }
  190699. #if !defined(PNG_1_0_X)
  190700. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190701. void PNGAPI
  190702. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190703. {
  190704. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190705. if(png_ptr == NULL) return;
  190706. png_ptr->transformations |= PNG_EXPAND;
  190707. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190708. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190709. #endif
  190710. }
  190711. #endif
  190712. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190713. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190714. /* Deprecated as of libpng-1.2.9 */
  190715. void PNGAPI
  190716. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190717. {
  190718. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190719. if(png_ptr == NULL) return;
  190720. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190721. }
  190722. #endif
  190723. /* Expand tRNS chunks to alpha channels. */
  190724. void PNGAPI
  190725. png_set_tRNS_to_alpha(png_structp png_ptr)
  190726. {
  190727. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190728. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190729. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190730. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190731. #endif
  190732. }
  190733. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190734. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190735. void PNGAPI
  190736. png_set_gray_to_rgb(png_structp png_ptr)
  190737. {
  190738. png_debug(1, "in png_set_gray_to_rgb\n");
  190739. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190740. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190741. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190742. #endif
  190743. }
  190744. #endif
  190745. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190746. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190747. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190748. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190749. */
  190750. void PNGAPI
  190751. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190752. double green)
  190753. {
  190754. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190755. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190756. if(png_ptr == NULL) return;
  190757. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190758. }
  190759. #endif
  190760. void PNGAPI
  190761. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190762. png_fixed_point red, png_fixed_point green)
  190763. {
  190764. png_debug(1, "in png_set_rgb_to_gray\n");
  190765. if(png_ptr == NULL) return;
  190766. switch(error_action)
  190767. {
  190768. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190769. break;
  190770. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190771. break;
  190772. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190773. }
  190774. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190775. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190776. png_ptr->transformations |= PNG_EXPAND;
  190777. #else
  190778. {
  190779. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190780. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190781. }
  190782. #endif
  190783. {
  190784. png_uint_16 red_int, green_int;
  190785. if(red < 0 || green < 0)
  190786. {
  190787. red_int = 6968; /* .212671 * 32768 + .5 */
  190788. green_int = 23434; /* .715160 * 32768 + .5 */
  190789. }
  190790. else if(red + green < 100000L)
  190791. {
  190792. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190793. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190794. }
  190795. else
  190796. {
  190797. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190798. red_int = 6968;
  190799. green_int = 23434;
  190800. }
  190801. png_ptr->rgb_to_gray_red_coeff = red_int;
  190802. png_ptr->rgb_to_gray_green_coeff = green_int;
  190803. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190804. }
  190805. }
  190806. #endif
  190807. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190808. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190809. defined(PNG_LEGACY_SUPPORTED)
  190810. void PNGAPI
  190811. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190812. read_user_transform_fn)
  190813. {
  190814. png_debug(1, "in png_set_read_user_transform_fn\n");
  190815. if(png_ptr == NULL) return;
  190816. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190817. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190818. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190819. #endif
  190820. #ifdef PNG_LEGACY_SUPPORTED
  190821. if(read_user_transform_fn)
  190822. png_warning(png_ptr,
  190823. "This version of libpng does not support user transforms");
  190824. #endif
  190825. }
  190826. #endif
  190827. /* Initialize everything needed for the read. This includes modifying
  190828. * the palette.
  190829. */
  190830. void /* PRIVATE */
  190831. png_init_read_transformations(png_structp png_ptr)
  190832. {
  190833. png_debug(1, "in png_init_read_transformations\n");
  190834. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190835. if(png_ptr != NULL)
  190836. #endif
  190837. {
  190838. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190839. || defined(PNG_READ_GAMMA_SUPPORTED)
  190840. int color_type = png_ptr->color_type;
  190841. #endif
  190842. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190843. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190844. /* Detect gray background and attempt to enable optimization
  190845. * for gray --> RGB case */
  190846. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190847. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190848. * background color might actually be gray yet not be flagged as such.
  190849. * This is not a problem for the current code, which uses
  190850. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190851. * png_do_gray_to_rgb() transformation.
  190852. */
  190853. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190854. !(color_type & PNG_COLOR_MASK_COLOR))
  190855. {
  190856. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190857. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190858. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190859. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190860. png_ptr->background.red == png_ptr->background.green &&
  190861. png_ptr->background.red == png_ptr->background.blue)
  190862. {
  190863. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190864. png_ptr->background.gray = png_ptr->background.red;
  190865. }
  190866. #endif
  190867. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190868. (png_ptr->transformations & PNG_EXPAND))
  190869. {
  190870. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190871. {
  190872. /* expand background and tRNS chunks */
  190873. switch (png_ptr->bit_depth)
  190874. {
  190875. case 1:
  190876. png_ptr->background.gray *= (png_uint_16)0xff;
  190877. png_ptr->background.red = png_ptr->background.green
  190878. = png_ptr->background.blue = png_ptr->background.gray;
  190879. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190880. {
  190881. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190882. png_ptr->trans_values.red = png_ptr->trans_values.green
  190883. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190884. }
  190885. break;
  190886. case 2:
  190887. png_ptr->background.gray *= (png_uint_16)0x55;
  190888. png_ptr->background.red = png_ptr->background.green
  190889. = png_ptr->background.blue = png_ptr->background.gray;
  190890. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190891. {
  190892. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190893. png_ptr->trans_values.red = png_ptr->trans_values.green
  190894. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190895. }
  190896. break;
  190897. case 4:
  190898. png_ptr->background.gray *= (png_uint_16)0x11;
  190899. png_ptr->background.red = png_ptr->background.green
  190900. = png_ptr->background.blue = png_ptr->background.gray;
  190901. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190902. {
  190903. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190904. png_ptr->trans_values.red = png_ptr->trans_values.green
  190905. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190906. }
  190907. break;
  190908. case 8:
  190909. case 16:
  190910. png_ptr->background.red = png_ptr->background.green
  190911. = png_ptr->background.blue = png_ptr->background.gray;
  190912. break;
  190913. }
  190914. }
  190915. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190916. {
  190917. png_ptr->background.red =
  190918. png_ptr->palette[png_ptr->background.index].red;
  190919. png_ptr->background.green =
  190920. png_ptr->palette[png_ptr->background.index].green;
  190921. png_ptr->background.blue =
  190922. png_ptr->palette[png_ptr->background.index].blue;
  190923. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190924. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190925. {
  190926. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190927. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190928. #endif
  190929. {
  190930. /* invert the alpha channel (in tRNS) unless the pixels are
  190931. going to be expanded, in which case leave it for later */
  190932. int i,istop;
  190933. istop=(int)png_ptr->num_trans;
  190934. for (i=0; i<istop; i++)
  190935. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190936. }
  190937. }
  190938. #endif
  190939. }
  190940. }
  190941. #endif
  190942. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190943. png_ptr->background_1 = png_ptr->background;
  190944. #endif
  190945. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190946. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190947. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190948. < PNG_GAMMA_THRESHOLD))
  190949. {
  190950. int i,k;
  190951. k=0;
  190952. for (i=0; i<png_ptr->num_trans; i++)
  190953. {
  190954. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190955. k=1; /* partial transparency is present */
  190956. }
  190957. if (k == 0)
  190958. png_ptr->transformations &= (~PNG_GAMMA);
  190959. }
  190960. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190961. png_ptr->gamma != 0.0)
  190962. {
  190963. png_build_gamma_table(png_ptr);
  190964. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190965. if (png_ptr->transformations & PNG_BACKGROUND)
  190966. {
  190967. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190968. {
  190969. /* could skip if no transparency and
  190970. */
  190971. png_color back, back_1;
  190972. png_colorp palette = png_ptr->palette;
  190973. int num_palette = png_ptr->num_palette;
  190974. int i;
  190975. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190976. {
  190977. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190978. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190979. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190980. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190981. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190982. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190983. }
  190984. else
  190985. {
  190986. double g, gs;
  190987. switch (png_ptr->background_gamma_type)
  190988. {
  190989. case PNG_BACKGROUND_GAMMA_SCREEN:
  190990. g = (png_ptr->screen_gamma);
  190991. gs = 1.0;
  190992. break;
  190993. case PNG_BACKGROUND_GAMMA_FILE:
  190994. g = 1.0 / (png_ptr->gamma);
  190995. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190996. break;
  190997. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190998. g = 1.0 / (png_ptr->background_gamma);
  190999. gs = 1.0 / (png_ptr->background_gamma *
  191000. png_ptr->screen_gamma);
  191001. break;
  191002. default:
  191003. g = 1.0; /* back_1 */
  191004. gs = 1.0; /* back */
  191005. }
  191006. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191007. {
  191008. back.red = (png_byte)png_ptr->background.red;
  191009. back.green = (png_byte)png_ptr->background.green;
  191010. back.blue = (png_byte)png_ptr->background.blue;
  191011. }
  191012. else
  191013. {
  191014. back.red = (png_byte)(pow(
  191015. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191016. back.green = (png_byte)(pow(
  191017. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191018. back.blue = (png_byte)(pow(
  191019. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191020. }
  191021. back_1.red = (png_byte)(pow(
  191022. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191023. back_1.green = (png_byte)(pow(
  191024. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191025. back_1.blue = (png_byte)(pow(
  191026. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191027. }
  191028. for (i = 0; i < num_palette; i++)
  191029. {
  191030. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191031. {
  191032. if (png_ptr->trans[i] == 0)
  191033. {
  191034. palette[i] = back;
  191035. }
  191036. else /* if (png_ptr->trans[i] != 0xff) */
  191037. {
  191038. png_byte v, w;
  191039. v = png_ptr->gamma_to_1[palette[i].red];
  191040. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191041. palette[i].red = png_ptr->gamma_from_1[w];
  191042. v = png_ptr->gamma_to_1[palette[i].green];
  191043. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191044. palette[i].green = png_ptr->gamma_from_1[w];
  191045. v = png_ptr->gamma_to_1[palette[i].blue];
  191046. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191047. palette[i].blue = png_ptr->gamma_from_1[w];
  191048. }
  191049. }
  191050. else
  191051. {
  191052. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191053. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191054. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191055. }
  191056. }
  191057. }
  191058. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191059. else
  191060. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191061. {
  191062. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191063. double g = 1.0;
  191064. double gs = 1.0;
  191065. switch (png_ptr->background_gamma_type)
  191066. {
  191067. case PNG_BACKGROUND_GAMMA_SCREEN:
  191068. g = (png_ptr->screen_gamma);
  191069. gs = 1.0;
  191070. break;
  191071. case PNG_BACKGROUND_GAMMA_FILE:
  191072. g = 1.0 / (png_ptr->gamma);
  191073. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191074. break;
  191075. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191076. g = 1.0 / (png_ptr->background_gamma);
  191077. gs = 1.0 / (png_ptr->background_gamma *
  191078. png_ptr->screen_gamma);
  191079. break;
  191080. }
  191081. png_ptr->background_1.gray = (png_uint_16)(pow(
  191082. (double)png_ptr->background.gray / m, g) * m + .5);
  191083. png_ptr->background.gray = (png_uint_16)(pow(
  191084. (double)png_ptr->background.gray / m, gs) * m + .5);
  191085. if ((png_ptr->background.red != png_ptr->background.green) ||
  191086. (png_ptr->background.red != png_ptr->background.blue) ||
  191087. (png_ptr->background.red != png_ptr->background.gray))
  191088. {
  191089. /* RGB or RGBA with color background */
  191090. png_ptr->background_1.red = (png_uint_16)(pow(
  191091. (double)png_ptr->background.red / m, g) * m + .5);
  191092. png_ptr->background_1.green = (png_uint_16)(pow(
  191093. (double)png_ptr->background.green / m, g) * m + .5);
  191094. png_ptr->background_1.blue = (png_uint_16)(pow(
  191095. (double)png_ptr->background.blue / m, g) * m + .5);
  191096. png_ptr->background.red = (png_uint_16)(pow(
  191097. (double)png_ptr->background.red / m, gs) * m + .5);
  191098. png_ptr->background.green = (png_uint_16)(pow(
  191099. (double)png_ptr->background.green / m, gs) * m + .5);
  191100. png_ptr->background.blue = (png_uint_16)(pow(
  191101. (double)png_ptr->background.blue / m, gs) * m + .5);
  191102. }
  191103. else
  191104. {
  191105. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191106. png_ptr->background_1.red = png_ptr->background_1.green
  191107. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191108. png_ptr->background.red = png_ptr->background.green
  191109. = png_ptr->background.blue = png_ptr->background.gray;
  191110. }
  191111. }
  191112. }
  191113. else
  191114. /* transformation does not include PNG_BACKGROUND */
  191115. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191116. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191117. {
  191118. png_colorp palette = png_ptr->palette;
  191119. int num_palette = png_ptr->num_palette;
  191120. int i;
  191121. for (i = 0; i < num_palette; i++)
  191122. {
  191123. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191124. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191125. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191126. }
  191127. }
  191128. }
  191129. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191130. else
  191131. #endif
  191132. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191133. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191134. /* No GAMMA transformation */
  191135. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191136. (color_type == PNG_COLOR_TYPE_PALETTE))
  191137. {
  191138. int i;
  191139. int istop = (int)png_ptr->num_trans;
  191140. png_color back;
  191141. png_colorp palette = png_ptr->palette;
  191142. back.red = (png_byte)png_ptr->background.red;
  191143. back.green = (png_byte)png_ptr->background.green;
  191144. back.blue = (png_byte)png_ptr->background.blue;
  191145. for (i = 0; i < istop; i++)
  191146. {
  191147. if (png_ptr->trans[i] == 0)
  191148. {
  191149. palette[i] = back;
  191150. }
  191151. else if (png_ptr->trans[i] != 0xff)
  191152. {
  191153. /* The png_composite() macro is defined in png.h */
  191154. png_composite(palette[i].red, palette[i].red,
  191155. png_ptr->trans[i], back.red);
  191156. png_composite(palette[i].green, palette[i].green,
  191157. png_ptr->trans[i], back.green);
  191158. png_composite(palette[i].blue, palette[i].blue,
  191159. png_ptr->trans[i], back.blue);
  191160. }
  191161. }
  191162. }
  191163. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191164. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191165. if ((png_ptr->transformations & PNG_SHIFT) &&
  191166. (color_type == PNG_COLOR_TYPE_PALETTE))
  191167. {
  191168. png_uint_16 i;
  191169. png_uint_16 istop = png_ptr->num_palette;
  191170. int sr = 8 - png_ptr->sig_bit.red;
  191171. int sg = 8 - png_ptr->sig_bit.green;
  191172. int sb = 8 - png_ptr->sig_bit.blue;
  191173. if (sr < 0 || sr > 8)
  191174. sr = 0;
  191175. if (sg < 0 || sg > 8)
  191176. sg = 0;
  191177. if (sb < 0 || sb > 8)
  191178. sb = 0;
  191179. for (i = 0; i < istop; i++)
  191180. {
  191181. png_ptr->palette[i].red >>= sr;
  191182. png_ptr->palette[i].green >>= sg;
  191183. png_ptr->palette[i].blue >>= sb;
  191184. }
  191185. }
  191186. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191187. }
  191188. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191189. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191190. if(png_ptr)
  191191. return;
  191192. #endif
  191193. }
  191194. /* Modify the info structure to reflect the transformations. The
  191195. * info should be updated so a PNG file could be written with it,
  191196. * assuming the transformations result in valid PNG data.
  191197. */
  191198. void /* PRIVATE */
  191199. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191200. {
  191201. png_debug(1, "in png_read_transform_info\n");
  191202. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191203. if (png_ptr->transformations & PNG_EXPAND)
  191204. {
  191205. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191206. {
  191207. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191208. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191209. else
  191210. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191211. info_ptr->bit_depth = 8;
  191212. info_ptr->num_trans = 0;
  191213. }
  191214. else
  191215. {
  191216. if (png_ptr->num_trans)
  191217. {
  191218. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191219. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191220. else
  191221. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191222. }
  191223. if (info_ptr->bit_depth < 8)
  191224. info_ptr->bit_depth = 8;
  191225. info_ptr->num_trans = 0;
  191226. }
  191227. }
  191228. #endif
  191229. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191230. if (png_ptr->transformations & PNG_BACKGROUND)
  191231. {
  191232. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191233. info_ptr->num_trans = 0;
  191234. info_ptr->background = png_ptr->background;
  191235. }
  191236. #endif
  191237. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191238. if (png_ptr->transformations & PNG_GAMMA)
  191239. {
  191240. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191241. info_ptr->gamma = png_ptr->gamma;
  191242. #endif
  191243. #ifdef PNG_FIXED_POINT_SUPPORTED
  191244. info_ptr->int_gamma = png_ptr->int_gamma;
  191245. #endif
  191246. }
  191247. #endif
  191248. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191249. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191250. info_ptr->bit_depth = 8;
  191251. #endif
  191252. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191253. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191254. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191255. #endif
  191256. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191257. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191258. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191259. #endif
  191260. #if defined(PNG_READ_DITHER_SUPPORTED)
  191261. if (png_ptr->transformations & PNG_DITHER)
  191262. {
  191263. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191264. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191265. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191266. {
  191267. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191268. }
  191269. }
  191270. #endif
  191271. #if defined(PNG_READ_PACK_SUPPORTED)
  191272. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191273. info_ptr->bit_depth = 8;
  191274. #endif
  191275. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191276. info_ptr->channels = 1;
  191277. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191278. info_ptr->channels = 3;
  191279. else
  191280. info_ptr->channels = 1;
  191281. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191282. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191283. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191284. #endif
  191285. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191286. info_ptr->channels++;
  191287. #if defined(PNG_READ_FILLER_SUPPORTED)
  191288. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191289. if ((png_ptr->transformations & PNG_FILLER) &&
  191290. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191291. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191292. {
  191293. info_ptr->channels++;
  191294. /* if adding a true alpha channel not just filler */
  191295. #if !defined(PNG_1_0_X)
  191296. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191297. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191298. #endif
  191299. }
  191300. #endif
  191301. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191302. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191303. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191304. {
  191305. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191306. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191307. if(info_ptr->channels < png_ptr->user_transform_channels)
  191308. info_ptr->channels = png_ptr->user_transform_channels;
  191309. }
  191310. #endif
  191311. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191312. info_ptr->bit_depth);
  191313. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191314. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191315. if(png_ptr)
  191316. return;
  191317. #endif
  191318. }
  191319. /* Transform the row. The order of transformations is significant,
  191320. * and is very touchy. If you add a transformation, take care to
  191321. * decide how it fits in with the other transformations here.
  191322. */
  191323. void /* PRIVATE */
  191324. png_do_read_transformations(png_structp png_ptr)
  191325. {
  191326. png_debug(1, "in png_do_read_transformations\n");
  191327. if (png_ptr->row_buf == NULL)
  191328. {
  191329. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191330. char msg[50];
  191331. png_snprintf2(msg, 50,
  191332. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191333. png_ptr->pass);
  191334. png_error(png_ptr, msg);
  191335. #else
  191336. png_error(png_ptr, "NULL row buffer");
  191337. #endif
  191338. }
  191339. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191340. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191341. /* Application has failed to call either png_read_start_image()
  191342. * or png_read_update_info() after setting transforms that expand
  191343. * pixels. This check added to libpng-1.2.19 */
  191344. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191345. png_error(png_ptr, "Uninitialized row");
  191346. #else
  191347. png_warning(png_ptr, "Uninitialized row");
  191348. #endif
  191349. #endif
  191350. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191351. if (png_ptr->transformations & PNG_EXPAND)
  191352. {
  191353. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191354. {
  191355. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191356. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191357. }
  191358. else
  191359. {
  191360. if (png_ptr->num_trans &&
  191361. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191362. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191363. &(png_ptr->trans_values));
  191364. else
  191365. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191366. NULL);
  191367. }
  191368. }
  191369. #endif
  191370. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191371. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191372. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191373. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191374. #endif
  191375. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191376. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191377. {
  191378. int rgb_error =
  191379. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191380. if(rgb_error)
  191381. {
  191382. png_ptr->rgb_to_gray_status=1;
  191383. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191384. PNG_RGB_TO_GRAY_WARN)
  191385. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191386. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191387. PNG_RGB_TO_GRAY_ERR)
  191388. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191389. }
  191390. }
  191391. #endif
  191392. /*
  191393. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191394. In most cases, the "simple transparency" should be done prior to doing
  191395. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191396. pixel is transparent. You would also need to make sure that the
  191397. transparency information is upgraded to RGB.
  191398. To summarize, the current flow is:
  191399. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191400. with background "in place" if transparent,
  191401. convert to RGB if necessary
  191402. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191403. convert to RGB if necessary
  191404. To support RGB backgrounds for gray images we need:
  191405. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191406. 3 or 6 bytes and composite with background
  191407. "in place" if transparent (3x compare/pixel
  191408. compared to doing composite with gray bkgrnd)
  191409. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191410. remove alpha bytes (3x float operations/pixel
  191411. compared with composite on gray background)
  191412. Greg's change will do this. The reason it wasn't done before is for
  191413. performance, as this increases the per-pixel operations. If we would check
  191414. in advance if the background was gray or RGB, and position the gray-to-RGB
  191415. transform appropriately, then it would save a lot of work/time.
  191416. */
  191417. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191418. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191419. * for performance reasons */
  191420. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191421. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191422. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191423. #endif
  191424. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191425. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191426. ((png_ptr->num_trans != 0 ) ||
  191427. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191428. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191429. &(png_ptr->trans_values), &(png_ptr->background)
  191430. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191431. , &(png_ptr->background_1),
  191432. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191433. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191434. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191435. png_ptr->gamma_shift
  191436. #endif
  191437. );
  191438. #endif
  191439. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191440. if ((png_ptr->transformations & PNG_GAMMA) &&
  191441. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191442. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191443. ((png_ptr->num_trans != 0) ||
  191444. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191445. #endif
  191446. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191447. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191448. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191449. png_ptr->gamma_shift);
  191450. #endif
  191451. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191452. if (png_ptr->transformations & PNG_16_TO_8)
  191453. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191454. #endif
  191455. #if defined(PNG_READ_DITHER_SUPPORTED)
  191456. if (png_ptr->transformations & PNG_DITHER)
  191457. {
  191458. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191459. png_ptr->palette_lookup, png_ptr->dither_index);
  191460. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191461. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191462. }
  191463. #endif
  191464. #if defined(PNG_READ_INVERT_SUPPORTED)
  191465. if (png_ptr->transformations & PNG_INVERT_MONO)
  191466. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191467. #endif
  191468. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191469. if (png_ptr->transformations & PNG_SHIFT)
  191470. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191471. &(png_ptr->shift));
  191472. #endif
  191473. #if defined(PNG_READ_PACK_SUPPORTED)
  191474. if (png_ptr->transformations & PNG_PACK)
  191475. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191476. #endif
  191477. #if defined(PNG_READ_BGR_SUPPORTED)
  191478. if (png_ptr->transformations & PNG_BGR)
  191479. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191480. #endif
  191481. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191482. if (png_ptr->transformations & PNG_PACKSWAP)
  191483. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191484. #endif
  191485. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191486. /* if gray -> RGB, do so now only if we did not do so above */
  191487. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191488. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191489. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191490. #endif
  191491. #if defined(PNG_READ_FILLER_SUPPORTED)
  191492. if (png_ptr->transformations & PNG_FILLER)
  191493. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191494. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191495. #endif
  191496. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191497. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191498. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191499. #endif
  191500. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191501. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191502. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191503. #endif
  191504. #if defined(PNG_READ_SWAP_SUPPORTED)
  191505. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191506. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191507. #endif
  191508. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191509. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191510. {
  191511. if(png_ptr->read_user_transform_fn != NULL)
  191512. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191513. (png_ptr, /* png_ptr */
  191514. &(png_ptr->row_info), /* row_info: */
  191515. /* png_uint_32 width; width of row */
  191516. /* png_uint_32 rowbytes; number of bytes in row */
  191517. /* png_byte color_type; color type of pixels */
  191518. /* png_byte bit_depth; bit depth of samples */
  191519. /* png_byte channels; number of channels (1-4) */
  191520. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191521. png_ptr->row_buf + 1); /* start of pixel data for row */
  191522. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191523. if(png_ptr->user_transform_depth)
  191524. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191525. if(png_ptr->user_transform_channels)
  191526. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191527. #endif
  191528. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191529. png_ptr->row_info.channels);
  191530. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191531. png_ptr->row_info.width);
  191532. }
  191533. #endif
  191534. }
  191535. #if defined(PNG_READ_PACK_SUPPORTED)
  191536. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191537. * without changing the actual values. Thus, if you had a row with
  191538. * a bit depth of 1, you would end up with bytes that only contained
  191539. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191540. * png_do_shift() after this.
  191541. */
  191542. void /* PRIVATE */
  191543. png_do_unpack(png_row_infop row_info, png_bytep row)
  191544. {
  191545. png_debug(1, "in png_do_unpack\n");
  191546. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191547. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191548. #else
  191549. if (row_info->bit_depth < 8)
  191550. #endif
  191551. {
  191552. png_uint_32 i;
  191553. png_uint_32 row_width=row_info->width;
  191554. switch (row_info->bit_depth)
  191555. {
  191556. case 1:
  191557. {
  191558. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191559. png_bytep dp = row + (png_size_t)row_width - 1;
  191560. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191561. for (i = 0; i < row_width; i++)
  191562. {
  191563. *dp = (png_byte)((*sp >> shift) & 0x01);
  191564. if (shift == 7)
  191565. {
  191566. shift = 0;
  191567. sp--;
  191568. }
  191569. else
  191570. shift++;
  191571. dp--;
  191572. }
  191573. break;
  191574. }
  191575. case 2:
  191576. {
  191577. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191578. png_bytep dp = row + (png_size_t)row_width - 1;
  191579. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191580. for (i = 0; i < row_width; i++)
  191581. {
  191582. *dp = (png_byte)((*sp >> shift) & 0x03);
  191583. if (shift == 6)
  191584. {
  191585. shift = 0;
  191586. sp--;
  191587. }
  191588. else
  191589. shift += 2;
  191590. dp--;
  191591. }
  191592. break;
  191593. }
  191594. case 4:
  191595. {
  191596. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191597. png_bytep dp = row + (png_size_t)row_width - 1;
  191598. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191599. for (i = 0; i < row_width; i++)
  191600. {
  191601. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191602. if (shift == 4)
  191603. {
  191604. shift = 0;
  191605. sp--;
  191606. }
  191607. else
  191608. shift = 4;
  191609. dp--;
  191610. }
  191611. break;
  191612. }
  191613. }
  191614. row_info->bit_depth = 8;
  191615. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191616. row_info->rowbytes = row_width * row_info->channels;
  191617. }
  191618. }
  191619. #endif
  191620. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191621. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191622. * pixels back to their significant bits values. Thus, if you have
  191623. * a row of bit depth 8, but only 5 are significant, this will shift
  191624. * the values back to 0 through 31.
  191625. */
  191626. void /* PRIVATE */
  191627. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191628. {
  191629. png_debug(1, "in png_do_unshift\n");
  191630. if (
  191631. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191632. row != NULL && row_info != NULL && sig_bits != NULL &&
  191633. #endif
  191634. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191635. {
  191636. int shift[4];
  191637. int channels = 0;
  191638. int c;
  191639. png_uint_16 value = 0;
  191640. png_uint_32 row_width = row_info->width;
  191641. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191642. {
  191643. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191644. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191645. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191646. }
  191647. else
  191648. {
  191649. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191650. }
  191651. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191652. {
  191653. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191654. }
  191655. for (c = 0; c < channels; c++)
  191656. {
  191657. if (shift[c] <= 0)
  191658. shift[c] = 0;
  191659. else
  191660. value = 1;
  191661. }
  191662. if (!value)
  191663. return;
  191664. switch (row_info->bit_depth)
  191665. {
  191666. case 2:
  191667. {
  191668. png_bytep bp;
  191669. png_uint_32 i;
  191670. png_uint_32 istop = row_info->rowbytes;
  191671. for (bp = row, i = 0; i < istop; i++)
  191672. {
  191673. *bp >>= 1;
  191674. *bp++ &= 0x55;
  191675. }
  191676. break;
  191677. }
  191678. case 4:
  191679. {
  191680. png_bytep bp = row;
  191681. png_uint_32 i;
  191682. png_uint_32 istop = row_info->rowbytes;
  191683. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191684. (png_byte)((int)0xf >> shift[0]));
  191685. for (i = 0; i < istop; i++)
  191686. {
  191687. *bp >>= shift[0];
  191688. *bp++ &= mask;
  191689. }
  191690. break;
  191691. }
  191692. case 8:
  191693. {
  191694. png_bytep bp = row;
  191695. png_uint_32 i;
  191696. png_uint_32 istop = row_width * channels;
  191697. for (i = 0; i < istop; i++)
  191698. {
  191699. *bp++ >>= shift[i%channels];
  191700. }
  191701. break;
  191702. }
  191703. case 16:
  191704. {
  191705. png_bytep bp = row;
  191706. png_uint_32 i;
  191707. png_uint_32 istop = channels * row_width;
  191708. for (i = 0; i < istop; i++)
  191709. {
  191710. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191711. value >>= shift[i%channels];
  191712. *bp++ = (png_byte)(value >> 8);
  191713. *bp++ = (png_byte)(value & 0xff);
  191714. }
  191715. break;
  191716. }
  191717. }
  191718. }
  191719. }
  191720. #endif
  191721. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191722. /* chop rows of bit depth 16 down to 8 */
  191723. void /* PRIVATE */
  191724. png_do_chop(png_row_infop row_info, png_bytep row)
  191725. {
  191726. png_debug(1, "in png_do_chop\n");
  191727. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191728. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191729. #else
  191730. if (row_info->bit_depth == 16)
  191731. #endif
  191732. {
  191733. png_bytep sp = row;
  191734. png_bytep dp = row;
  191735. png_uint_32 i;
  191736. png_uint_32 istop = row_info->width * row_info->channels;
  191737. for (i = 0; i<istop; i++, sp += 2, dp++)
  191738. {
  191739. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191740. /* This does a more accurate scaling of the 16-bit color
  191741. * value, rather than a simple low-byte truncation.
  191742. *
  191743. * What the ideal calculation should be:
  191744. * *dp = (((((png_uint_32)(*sp) << 8) |
  191745. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191746. *
  191747. * GRR: no, I think this is what it really should be:
  191748. * *dp = (((((png_uint_32)(*sp) << 8) |
  191749. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191750. *
  191751. * GRR: here's the exact calculation with shifts:
  191752. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191753. * *dp = (temp - (temp >> 8)) >> 8;
  191754. *
  191755. * Approximate calculation with shift/add instead of multiply/divide:
  191756. * *dp = ((((png_uint_32)(*sp) << 8) |
  191757. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191758. *
  191759. * What we actually do to avoid extra shifting and conversion:
  191760. */
  191761. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191762. #else
  191763. /* Simply discard the low order byte */
  191764. *dp = *sp;
  191765. #endif
  191766. }
  191767. row_info->bit_depth = 8;
  191768. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191769. row_info->rowbytes = row_info->width * row_info->channels;
  191770. }
  191771. }
  191772. #endif
  191773. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191774. void /* PRIVATE */
  191775. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191776. {
  191777. png_debug(1, "in png_do_read_swap_alpha\n");
  191778. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191779. if (row != NULL && row_info != NULL)
  191780. #endif
  191781. {
  191782. png_uint_32 row_width = row_info->width;
  191783. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191784. {
  191785. /* This converts from RGBA to ARGB */
  191786. if (row_info->bit_depth == 8)
  191787. {
  191788. png_bytep sp = row + row_info->rowbytes;
  191789. png_bytep dp = sp;
  191790. png_byte save;
  191791. png_uint_32 i;
  191792. for (i = 0; i < row_width; i++)
  191793. {
  191794. save = *(--sp);
  191795. *(--dp) = *(--sp);
  191796. *(--dp) = *(--sp);
  191797. *(--dp) = *(--sp);
  191798. *(--dp) = save;
  191799. }
  191800. }
  191801. /* This converts from RRGGBBAA to AARRGGBB */
  191802. else
  191803. {
  191804. png_bytep sp = row + row_info->rowbytes;
  191805. png_bytep dp = sp;
  191806. png_byte save[2];
  191807. png_uint_32 i;
  191808. for (i = 0; i < row_width; i++)
  191809. {
  191810. save[0] = *(--sp);
  191811. save[1] = *(--sp);
  191812. *(--dp) = *(--sp);
  191813. *(--dp) = *(--sp);
  191814. *(--dp) = *(--sp);
  191815. *(--dp) = *(--sp);
  191816. *(--dp) = *(--sp);
  191817. *(--dp) = *(--sp);
  191818. *(--dp) = save[0];
  191819. *(--dp) = save[1];
  191820. }
  191821. }
  191822. }
  191823. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191824. {
  191825. /* This converts from GA to AG */
  191826. if (row_info->bit_depth == 8)
  191827. {
  191828. png_bytep sp = row + row_info->rowbytes;
  191829. png_bytep dp = sp;
  191830. png_byte save;
  191831. png_uint_32 i;
  191832. for (i = 0; i < row_width; i++)
  191833. {
  191834. save = *(--sp);
  191835. *(--dp) = *(--sp);
  191836. *(--dp) = save;
  191837. }
  191838. }
  191839. /* This converts from GGAA to AAGG */
  191840. else
  191841. {
  191842. png_bytep sp = row + row_info->rowbytes;
  191843. png_bytep dp = sp;
  191844. png_byte save[2];
  191845. png_uint_32 i;
  191846. for (i = 0; i < row_width; i++)
  191847. {
  191848. save[0] = *(--sp);
  191849. save[1] = *(--sp);
  191850. *(--dp) = *(--sp);
  191851. *(--dp) = *(--sp);
  191852. *(--dp) = save[0];
  191853. *(--dp) = save[1];
  191854. }
  191855. }
  191856. }
  191857. }
  191858. }
  191859. #endif
  191860. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191861. void /* PRIVATE */
  191862. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191863. {
  191864. png_debug(1, "in png_do_read_invert_alpha\n");
  191865. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191866. if (row != NULL && row_info != NULL)
  191867. #endif
  191868. {
  191869. png_uint_32 row_width = row_info->width;
  191870. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191871. {
  191872. /* This inverts the alpha channel in RGBA */
  191873. if (row_info->bit_depth == 8)
  191874. {
  191875. png_bytep sp = row + row_info->rowbytes;
  191876. png_bytep dp = sp;
  191877. png_uint_32 i;
  191878. for (i = 0; i < row_width; i++)
  191879. {
  191880. *(--dp) = (png_byte)(255 - *(--sp));
  191881. /* This does nothing:
  191882. *(--dp) = *(--sp);
  191883. *(--dp) = *(--sp);
  191884. *(--dp) = *(--sp);
  191885. We can replace it with:
  191886. */
  191887. sp-=3;
  191888. dp=sp;
  191889. }
  191890. }
  191891. /* This inverts the alpha channel in RRGGBBAA */
  191892. else
  191893. {
  191894. png_bytep sp = row + row_info->rowbytes;
  191895. png_bytep dp = sp;
  191896. png_uint_32 i;
  191897. for (i = 0; i < row_width; i++)
  191898. {
  191899. *(--dp) = (png_byte)(255 - *(--sp));
  191900. *(--dp) = (png_byte)(255 - *(--sp));
  191901. /* This does nothing:
  191902. *(--dp) = *(--sp);
  191903. *(--dp) = *(--sp);
  191904. *(--dp) = *(--sp);
  191905. *(--dp) = *(--sp);
  191906. *(--dp) = *(--sp);
  191907. *(--dp) = *(--sp);
  191908. We can replace it with:
  191909. */
  191910. sp-=6;
  191911. dp=sp;
  191912. }
  191913. }
  191914. }
  191915. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191916. {
  191917. /* This inverts the alpha channel in GA */
  191918. if (row_info->bit_depth == 8)
  191919. {
  191920. png_bytep sp = row + row_info->rowbytes;
  191921. png_bytep dp = sp;
  191922. png_uint_32 i;
  191923. for (i = 0; i < row_width; i++)
  191924. {
  191925. *(--dp) = (png_byte)(255 - *(--sp));
  191926. *(--dp) = *(--sp);
  191927. }
  191928. }
  191929. /* This inverts the alpha channel in GGAA */
  191930. else
  191931. {
  191932. png_bytep sp = row + row_info->rowbytes;
  191933. png_bytep dp = sp;
  191934. png_uint_32 i;
  191935. for (i = 0; i < row_width; i++)
  191936. {
  191937. *(--dp) = (png_byte)(255 - *(--sp));
  191938. *(--dp) = (png_byte)(255 - *(--sp));
  191939. /*
  191940. *(--dp) = *(--sp);
  191941. *(--dp) = *(--sp);
  191942. */
  191943. sp-=2;
  191944. dp=sp;
  191945. }
  191946. }
  191947. }
  191948. }
  191949. }
  191950. #endif
  191951. #if defined(PNG_READ_FILLER_SUPPORTED)
  191952. /* Add filler channel if we have RGB color */
  191953. void /* PRIVATE */
  191954. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191955. png_uint_32 filler, png_uint_32 flags)
  191956. {
  191957. png_uint_32 i;
  191958. png_uint_32 row_width = row_info->width;
  191959. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191960. png_byte lo_filler = (png_byte)(filler & 0xff);
  191961. png_debug(1, "in png_do_read_filler\n");
  191962. if (
  191963. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191964. row != NULL && row_info != NULL &&
  191965. #endif
  191966. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191967. {
  191968. if(row_info->bit_depth == 8)
  191969. {
  191970. /* This changes the data from G to GX */
  191971. if (flags & PNG_FLAG_FILLER_AFTER)
  191972. {
  191973. png_bytep sp = row + (png_size_t)row_width;
  191974. png_bytep dp = sp + (png_size_t)row_width;
  191975. for (i = 1; i < row_width; i++)
  191976. {
  191977. *(--dp) = lo_filler;
  191978. *(--dp) = *(--sp);
  191979. }
  191980. *(--dp) = lo_filler;
  191981. row_info->channels = 2;
  191982. row_info->pixel_depth = 16;
  191983. row_info->rowbytes = row_width * 2;
  191984. }
  191985. /* This changes the data from G to XG */
  191986. else
  191987. {
  191988. png_bytep sp = row + (png_size_t)row_width;
  191989. png_bytep dp = sp + (png_size_t)row_width;
  191990. for (i = 0; i < row_width; i++)
  191991. {
  191992. *(--dp) = *(--sp);
  191993. *(--dp) = lo_filler;
  191994. }
  191995. row_info->channels = 2;
  191996. row_info->pixel_depth = 16;
  191997. row_info->rowbytes = row_width * 2;
  191998. }
  191999. }
  192000. else if(row_info->bit_depth == 16)
  192001. {
  192002. /* This changes the data from GG to GGXX */
  192003. if (flags & PNG_FLAG_FILLER_AFTER)
  192004. {
  192005. png_bytep sp = row + (png_size_t)row_width * 2;
  192006. png_bytep dp = sp + (png_size_t)row_width * 2;
  192007. for (i = 1; i < row_width; i++)
  192008. {
  192009. *(--dp) = hi_filler;
  192010. *(--dp) = lo_filler;
  192011. *(--dp) = *(--sp);
  192012. *(--dp) = *(--sp);
  192013. }
  192014. *(--dp) = hi_filler;
  192015. *(--dp) = lo_filler;
  192016. row_info->channels = 2;
  192017. row_info->pixel_depth = 32;
  192018. row_info->rowbytes = row_width * 4;
  192019. }
  192020. /* This changes the data from GG to XXGG */
  192021. else
  192022. {
  192023. png_bytep sp = row + (png_size_t)row_width * 2;
  192024. png_bytep dp = sp + (png_size_t)row_width * 2;
  192025. for (i = 0; i < row_width; i++)
  192026. {
  192027. *(--dp) = *(--sp);
  192028. *(--dp) = *(--sp);
  192029. *(--dp) = hi_filler;
  192030. *(--dp) = lo_filler;
  192031. }
  192032. row_info->channels = 2;
  192033. row_info->pixel_depth = 32;
  192034. row_info->rowbytes = row_width * 4;
  192035. }
  192036. }
  192037. } /* COLOR_TYPE == GRAY */
  192038. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192039. {
  192040. if(row_info->bit_depth == 8)
  192041. {
  192042. /* This changes the data from RGB to RGBX */
  192043. if (flags & PNG_FLAG_FILLER_AFTER)
  192044. {
  192045. png_bytep sp = row + (png_size_t)row_width * 3;
  192046. png_bytep dp = sp + (png_size_t)row_width;
  192047. for (i = 1; i < row_width; i++)
  192048. {
  192049. *(--dp) = lo_filler;
  192050. *(--dp) = *(--sp);
  192051. *(--dp) = *(--sp);
  192052. *(--dp) = *(--sp);
  192053. }
  192054. *(--dp) = lo_filler;
  192055. row_info->channels = 4;
  192056. row_info->pixel_depth = 32;
  192057. row_info->rowbytes = row_width * 4;
  192058. }
  192059. /* This changes the data from RGB to XRGB */
  192060. else
  192061. {
  192062. png_bytep sp = row + (png_size_t)row_width * 3;
  192063. png_bytep dp = sp + (png_size_t)row_width;
  192064. for (i = 0; i < row_width; i++)
  192065. {
  192066. *(--dp) = *(--sp);
  192067. *(--dp) = *(--sp);
  192068. *(--dp) = *(--sp);
  192069. *(--dp) = lo_filler;
  192070. }
  192071. row_info->channels = 4;
  192072. row_info->pixel_depth = 32;
  192073. row_info->rowbytes = row_width * 4;
  192074. }
  192075. }
  192076. else if(row_info->bit_depth == 16)
  192077. {
  192078. /* This changes the data from RRGGBB to RRGGBBXX */
  192079. if (flags & PNG_FLAG_FILLER_AFTER)
  192080. {
  192081. png_bytep sp = row + (png_size_t)row_width * 6;
  192082. png_bytep dp = sp + (png_size_t)row_width * 2;
  192083. for (i = 1; i < row_width; i++)
  192084. {
  192085. *(--dp) = hi_filler;
  192086. *(--dp) = lo_filler;
  192087. *(--dp) = *(--sp);
  192088. *(--dp) = *(--sp);
  192089. *(--dp) = *(--sp);
  192090. *(--dp) = *(--sp);
  192091. *(--dp) = *(--sp);
  192092. *(--dp) = *(--sp);
  192093. }
  192094. *(--dp) = hi_filler;
  192095. *(--dp) = lo_filler;
  192096. row_info->channels = 4;
  192097. row_info->pixel_depth = 64;
  192098. row_info->rowbytes = row_width * 8;
  192099. }
  192100. /* This changes the data from RRGGBB to XXRRGGBB */
  192101. else
  192102. {
  192103. png_bytep sp = row + (png_size_t)row_width * 6;
  192104. png_bytep dp = sp + (png_size_t)row_width * 2;
  192105. for (i = 0; i < row_width; i++)
  192106. {
  192107. *(--dp) = *(--sp);
  192108. *(--dp) = *(--sp);
  192109. *(--dp) = *(--sp);
  192110. *(--dp) = *(--sp);
  192111. *(--dp) = *(--sp);
  192112. *(--dp) = *(--sp);
  192113. *(--dp) = hi_filler;
  192114. *(--dp) = lo_filler;
  192115. }
  192116. row_info->channels = 4;
  192117. row_info->pixel_depth = 64;
  192118. row_info->rowbytes = row_width * 8;
  192119. }
  192120. }
  192121. } /* COLOR_TYPE == RGB */
  192122. }
  192123. #endif
  192124. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192125. /* expand grayscale files to RGB, with or without alpha */
  192126. void /* PRIVATE */
  192127. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192128. {
  192129. png_uint_32 i;
  192130. png_uint_32 row_width = row_info->width;
  192131. png_debug(1, "in png_do_gray_to_rgb\n");
  192132. if (row_info->bit_depth >= 8 &&
  192133. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192134. row != NULL && row_info != NULL &&
  192135. #endif
  192136. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192137. {
  192138. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192139. {
  192140. if (row_info->bit_depth == 8)
  192141. {
  192142. png_bytep sp = row + (png_size_t)row_width - 1;
  192143. png_bytep dp = sp + (png_size_t)row_width * 2;
  192144. for (i = 0; i < row_width; i++)
  192145. {
  192146. *(dp--) = *sp;
  192147. *(dp--) = *sp;
  192148. *(dp--) = *(sp--);
  192149. }
  192150. }
  192151. else
  192152. {
  192153. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192154. png_bytep dp = sp + (png_size_t)row_width * 4;
  192155. for (i = 0; i < row_width; i++)
  192156. {
  192157. *(dp--) = *sp;
  192158. *(dp--) = *(sp - 1);
  192159. *(dp--) = *sp;
  192160. *(dp--) = *(sp - 1);
  192161. *(dp--) = *(sp--);
  192162. *(dp--) = *(sp--);
  192163. }
  192164. }
  192165. }
  192166. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192167. {
  192168. if (row_info->bit_depth == 8)
  192169. {
  192170. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192171. png_bytep dp = sp + (png_size_t)row_width * 2;
  192172. for (i = 0; i < row_width; i++)
  192173. {
  192174. *(dp--) = *(sp--);
  192175. *(dp--) = *sp;
  192176. *(dp--) = *sp;
  192177. *(dp--) = *(sp--);
  192178. }
  192179. }
  192180. else
  192181. {
  192182. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192183. png_bytep dp = sp + (png_size_t)row_width * 4;
  192184. for (i = 0; i < row_width; i++)
  192185. {
  192186. *(dp--) = *(sp--);
  192187. *(dp--) = *(sp--);
  192188. *(dp--) = *sp;
  192189. *(dp--) = *(sp - 1);
  192190. *(dp--) = *sp;
  192191. *(dp--) = *(sp - 1);
  192192. *(dp--) = *(sp--);
  192193. *(dp--) = *(sp--);
  192194. }
  192195. }
  192196. }
  192197. row_info->channels += (png_byte)2;
  192198. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192199. row_info->pixel_depth = (png_byte)(row_info->channels *
  192200. row_info->bit_depth);
  192201. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192202. }
  192203. }
  192204. #endif
  192205. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192206. /* reduce RGB files to grayscale, with or without alpha
  192207. * using the equation given in Poynton's ColorFAQ at
  192208. * <http://www.inforamp.net/~poynton/>
  192209. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192210. *
  192211. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192212. *
  192213. * We approximate this with
  192214. *
  192215. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192216. *
  192217. * which can be expressed with integers as
  192218. *
  192219. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192220. *
  192221. * The calculation is to be done in a linear colorspace.
  192222. *
  192223. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192224. */
  192225. int /* PRIVATE */
  192226. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192227. {
  192228. png_uint_32 i;
  192229. png_uint_32 row_width = row_info->width;
  192230. int rgb_error = 0;
  192231. png_debug(1, "in png_do_rgb_to_gray\n");
  192232. if (
  192233. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192234. row != NULL && row_info != NULL &&
  192235. #endif
  192236. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192237. {
  192238. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192239. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192240. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192241. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192242. {
  192243. if (row_info->bit_depth == 8)
  192244. {
  192245. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192246. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192247. {
  192248. png_bytep sp = row;
  192249. png_bytep dp = row;
  192250. for (i = 0; i < row_width; i++)
  192251. {
  192252. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192253. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192254. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192255. if(red != green || red != blue)
  192256. {
  192257. rgb_error |= 1;
  192258. *(dp++) = png_ptr->gamma_from_1[
  192259. (rc*red+gc*green+bc*blue)>>15];
  192260. }
  192261. else
  192262. *(dp++) = *(sp-1);
  192263. }
  192264. }
  192265. else
  192266. #endif
  192267. {
  192268. png_bytep sp = row;
  192269. png_bytep dp = row;
  192270. for (i = 0; i < row_width; i++)
  192271. {
  192272. png_byte red = *(sp++);
  192273. png_byte green = *(sp++);
  192274. png_byte blue = *(sp++);
  192275. if(red != green || red != blue)
  192276. {
  192277. rgb_error |= 1;
  192278. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192279. }
  192280. else
  192281. *(dp++) = *(sp-1);
  192282. }
  192283. }
  192284. }
  192285. else /* RGB bit_depth == 16 */
  192286. {
  192287. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192288. if (png_ptr->gamma_16_to_1 != NULL &&
  192289. png_ptr->gamma_16_from_1 != NULL)
  192290. {
  192291. png_bytep sp = row;
  192292. png_bytep dp = row;
  192293. for (i = 0; i < row_width; i++)
  192294. {
  192295. png_uint_16 red, green, blue, w;
  192296. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192297. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192298. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192299. if(red == green && red == blue)
  192300. w = red;
  192301. else
  192302. {
  192303. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192304. png_ptr->gamma_shift][red>>8];
  192305. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192306. png_ptr->gamma_shift][green>>8];
  192307. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192308. png_ptr->gamma_shift][blue>>8];
  192309. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192310. + bc*blue_1)>>15);
  192311. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192312. png_ptr->gamma_shift][gray16 >> 8];
  192313. rgb_error |= 1;
  192314. }
  192315. *(dp++) = (png_byte)((w>>8) & 0xff);
  192316. *(dp++) = (png_byte)(w & 0xff);
  192317. }
  192318. }
  192319. else
  192320. #endif
  192321. {
  192322. png_bytep sp = row;
  192323. png_bytep dp = row;
  192324. for (i = 0; i < row_width; i++)
  192325. {
  192326. png_uint_16 red, green, blue, gray16;
  192327. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192328. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192329. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192330. if(red != green || red != blue)
  192331. rgb_error |= 1;
  192332. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192333. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192334. *(dp++) = (png_byte)(gray16 & 0xff);
  192335. }
  192336. }
  192337. }
  192338. }
  192339. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192340. {
  192341. if (row_info->bit_depth == 8)
  192342. {
  192343. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192344. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192345. {
  192346. png_bytep sp = row;
  192347. png_bytep dp = row;
  192348. for (i = 0; i < row_width; i++)
  192349. {
  192350. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192351. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192352. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192353. if(red != green || red != blue)
  192354. rgb_error |= 1;
  192355. *(dp++) = png_ptr->gamma_from_1
  192356. [(rc*red + gc*green + bc*blue)>>15];
  192357. *(dp++) = *(sp++); /* alpha */
  192358. }
  192359. }
  192360. else
  192361. #endif
  192362. {
  192363. png_bytep sp = row;
  192364. png_bytep dp = row;
  192365. for (i = 0; i < row_width; i++)
  192366. {
  192367. png_byte red = *(sp++);
  192368. png_byte green = *(sp++);
  192369. png_byte blue = *(sp++);
  192370. if(red != green || red != blue)
  192371. rgb_error |= 1;
  192372. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192373. *(dp++) = *(sp++); /* alpha */
  192374. }
  192375. }
  192376. }
  192377. else /* RGBA bit_depth == 16 */
  192378. {
  192379. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192380. if (png_ptr->gamma_16_to_1 != NULL &&
  192381. png_ptr->gamma_16_from_1 != NULL)
  192382. {
  192383. png_bytep sp = row;
  192384. png_bytep dp = row;
  192385. for (i = 0; i < row_width; i++)
  192386. {
  192387. png_uint_16 red, green, blue, w;
  192388. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192389. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192390. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192391. if(red == green && red == blue)
  192392. w = red;
  192393. else
  192394. {
  192395. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192396. png_ptr->gamma_shift][red>>8];
  192397. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192398. png_ptr->gamma_shift][green>>8];
  192399. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192400. png_ptr->gamma_shift][blue>>8];
  192401. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192402. + gc * green_1 + bc * blue_1)>>15);
  192403. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192404. png_ptr->gamma_shift][gray16 >> 8];
  192405. rgb_error |= 1;
  192406. }
  192407. *(dp++) = (png_byte)((w>>8) & 0xff);
  192408. *(dp++) = (png_byte)(w & 0xff);
  192409. *(dp++) = *(sp++); /* alpha */
  192410. *(dp++) = *(sp++);
  192411. }
  192412. }
  192413. else
  192414. #endif
  192415. {
  192416. png_bytep sp = row;
  192417. png_bytep dp = row;
  192418. for (i = 0; i < row_width; i++)
  192419. {
  192420. png_uint_16 red, green, blue, gray16;
  192421. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192422. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192423. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192424. if(red != green || red != blue)
  192425. rgb_error |= 1;
  192426. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192427. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192428. *(dp++) = (png_byte)(gray16 & 0xff);
  192429. *(dp++) = *(sp++); /* alpha */
  192430. *(dp++) = *(sp++);
  192431. }
  192432. }
  192433. }
  192434. }
  192435. row_info->channels -= (png_byte)2;
  192436. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192437. row_info->pixel_depth = (png_byte)(row_info->channels *
  192438. row_info->bit_depth);
  192439. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192440. }
  192441. return rgb_error;
  192442. }
  192443. #endif
  192444. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192445. * large of png_color. This lets grayscale images be treated as
  192446. * paletted. Most useful for gamma correction and simplification
  192447. * of code.
  192448. */
  192449. void PNGAPI
  192450. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192451. {
  192452. int num_palette;
  192453. int color_inc;
  192454. int i;
  192455. int v;
  192456. png_debug(1, "in png_do_build_grayscale_palette\n");
  192457. if (palette == NULL)
  192458. return;
  192459. switch (bit_depth)
  192460. {
  192461. case 1:
  192462. num_palette = 2;
  192463. color_inc = 0xff;
  192464. break;
  192465. case 2:
  192466. num_palette = 4;
  192467. color_inc = 0x55;
  192468. break;
  192469. case 4:
  192470. num_palette = 16;
  192471. color_inc = 0x11;
  192472. break;
  192473. case 8:
  192474. num_palette = 256;
  192475. color_inc = 1;
  192476. break;
  192477. default:
  192478. num_palette = 0;
  192479. color_inc = 0;
  192480. break;
  192481. }
  192482. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192483. {
  192484. palette[i].red = (png_byte)v;
  192485. palette[i].green = (png_byte)v;
  192486. palette[i].blue = (png_byte)v;
  192487. }
  192488. }
  192489. /* This function is currently unused. Do we really need it? */
  192490. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192491. void /* PRIVATE */
  192492. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192493. int num_palette)
  192494. {
  192495. png_debug(1, "in png_correct_palette\n");
  192496. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192497. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192498. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192499. {
  192500. png_color back, back_1;
  192501. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192502. {
  192503. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192504. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192505. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192506. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192507. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192508. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192509. }
  192510. else
  192511. {
  192512. double g;
  192513. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192514. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192515. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192516. {
  192517. back.red = png_ptr->background.red;
  192518. back.green = png_ptr->background.green;
  192519. back.blue = png_ptr->background.blue;
  192520. }
  192521. else
  192522. {
  192523. back.red =
  192524. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192525. 255.0 + 0.5);
  192526. back.green =
  192527. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192528. 255.0 + 0.5);
  192529. back.blue =
  192530. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192531. 255.0 + 0.5);
  192532. }
  192533. g = 1.0 / png_ptr->background_gamma;
  192534. back_1.red =
  192535. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192536. 255.0 + 0.5);
  192537. back_1.green =
  192538. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192539. 255.0 + 0.5);
  192540. back_1.blue =
  192541. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192542. 255.0 + 0.5);
  192543. }
  192544. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192545. {
  192546. png_uint_32 i;
  192547. for (i = 0; i < (png_uint_32)num_palette; i++)
  192548. {
  192549. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192550. {
  192551. palette[i] = back;
  192552. }
  192553. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192554. {
  192555. png_byte v, w;
  192556. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192557. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192558. palette[i].red = png_ptr->gamma_from_1[w];
  192559. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192560. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192561. palette[i].green = png_ptr->gamma_from_1[w];
  192562. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192563. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192564. palette[i].blue = png_ptr->gamma_from_1[w];
  192565. }
  192566. else
  192567. {
  192568. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192569. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192570. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192571. }
  192572. }
  192573. }
  192574. else
  192575. {
  192576. int i;
  192577. for (i = 0; i < num_palette; i++)
  192578. {
  192579. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192580. {
  192581. palette[i] = back;
  192582. }
  192583. else
  192584. {
  192585. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192586. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192587. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192588. }
  192589. }
  192590. }
  192591. }
  192592. else
  192593. #endif
  192594. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192595. if (png_ptr->transformations & PNG_GAMMA)
  192596. {
  192597. int i;
  192598. for (i = 0; i < num_palette; i++)
  192599. {
  192600. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192601. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192602. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192603. }
  192604. }
  192605. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192606. else
  192607. #endif
  192608. #endif
  192609. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192610. if (png_ptr->transformations & PNG_BACKGROUND)
  192611. {
  192612. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192613. {
  192614. png_color back;
  192615. back.red = (png_byte)png_ptr->background.red;
  192616. back.green = (png_byte)png_ptr->background.green;
  192617. back.blue = (png_byte)png_ptr->background.blue;
  192618. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192619. {
  192620. if (png_ptr->trans[i] == 0)
  192621. {
  192622. palette[i].red = back.red;
  192623. palette[i].green = back.green;
  192624. palette[i].blue = back.blue;
  192625. }
  192626. else if (png_ptr->trans[i] != 0xff)
  192627. {
  192628. png_composite(palette[i].red, png_ptr->palette[i].red,
  192629. png_ptr->trans[i], back.red);
  192630. png_composite(palette[i].green, png_ptr->palette[i].green,
  192631. png_ptr->trans[i], back.green);
  192632. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192633. png_ptr->trans[i], back.blue);
  192634. }
  192635. }
  192636. }
  192637. else /* assume grayscale palette (what else could it be?) */
  192638. {
  192639. int i;
  192640. for (i = 0; i < num_palette; i++)
  192641. {
  192642. if (i == (png_byte)png_ptr->trans_values.gray)
  192643. {
  192644. palette[i].red = (png_byte)png_ptr->background.red;
  192645. palette[i].green = (png_byte)png_ptr->background.green;
  192646. palette[i].blue = (png_byte)png_ptr->background.blue;
  192647. }
  192648. }
  192649. }
  192650. }
  192651. #endif
  192652. }
  192653. #endif
  192654. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192655. /* Replace any alpha or transparency with the supplied background color.
  192656. * "background" is already in the screen gamma, while "background_1" is
  192657. * at a gamma of 1.0. Paletted files have already been taken care of.
  192658. */
  192659. void /* PRIVATE */
  192660. png_do_background(png_row_infop row_info, png_bytep row,
  192661. png_color_16p trans_values, png_color_16p background
  192662. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192663. , png_color_16p background_1,
  192664. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192665. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192666. png_uint_16pp gamma_16_to_1, int gamma_shift
  192667. #endif
  192668. )
  192669. {
  192670. png_bytep sp, dp;
  192671. png_uint_32 i;
  192672. png_uint_32 row_width=row_info->width;
  192673. int shift;
  192674. png_debug(1, "in png_do_background\n");
  192675. if (background != NULL &&
  192676. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192677. row != NULL && row_info != NULL &&
  192678. #endif
  192679. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192680. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192681. {
  192682. switch (row_info->color_type)
  192683. {
  192684. case PNG_COLOR_TYPE_GRAY:
  192685. {
  192686. switch (row_info->bit_depth)
  192687. {
  192688. case 1:
  192689. {
  192690. sp = row;
  192691. shift = 7;
  192692. for (i = 0; i < row_width; i++)
  192693. {
  192694. if ((png_uint_16)((*sp >> shift) & 0x01)
  192695. == trans_values->gray)
  192696. {
  192697. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192698. *sp |= (png_byte)(background->gray << shift);
  192699. }
  192700. if (!shift)
  192701. {
  192702. shift = 7;
  192703. sp++;
  192704. }
  192705. else
  192706. shift--;
  192707. }
  192708. break;
  192709. }
  192710. case 2:
  192711. {
  192712. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192713. if (gamma_table != NULL)
  192714. {
  192715. sp = row;
  192716. shift = 6;
  192717. for (i = 0; i < row_width; i++)
  192718. {
  192719. if ((png_uint_16)((*sp >> shift) & 0x03)
  192720. == trans_values->gray)
  192721. {
  192722. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192723. *sp |= (png_byte)(background->gray << shift);
  192724. }
  192725. else
  192726. {
  192727. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192728. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192729. (p << 4) | (p << 6)] >> 6) & 0x03);
  192730. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192731. *sp |= (png_byte)(g << shift);
  192732. }
  192733. if (!shift)
  192734. {
  192735. shift = 6;
  192736. sp++;
  192737. }
  192738. else
  192739. shift -= 2;
  192740. }
  192741. }
  192742. else
  192743. #endif
  192744. {
  192745. sp = row;
  192746. shift = 6;
  192747. for (i = 0; i < row_width; i++)
  192748. {
  192749. if ((png_uint_16)((*sp >> shift) & 0x03)
  192750. == trans_values->gray)
  192751. {
  192752. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192753. *sp |= (png_byte)(background->gray << shift);
  192754. }
  192755. if (!shift)
  192756. {
  192757. shift = 6;
  192758. sp++;
  192759. }
  192760. else
  192761. shift -= 2;
  192762. }
  192763. }
  192764. break;
  192765. }
  192766. case 4:
  192767. {
  192768. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192769. if (gamma_table != NULL)
  192770. {
  192771. sp = row;
  192772. shift = 4;
  192773. for (i = 0; i < row_width; i++)
  192774. {
  192775. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192776. == trans_values->gray)
  192777. {
  192778. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192779. *sp |= (png_byte)(background->gray << shift);
  192780. }
  192781. else
  192782. {
  192783. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192784. png_byte g = (png_byte)((gamma_table[p |
  192785. (p << 4)] >> 4) & 0x0f);
  192786. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192787. *sp |= (png_byte)(g << shift);
  192788. }
  192789. if (!shift)
  192790. {
  192791. shift = 4;
  192792. sp++;
  192793. }
  192794. else
  192795. shift -= 4;
  192796. }
  192797. }
  192798. else
  192799. #endif
  192800. {
  192801. sp = row;
  192802. shift = 4;
  192803. for (i = 0; i < row_width; i++)
  192804. {
  192805. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192806. == trans_values->gray)
  192807. {
  192808. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192809. *sp |= (png_byte)(background->gray << shift);
  192810. }
  192811. if (!shift)
  192812. {
  192813. shift = 4;
  192814. sp++;
  192815. }
  192816. else
  192817. shift -= 4;
  192818. }
  192819. }
  192820. break;
  192821. }
  192822. case 8:
  192823. {
  192824. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192825. if (gamma_table != NULL)
  192826. {
  192827. sp = row;
  192828. for (i = 0; i < row_width; i++, sp++)
  192829. {
  192830. if (*sp == trans_values->gray)
  192831. {
  192832. *sp = (png_byte)background->gray;
  192833. }
  192834. else
  192835. {
  192836. *sp = gamma_table[*sp];
  192837. }
  192838. }
  192839. }
  192840. else
  192841. #endif
  192842. {
  192843. sp = row;
  192844. for (i = 0; i < row_width; i++, sp++)
  192845. {
  192846. if (*sp == trans_values->gray)
  192847. {
  192848. *sp = (png_byte)background->gray;
  192849. }
  192850. }
  192851. }
  192852. break;
  192853. }
  192854. case 16:
  192855. {
  192856. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192857. if (gamma_16 != NULL)
  192858. {
  192859. sp = row;
  192860. for (i = 0; i < row_width; i++, sp += 2)
  192861. {
  192862. png_uint_16 v;
  192863. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192864. if (v == trans_values->gray)
  192865. {
  192866. /* background is already in screen gamma */
  192867. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192868. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192869. }
  192870. else
  192871. {
  192872. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192873. *sp = (png_byte)((v >> 8) & 0xff);
  192874. *(sp + 1) = (png_byte)(v & 0xff);
  192875. }
  192876. }
  192877. }
  192878. else
  192879. #endif
  192880. {
  192881. sp = row;
  192882. for (i = 0; i < row_width; i++, sp += 2)
  192883. {
  192884. png_uint_16 v;
  192885. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192886. if (v == trans_values->gray)
  192887. {
  192888. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192889. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192890. }
  192891. }
  192892. }
  192893. break;
  192894. }
  192895. }
  192896. break;
  192897. }
  192898. case PNG_COLOR_TYPE_RGB:
  192899. {
  192900. if (row_info->bit_depth == 8)
  192901. {
  192902. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192903. if (gamma_table != NULL)
  192904. {
  192905. sp = row;
  192906. for (i = 0; i < row_width; i++, sp += 3)
  192907. {
  192908. if (*sp == trans_values->red &&
  192909. *(sp + 1) == trans_values->green &&
  192910. *(sp + 2) == trans_values->blue)
  192911. {
  192912. *sp = (png_byte)background->red;
  192913. *(sp + 1) = (png_byte)background->green;
  192914. *(sp + 2) = (png_byte)background->blue;
  192915. }
  192916. else
  192917. {
  192918. *sp = gamma_table[*sp];
  192919. *(sp + 1) = gamma_table[*(sp + 1)];
  192920. *(sp + 2) = gamma_table[*(sp + 2)];
  192921. }
  192922. }
  192923. }
  192924. else
  192925. #endif
  192926. {
  192927. sp = row;
  192928. for (i = 0; i < row_width; i++, sp += 3)
  192929. {
  192930. if (*sp == trans_values->red &&
  192931. *(sp + 1) == trans_values->green &&
  192932. *(sp + 2) == trans_values->blue)
  192933. {
  192934. *sp = (png_byte)background->red;
  192935. *(sp + 1) = (png_byte)background->green;
  192936. *(sp + 2) = (png_byte)background->blue;
  192937. }
  192938. }
  192939. }
  192940. }
  192941. else /* if (row_info->bit_depth == 16) */
  192942. {
  192943. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192944. if (gamma_16 != NULL)
  192945. {
  192946. sp = row;
  192947. for (i = 0; i < row_width; i++, sp += 6)
  192948. {
  192949. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192950. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192951. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192952. if (r == trans_values->red && g == trans_values->green &&
  192953. b == trans_values->blue)
  192954. {
  192955. /* background is already in screen gamma */
  192956. *sp = (png_byte)((background->red >> 8) & 0xff);
  192957. *(sp + 1) = (png_byte)(background->red & 0xff);
  192958. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192959. *(sp + 3) = (png_byte)(background->green & 0xff);
  192960. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192961. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192962. }
  192963. else
  192964. {
  192965. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192966. *sp = (png_byte)((v >> 8) & 0xff);
  192967. *(sp + 1) = (png_byte)(v & 0xff);
  192968. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192969. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192970. *(sp + 3) = (png_byte)(v & 0xff);
  192971. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192972. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192973. *(sp + 5) = (png_byte)(v & 0xff);
  192974. }
  192975. }
  192976. }
  192977. else
  192978. #endif
  192979. {
  192980. sp = row;
  192981. for (i = 0; i < row_width; i++, sp += 6)
  192982. {
  192983. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192984. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192985. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192986. if (r == trans_values->red && g == trans_values->green &&
  192987. b == trans_values->blue)
  192988. {
  192989. *sp = (png_byte)((background->red >> 8) & 0xff);
  192990. *(sp + 1) = (png_byte)(background->red & 0xff);
  192991. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192992. *(sp + 3) = (png_byte)(background->green & 0xff);
  192993. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192994. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192995. }
  192996. }
  192997. }
  192998. }
  192999. break;
  193000. }
  193001. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193002. {
  193003. if (row_info->bit_depth == 8)
  193004. {
  193005. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193006. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193007. gamma_table != NULL)
  193008. {
  193009. sp = row;
  193010. dp = row;
  193011. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193012. {
  193013. png_uint_16 a = *(sp + 1);
  193014. if (a == 0xff)
  193015. {
  193016. *dp = gamma_table[*sp];
  193017. }
  193018. else if (a == 0)
  193019. {
  193020. /* background is already in screen gamma */
  193021. *dp = (png_byte)background->gray;
  193022. }
  193023. else
  193024. {
  193025. png_byte v, w;
  193026. v = gamma_to_1[*sp];
  193027. png_composite(w, v, a, background_1->gray);
  193028. *dp = gamma_from_1[w];
  193029. }
  193030. }
  193031. }
  193032. else
  193033. #endif
  193034. {
  193035. sp = row;
  193036. dp = row;
  193037. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193038. {
  193039. png_byte a = *(sp + 1);
  193040. if (a == 0xff)
  193041. {
  193042. *dp = *sp;
  193043. }
  193044. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193045. else if (a == 0)
  193046. {
  193047. *dp = (png_byte)background->gray;
  193048. }
  193049. else
  193050. {
  193051. png_composite(*dp, *sp, a, background_1->gray);
  193052. }
  193053. #else
  193054. *dp = (png_byte)background->gray;
  193055. #endif
  193056. }
  193057. }
  193058. }
  193059. else /* if (png_ptr->bit_depth == 16) */
  193060. {
  193061. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193062. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193063. gamma_16_to_1 != NULL)
  193064. {
  193065. sp = row;
  193066. dp = row;
  193067. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193068. {
  193069. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193070. if (a == (png_uint_16)0xffff)
  193071. {
  193072. png_uint_16 v;
  193073. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193074. *dp = (png_byte)((v >> 8) & 0xff);
  193075. *(dp + 1) = (png_byte)(v & 0xff);
  193076. }
  193077. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193078. else if (a == 0)
  193079. #else
  193080. else
  193081. #endif
  193082. {
  193083. /* background is already in screen gamma */
  193084. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193085. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193086. }
  193087. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193088. else
  193089. {
  193090. png_uint_16 g, v, w;
  193091. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193092. png_composite_16(v, g, a, background_1->gray);
  193093. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193094. *dp = (png_byte)((w >> 8) & 0xff);
  193095. *(dp + 1) = (png_byte)(w & 0xff);
  193096. }
  193097. #endif
  193098. }
  193099. }
  193100. else
  193101. #endif
  193102. {
  193103. sp = row;
  193104. dp = row;
  193105. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193106. {
  193107. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193108. if (a == (png_uint_16)0xffff)
  193109. {
  193110. png_memcpy(dp, sp, 2);
  193111. }
  193112. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193113. else if (a == 0)
  193114. #else
  193115. else
  193116. #endif
  193117. {
  193118. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193119. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193120. }
  193121. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193122. else
  193123. {
  193124. png_uint_16 g, v;
  193125. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193126. png_composite_16(v, g, a, background_1->gray);
  193127. *dp = (png_byte)((v >> 8) & 0xff);
  193128. *(dp + 1) = (png_byte)(v & 0xff);
  193129. }
  193130. #endif
  193131. }
  193132. }
  193133. }
  193134. break;
  193135. }
  193136. case PNG_COLOR_TYPE_RGB_ALPHA:
  193137. {
  193138. if (row_info->bit_depth == 8)
  193139. {
  193140. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193141. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193142. gamma_table != NULL)
  193143. {
  193144. sp = row;
  193145. dp = row;
  193146. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193147. {
  193148. png_byte a = *(sp + 3);
  193149. if (a == 0xff)
  193150. {
  193151. *dp = gamma_table[*sp];
  193152. *(dp + 1) = gamma_table[*(sp + 1)];
  193153. *(dp + 2) = gamma_table[*(sp + 2)];
  193154. }
  193155. else if (a == 0)
  193156. {
  193157. /* background is already in screen gamma */
  193158. *dp = (png_byte)background->red;
  193159. *(dp + 1) = (png_byte)background->green;
  193160. *(dp + 2) = (png_byte)background->blue;
  193161. }
  193162. else
  193163. {
  193164. png_byte v, w;
  193165. v = gamma_to_1[*sp];
  193166. png_composite(w, v, a, background_1->red);
  193167. *dp = gamma_from_1[w];
  193168. v = gamma_to_1[*(sp + 1)];
  193169. png_composite(w, v, a, background_1->green);
  193170. *(dp + 1) = gamma_from_1[w];
  193171. v = gamma_to_1[*(sp + 2)];
  193172. png_composite(w, v, a, background_1->blue);
  193173. *(dp + 2) = gamma_from_1[w];
  193174. }
  193175. }
  193176. }
  193177. else
  193178. #endif
  193179. {
  193180. sp = row;
  193181. dp = row;
  193182. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193183. {
  193184. png_byte a = *(sp + 3);
  193185. if (a == 0xff)
  193186. {
  193187. *dp = *sp;
  193188. *(dp + 1) = *(sp + 1);
  193189. *(dp + 2) = *(sp + 2);
  193190. }
  193191. else if (a == 0)
  193192. {
  193193. *dp = (png_byte)background->red;
  193194. *(dp + 1) = (png_byte)background->green;
  193195. *(dp + 2) = (png_byte)background->blue;
  193196. }
  193197. else
  193198. {
  193199. png_composite(*dp, *sp, a, background->red);
  193200. png_composite(*(dp + 1), *(sp + 1), a,
  193201. background->green);
  193202. png_composite(*(dp + 2), *(sp + 2), a,
  193203. background->blue);
  193204. }
  193205. }
  193206. }
  193207. }
  193208. else /* if (row_info->bit_depth == 16) */
  193209. {
  193210. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193211. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193212. gamma_16_to_1 != NULL)
  193213. {
  193214. sp = row;
  193215. dp = row;
  193216. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193217. {
  193218. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193219. << 8) + (png_uint_16)(*(sp + 7)));
  193220. if (a == (png_uint_16)0xffff)
  193221. {
  193222. png_uint_16 v;
  193223. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193224. *dp = (png_byte)((v >> 8) & 0xff);
  193225. *(dp + 1) = (png_byte)(v & 0xff);
  193226. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193227. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193228. *(dp + 3) = (png_byte)(v & 0xff);
  193229. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193230. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193231. *(dp + 5) = (png_byte)(v & 0xff);
  193232. }
  193233. else if (a == 0)
  193234. {
  193235. /* background is already in screen gamma */
  193236. *dp = (png_byte)((background->red >> 8) & 0xff);
  193237. *(dp + 1) = (png_byte)(background->red & 0xff);
  193238. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193239. *(dp + 3) = (png_byte)(background->green & 0xff);
  193240. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193241. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193242. }
  193243. else
  193244. {
  193245. png_uint_16 v, w, x;
  193246. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193247. png_composite_16(w, v, a, background_1->red);
  193248. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193249. *dp = (png_byte)((x >> 8) & 0xff);
  193250. *(dp + 1) = (png_byte)(x & 0xff);
  193251. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193252. png_composite_16(w, v, a, background_1->green);
  193253. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193254. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193255. *(dp + 3) = (png_byte)(x & 0xff);
  193256. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193257. png_composite_16(w, v, a, background_1->blue);
  193258. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193259. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193260. *(dp + 5) = (png_byte)(x & 0xff);
  193261. }
  193262. }
  193263. }
  193264. else
  193265. #endif
  193266. {
  193267. sp = row;
  193268. dp = row;
  193269. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193270. {
  193271. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193272. << 8) + (png_uint_16)(*(sp + 7)));
  193273. if (a == (png_uint_16)0xffff)
  193274. {
  193275. png_memcpy(dp, sp, 6);
  193276. }
  193277. else if (a == 0)
  193278. {
  193279. *dp = (png_byte)((background->red >> 8) & 0xff);
  193280. *(dp + 1) = (png_byte)(background->red & 0xff);
  193281. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193282. *(dp + 3) = (png_byte)(background->green & 0xff);
  193283. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193284. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193285. }
  193286. else
  193287. {
  193288. png_uint_16 v;
  193289. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193290. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193291. + *(sp + 3));
  193292. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193293. + *(sp + 5));
  193294. png_composite_16(v, r, a, background->red);
  193295. *dp = (png_byte)((v >> 8) & 0xff);
  193296. *(dp + 1) = (png_byte)(v & 0xff);
  193297. png_composite_16(v, g, a, background->green);
  193298. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193299. *(dp + 3) = (png_byte)(v & 0xff);
  193300. png_composite_16(v, b, a, background->blue);
  193301. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193302. *(dp + 5) = (png_byte)(v & 0xff);
  193303. }
  193304. }
  193305. }
  193306. }
  193307. break;
  193308. }
  193309. }
  193310. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193311. {
  193312. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193313. row_info->channels--;
  193314. row_info->pixel_depth = (png_byte)(row_info->channels *
  193315. row_info->bit_depth);
  193316. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193317. }
  193318. }
  193319. }
  193320. #endif
  193321. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193322. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193323. * you do this after you deal with the transparency issue on grayscale
  193324. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193325. * is 16, use gamma_16_table and gamma_shift. Build these with
  193326. * build_gamma_table().
  193327. */
  193328. void /* PRIVATE */
  193329. png_do_gamma(png_row_infop row_info, png_bytep row,
  193330. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193331. int gamma_shift)
  193332. {
  193333. png_bytep sp;
  193334. png_uint_32 i;
  193335. png_uint_32 row_width=row_info->width;
  193336. png_debug(1, "in png_do_gamma\n");
  193337. if (
  193338. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193339. row != NULL && row_info != NULL &&
  193340. #endif
  193341. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193342. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193343. {
  193344. switch (row_info->color_type)
  193345. {
  193346. case PNG_COLOR_TYPE_RGB:
  193347. {
  193348. if (row_info->bit_depth == 8)
  193349. {
  193350. sp = row;
  193351. for (i = 0; i < row_width; i++)
  193352. {
  193353. *sp = gamma_table[*sp];
  193354. sp++;
  193355. *sp = gamma_table[*sp];
  193356. sp++;
  193357. *sp = gamma_table[*sp];
  193358. sp++;
  193359. }
  193360. }
  193361. else /* if (row_info->bit_depth == 16) */
  193362. {
  193363. sp = row;
  193364. for (i = 0; i < row_width; i++)
  193365. {
  193366. png_uint_16 v;
  193367. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193368. *sp = (png_byte)((v >> 8) & 0xff);
  193369. *(sp + 1) = (png_byte)(v & 0xff);
  193370. sp += 2;
  193371. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193372. *sp = (png_byte)((v >> 8) & 0xff);
  193373. *(sp + 1) = (png_byte)(v & 0xff);
  193374. sp += 2;
  193375. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193376. *sp = (png_byte)((v >> 8) & 0xff);
  193377. *(sp + 1) = (png_byte)(v & 0xff);
  193378. sp += 2;
  193379. }
  193380. }
  193381. break;
  193382. }
  193383. case PNG_COLOR_TYPE_RGB_ALPHA:
  193384. {
  193385. if (row_info->bit_depth == 8)
  193386. {
  193387. sp = row;
  193388. for (i = 0; i < row_width; i++)
  193389. {
  193390. *sp = gamma_table[*sp];
  193391. sp++;
  193392. *sp = gamma_table[*sp];
  193393. sp++;
  193394. *sp = gamma_table[*sp];
  193395. sp++;
  193396. sp++;
  193397. }
  193398. }
  193399. else /* if (row_info->bit_depth == 16) */
  193400. {
  193401. sp = row;
  193402. for (i = 0; i < row_width; i++)
  193403. {
  193404. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193405. *sp = (png_byte)((v >> 8) & 0xff);
  193406. *(sp + 1) = (png_byte)(v & 0xff);
  193407. sp += 2;
  193408. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193409. *sp = (png_byte)((v >> 8) & 0xff);
  193410. *(sp + 1) = (png_byte)(v & 0xff);
  193411. sp += 2;
  193412. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193413. *sp = (png_byte)((v >> 8) & 0xff);
  193414. *(sp + 1) = (png_byte)(v & 0xff);
  193415. sp += 4;
  193416. }
  193417. }
  193418. break;
  193419. }
  193420. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193421. {
  193422. if (row_info->bit_depth == 8)
  193423. {
  193424. sp = row;
  193425. for (i = 0; i < row_width; i++)
  193426. {
  193427. *sp = gamma_table[*sp];
  193428. sp += 2;
  193429. }
  193430. }
  193431. else /* if (row_info->bit_depth == 16) */
  193432. {
  193433. sp = row;
  193434. for (i = 0; i < row_width; i++)
  193435. {
  193436. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193437. *sp = (png_byte)((v >> 8) & 0xff);
  193438. *(sp + 1) = (png_byte)(v & 0xff);
  193439. sp += 4;
  193440. }
  193441. }
  193442. break;
  193443. }
  193444. case PNG_COLOR_TYPE_GRAY:
  193445. {
  193446. if (row_info->bit_depth == 2)
  193447. {
  193448. sp = row;
  193449. for (i = 0; i < row_width; i += 4)
  193450. {
  193451. int a = *sp & 0xc0;
  193452. int b = *sp & 0x30;
  193453. int c = *sp & 0x0c;
  193454. int d = *sp & 0x03;
  193455. *sp = (png_byte)(
  193456. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193457. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193458. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193459. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193460. sp++;
  193461. }
  193462. }
  193463. if (row_info->bit_depth == 4)
  193464. {
  193465. sp = row;
  193466. for (i = 0; i < row_width; i += 2)
  193467. {
  193468. int msb = *sp & 0xf0;
  193469. int lsb = *sp & 0x0f;
  193470. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193471. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193472. sp++;
  193473. }
  193474. }
  193475. else if (row_info->bit_depth == 8)
  193476. {
  193477. sp = row;
  193478. for (i = 0; i < row_width; i++)
  193479. {
  193480. *sp = gamma_table[*sp];
  193481. sp++;
  193482. }
  193483. }
  193484. else if (row_info->bit_depth == 16)
  193485. {
  193486. sp = row;
  193487. for (i = 0; i < row_width; i++)
  193488. {
  193489. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193490. *sp = (png_byte)((v >> 8) & 0xff);
  193491. *(sp + 1) = (png_byte)(v & 0xff);
  193492. sp += 2;
  193493. }
  193494. }
  193495. break;
  193496. }
  193497. }
  193498. }
  193499. }
  193500. #endif
  193501. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193502. /* Expands a palette row to an RGB or RGBA row depending
  193503. * upon whether you supply trans and num_trans.
  193504. */
  193505. void /* PRIVATE */
  193506. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193507. png_colorp palette, png_bytep trans, int num_trans)
  193508. {
  193509. int shift, value;
  193510. png_bytep sp, dp;
  193511. png_uint_32 i;
  193512. png_uint_32 row_width=row_info->width;
  193513. png_debug(1, "in png_do_expand_palette\n");
  193514. if (
  193515. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193516. row != NULL && row_info != NULL &&
  193517. #endif
  193518. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193519. {
  193520. if (row_info->bit_depth < 8)
  193521. {
  193522. switch (row_info->bit_depth)
  193523. {
  193524. case 1:
  193525. {
  193526. sp = row + (png_size_t)((row_width - 1) >> 3);
  193527. dp = row + (png_size_t)row_width - 1;
  193528. shift = 7 - (int)((row_width + 7) & 0x07);
  193529. for (i = 0; i < row_width; i++)
  193530. {
  193531. if ((*sp >> shift) & 0x01)
  193532. *dp = 1;
  193533. else
  193534. *dp = 0;
  193535. if (shift == 7)
  193536. {
  193537. shift = 0;
  193538. sp--;
  193539. }
  193540. else
  193541. shift++;
  193542. dp--;
  193543. }
  193544. break;
  193545. }
  193546. case 2:
  193547. {
  193548. sp = row + (png_size_t)((row_width - 1) >> 2);
  193549. dp = row + (png_size_t)row_width - 1;
  193550. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193551. for (i = 0; i < row_width; i++)
  193552. {
  193553. value = (*sp >> shift) & 0x03;
  193554. *dp = (png_byte)value;
  193555. if (shift == 6)
  193556. {
  193557. shift = 0;
  193558. sp--;
  193559. }
  193560. else
  193561. shift += 2;
  193562. dp--;
  193563. }
  193564. break;
  193565. }
  193566. case 4:
  193567. {
  193568. sp = row + (png_size_t)((row_width - 1) >> 1);
  193569. dp = row + (png_size_t)row_width - 1;
  193570. shift = (int)((row_width & 0x01) << 2);
  193571. for (i = 0; i < row_width; i++)
  193572. {
  193573. value = (*sp >> shift) & 0x0f;
  193574. *dp = (png_byte)value;
  193575. if (shift == 4)
  193576. {
  193577. shift = 0;
  193578. sp--;
  193579. }
  193580. else
  193581. shift += 4;
  193582. dp--;
  193583. }
  193584. break;
  193585. }
  193586. }
  193587. row_info->bit_depth = 8;
  193588. row_info->pixel_depth = 8;
  193589. row_info->rowbytes = row_width;
  193590. }
  193591. switch (row_info->bit_depth)
  193592. {
  193593. case 8:
  193594. {
  193595. if (trans != NULL)
  193596. {
  193597. sp = row + (png_size_t)row_width - 1;
  193598. dp = row + (png_size_t)(row_width << 2) - 1;
  193599. for (i = 0; i < row_width; i++)
  193600. {
  193601. if ((int)(*sp) >= num_trans)
  193602. *dp-- = 0xff;
  193603. else
  193604. *dp-- = trans[*sp];
  193605. *dp-- = palette[*sp].blue;
  193606. *dp-- = palette[*sp].green;
  193607. *dp-- = palette[*sp].red;
  193608. sp--;
  193609. }
  193610. row_info->bit_depth = 8;
  193611. row_info->pixel_depth = 32;
  193612. row_info->rowbytes = row_width * 4;
  193613. row_info->color_type = 6;
  193614. row_info->channels = 4;
  193615. }
  193616. else
  193617. {
  193618. sp = row + (png_size_t)row_width - 1;
  193619. dp = row + (png_size_t)(row_width * 3) - 1;
  193620. for (i = 0; i < row_width; i++)
  193621. {
  193622. *dp-- = palette[*sp].blue;
  193623. *dp-- = palette[*sp].green;
  193624. *dp-- = palette[*sp].red;
  193625. sp--;
  193626. }
  193627. row_info->bit_depth = 8;
  193628. row_info->pixel_depth = 24;
  193629. row_info->rowbytes = row_width * 3;
  193630. row_info->color_type = 2;
  193631. row_info->channels = 3;
  193632. }
  193633. break;
  193634. }
  193635. }
  193636. }
  193637. }
  193638. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193639. * expanded transparency value is supplied, an alpha channel is built.
  193640. */
  193641. void /* PRIVATE */
  193642. png_do_expand(png_row_infop row_info, png_bytep row,
  193643. png_color_16p trans_value)
  193644. {
  193645. int shift, value;
  193646. png_bytep sp, dp;
  193647. png_uint_32 i;
  193648. png_uint_32 row_width=row_info->width;
  193649. png_debug(1, "in png_do_expand\n");
  193650. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193651. if (row != NULL && row_info != NULL)
  193652. #endif
  193653. {
  193654. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193655. {
  193656. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193657. if (row_info->bit_depth < 8)
  193658. {
  193659. switch (row_info->bit_depth)
  193660. {
  193661. case 1:
  193662. {
  193663. gray = (png_uint_16)((gray&0x01)*0xff);
  193664. sp = row + (png_size_t)((row_width - 1) >> 3);
  193665. dp = row + (png_size_t)row_width - 1;
  193666. shift = 7 - (int)((row_width + 7) & 0x07);
  193667. for (i = 0; i < row_width; i++)
  193668. {
  193669. if ((*sp >> shift) & 0x01)
  193670. *dp = 0xff;
  193671. else
  193672. *dp = 0;
  193673. if (shift == 7)
  193674. {
  193675. shift = 0;
  193676. sp--;
  193677. }
  193678. else
  193679. shift++;
  193680. dp--;
  193681. }
  193682. break;
  193683. }
  193684. case 2:
  193685. {
  193686. gray = (png_uint_16)((gray&0x03)*0x55);
  193687. sp = row + (png_size_t)((row_width - 1) >> 2);
  193688. dp = row + (png_size_t)row_width - 1;
  193689. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193690. for (i = 0; i < row_width; i++)
  193691. {
  193692. value = (*sp >> shift) & 0x03;
  193693. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193694. (value << 6));
  193695. if (shift == 6)
  193696. {
  193697. shift = 0;
  193698. sp--;
  193699. }
  193700. else
  193701. shift += 2;
  193702. dp--;
  193703. }
  193704. break;
  193705. }
  193706. case 4:
  193707. {
  193708. gray = (png_uint_16)((gray&0x0f)*0x11);
  193709. sp = row + (png_size_t)((row_width - 1) >> 1);
  193710. dp = row + (png_size_t)row_width - 1;
  193711. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193712. for (i = 0; i < row_width; i++)
  193713. {
  193714. value = (*sp >> shift) & 0x0f;
  193715. *dp = (png_byte)(value | (value << 4));
  193716. if (shift == 4)
  193717. {
  193718. shift = 0;
  193719. sp--;
  193720. }
  193721. else
  193722. shift = 4;
  193723. dp--;
  193724. }
  193725. break;
  193726. }
  193727. }
  193728. row_info->bit_depth = 8;
  193729. row_info->pixel_depth = 8;
  193730. row_info->rowbytes = row_width;
  193731. }
  193732. if (trans_value != NULL)
  193733. {
  193734. if (row_info->bit_depth == 8)
  193735. {
  193736. gray = gray & 0xff;
  193737. sp = row + (png_size_t)row_width - 1;
  193738. dp = row + (png_size_t)(row_width << 1) - 1;
  193739. for (i = 0; i < row_width; i++)
  193740. {
  193741. if (*sp == gray)
  193742. *dp-- = 0;
  193743. else
  193744. *dp-- = 0xff;
  193745. *dp-- = *sp--;
  193746. }
  193747. }
  193748. else if (row_info->bit_depth == 16)
  193749. {
  193750. png_byte gray_high = (gray >> 8) & 0xff;
  193751. png_byte gray_low = gray & 0xff;
  193752. sp = row + row_info->rowbytes - 1;
  193753. dp = row + (row_info->rowbytes << 1) - 1;
  193754. for (i = 0; i < row_width; i++)
  193755. {
  193756. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193757. {
  193758. *dp-- = 0;
  193759. *dp-- = 0;
  193760. }
  193761. else
  193762. {
  193763. *dp-- = 0xff;
  193764. *dp-- = 0xff;
  193765. }
  193766. *dp-- = *sp--;
  193767. *dp-- = *sp--;
  193768. }
  193769. }
  193770. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193771. row_info->channels = 2;
  193772. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193773. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193774. row_width);
  193775. }
  193776. }
  193777. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193778. {
  193779. if (row_info->bit_depth == 8)
  193780. {
  193781. png_byte red = trans_value->red & 0xff;
  193782. png_byte green = trans_value->green & 0xff;
  193783. png_byte blue = trans_value->blue & 0xff;
  193784. sp = row + (png_size_t)row_info->rowbytes - 1;
  193785. dp = row + (png_size_t)(row_width << 2) - 1;
  193786. for (i = 0; i < row_width; i++)
  193787. {
  193788. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193789. *dp-- = 0;
  193790. else
  193791. *dp-- = 0xff;
  193792. *dp-- = *sp--;
  193793. *dp-- = *sp--;
  193794. *dp-- = *sp--;
  193795. }
  193796. }
  193797. else if (row_info->bit_depth == 16)
  193798. {
  193799. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193800. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193801. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193802. png_byte red_low = trans_value->red & 0xff;
  193803. png_byte green_low = trans_value->green & 0xff;
  193804. png_byte blue_low = trans_value->blue & 0xff;
  193805. sp = row + row_info->rowbytes - 1;
  193806. dp = row + (png_size_t)(row_width << 3) - 1;
  193807. for (i = 0; i < row_width; i++)
  193808. {
  193809. if (*(sp - 5) == red_high &&
  193810. *(sp - 4) == red_low &&
  193811. *(sp - 3) == green_high &&
  193812. *(sp - 2) == green_low &&
  193813. *(sp - 1) == blue_high &&
  193814. *(sp ) == blue_low)
  193815. {
  193816. *dp-- = 0;
  193817. *dp-- = 0;
  193818. }
  193819. else
  193820. {
  193821. *dp-- = 0xff;
  193822. *dp-- = 0xff;
  193823. }
  193824. *dp-- = *sp--;
  193825. *dp-- = *sp--;
  193826. *dp-- = *sp--;
  193827. *dp-- = *sp--;
  193828. *dp-- = *sp--;
  193829. *dp-- = *sp--;
  193830. }
  193831. }
  193832. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193833. row_info->channels = 4;
  193834. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193835. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193836. }
  193837. }
  193838. }
  193839. #endif
  193840. #if defined(PNG_READ_DITHER_SUPPORTED)
  193841. void /* PRIVATE */
  193842. png_do_dither(png_row_infop row_info, png_bytep row,
  193843. png_bytep palette_lookup, png_bytep dither_lookup)
  193844. {
  193845. png_bytep sp, dp;
  193846. png_uint_32 i;
  193847. png_uint_32 row_width=row_info->width;
  193848. png_debug(1, "in png_do_dither\n");
  193849. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193850. if (row != NULL && row_info != NULL)
  193851. #endif
  193852. {
  193853. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193854. palette_lookup && row_info->bit_depth == 8)
  193855. {
  193856. int r, g, b, p;
  193857. sp = row;
  193858. dp = row;
  193859. for (i = 0; i < row_width; i++)
  193860. {
  193861. r = *sp++;
  193862. g = *sp++;
  193863. b = *sp++;
  193864. /* this looks real messy, but the compiler will reduce
  193865. it down to a reasonable formula. For example, with
  193866. 5 bits per color, we get:
  193867. p = (((r >> 3) & 0x1f) << 10) |
  193868. (((g >> 3) & 0x1f) << 5) |
  193869. ((b >> 3) & 0x1f);
  193870. */
  193871. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193872. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193873. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193874. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193875. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193876. (PNG_DITHER_BLUE_BITS)) |
  193877. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193878. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193879. *dp++ = palette_lookup[p];
  193880. }
  193881. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193882. row_info->channels = 1;
  193883. row_info->pixel_depth = row_info->bit_depth;
  193884. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193885. }
  193886. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193887. palette_lookup != NULL && row_info->bit_depth == 8)
  193888. {
  193889. int r, g, b, p;
  193890. sp = row;
  193891. dp = row;
  193892. for (i = 0; i < row_width; i++)
  193893. {
  193894. r = *sp++;
  193895. g = *sp++;
  193896. b = *sp++;
  193897. sp++;
  193898. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193899. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193900. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193901. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193902. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193903. (PNG_DITHER_BLUE_BITS)) |
  193904. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193905. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193906. *dp++ = palette_lookup[p];
  193907. }
  193908. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193909. row_info->channels = 1;
  193910. row_info->pixel_depth = row_info->bit_depth;
  193911. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193912. }
  193913. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193914. dither_lookup && row_info->bit_depth == 8)
  193915. {
  193916. sp = row;
  193917. for (i = 0; i < row_width; i++, sp++)
  193918. {
  193919. *sp = dither_lookup[*sp];
  193920. }
  193921. }
  193922. }
  193923. }
  193924. #endif
  193925. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193926. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193927. static PNG_CONST int png_gamma_shift[] =
  193928. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193929. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193930. * tables, we don't make a full table if we are reducing to 8-bit in
  193931. * the future. Note also how the gamma_16 tables are segmented so that
  193932. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193933. */
  193934. void /* PRIVATE */
  193935. png_build_gamma_table(png_structp png_ptr)
  193936. {
  193937. png_debug(1, "in png_build_gamma_table\n");
  193938. if (png_ptr->bit_depth <= 8)
  193939. {
  193940. int i;
  193941. double g;
  193942. if (png_ptr->screen_gamma > .000001)
  193943. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193944. else
  193945. g = 1.0;
  193946. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193947. (png_uint_32)256);
  193948. for (i = 0; i < 256; i++)
  193949. {
  193950. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193951. g) * 255.0 + .5);
  193952. }
  193953. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193954. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193955. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193956. {
  193957. g = 1.0 / (png_ptr->gamma);
  193958. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193959. (png_uint_32)256);
  193960. for (i = 0; i < 256; i++)
  193961. {
  193962. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193963. g) * 255.0 + .5);
  193964. }
  193965. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193966. (png_uint_32)256);
  193967. if(png_ptr->screen_gamma > 0.000001)
  193968. g = 1.0 / png_ptr->screen_gamma;
  193969. else
  193970. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193971. for (i = 0; i < 256; i++)
  193972. {
  193973. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193974. g) * 255.0 + .5);
  193975. }
  193976. }
  193977. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193978. }
  193979. else
  193980. {
  193981. double g;
  193982. int i, j, shift, num;
  193983. int sig_bit;
  193984. png_uint_32 ig;
  193985. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193986. {
  193987. sig_bit = (int)png_ptr->sig_bit.red;
  193988. if ((int)png_ptr->sig_bit.green > sig_bit)
  193989. sig_bit = png_ptr->sig_bit.green;
  193990. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193991. sig_bit = png_ptr->sig_bit.blue;
  193992. }
  193993. else
  193994. {
  193995. sig_bit = (int)png_ptr->sig_bit.gray;
  193996. }
  193997. if (sig_bit > 0)
  193998. shift = 16 - sig_bit;
  193999. else
  194000. shift = 0;
  194001. if (png_ptr->transformations & PNG_16_TO_8)
  194002. {
  194003. if (shift < (16 - PNG_MAX_GAMMA_8))
  194004. shift = (16 - PNG_MAX_GAMMA_8);
  194005. }
  194006. if (shift > 8)
  194007. shift = 8;
  194008. if (shift < 0)
  194009. shift = 0;
  194010. png_ptr->gamma_shift = (png_byte)shift;
  194011. num = (1 << (8 - shift));
  194012. if (png_ptr->screen_gamma > .000001)
  194013. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194014. else
  194015. g = 1.0;
  194016. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194017. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194018. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194019. {
  194020. double fin, fout;
  194021. png_uint_32 last, max;
  194022. for (i = 0; i < num; i++)
  194023. {
  194024. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194025. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194026. }
  194027. g = 1.0 / g;
  194028. last = 0;
  194029. for (i = 0; i < 256; i++)
  194030. {
  194031. fout = ((double)i + 0.5) / 256.0;
  194032. fin = pow(fout, g);
  194033. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194034. while (last <= max)
  194035. {
  194036. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194037. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194038. (png_uint_16)i | ((png_uint_16)i << 8));
  194039. last++;
  194040. }
  194041. }
  194042. while (last < ((png_uint_32)num << 8))
  194043. {
  194044. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194045. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194046. last++;
  194047. }
  194048. }
  194049. else
  194050. {
  194051. for (i = 0; i < num; i++)
  194052. {
  194053. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194054. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194055. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194056. for (j = 0; j < 256; j++)
  194057. {
  194058. png_ptr->gamma_16_table[i][j] =
  194059. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194060. 65535.0, g) * 65535.0 + .5);
  194061. }
  194062. }
  194063. }
  194064. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194065. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194066. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194067. {
  194068. g = 1.0 / (png_ptr->gamma);
  194069. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194070. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194071. for (i = 0; i < num; i++)
  194072. {
  194073. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194074. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194075. ig = (((png_uint_32)i *
  194076. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194077. for (j = 0; j < 256; j++)
  194078. {
  194079. png_ptr->gamma_16_to_1[i][j] =
  194080. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194081. 65535.0, g) * 65535.0 + .5);
  194082. }
  194083. }
  194084. if(png_ptr->screen_gamma > 0.000001)
  194085. g = 1.0 / png_ptr->screen_gamma;
  194086. else
  194087. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194088. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194089. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194090. for (i = 0; i < num; i++)
  194091. {
  194092. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194093. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194094. ig = (((png_uint_32)i *
  194095. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194096. for (j = 0; j < 256; j++)
  194097. {
  194098. png_ptr->gamma_16_from_1[i][j] =
  194099. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194100. 65535.0, g) * 65535.0 + .5);
  194101. }
  194102. }
  194103. }
  194104. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194105. }
  194106. }
  194107. #endif
  194108. /* To do: install integer version of png_build_gamma_table here */
  194109. #endif
  194110. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194111. /* undoes intrapixel differencing */
  194112. void /* PRIVATE */
  194113. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194114. {
  194115. png_debug(1, "in png_do_read_intrapixel\n");
  194116. if (
  194117. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194118. row != NULL && row_info != NULL &&
  194119. #endif
  194120. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194121. {
  194122. int bytes_per_pixel;
  194123. png_uint_32 row_width = row_info->width;
  194124. if (row_info->bit_depth == 8)
  194125. {
  194126. png_bytep rp;
  194127. png_uint_32 i;
  194128. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194129. bytes_per_pixel = 3;
  194130. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194131. bytes_per_pixel = 4;
  194132. else
  194133. return;
  194134. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194135. {
  194136. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194137. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194138. }
  194139. }
  194140. else if (row_info->bit_depth == 16)
  194141. {
  194142. png_bytep rp;
  194143. png_uint_32 i;
  194144. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194145. bytes_per_pixel = 6;
  194146. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194147. bytes_per_pixel = 8;
  194148. else
  194149. return;
  194150. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194151. {
  194152. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194153. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194154. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194155. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194156. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194157. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194158. *(rp+1) = (png_byte)(red & 0xff);
  194159. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194160. *(rp+5) = (png_byte)(blue & 0xff);
  194161. }
  194162. }
  194163. }
  194164. }
  194165. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194166. #endif /* PNG_READ_SUPPORTED */
  194167. /*** End of inlined file: pngrtran.c ***/
  194168. /*** Start of inlined file: pngrutil.c ***/
  194169. /* pngrutil.c - utilities to read a PNG file
  194170. *
  194171. * Last changed in libpng 1.2.21 [October 4, 2007]
  194172. * For conditions of distribution and use, see copyright notice in png.h
  194173. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194174. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194175. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194176. *
  194177. * This file contains routines that are only called from within
  194178. * libpng itself during the course of reading an image.
  194179. */
  194180. #define PNG_INTERNAL
  194181. #if defined(PNG_READ_SUPPORTED)
  194182. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194183. # define WIN32_WCE_OLD
  194184. #endif
  194185. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194186. # if defined(WIN32_WCE_OLD)
  194187. /* strtod() function is not supported on WindowsCE */
  194188. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194189. {
  194190. double result = 0;
  194191. int len;
  194192. wchar_t *str, *end;
  194193. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194194. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194195. if ( NULL != str )
  194196. {
  194197. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194198. result = wcstod(str, &end);
  194199. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194200. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194201. png_free(png_ptr, str);
  194202. }
  194203. return result;
  194204. }
  194205. # else
  194206. # define png_strtod(p,a,b) strtod(a,b)
  194207. # endif
  194208. #endif
  194209. png_uint_32 PNGAPI
  194210. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194211. {
  194212. png_uint_32 i = png_get_uint_32(buf);
  194213. if (i > PNG_UINT_31_MAX)
  194214. png_error(png_ptr, "PNG unsigned integer out of range.");
  194215. return (i);
  194216. }
  194217. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194218. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194219. png_uint_32 PNGAPI
  194220. png_get_uint_32(png_bytep buf)
  194221. {
  194222. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194223. ((png_uint_32)(*(buf + 1)) << 16) +
  194224. ((png_uint_32)(*(buf + 2)) << 8) +
  194225. (png_uint_32)(*(buf + 3));
  194226. return (i);
  194227. }
  194228. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194229. * data is stored in the PNG file in two's complement format, and it is
  194230. * assumed that the machine format for signed integers is the same. */
  194231. png_int_32 PNGAPI
  194232. png_get_int_32(png_bytep buf)
  194233. {
  194234. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194235. ((png_int_32)(*(buf + 1)) << 16) +
  194236. ((png_int_32)(*(buf + 2)) << 8) +
  194237. (png_int_32)(*(buf + 3));
  194238. return (i);
  194239. }
  194240. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194241. png_uint_16 PNGAPI
  194242. png_get_uint_16(png_bytep buf)
  194243. {
  194244. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194245. (png_uint_16)(*(buf + 1)));
  194246. return (i);
  194247. }
  194248. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194249. /* Read data, and (optionally) run it through the CRC. */
  194250. void /* PRIVATE */
  194251. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194252. {
  194253. if(png_ptr == NULL) return;
  194254. png_read_data(png_ptr, buf, length);
  194255. png_calculate_crc(png_ptr, buf, length);
  194256. }
  194257. /* Optionally skip data and then check the CRC. Depending on whether we
  194258. are reading a ancillary or critical chunk, and how the program has set
  194259. things up, we may calculate the CRC on the data and print a message.
  194260. Returns '1' if there was a CRC error, '0' otherwise. */
  194261. int /* PRIVATE */
  194262. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194263. {
  194264. png_size_t i;
  194265. png_size_t istop = png_ptr->zbuf_size;
  194266. for (i = (png_size_t)skip; i > istop; i -= istop)
  194267. {
  194268. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194269. }
  194270. if (i)
  194271. {
  194272. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194273. }
  194274. if (png_crc_error(png_ptr))
  194275. {
  194276. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194277. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194278. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194279. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194280. {
  194281. png_chunk_warning(png_ptr, "CRC error");
  194282. }
  194283. else
  194284. {
  194285. png_chunk_error(png_ptr, "CRC error");
  194286. }
  194287. return (1);
  194288. }
  194289. return (0);
  194290. }
  194291. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194292. the data it has read thus far. */
  194293. int /* PRIVATE */
  194294. png_crc_error(png_structp png_ptr)
  194295. {
  194296. png_byte crc_bytes[4];
  194297. png_uint_32 crc;
  194298. int need_crc = 1;
  194299. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194300. {
  194301. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194302. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194303. need_crc = 0;
  194304. }
  194305. else /* critical */
  194306. {
  194307. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194308. need_crc = 0;
  194309. }
  194310. png_read_data(png_ptr, crc_bytes, 4);
  194311. if (need_crc)
  194312. {
  194313. crc = png_get_uint_32(crc_bytes);
  194314. return ((int)(crc != png_ptr->crc));
  194315. }
  194316. else
  194317. return (0);
  194318. }
  194319. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194320. defined(PNG_READ_iCCP_SUPPORTED)
  194321. /*
  194322. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194323. * points at an allocated area holding the contents of a chunk with a
  194324. * trailing compressed part. What we get back is an allocated area
  194325. * holding the original prefix part and an uncompressed version of the
  194326. * trailing part (the malloc area passed in is freed).
  194327. */
  194328. png_charp /* PRIVATE */
  194329. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194330. png_charp chunkdata, png_size_t chunklength,
  194331. png_size_t prefix_size, png_size_t *newlength)
  194332. {
  194333. static PNG_CONST char msg[] = "Error decoding compressed text";
  194334. png_charp text;
  194335. png_size_t text_size;
  194336. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194337. {
  194338. int ret = Z_OK;
  194339. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194340. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194341. png_ptr->zstream.next_out = png_ptr->zbuf;
  194342. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194343. text_size = 0;
  194344. text = NULL;
  194345. while (png_ptr->zstream.avail_in)
  194346. {
  194347. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194348. if (ret != Z_OK && ret != Z_STREAM_END)
  194349. {
  194350. if (png_ptr->zstream.msg != NULL)
  194351. png_warning(png_ptr, png_ptr->zstream.msg);
  194352. else
  194353. png_warning(png_ptr, msg);
  194354. inflateReset(&png_ptr->zstream);
  194355. png_ptr->zstream.avail_in = 0;
  194356. if (text == NULL)
  194357. {
  194358. text_size = prefix_size + png_sizeof(msg) + 1;
  194359. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194360. if (text == NULL)
  194361. {
  194362. png_free(png_ptr,chunkdata);
  194363. png_error(png_ptr,"Not enough memory to decompress chunk");
  194364. }
  194365. png_memcpy(text, chunkdata, prefix_size);
  194366. }
  194367. text[text_size - 1] = 0x00;
  194368. /* Copy what we can of the error message into the text chunk */
  194369. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194370. text_size = png_sizeof(msg) > text_size ? text_size :
  194371. png_sizeof(msg);
  194372. png_memcpy(text + prefix_size, msg, text_size + 1);
  194373. break;
  194374. }
  194375. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194376. {
  194377. if (text == NULL)
  194378. {
  194379. text_size = prefix_size +
  194380. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194381. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194382. if (text == NULL)
  194383. {
  194384. png_free(png_ptr,chunkdata);
  194385. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194386. }
  194387. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194388. text_size - prefix_size);
  194389. png_memcpy(text, chunkdata, prefix_size);
  194390. *(text + text_size) = 0x00;
  194391. }
  194392. else
  194393. {
  194394. png_charp tmp;
  194395. tmp = text;
  194396. text = (png_charp)png_malloc_warn(png_ptr,
  194397. (png_uint_32)(text_size +
  194398. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194399. if (text == NULL)
  194400. {
  194401. png_free(png_ptr, tmp);
  194402. png_free(png_ptr, chunkdata);
  194403. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194404. }
  194405. png_memcpy(text, tmp, text_size);
  194406. png_free(png_ptr, tmp);
  194407. png_memcpy(text + text_size, png_ptr->zbuf,
  194408. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194409. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194410. *(text + text_size) = 0x00;
  194411. }
  194412. if (ret == Z_STREAM_END)
  194413. break;
  194414. else
  194415. {
  194416. png_ptr->zstream.next_out = png_ptr->zbuf;
  194417. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194418. }
  194419. }
  194420. }
  194421. if (ret != Z_STREAM_END)
  194422. {
  194423. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194424. char umsg[52];
  194425. if (ret == Z_BUF_ERROR)
  194426. png_snprintf(umsg, 52,
  194427. "Buffer error in compressed datastream in %s chunk",
  194428. png_ptr->chunk_name);
  194429. else if (ret == Z_DATA_ERROR)
  194430. png_snprintf(umsg, 52,
  194431. "Data error in compressed datastream in %s chunk",
  194432. png_ptr->chunk_name);
  194433. else
  194434. png_snprintf(umsg, 52,
  194435. "Incomplete compressed datastream in %s chunk",
  194436. png_ptr->chunk_name);
  194437. png_warning(png_ptr, umsg);
  194438. #else
  194439. png_warning(png_ptr,
  194440. "Incomplete compressed datastream in chunk other than IDAT");
  194441. #endif
  194442. text_size=prefix_size;
  194443. if (text == NULL)
  194444. {
  194445. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194446. if (text == NULL)
  194447. {
  194448. png_free(png_ptr, chunkdata);
  194449. png_error(png_ptr,"Not enough memory for text.");
  194450. }
  194451. png_memcpy(text, chunkdata, prefix_size);
  194452. }
  194453. *(text + text_size) = 0x00;
  194454. }
  194455. inflateReset(&png_ptr->zstream);
  194456. png_ptr->zstream.avail_in = 0;
  194457. png_free(png_ptr, chunkdata);
  194458. chunkdata = text;
  194459. *newlength=text_size;
  194460. }
  194461. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194462. {
  194463. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194464. char umsg[50];
  194465. png_snprintf(umsg, 50,
  194466. "Unknown zTXt compression type %d", comp_type);
  194467. png_warning(png_ptr, umsg);
  194468. #else
  194469. png_warning(png_ptr, "Unknown zTXt compression type");
  194470. #endif
  194471. *(chunkdata + prefix_size) = 0x00;
  194472. *newlength=prefix_size;
  194473. }
  194474. return chunkdata;
  194475. }
  194476. #endif
  194477. /* read and check the IDHR chunk */
  194478. void /* PRIVATE */
  194479. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194480. {
  194481. png_byte buf[13];
  194482. png_uint_32 width, height;
  194483. int bit_depth, color_type, compression_type, filter_type;
  194484. int interlace_type;
  194485. png_debug(1, "in png_handle_IHDR\n");
  194486. if (png_ptr->mode & PNG_HAVE_IHDR)
  194487. png_error(png_ptr, "Out of place IHDR");
  194488. /* check the length */
  194489. if (length != 13)
  194490. png_error(png_ptr, "Invalid IHDR chunk");
  194491. png_ptr->mode |= PNG_HAVE_IHDR;
  194492. png_crc_read(png_ptr, buf, 13);
  194493. png_crc_finish(png_ptr, 0);
  194494. width = png_get_uint_31(png_ptr, buf);
  194495. height = png_get_uint_31(png_ptr, buf + 4);
  194496. bit_depth = buf[8];
  194497. color_type = buf[9];
  194498. compression_type = buf[10];
  194499. filter_type = buf[11];
  194500. interlace_type = buf[12];
  194501. /* set internal variables */
  194502. png_ptr->width = width;
  194503. png_ptr->height = height;
  194504. png_ptr->bit_depth = (png_byte)bit_depth;
  194505. png_ptr->interlaced = (png_byte)interlace_type;
  194506. png_ptr->color_type = (png_byte)color_type;
  194507. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194508. png_ptr->filter_type = (png_byte)filter_type;
  194509. #endif
  194510. png_ptr->compression_type = (png_byte)compression_type;
  194511. /* find number of channels */
  194512. switch (png_ptr->color_type)
  194513. {
  194514. case PNG_COLOR_TYPE_GRAY:
  194515. case PNG_COLOR_TYPE_PALETTE:
  194516. png_ptr->channels = 1;
  194517. break;
  194518. case PNG_COLOR_TYPE_RGB:
  194519. png_ptr->channels = 3;
  194520. break;
  194521. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194522. png_ptr->channels = 2;
  194523. break;
  194524. case PNG_COLOR_TYPE_RGB_ALPHA:
  194525. png_ptr->channels = 4;
  194526. break;
  194527. }
  194528. /* set up other useful info */
  194529. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194530. png_ptr->channels);
  194531. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194532. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194533. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194534. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194535. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194536. color_type, interlace_type, compression_type, filter_type);
  194537. }
  194538. /* read and check the palette */
  194539. void /* PRIVATE */
  194540. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194541. {
  194542. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194543. int num, i;
  194544. #ifndef PNG_NO_POINTER_INDEXING
  194545. png_colorp pal_ptr;
  194546. #endif
  194547. png_debug(1, "in png_handle_PLTE\n");
  194548. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194549. png_error(png_ptr, "Missing IHDR before PLTE");
  194550. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194551. {
  194552. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194553. png_crc_finish(png_ptr, length);
  194554. return;
  194555. }
  194556. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194557. png_error(png_ptr, "Duplicate PLTE chunk");
  194558. png_ptr->mode |= PNG_HAVE_PLTE;
  194559. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194560. {
  194561. png_warning(png_ptr,
  194562. "Ignoring PLTE chunk in grayscale PNG");
  194563. png_crc_finish(png_ptr, length);
  194564. return;
  194565. }
  194566. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194567. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194568. {
  194569. png_crc_finish(png_ptr, length);
  194570. return;
  194571. }
  194572. #endif
  194573. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194574. {
  194575. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194576. {
  194577. png_warning(png_ptr, "Invalid palette chunk");
  194578. png_crc_finish(png_ptr, length);
  194579. return;
  194580. }
  194581. else
  194582. {
  194583. png_error(png_ptr, "Invalid palette chunk");
  194584. }
  194585. }
  194586. num = (int)length / 3;
  194587. #ifndef PNG_NO_POINTER_INDEXING
  194588. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194589. {
  194590. png_byte buf[3];
  194591. png_crc_read(png_ptr, buf, 3);
  194592. pal_ptr->red = buf[0];
  194593. pal_ptr->green = buf[1];
  194594. pal_ptr->blue = buf[2];
  194595. }
  194596. #else
  194597. for (i = 0; i < num; i++)
  194598. {
  194599. png_byte buf[3];
  194600. png_crc_read(png_ptr, buf, 3);
  194601. /* don't depend upon png_color being any order */
  194602. palette[i].red = buf[0];
  194603. palette[i].green = buf[1];
  194604. palette[i].blue = buf[2];
  194605. }
  194606. #endif
  194607. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194608. whatever the normal CRC configuration tells us. However, if we
  194609. have an RGB image, the PLTE can be considered ancillary, so
  194610. we will act as though it is. */
  194611. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194612. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194613. #endif
  194614. {
  194615. png_crc_finish(png_ptr, 0);
  194616. }
  194617. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194618. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194619. {
  194620. /* If we don't want to use the data from an ancillary chunk,
  194621. we have two options: an error abort, or a warning and we
  194622. ignore the data in this chunk (which should be OK, since
  194623. it's considered ancillary for a RGB or RGBA image). */
  194624. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194625. {
  194626. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194627. {
  194628. png_chunk_error(png_ptr, "CRC error");
  194629. }
  194630. else
  194631. {
  194632. png_chunk_warning(png_ptr, "CRC error");
  194633. return;
  194634. }
  194635. }
  194636. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194637. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194638. {
  194639. png_chunk_warning(png_ptr, "CRC error");
  194640. }
  194641. }
  194642. #endif
  194643. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194644. #if defined(PNG_READ_tRNS_SUPPORTED)
  194645. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194646. {
  194647. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194648. {
  194649. if (png_ptr->num_trans > (png_uint_16)num)
  194650. {
  194651. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194652. png_ptr->num_trans = (png_uint_16)num;
  194653. }
  194654. if (info_ptr->num_trans > (png_uint_16)num)
  194655. {
  194656. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194657. info_ptr->num_trans = (png_uint_16)num;
  194658. }
  194659. }
  194660. }
  194661. #endif
  194662. }
  194663. void /* PRIVATE */
  194664. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194665. {
  194666. png_debug(1, "in png_handle_IEND\n");
  194667. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194668. {
  194669. png_error(png_ptr, "No image in file");
  194670. }
  194671. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194672. if (length != 0)
  194673. {
  194674. png_warning(png_ptr, "Incorrect IEND chunk length");
  194675. }
  194676. png_crc_finish(png_ptr, length);
  194677. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194678. }
  194679. #if defined(PNG_READ_gAMA_SUPPORTED)
  194680. void /* PRIVATE */
  194681. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194682. {
  194683. png_fixed_point igamma;
  194684. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194685. float file_gamma;
  194686. #endif
  194687. png_byte buf[4];
  194688. png_debug(1, "in png_handle_gAMA\n");
  194689. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194690. png_error(png_ptr, "Missing IHDR before gAMA");
  194691. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194692. {
  194693. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194694. png_crc_finish(png_ptr, length);
  194695. return;
  194696. }
  194697. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194698. /* Should be an error, but we can cope with it */
  194699. png_warning(png_ptr, "Out of place gAMA chunk");
  194700. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194701. #if defined(PNG_READ_sRGB_SUPPORTED)
  194702. && !(info_ptr->valid & PNG_INFO_sRGB)
  194703. #endif
  194704. )
  194705. {
  194706. png_warning(png_ptr, "Duplicate gAMA chunk");
  194707. png_crc_finish(png_ptr, length);
  194708. return;
  194709. }
  194710. if (length != 4)
  194711. {
  194712. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194713. png_crc_finish(png_ptr, length);
  194714. return;
  194715. }
  194716. png_crc_read(png_ptr, buf, 4);
  194717. if (png_crc_finish(png_ptr, 0))
  194718. return;
  194719. igamma = (png_fixed_point)png_get_uint_32(buf);
  194720. /* check for zero gamma */
  194721. if (igamma == 0)
  194722. {
  194723. png_warning(png_ptr,
  194724. "Ignoring gAMA chunk with gamma=0");
  194725. return;
  194726. }
  194727. #if defined(PNG_READ_sRGB_SUPPORTED)
  194728. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194729. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194730. {
  194731. png_warning(png_ptr,
  194732. "Ignoring incorrect gAMA value when sRGB is also present");
  194733. #ifndef PNG_NO_CONSOLE_IO
  194734. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194735. #endif
  194736. return;
  194737. }
  194738. #endif /* PNG_READ_sRGB_SUPPORTED */
  194739. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194740. file_gamma = (float)igamma / (float)100000.0;
  194741. # ifdef PNG_READ_GAMMA_SUPPORTED
  194742. png_ptr->gamma = file_gamma;
  194743. # endif
  194744. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194745. #endif
  194746. #ifdef PNG_FIXED_POINT_SUPPORTED
  194747. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194748. #endif
  194749. }
  194750. #endif
  194751. #if defined(PNG_READ_sBIT_SUPPORTED)
  194752. void /* PRIVATE */
  194753. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194754. {
  194755. png_size_t truelen;
  194756. png_byte buf[4];
  194757. png_debug(1, "in png_handle_sBIT\n");
  194758. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194759. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194760. png_error(png_ptr, "Missing IHDR before sBIT");
  194761. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194762. {
  194763. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194764. png_crc_finish(png_ptr, length);
  194765. return;
  194766. }
  194767. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194768. {
  194769. /* Should be an error, but we can cope with it */
  194770. png_warning(png_ptr, "Out of place sBIT chunk");
  194771. }
  194772. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194773. {
  194774. png_warning(png_ptr, "Duplicate sBIT chunk");
  194775. png_crc_finish(png_ptr, length);
  194776. return;
  194777. }
  194778. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194779. truelen = 3;
  194780. else
  194781. truelen = (png_size_t)png_ptr->channels;
  194782. if (length != truelen || length > 4)
  194783. {
  194784. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194785. png_crc_finish(png_ptr, length);
  194786. return;
  194787. }
  194788. png_crc_read(png_ptr, buf, truelen);
  194789. if (png_crc_finish(png_ptr, 0))
  194790. return;
  194791. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194792. {
  194793. png_ptr->sig_bit.red = buf[0];
  194794. png_ptr->sig_bit.green = buf[1];
  194795. png_ptr->sig_bit.blue = buf[2];
  194796. png_ptr->sig_bit.alpha = buf[3];
  194797. }
  194798. else
  194799. {
  194800. png_ptr->sig_bit.gray = buf[0];
  194801. png_ptr->sig_bit.red = buf[0];
  194802. png_ptr->sig_bit.green = buf[0];
  194803. png_ptr->sig_bit.blue = buf[0];
  194804. png_ptr->sig_bit.alpha = buf[1];
  194805. }
  194806. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194807. }
  194808. #endif
  194809. #if defined(PNG_READ_cHRM_SUPPORTED)
  194810. void /* PRIVATE */
  194811. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194812. {
  194813. png_byte buf[4];
  194814. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194815. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194816. #endif
  194817. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194818. int_y_green, int_x_blue, int_y_blue;
  194819. png_uint_32 uint_x, uint_y;
  194820. png_debug(1, "in png_handle_cHRM\n");
  194821. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194822. png_error(png_ptr, "Missing IHDR before cHRM");
  194823. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194824. {
  194825. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194826. png_crc_finish(png_ptr, length);
  194827. return;
  194828. }
  194829. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194830. /* Should be an error, but we can cope with it */
  194831. png_warning(png_ptr, "Missing PLTE before cHRM");
  194832. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194833. #if defined(PNG_READ_sRGB_SUPPORTED)
  194834. && !(info_ptr->valid & PNG_INFO_sRGB)
  194835. #endif
  194836. )
  194837. {
  194838. png_warning(png_ptr, "Duplicate cHRM chunk");
  194839. png_crc_finish(png_ptr, length);
  194840. return;
  194841. }
  194842. if (length != 32)
  194843. {
  194844. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194845. png_crc_finish(png_ptr, length);
  194846. return;
  194847. }
  194848. png_crc_read(png_ptr, buf, 4);
  194849. uint_x = png_get_uint_32(buf);
  194850. png_crc_read(png_ptr, buf, 4);
  194851. uint_y = png_get_uint_32(buf);
  194852. if (uint_x > 80000L || uint_y > 80000L ||
  194853. uint_x + uint_y > 100000L)
  194854. {
  194855. png_warning(png_ptr, "Invalid cHRM white point");
  194856. png_crc_finish(png_ptr, 24);
  194857. return;
  194858. }
  194859. int_x_white = (png_fixed_point)uint_x;
  194860. int_y_white = (png_fixed_point)uint_y;
  194861. png_crc_read(png_ptr, buf, 4);
  194862. uint_x = png_get_uint_32(buf);
  194863. png_crc_read(png_ptr, buf, 4);
  194864. uint_y = png_get_uint_32(buf);
  194865. if (uint_x + uint_y > 100000L)
  194866. {
  194867. png_warning(png_ptr, "Invalid cHRM red point");
  194868. png_crc_finish(png_ptr, 16);
  194869. return;
  194870. }
  194871. int_x_red = (png_fixed_point)uint_x;
  194872. int_y_red = (png_fixed_point)uint_y;
  194873. png_crc_read(png_ptr, buf, 4);
  194874. uint_x = png_get_uint_32(buf);
  194875. png_crc_read(png_ptr, buf, 4);
  194876. uint_y = png_get_uint_32(buf);
  194877. if (uint_x + uint_y > 100000L)
  194878. {
  194879. png_warning(png_ptr, "Invalid cHRM green point");
  194880. png_crc_finish(png_ptr, 8);
  194881. return;
  194882. }
  194883. int_x_green = (png_fixed_point)uint_x;
  194884. int_y_green = (png_fixed_point)uint_y;
  194885. png_crc_read(png_ptr, buf, 4);
  194886. uint_x = png_get_uint_32(buf);
  194887. png_crc_read(png_ptr, buf, 4);
  194888. uint_y = png_get_uint_32(buf);
  194889. if (uint_x + uint_y > 100000L)
  194890. {
  194891. png_warning(png_ptr, "Invalid cHRM blue point");
  194892. png_crc_finish(png_ptr, 0);
  194893. return;
  194894. }
  194895. int_x_blue = (png_fixed_point)uint_x;
  194896. int_y_blue = (png_fixed_point)uint_y;
  194897. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194898. white_x = (float)int_x_white / (float)100000.0;
  194899. white_y = (float)int_y_white / (float)100000.0;
  194900. red_x = (float)int_x_red / (float)100000.0;
  194901. red_y = (float)int_y_red / (float)100000.0;
  194902. green_x = (float)int_x_green / (float)100000.0;
  194903. green_y = (float)int_y_green / (float)100000.0;
  194904. blue_x = (float)int_x_blue / (float)100000.0;
  194905. blue_y = (float)int_y_blue / (float)100000.0;
  194906. #endif
  194907. #if defined(PNG_READ_sRGB_SUPPORTED)
  194908. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194909. {
  194910. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194911. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194912. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194913. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194914. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194915. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194916. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194917. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194918. {
  194919. png_warning(png_ptr,
  194920. "Ignoring incorrect cHRM value when sRGB is also present");
  194921. #ifndef PNG_NO_CONSOLE_IO
  194922. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194923. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194924. white_x, white_y, red_x, red_y);
  194925. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194926. green_x, green_y, blue_x, blue_y);
  194927. #else
  194928. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194929. int_x_white, int_y_white, int_x_red, int_y_red);
  194930. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194931. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194932. #endif
  194933. #endif /* PNG_NO_CONSOLE_IO */
  194934. }
  194935. png_crc_finish(png_ptr, 0);
  194936. return;
  194937. }
  194938. #endif /* PNG_READ_sRGB_SUPPORTED */
  194939. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194940. png_set_cHRM(png_ptr, info_ptr,
  194941. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194942. #endif
  194943. #ifdef PNG_FIXED_POINT_SUPPORTED
  194944. png_set_cHRM_fixed(png_ptr, info_ptr,
  194945. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194946. int_y_green, int_x_blue, int_y_blue);
  194947. #endif
  194948. if (png_crc_finish(png_ptr, 0))
  194949. return;
  194950. }
  194951. #endif
  194952. #if defined(PNG_READ_sRGB_SUPPORTED)
  194953. void /* PRIVATE */
  194954. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194955. {
  194956. int intent;
  194957. png_byte buf[1];
  194958. png_debug(1, "in png_handle_sRGB\n");
  194959. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194960. png_error(png_ptr, "Missing IHDR before sRGB");
  194961. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194962. {
  194963. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194964. png_crc_finish(png_ptr, length);
  194965. return;
  194966. }
  194967. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194968. /* Should be an error, but we can cope with it */
  194969. png_warning(png_ptr, "Out of place sRGB chunk");
  194970. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194971. {
  194972. png_warning(png_ptr, "Duplicate sRGB chunk");
  194973. png_crc_finish(png_ptr, length);
  194974. return;
  194975. }
  194976. if (length != 1)
  194977. {
  194978. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194979. png_crc_finish(png_ptr, length);
  194980. return;
  194981. }
  194982. png_crc_read(png_ptr, buf, 1);
  194983. if (png_crc_finish(png_ptr, 0))
  194984. return;
  194985. intent = buf[0];
  194986. /* check for bad intent */
  194987. if (intent >= PNG_sRGB_INTENT_LAST)
  194988. {
  194989. png_warning(png_ptr, "Unknown sRGB intent");
  194990. return;
  194991. }
  194992. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194993. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194994. {
  194995. png_fixed_point igamma;
  194996. #ifdef PNG_FIXED_POINT_SUPPORTED
  194997. igamma=info_ptr->int_gamma;
  194998. #else
  194999. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195000. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195001. # endif
  195002. #endif
  195003. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195004. {
  195005. png_warning(png_ptr,
  195006. "Ignoring incorrect gAMA value when sRGB is also present");
  195007. #ifndef PNG_NO_CONSOLE_IO
  195008. # ifdef PNG_FIXED_POINT_SUPPORTED
  195009. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195010. # else
  195011. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195012. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195013. # endif
  195014. # endif
  195015. #endif
  195016. }
  195017. }
  195018. #endif /* PNG_READ_gAMA_SUPPORTED */
  195019. #ifdef PNG_READ_cHRM_SUPPORTED
  195020. #ifdef PNG_FIXED_POINT_SUPPORTED
  195021. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195022. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195023. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195024. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195025. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195026. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195027. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195028. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195029. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195030. {
  195031. png_warning(png_ptr,
  195032. "Ignoring incorrect cHRM value when sRGB is also present");
  195033. }
  195034. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195035. #endif /* PNG_READ_cHRM_SUPPORTED */
  195036. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195037. }
  195038. #endif /* PNG_READ_sRGB_SUPPORTED */
  195039. #if defined(PNG_READ_iCCP_SUPPORTED)
  195040. void /* PRIVATE */
  195041. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195042. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195043. {
  195044. png_charp chunkdata;
  195045. png_byte compression_type;
  195046. png_bytep pC;
  195047. png_charp profile;
  195048. png_uint_32 skip = 0;
  195049. png_uint_32 profile_size, profile_length;
  195050. png_size_t slength, prefix_length, data_length;
  195051. png_debug(1, "in png_handle_iCCP\n");
  195052. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195053. png_error(png_ptr, "Missing IHDR before iCCP");
  195054. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195055. {
  195056. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195057. png_crc_finish(png_ptr, length);
  195058. return;
  195059. }
  195060. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195061. /* Should be an error, but we can cope with it */
  195062. png_warning(png_ptr, "Out of place iCCP chunk");
  195063. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195064. {
  195065. png_warning(png_ptr, "Duplicate iCCP chunk");
  195066. png_crc_finish(png_ptr, length);
  195067. return;
  195068. }
  195069. #ifdef PNG_MAX_MALLOC_64K
  195070. if (length > (png_uint_32)65535L)
  195071. {
  195072. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195073. skip = length - (png_uint_32)65535L;
  195074. length = (png_uint_32)65535L;
  195075. }
  195076. #endif
  195077. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195078. slength = (png_size_t)length;
  195079. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195080. if (png_crc_finish(png_ptr, skip))
  195081. {
  195082. png_free(png_ptr, chunkdata);
  195083. return;
  195084. }
  195085. chunkdata[slength] = 0x00;
  195086. for (profile = chunkdata; *profile; profile++)
  195087. /* empty loop to find end of name */ ;
  195088. ++profile;
  195089. /* there should be at least one zero (the compression type byte)
  195090. following the separator, and we should be on it */
  195091. if ( profile >= chunkdata + slength - 1)
  195092. {
  195093. png_free(png_ptr, chunkdata);
  195094. png_warning(png_ptr, "Malformed iCCP chunk");
  195095. return;
  195096. }
  195097. /* compression_type should always be zero */
  195098. compression_type = *profile++;
  195099. if (compression_type)
  195100. {
  195101. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195102. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195103. wrote nonzero) */
  195104. }
  195105. prefix_length = profile - chunkdata;
  195106. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195107. slength, prefix_length, &data_length);
  195108. profile_length = data_length - prefix_length;
  195109. if ( prefix_length > data_length || profile_length < 4)
  195110. {
  195111. png_free(png_ptr, chunkdata);
  195112. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195113. return;
  195114. }
  195115. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195116. pC = (png_bytep)(chunkdata+prefix_length);
  195117. profile_size = ((*(pC ))<<24) |
  195118. ((*(pC+1))<<16) |
  195119. ((*(pC+2))<< 8) |
  195120. ((*(pC+3)) );
  195121. if(profile_size < profile_length)
  195122. profile_length = profile_size;
  195123. if(profile_size > profile_length)
  195124. {
  195125. png_free(png_ptr, chunkdata);
  195126. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195127. return;
  195128. }
  195129. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195130. chunkdata + prefix_length, profile_length);
  195131. png_free(png_ptr, chunkdata);
  195132. }
  195133. #endif /* PNG_READ_iCCP_SUPPORTED */
  195134. #if defined(PNG_READ_sPLT_SUPPORTED)
  195135. void /* PRIVATE */
  195136. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195137. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195138. {
  195139. png_bytep chunkdata;
  195140. png_bytep entry_start;
  195141. png_sPLT_t new_palette;
  195142. #ifdef PNG_NO_POINTER_INDEXING
  195143. png_sPLT_entryp pp;
  195144. #endif
  195145. int data_length, entry_size, i;
  195146. png_uint_32 skip = 0;
  195147. png_size_t slength;
  195148. png_debug(1, "in png_handle_sPLT\n");
  195149. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195150. png_error(png_ptr, "Missing IHDR before sPLT");
  195151. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195152. {
  195153. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195154. png_crc_finish(png_ptr, length);
  195155. return;
  195156. }
  195157. #ifdef PNG_MAX_MALLOC_64K
  195158. if (length > (png_uint_32)65535L)
  195159. {
  195160. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195161. skip = length - (png_uint_32)65535L;
  195162. length = (png_uint_32)65535L;
  195163. }
  195164. #endif
  195165. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195166. slength = (png_size_t)length;
  195167. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195168. if (png_crc_finish(png_ptr, skip))
  195169. {
  195170. png_free(png_ptr, chunkdata);
  195171. return;
  195172. }
  195173. chunkdata[slength] = 0x00;
  195174. for (entry_start = chunkdata; *entry_start; entry_start++)
  195175. /* empty loop to find end of name */ ;
  195176. ++entry_start;
  195177. /* a sample depth should follow the separator, and we should be on it */
  195178. if (entry_start > chunkdata + slength - 2)
  195179. {
  195180. png_free(png_ptr, chunkdata);
  195181. png_warning(png_ptr, "malformed sPLT chunk");
  195182. return;
  195183. }
  195184. new_palette.depth = *entry_start++;
  195185. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195186. data_length = (slength - (entry_start - chunkdata));
  195187. /* integrity-check the data length */
  195188. if (data_length % entry_size)
  195189. {
  195190. png_free(png_ptr, chunkdata);
  195191. png_warning(png_ptr, "sPLT chunk has bad length");
  195192. return;
  195193. }
  195194. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195195. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195196. png_sizeof(png_sPLT_entry)))
  195197. {
  195198. png_warning(png_ptr, "sPLT chunk too long");
  195199. return;
  195200. }
  195201. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195202. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195203. if (new_palette.entries == NULL)
  195204. {
  195205. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195206. return;
  195207. }
  195208. #ifndef PNG_NO_POINTER_INDEXING
  195209. for (i = 0; i < new_palette.nentries; i++)
  195210. {
  195211. png_sPLT_entryp pp = new_palette.entries + i;
  195212. if (new_palette.depth == 8)
  195213. {
  195214. pp->red = *entry_start++;
  195215. pp->green = *entry_start++;
  195216. pp->blue = *entry_start++;
  195217. pp->alpha = *entry_start++;
  195218. }
  195219. else
  195220. {
  195221. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195222. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195223. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195224. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195225. }
  195226. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195227. }
  195228. #else
  195229. pp = new_palette.entries;
  195230. for (i = 0; i < new_palette.nentries; i++)
  195231. {
  195232. if (new_palette.depth == 8)
  195233. {
  195234. pp[i].red = *entry_start++;
  195235. pp[i].green = *entry_start++;
  195236. pp[i].blue = *entry_start++;
  195237. pp[i].alpha = *entry_start++;
  195238. }
  195239. else
  195240. {
  195241. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195242. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195243. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195244. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195245. }
  195246. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195247. }
  195248. #endif
  195249. /* discard all chunk data except the name and stash that */
  195250. new_palette.name = (png_charp)chunkdata;
  195251. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195252. png_free(png_ptr, chunkdata);
  195253. png_free(png_ptr, new_palette.entries);
  195254. }
  195255. #endif /* PNG_READ_sPLT_SUPPORTED */
  195256. #if defined(PNG_READ_tRNS_SUPPORTED)
  195257. void /* PRIVATE */
  195258. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195259. {
  195260. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195261. int bit_mask;
  195262. png_debug(1, "in png_handle_tRNS\n");
  195263. /* For non-indexed color, mask off any bits in the tRNS value that
  195264. * exceed the bit depth. Some creators were writing extra bits there.
  195265. * This is not needed for indexed color. */
  195266. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195267. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195268. png_error(png_ptr, "Missing IHDR before tRNS");
  195269. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195270. {
  195271. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195272. png_crc_finish(png_ptr, length);
  195273. return;
  195274. }
  195275. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195276. {
  195277. png_warning(png_ptr, "Duplicate tRNS chunk");
  195278. png_crc_finish(png_ptr, length);
  195279. return;
  195280. }
  195281. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195282. {
  195283. png_byte buf[2];
  195284. if (length != 2)
  195285. {
  195286. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195287. png_crc_finish(png_ptr, length);
  195288. return;
  195289. }
  195290. png_crc_read(png_ptr, buf, 2);
  195291. png_ptr->num_trans = 1;
  195292. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195293. }
  195294. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195295. {
  195296. png_byte buf[6];
  195297. if (length != 6)
  195298. {
  195299. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195300. png_crc_finish(png_ptr, length);
  195301. return;
  195302. }
  195303. png_crc_read(png_ptr, buf, (png_size_t)length);
  195304. png_ptr->num_trans = 1;
  195305. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195306. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195307. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195308. }
  195309. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195310. {
  195311. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195312. {
  195313. /* Should be an error, but we can cope with it. */
  195314. png_warning(png_ptr, "Missing PLTE before tRNS");
  195315. }
  195316. if (length > (png_uint_32)png_ptr->num_palette ||
  195317. length > PNG_MAX_PALETTE_LENGTH)
  195318. {
  195319. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195320. png_crc_finish(png_ptr, length);
  195321. return;
  195322. }
  195323. if (length == 0)
  195324. {
  195325. png_warning(png_ptr, "Zero length tRNS chunk");
  195326. png_crc_finish(png_ptr, length);
  195327. return;
  195328. }
  195329. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195330. png_ptr->num_trans = (png_uint_16)length;
  195331. }
  195332. else
  195333. {
  195334. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195335. png_crc_finish(png_ptr, length);
  195336. return;
  195337. }
  195338. if (png_crc_finish(png_ptr, 0))
  195339. {
  195340. png_ptr->num_trans = 0;
  195341. return;
  195342. }
  195343. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195344. &(png_ptr->trans_values));
  195345. }
  195346. #endif
  195347. #if defined(PNG_READ_bKGD_SUPPORTED)
  195348. void /* PRIVATE */
  195349. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195350. {
  195351. png_size_t truelen;
  195352. png_byte buf[6];
  195353. png_debug(1, "in png_handle_bKGD\n");
  195354. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195355. png_error(png_ptr, "Missing IHDR before bKGD");
  195356. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195357. {
  195358. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195359. png_crc_finish(png_ptr, length);
  195360. return;
  195361. }
  195362. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195363. !(png_ptr->mode & PNG_HAVE_PLTE))
  195364. {
  195365. png_warning(png_ptr, "Missing PLTE before bKGD");
  195366. png_crc_finish(png_ptr, length);
  195367. return;
  195368. }
  195369. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195370. {
  195371. png_warning(png_ptr, "Duplicate bKGD chunk");
  195372. png_crc_finish(png_ptr, length);
  195373. return;
  195374. }
  195375. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195376. truelen = 1;
  195377. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195378. truelen = 6;
  195379. else
  195380. truelen = 2;
  195381. if (length != truelen)
  195382. {
  195383. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195384. png_crc_finish(png_ptr, length);
  195385. return;
  195386. }
  195387. png_crc_read(png_ptr, buf, truelen);
  195388. if (png_crc_finish(png_ptr, 0))
  195389. return;
  195390. /* We convert the index value into RGB components so that we can allow
  195391. * arbitrary RGB values for background when we have transparency, and
  195392. * so it is easy to determine the RGB values of the background color
  195393. * from the info_ptr struct. */
  195394. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195395. {
  195396. png_ptr->background.index = buf[0];
  195397. if(info_ptr->num_palette)
  195398. {
  195399. if(buf[0] > info_ptr->num_palette)
  195400. {
  195401. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195402. return;
  195403. }
  195404. png_ptr->background.red =
  195405. (png_uint_16)png_ptr->palette[buf[0]].red;
  195406. png_ptr->background.green =
  195407. (png_uint_16)png_ptr->palette[buf[0]].green;
  195408. png_ptr->background.blue =
  195409. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195410. }
  195411. }
  195412. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195413. {
  195414. png_ptr->background.red =
  195415. png_ptr->background.green =
  195416. png_ptr->background.blue =
  195417. png_ptr->background.gray = png_get_uint_16(buf);
  195418. }
  195419. else
  195420. {
  195421. png_ptr->background.red = png_get_uint_16(buf);
  195422. png_ptr->background.green = png_get_uint_16(buf + 2);
  195423. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195424. }
  195425. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195426. }
  195427. #endif
  195428. #if defined(PNG_READ_hIST_SUPPORTED)
  195429. void /* PRIVATE */
  195430. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195431. {
  195432. unsigned int num, i;
  195433. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195434. png_debug(1, "in png_handle_hIST\n");
  195435. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195436. png_error(png_ptr, "Missing IHDR before hIST");
  195437. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195438. {
  195439. png_warning(png_ptr, "Invalid hIST after IDAT");
  195440. png_crc_finish(png_ptr, length);
  195441. return;
  195442. }
  195443. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195444. {
  195445. png_warning(png_ptr, "Missing PLTE before hIST");
  195446. png_crc_finish(png_ptr, length);
  195447. return;
  195448. }
  195449. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195450. {
  195451. png_warning(png_ptr, "Duplicate hIST chunk");
  195452. png_crc_finish(png_ptr, length);
  195453. return;
  195454. }
  195455. num = length / 2 ;
  195456. if (num != (unsigned int) png_ptr->num_palette || num >
  195457. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195458. {
  195459. png_warning(png_ptr, "Incorrect hIST chunk length");
  195460. png_crc_finish(png_ptr, length);
  195461. return;
  195462. }
  195463. for (i = 0; i < num; i++)
  195464. {
  195465. png_byte buf[2];
  195466. png_crc_read(png_ptr, buf, 2);
  195467. readbuf[i] = png_get_uint_16(buf);
  195468. }
  195469. if (png_crc_finish(png_ptr, 0))
  195470. return;
  195471. png_set_hIST(png_ptr, info_ptr, readbuf);
  195472. }
  195473. #endif
  195474. #if defined(PNG_READ_pHYs_SUPPORTED)
  195475. void /* PRIVATE */
  195476. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195477. {
  195478. png_byte buf[9];
  195479. png_uint_32 res_x, res_y;
  195480. int unit_type;
  195481. png_debug(1, "in png_handle_pHYs\n");
  195482. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195483. png_error(png_ptr, "Missing IHDR before pHYs");
  195484. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195485. {
  195486. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195487. png_crc_finish(png_ptr, length);
  195488. return;
  195489. }
  195490. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195491. {
  195492. png_warning(png_ptr, "Duplicate pHYs chunk");
  195493. png_crc_finish(png_ptr, length);
  195494. return;
  195495. }
  195496. if (length != 9)
  195497. {
  195498. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195499. png_crc_finish(png_ptr, length);
  195500. return;
  195501. }
  195502. png_crc_read(png_ptr, buf, 9);
  195503. if (png_crc_finish(png_ptr, 0))
  195504. return;
  195505. res_x = png_get_uint_32(buf);
  195506. res_y = png_get_uint_32(buf + 4);
  195507. unit_type = buf[8];
  195508. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195509. }
  195510. #endif
  195511. #if defined(PNG_READ_oFFs_SUPPORTED)
  195512. void /* PRIVATE */
  195513. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195514. {
  195515. png_byte buf[9];
  195516. png_int_32 offset_x, offset_y;
  195517. int unit_type;
  195518. png_debug(1, "in png_handle_oFFs\n");
  195519. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195520. png_error(png_ptr, "Missing IHDR before oFFs");
  195521. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195522. {
  195523. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195524. png_crc_finish(png_ptr, length);
  195525. return;
  195526. }
  195527. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195528. {
  195529. png_warning(png_ptr, "Duplicate oFFs chunk");
  195530. png_crc_finish(png_ptr, length);
  195531. return;
  195532. }
  195533. if (length != 9)
  195534. {
  195535. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195536. png_crc_finish(png_ptr, length);
  195537. return;
  195538. }
  195539. png_crc_read(png_ptr, buf, 9);
  195540. if (png_crc_finish(png_ptr, 0))
  195541. return;
  195542. offset_x = png_get_int_32(buf);
  195543. offset_y = png_get_int_32(buf + 4);
  195544. unit_type = buf[8];
  195545. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195546. }
  195547. #endif
  195548. #if defined(PNG_READ_pCAL_SUPPORTED)
  195549. /* read the pCAL chunk (described in the PNG Extensions document) */
  195550. void /* PRIVATE */
  195551. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195552. {
  195553. png_charp purpose;
  195554. png_int_32 X0, X1;
  195555. png_byte type, nparams;
  195556. png_charp buf, units, endptr;
  195557. png_charpp params;
  195558. png_size_t slength;
  195559. int i;
  195560. png_debug(1, "in png_handle_pCAL\n");
  195561. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195562. png_error(png_ptr, "Missing IHDR before pCAL");
  195563. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195564. {
  195565. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195566. png_crc_finish(png_ptr, length);
  195567. return;
  195568. }
  195569. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195570. {
  195571. png_warning(png_ptr, "Duplicate pCAL chunk");
  195572. png_crc_finish(png_ptr, length);
  195573. return;
  195574. }
  195575. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195576. length + 1);
  195577. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195578. if (purpose == NULL)
  195579. {
  195580. png_warning(png_ptr, "No memory for pCAL purpose.");
  195581. return;
  195582. }
  195583. slength = (png_size_t)length;
  195584. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195585. if (png_crc_finish(png_ptr, 0))
  195586. {
  195587. png_free(png_ptr, purpose);
  195588. return;
  195589. }
  195590. purpose[slength] = 0x00; /* null terminate the last string */
  195591. png_debug(3, "Finding end of pCAL purpose string\n");
  195592. for (buf = purpose; *buf; buf++)
  195593. /* empty loop */ ;
  195594. endptr = purpose + slength;
  195595. /* We need to have at least 12 bytes after the purpose string
  195596. in order to get the parameter information. */
  195597. if (endptr <= buf + 12)
  195598. {
  195599. png_warning(png_ptr, "Invalid pCAL data");
  195600. png_free(png_ptr, purpose);
  195601. return;
  195602. }
  195603. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195604. X0 = png_get_int_32((png_bytep)buf+1);
  195605. X1 = png_get_int_32((png_bytep)buf+5);
  195606. type = buf[9];
  195607. nparams = buf[10];
  195608. units = buf + 11;
  195609. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195610. /* Check that we have the right number of parameters for known
  195611. equation types. */
  195612. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195613. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195614. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195615. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195616. {
  195617. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195618. png_free(png_ptr, purpose);
  195619. return;
  195620. }
  195621. else if (type >= PNG_EQUATION_LAST)
  195622. {
  195623. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195624. }
  195625. for (buf = units; *buf; buf++)
  195626. /* Empty loop to move past the units string. */ ;
  195627. png_debug(3, "Allocating pCAL parameters array\n");
  195628. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195629. *png_sizeof(png_charp))) ;
  195630. if (params == NULL)
  195631. {
  195632. png_free(png_ptr, purpose);
  195633. png_warning(png_ptr, "No memory for pCAL params.");
  195634. return;
  195635. }
  195636. /* Get pointers to the start of each parameter string. */
  195637. for (i = 0; i < (int)nparams; i++)
  195638. {
  195639. buf++; /* Skip the null string terminator from previous parameter. */
  195640. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195641. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195642. /* Empty loop to move past each parameter string */ ;
  195643. /* Make sure we haven't run out of data yet */
  195644. if (buf > endptr)
  195645. {
  195646. png_warning(png_ptr, "Invalid pCAL data");
  195647. png_free(png_ptr, purpose);
  195648. png_free(png_ptr, params);
  195649. return;
  195650. }
  195651. }
  195652. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195653. units, params);
  195654. png_free(png_ptr, purpose);
  195655. png_free(png_ptr, params);
  195656. }
  195657. #endif
  195658. #if defined(PNG_READ_sCAL_SUPPORTED)
  195659. /* read the sCAL chunk */
  195660. void /* PRIVATE */
  195661. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195662. {
  195663. png_charp buffer, ep;
  195664. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195665. double width, height;
  195666. png_charp vp;
  195667. #else
  195668. #ifdef PNG_FIXED_POINT_SUPPORTED
  195669. png_charp swidth, sheight;
  195670. #endif
  195671. #endif
  195672. png_size_t slength;
  195673. png_debug(1, "in png_handle_sCAL\n");
  195674. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195675. png_error(png_ptr, "Missing IHDR before sCAL");
  195676. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195677. {
  195678. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195679. png_crc_finish(png_ptr, length);
  195680. return;
  195681. }
  195682. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195683. {
  195684. png_warning(png_ptr, "Duplicate sCAL chunk");
  195685. png_crc_finish(png_ptr, length);
  195686. return;
  195687. }
  195688. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195689. length + 1);
  195690. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195691. if (buffer == NULL)
  195692. {
  195693. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195694. return;
  195695. }
  195696. slength = (png_size_t)length;
  195697. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195698. if (png_crc_finish(png_ptr, 0))
  195699. {
  195700. png_free(png_ptr, buffer);
  195701. return;
  195702. }
  195703. buffer[slength] = 0x00; /* null terminate the last string */
  195704. ep = buffer + 1; /* skip unit byte */
  195705. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195706. width = png_strtod(png_ptr, ep, &vp);
  195707. if (*vp)
  195708. {
  195709. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195710. return;
  195711. }
  195712. #else
  195713. #ifdef PNG_FIXED_POINT_SUPPORTED
  195714. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195715. if (swidth == NULL)
  195716. {
  195717. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195718. return;
  195719. }
  195720. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195721. #endif
  195722. #endif
  195723. for (ep = buffer; *ep; ep++)
  195724. /* empty loop */ ;
  195725. ep++;
  195726. if (buffer + slength < ep)
  195727. {
  195728. png_warning(png_ptr, "Truncated sCAL chunk");
  195729. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195730. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195731. png_free(png_ptr, swidth);
  195732. #endif
  195733. png_free(png_ptr, buffer);
  195734. return;
  195735. }
  195736. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195737. height = png_strtod(png_ptr, ep, &vp);
  195738. if (*vp)
  195739. {
  195740. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195741. return;
  195742. }
  195743. #else
  195744. #ifdef PNG_FIXED_POINT_SUPPORTED
  195745. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195746. if (swidth == NULL)
  195747. {
  195748. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195749. return;
  195750. }
  195751. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195752. #endif
  195753. #endif
  195754. if (buffer + slength < ep
  195755. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195756. || width <= 0. || height <= 0.
  195757. #endif
  195758. )
  195759. {
  195760. png_warning(png_ptr, "Invalid sCAL data");
  195761. png_free(png_ptr, buffer);
  195762. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195763. png_free(png_ptr, swidth);
  195764. png_free(png_ptr, sheight);
  195765. #endif
  195766. return;
  195767. }
  195768. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195769. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195770. #else
  195771. #ifdef PNG_FIXED_POINT_SUPPORTED
  195772. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195773. #endif
  195774. #endif
  195775. png_free(png_ptr, buffer);
  195776. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195777. png_free(png_ptr, swidth);
  195778. png_free(png_ptr, sheight);
  195779. #endif
  195780. }
  195781. #endif
  195782. #if defined(PNG_READ_tIME_SUPPORTED)
  195783. void /* PRIVATE */
  195784. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195785. {
  195786. png_byte buf[7];
  195787. png_time mod_time;
  195788. png_debug(1, "in png_handle_tIME\n");
  195789. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195790. png_error(png_ptr, "Out of place tIME chunk");
  195791. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195792. {
  195793. png_warning(png_ptr, "Duplicate tIME chunk");
  195794. png_crc_finish(png_ptr, length);
  195795. return;
  195796. }
  195797. if (png_ptr->mode & PNG_HAVE_IDAT)
  195798. png_ptr->mode |= PNG_AFTER_IDAT;
  195799. if (length != 7)
  195800. {
  195801. png_warning(png_ptr, "Incorrect tIME chunk length");
  195802. png_crc_finish(png_ptr, length);
  195803. return;
  195804. }
  195805. png_crc_read(png_ptr, buf, 7);
  195806. if (png_crc_finish(png_ptr, 0))
  195807. return;
  195808. mod_time.second = buf[6];
  195809. mod_time.minute = buf[5];
  195810. mod_time.hour = buf[4];
  195811. mod_time.day = buf[3];
  195812. mod_time.month = buf[2];
  195813. mod_time.year = png_get_uint_16(buf);
  195814. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195815. }
  195816. #endif
  195817. #if defined(PNG_READ_tEXt_SUPPORTED)
  195818. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195819. void /* PRIVATE */
  195820. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195821. {
  195822. png_textp text_ptr;
  195823. png_charp key;
  195824. png_charp text;
  195825. png_uint_32 skip = 0;
  195826. png_size_t slength;
  195827. int ret;
  195828. png_debug(1, "in png_handle_tEXt\n");
  195829. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195830. png_error(png_ptr, "Missing IHDR before tEXt");
  195831. if (png_ptr->mode & PNG_HAVE_IDAT)
  195832. png_ptr->mode |= PNG_AFTER_IDAT;
  195833. #ifdef PNG_MAX_MALLOC_64K
  195834. if (length > (png_uint_32)65535L)
  195835. {
  195836. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195837. skip = length - (png_uint_32)65535L;
  195838. length = (png_uint_32)65535L;
  195839. }
  195840. #endif
  195841. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195842. if (key == NULL)
  195843. {
  195844. png_warning(png_ptr, "No memory to process text chunk.");
  195845. return;
  195846. }
  195847. slength = (png_size_t)length;
  195848. png_crc_read(png_ptr, (png_bytep)key, slength);
  195849. if (png_crc_finish(png_ptr, skip))
  195850. {
  195851. png_free(png_ptr, key);
  195852. return;
  195853. }
  195854. key[slength] = 0x00;
  195855. for (text = key; *text; text++)
  195856. /* empty loop to find end of key */ ;
  195857. if (text != key + slength)
  195858. text++;
  195859. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195860. (png_uint_32)png_sizeof(png_text));
  195861. if (text_ptr == NULL)
  195862. {
  195863. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195864. png_free(png_ptr, key);
  195865. return;
  195866. }
  195867. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195868. text_ptr->key = key;
  195869. #ifdef PNG_iTXt_SUPPORTED
  195870. text_ptr->lang = NULL;
  195871. text_ptr->lang_key = NULL;
  195872. text_ptr->itxt_length = 0;
  195873. #endif
  195874. text_ptr->text = text;
  195875. text_ptr->text_length = png_strlen(text);
  195876. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195877. png_free(png_ptr, key);
  195878. png_free(png_ptr, text_ptr);
  195879. if (ret)
  195880. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195881. }
  195882. #endif
  195883. #if defined(PNG_READ_zTXt_SUPPORTED)
  195884. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195885. void /* PRIVATE */
  195886. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195887. {
  195888. png_textp text_ptr;
  195889. png_charp chunkdata;
  195890. png_charp text;
  195891. int comp_type;
  195892. int ret;
  195893. png_size_t slength, prefix_len, data_len;
  195894. png_debug(1, "in png_handle_zTXt\n");
  195895. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195896. png_error(png_ptr, "Missing IHDR before zTXt");
  195897. if (png_ptr->mode & PNG_HAVE_IDAT)
  195898. png_ptr->mode |= PNG_AFTER_IDAT;
  195899. #ifdef PNG_MAX_MALLOC_64K
  195900. /* We will no doubt have problems with chunks even half this size, but
  195901. there is no hard and fast rule to tell us where to stop. */
  195902. if (length > (png_uint_32)65535L)
  195903. {
  195904. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195905. png_crc_finish(png_ptr, length);
  195906. return;
  195907. }
  195908. #endif
  195909. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195910. if (chunkdata == NULL)
  195911. {
  195912. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195913. return;
  195914. }
  195915. slength = (png_size_t)length;
  195916. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195917. if (png_crc_finish(png_ptr, 0))
  195918. {
  195919. png_free(png_ptr, chunkdata);
  195920. return;
  195921. }
  195922. chunkdata[slength] = 0x00;
  195923. for (text = chunkdata; *text; text++)
  195924. /* empty loop */ ;
  195925. /* zTXt must have some text after the chunkdataword */
  195926. if (text >= chunkdata + slength - 2)
  195927. {
  195928. png_warning(png_ptr, "Truncated zTXt chunk");
  195929. png_free(png_ptr, chunkdata);
  195930. return;
  195931. }
  195932. else
  195933. {
  195934. comp_type = *(++text);
  195935. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195936. {
  195937. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195938. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195939. }
  195940. text++; /* skip the compression_method byte */
  195941. }
  195942. prefix_len = text - chunkdata;
  195943. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195944. (png_size_t)length, prefix_len, &data_len);
  195945. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195946. (png_uint_32)png_sizeof(png_text));
  195947. if (text_ptr == NULL)
  195948. {
  195949. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195950. png_free(png_ptr, chunkdata);
  195951. return;
  195952. }
  195953. text_ptr->compression = comp_type;
  195954. text_ptr->key = chunkdata;
  195955. #ifdef PNG_iTXt_SUPPORTED
  195956. text_ptr->lang = NULL;
  195957. text_ptr->lang_key = NULL;
  195958. text_ptr->itxt_length = 0;
  195959. #endif
  195960. text_ptr->text = chunkdata + prefix_len;
  195961. text_ptr->text_length = data_len;
  195962. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195963. png_free(png_ptr, text_ptr);
  195964. png_free(png_ptr, chunkdata);
  195965. if (ret)
  195966. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195967. }
  195968. #endif
  195969. #if defined(PNG_READ_iTXt_SUPPORTED)
  195970. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195971. void /* PRIVATE */
  195972. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195973. {
  195974. png_textp text_ptr;
  195975. png_charp chunkdata;
  195976. png_charp key, lang, text, lang_key;
  195977. int comp_flag;
  195978. int comp_type = 0;
  195979. int ret;
  195980. png_size_t slength, prefix_len, data_len;
  195981. png_debug(1, "in png_handle_iTXt\n");
  195982. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195983. png_error(png_ptr, "Missing IHDR before iTXt");
  195984. if (png_ptr->mode & PNG_HAVE_IDAT)
  195985. png_ptr->mode |= PNG_AFTER_IDAT;
  195986. #ifdef PNG_MAX_MALLOC_64K
  195987. /* We will no doubt have problems with chunks even half this size, but
  195988. there is no hard and fast rule to tell us where to stop. */
  195989. if (length > (png_uint_32)65535L)
  195990. {
  195991. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195992. png_crc_finish(png_ptr, length);
  195993. return;
  195994. }
  195995. #endif
  195996. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195997. if (chunkdata == NULL)
  195998. {
  195999. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196000. return;
  196001. }
  196002. slength = (png_size_t)length;
  196003. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196004. if (png_crc_finish(png_ptr, 0))
  196005. {
  196006. png_free(png_ptr, chunkdata);
  196007. return;
  196008. }
  196009. chunkdata[slength] = 0x00;
  196010. for (lang = chunkdata; *lang; lang++)
  196011. /* empty loop */ ;
  196012. lang++; /* skip NUL separator */
  196013. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196014. translated keyword (possibly empty), and possibly some text after the
  196015. keyword */
  196016. if (lang >= chunkdata + slength - 3)
  196017. {
  196018. png_warning(png_ptr, "Truncated iTXt chunk");
  196019. png_free(png_ptr, chunkdata);
  196020. return;
  196021. }
  196022. else
  196023. {
  196024. comp_flag = *lang++;
  196025. comp_type = *lang++;
  196026. }
  196027. for (lang_key = lang; *lang_key; lang_key++)
  196028. /* empty loop */ ;
  196029. lang_key++; /* skip NUL separator */
  196030. if (lang_key >= chunkdata + slength)
  196031. {
  196032. png_warning(png_ptr, "Truncated iTXt chunk");
  196033. png_free(png_ptr, chunkdata);
  196034. return;
  196035. }
  196036. for (text = lang_key; *text; text++)
  196037. /* empty loop */ ;
  196038. text++; /* skip NUL separator */
  196039. if (text >= chunkdata + slength)
  196040. {
  196041. png_warning(png_ptr, "Malformed iTXt chunk");
  196042. png_free(png_ptr, chunkdata);
  196043. return;
  196044. }
  196045. prefix_len = text - chunkdata;
  196046. key=chunkdata;
  196047. if (comp_flag)
  196048. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196049. (size_t)length, prefix_len, &data_len);
  196050. else
  196051. data_len=png_strlen(chunkdata + prefix_len);
  196052. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196053. (png_uint_32)png_sizeof(png_text));
  196054. if (text_ptr == NULL)
  196055. {
  196056. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196057. png_free(png_ptr, chunkdata);
  196058. return;
  196059. }
  196060. text_ptr->compression = (int)comp_flag + 1;
  196061. text_ptr->lang_key = chunkdata+(lang_key-key);
  196062. text_ptr->lang = chunkdata+(lang-key);
  196063. text_ptr->itxt_length = data_len;
  196064. text_ptr->text_length = 0;
  196065. text_ptr->key = chunkdata;
  196066. text_ptr->text = chunkdata + prefix_len;
  196067. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196068. png_free(png_ptr, text_ptr);
  196069. png_free(png_ptr, chunkdata);
  196070. if (ret)
  196071. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196072. }
  196073. #endif
  196074. /* This function is called when we haven't found a handler for a
  196075. chunk. If there isn't a problem with the chunk itself (ie bad
  196076. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196077. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196078. case it will be saved away to be written out later. */
  196079. void /* PRIVATE */
  196080. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196081. {
  196082. png_uint_32 skip = 0;
  196083. png_debug(1, "in png_handle_unknown\n");
  196084. if (png_ptr->mode & PNG_HAVE_IDAT)
  196085. {
  196086. #ifdef PNG_USE_LOCAL_ARRAYS
  196087. PNG_CONST PNG_IDAT;
  196088. #endif
  196089. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196090. png_ptr->mode |= PNG_AFTER_IDAT;
  196091. }
  196092. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196093. if (!(png_ptr->chunk_name[0] & 0x20))
  196094. {
  196095. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196096. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196097. PNG_HANDLE_CHUNK_ALWAYS
  196098. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196099. && png_ptr->read_user_chunk_fn == NULL
  196100. #endif
  196101. )
  196102. #endif
  196103. png_chunk_error(png_ptr, "unknown critical chunk");
  196104. }
  196105. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196106. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196107. (png_ptr->read_user_chunk_fn != NULL))
  196108. {
  196109. #ifdef PNG_MAX_MALLOC_64K
  196110. if (length > (png_uint_32)65535L)
  196111. {
  196112. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196113. skip = length - (png_uint_32)65535L;
  196114. length = (png_uint_32)65535L;
  196115. }
  196116. #endif
  196117. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196118. (png_charp)png_ptr->chunk_name, 5);
  196119. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196120. png_ptr->unknown_chunk.size = (png_size_t)length;
  196121. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196122. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196123. if(png_ptr->read_user_chunk_fn != NULL)
  196124. {
  196125. /* callback to user unknown chunk handler */
  196126. int ret;
  196127. ret = (*(png_ptr->read_user_chunk_fn))
  196128. (png_ptr, &png_ptr->unknown_chunk);
  196129. if (ret < 0)
  196130. png_chunk_error(png_ptr, "error in user chunk");
  196131. if (ret == 0)
  196132. {
  196133. if (!(png_ptr->chunk_name[0] & 0x20))
  196134. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196135. PNG_HANDLE_CHUNK_ALWAYS)
  196136. png_chunk_error(png_ptr, "unknown critical chunk");
  196137. png_set_unknown_chunks(png_ptr, info_ptr,
  196138. &png_ptr->unknown_chunk, 1);
  196139. }
  196140. }
  196141. #else
  196142. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196143. #endif
  196144. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196145. png_ptr->unknown_chunk.data = NULL;
  196146. }
  196147. else
  196148. #endif
  196149. skip = length;
  196150. png_crc_finish(png_ptr, skip);
  196151. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196152. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196153. #endif
  196154. }
  196155. /* This function is called to verify that a chunk name is valid.
  196156. This function can't have the "critical chunk check" incorporated
  196157. into it, since in the future we will need to be able to call user
  196158. functions to handle unknown critical chunks after we check that
  196159. the chunk name itself is valid. */
  196160. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196161. void /* PRIVATE */
  196162. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196163. {
  196164. png_debug(1, "in png_check_chunk_name\n");
  196165. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196166. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196167. {
  196168. png_chunk_error(png_ptr, "invalid chunk type");
  196169. }
  196170. }
  196171. /* Combines the row recently read in with the existing pixels in the
  196172. row. This routine takes care of alpha and transparency if requested.
  196173. This routine also handles the two methods of progressive display
  196174. of interlaced images, depending on the mask value.
  196175. The mask value describes which pixels are to be combined with
  196176. the row. The pattern always repeats every 8 pixels, so just 8
  196177. bits are needed. A one indicates the pixel is to be combined,
  196178. a zero indicates the pixel is to be skipped. This is in addition
  196179. to any alpha or transparency value associated with the pixel. If
  196180. you want all pixels to be combined, pass 0xff (255) in mask. */
  196181. void /* PRIVATE */
  196182. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196183. {
  196184. png_debug(1,"in png_combine_row\n");
  196185. if (mask == 0xff)
  196186. {
  196187. png_memcpy(row, png_ptr->row_buf + 1,
  196188. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196189. }
  196190. else
  196191. {
  196192. switch (png_ptr->row_info.pixel_depth)
  196193. {
  196194. case 1:
  196195. {
  196196. png_bytep sp = png_ptr->row_buf + 1;
  196197. png_bytep dp = row;
  196198. int s_inc, s_start, s_end;
  196199. int m = 0x80;
  196200. int shift;
  196201. png_uint_32 i;
  196202. png_uint_32 row_width = png_ptr->width;
  196203. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196204. if (png_ptr->transformations & PNG_PACKSWAP)
  196205. {
  196206. s_start = 0;
  196207. s_end = 7;
  196208. s_inc = 1;
  196209. }
  196210. else
  196211. #endif
  196212. {
  196213. s_start = 7;
  196214. s_end = 0;
  196215. s_inc = -1;
  196216. }
  196217. shift = s_start;
  196218. for (i = 0; i < row_width; i++)
  196219. {
  196220. if (m & mask)
  196221. {
  196222. int value;
  196223. value = (*sp >> shift) & 0x01;
  196224. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196225. *dp |= (png_byte)(value << shift);
  196226. }
  196227. if (shift == s_end)
  196228. {
  196229. shift = s_start;
  196230. sp++;
  196231. dp++;
  196232. }
  196233. else
  196234. shift += s_inc;
  196235. if (m == 1)
  196236. m = 0x80;
  196237. else
  196238. m >>= 1;
  196239. }
  196240. break;
  196241. }
  196242. case 2:
  196243. {
  196244. png_bytep sp = png_ptr->row_buf + 1;
  196245. png_bytep dp = row;
  196246. int s_start, s_end, s_inc;
  196247. int m = 0x80;
  196248. int shift;
  196249. png_uint_32 i;
  196250. png_uint_32 row_width = png_ptr->width;
  196251. int value;
  196252. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196253. if (png_ptr->transformations & PNG_PACKSWAP)
  196254. {
  196255. s_start = 0;
  196256. s_end = 6;
  196257. s_inc = 2;
  196258. }
  196259. else
  196260. #endif
  196261. {
  196262. s_start = 6;
  196263. s_end = 0;
  196264. s_inc = -2;
  196265. }
  196266. shift = s_start;
  196267. for (i = 0; i < row_width; i++)
  196268. {
  196269. if (m & mask)
  196270. {
  196271. value = (*sp >> shift) & 0x03;
  196272. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196273. *dp |= (png_byte)(value << shift);
  196274. }
  196275. if (shift == s_end)
  196276. {
  196277. shift = s_start;
  196278. sp++;
  196279. dp++;
  196280. }
  196281. else
  196282. shift += s_inc;
  196283. if (m == 1)
  196284. m = 0x80;
  196285. else
  196286. m >>= 1;
  196287. }
  196288. break;
  196289. }
  196290. case 4:
  196291. {
  196292. png_bytep sp = png_ptr->row_buf + 1;
  196293. png_bytep dp = row;
  196294. int s_start, s_end, s_inc;
  196295. int m = 0x80;
  196296. int shift;
  196297. png_uint_32 i;
  196298. png_uint_32 row_width = png_ptr->width;
  196299. int value;
  196300. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196301. if (png_ptr->transformations & PNG_PACKSWAP)
  196302. {
  196303. s_start = 0;
  196304. s_end = 4;
  196305. s_inc = 4;
  196306. }
  196307. else
  196308. #endif
  196309. {
  196310. s_start = 4;
  196311. s_end = 0;
  196312. s_inc = -4;
  196313. }
  196314. shift = s_start;
  196315. for (i = 0; i < row_width; i++)
  196316. {
  196317. if (m & mask)
  196318. {
  196319. value = (*sp >> shift) & 0xf;
  196320. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196321. *dp |= (png_byte)(value << shift);
  196322. }
  196323. if (shift == s_end)
  196324. {
  196325. shift = s_start;
  196326. sp++;
  196327. dp++;
  196328. }
  196329. else
  196330. shift += s_inc;
  196331. if (m == 1)
  196332. m = 0x80;
  196333. else
  196334. m >>= 1;
  196335. }
  196336. break;
  196337. }
  196338. default:
  196339. {
  196340. png_bytep sp = png_ptr->row_buf + 1;
  196341. png_bytep dp = row;
  196342. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196343. png_uint_32 i;
  196344. png_uint_32 row_width = png_ptr->width;
  196345. png_byte m = 0x80;
  196346. for (i = 0; i < row_width; i++)
  196347. {
  196348. if (m & mask)
  196349. {
  196350. png_memcpy(dp, sp, pixel_bytes);
  196351. }
  196352. sp += pixel_bytes;
  196353. dp += pixel_bytes;
  196354. if (m == 1)
  196355. m = 0x80;
  196356. else
  196357. m >>= 1;
  196358. }
  196359. break;
  196360. }
  196361. }
  196362. }
  196363. }
  196364. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196365. /* OLD pre-1.0.9 interface:
  196366. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196367. png_uint_32 transformations)
  196368. */
  196369. void /* PRIVATE */
  196370. png_do_read_interlace(png_structp png_ptr)
  196371. {
  196372. png_row_infop row_info = &(png_ptr->row_info);
  196373. png_bytep row = png_ptr->row_buf + 1;
  196374. int pass = png_ptr->pass;
  196375. png_uint_32 transformations = png_ptr->transformations;
  196376. #ifdef PNG_USE_LOCAL_ARRAYS
  196377. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196378. /* offset to next interlace block */
  196379. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196380. #endif
  196381. png_debug(1,"in png_do_read_interlace\n");
  196382. if (row != NULL && row_info != NULL)
  196383. {
  196384. png_uint_32 final_width;
  196385. final_width = row_info->width * png_pass_inc[pass];
  196386. switch (row_info->pixel_depth)
  196387. {
  196388. case 1:
  196389. {
  196390. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196391. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196392. int sshift, dshift;
  196393. int s_start, s_end, s_inc;
  196394. int jstop = png_pass_inc[pass];
  196395. png_byte v;
  196396. png_uint_32 i;
  196397. int j;
  196398. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196399. if (transformations & PNG_PACKSWAP)
  196400. {
  196401. sshift = (int)((row_info->width + 7) & 0x07);
  196402. dshift = (int)((final_width + 7) & 0x07);
  196403. s_start = 7;
  196404. s_end = 0;
  196405. s_inc = -1;
  196406. }
  196407. else
  196408. #endif
  196409. {
  196410. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196411. dshift = 7 - (int)((final_width + 7) & 0x07);
  196412. s_start = 0;
  196413. s_end = 7;
  196414. s_inc = 1;
  196415. }
  196416. for (i = 0; i < row_info->width; i++)
  196417. {
  196418. v = (png_byte)((*sp >> sshift) & 0x01);
  196419. for (j = 0; j < jstop; j++)
  196420. {
  196421. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196422. *dp |= (png_byte)(v << dshift);
  196423. if (dshift == s_end)
  196424. {
  196425. dshift = s_start;
  196426. dp--;
  196427. }
  196428. else
  196429. dshift += s_inc;
  196430. }
  196431. if (sshift == s_end)
  196432. {
  196433. sshift = s_start;
  196434. sp--;
  196435. }
  196436. else
  196437. sshift += s_inc;
  196438. }
  196439. break;
  196440. }
  196441. case 2:
  196442. {
  196443. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196444. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196445. int sshift, dshift;
  196446. int s_start, s_end, s_inc;
  196447. int jstop = png_pass_inc[pass];
  196448. png_uint_32 i;
  196449. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196450. if (transformations & PNG_PACKSWAP)
  196451. {
  196452. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196453. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196454. s_start = 6;
  196455. s_end = 0;
  196456. s_inc = -2;
  196457. }
  196458. else
  196459. #endif
  196460. {
  196461. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196462. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196463. s_start = 0;
  196464. s_end = 6;
  196465. s_inc = 2;
  196466. }
  196467. for (i = 0; i < row_info->width; i++)
  196468. {
  196469. png_byte v;
  196470. int j;
  196471. v = (png_byte)((*sp >> sshift) & 0x03);
  196472. for (j = 0; j < jstop; j++)
  196473. {
  196474. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196475. *dp |= (png_byte)(v << dshift);
  196476. if (dshift == s_end)
  196477. {
  196478. dshift = s_start;
  196479. dp--;
  196480. }
  196481. else
  196482. dshift += s_inc;
  196483. }
  196484. if (sshift == s_end)
  196485. {
  196486. sshift = s_start;
  196487. sp--;
  196488. }
  196489. else
  196490. sshift += s_inc;
  196491. }
  196492. break;
  196493. }
  196494. case 4:
  196495. {
  196496. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196497. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196498. int sshift, dshift;
  196499. int s_start, s_end, s_inc;
  196500. png_uint_32 i;
  196501. int jstop = png_pass_inc[pass];
  196502. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196503. if (transformations & PNG_PACKSWAP)
  196504. {
  196505. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196506. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196507. s_start = 4;
  196508. s_end = 0;
  196509. s_inc = -4;
  196510. }
  196511. else
  196512. #endif
  196513. {
  196514. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196515. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196516. s_start = 0;
  196517. s_end = 4;
  196518. s_inc = 4;
  196519. }
  196520. for (i = 0; i < row_info->width; i++)
  196521. {
  196522. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196523. int j;
  196524. for (j = 0; j < jstop; j++)
  196525. {
  196526. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196527. *dp |= (png_byte)(v << dshift);
  196528. if (dshift == s_end)
  196529. {
  196530. dshift = s_start;
  196531. dp--;
  196532. }
  196533. else
  196534. dshift += s_inc;
  196535. }
  196536. if (sshift == s_end)
  196537. {
  196538. sshift = s_start;
  196539. sp--;
  196540. }
  196541. else
  196542. sshift += s_inc;
  196543. }
  196544. break;
  196545. }
  196546. default:
  196547. {
  196548. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196549. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196550. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196551. int jstop = png_pass_inc[pass];
  196552. png_uint_32 i;
  196553. for (i = 0; i < row_info->width; i++)
  196554. {
  196555. png_byte v[8];
  196556. int j;
  196557. png_memcpy(v, sp, pixel_bytes);
  196558. for (j = 0; j < jstop; j++)
  196559. {
  196560. png_memcpy(dp, v, pixel_bytes);
  196561. dp -= pixel_bytes;
  196562. }
  196563. sp -= pixel_bytes;
  196564. }
  196565. break;
  196566. }
  196567. }
  196568. row_info->width = final_width;
  196569. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196570. }
  196571. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196572. transformations = transformations; /* silence compiler warning */
  196573. #endif
  196574. }
  196575. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196576. void /* PRIVATE */
  196577. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196578. png_bytep prev_row, int filter)
  196579. {
  196580. png_debug(1, "in png_read_filter_row\n");
  196581. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196582. switch (filter)
  196583. {
  196584. case PNG_FILTER_VALUE_NONE:
  196585. break;
  196586. case PNG_FILTER_VALUE_SUB:
  196587. {
  196588. png_uint_32 i;
  196589. png_uint_32 istop = row_info->rowbytes;
  196590. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196591. png_bytep rp = row + bpp;
  196592. png_bytep lp = row;
  196593. for (i = bpp; i < istop; i++)
  196594. {
  196595. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196596. rp++;
  196597. }
  196598. break;
  196599. }
  196600. case PNG_FILTER_VALUE_UP:
  196601. {
  196602. png_uint_32 i;
  196603. png_uint_32 istop = row_info->rowbytes;
  196604. png_bytep rp = row;
  196605. png_bytep pp = prev_row;
  196606. for (i = 0; i < istop; i++)
  196607. {
  196608. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196609. rp++;
  196610. }
  196611. break;
  196612. }
  196613. case PNG_FILTER_VALUE_AVG:
  196614. {
  196615. png_uint_32 i;
  196616. png_bytep rp = row;
  196617. png_bytep pp = prev_row;
  196618. png_bytep lp = row;
  196619. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196620. png_uint_32 istop = row_info->rowbytes - bpp;
  196621. for (i = 0; i < bpp; i++)
  196622. {
  196623. *rp = (png_byte)(((int)(*rp) +
  196624. ((int)(*pp++) / 2 )) & 0xff);
  196625. rp++;
  196626. }
  196627. for (i = 0; i < istop; i++)
  196628. {
  196629. *rp = (png_byte)(((int)(*rp) +
  196630. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196631. rp++;
  196632. }
  196633. break;
  196634. }
  196635. case PNG_FILTER_VALUE_PAETH:
  196636. {
  196637. png_uint_32 i;
  196638. png_bytep rp = row;
  196639. png_bytep pp = prev_row;
  196640. png_bytep lp = row;
  196641. png_bytep cp = prev_row;
  196642. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196643. png_uint_32 istop=row_info->rowbytes - bpp;
  196644. for (i = 0; i < bpp; i++)
  196645. {
  196646. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196647. rp++;
  196648. }
  196649. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196650. {
  196651. int a, b, c, pa, pb, pc, p;
  196652. a = *lp++;
  196653. b = *pp++;
  196654. c = *cp++;
  196655. p = b - c;
  196656. pc = a - c;
  196657. #ifdef PNG_USE_ABS
  196658. pa = abs(p);
  196659. pb = abs(pc);
  196660. pc = abs(p + pc);
  196661. #else
  196662. pa = p < 0 ? -p : p;
  196663. pb = pc < 0 ? -pc : pc;
  196664. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196665. #endif
  196666. /*
  196667. if (pa <= pb && pa <= pc)
  196668. p = a;
  196669. else if (pb <= pc)
  196670. p = b;
  196671. else
  196672. p = c;
  196673. */
  196674. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196675. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196676. rp++;
  196677. }
  196678. break;
  196679. }
  196680. default:
  196681. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196682. *row=0;
  196683. break;
  196684. }
  196685. }
  196686. void /* PRIVATE */
  196687. png_read_finish_row(png_structp png_ptr)
  196688. {
  196689. #ifdef PNG_USE_LOCAL_ARRAYS
  196690. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196691. /* start of interlace block */
  196692. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196693. /* offset to next interlace block */
  196694. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196695. /* start of interlace block in the y direction */
  196696. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196697. /* offset to next interlace block in the y direction */
  196698. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196699. #endif
  196700. png_debug(1, "in png_read_finish_row\n");
  196701. png_ptr->row_number++;
  196702. if (png_ptr->row_number < png_ptr->num_rows)
  196703. return;
  196704. if (png_ptr->interlaced)
  196705. {
  196706. png_ptr->row_number = 0;
  196707. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196708. png_ptr->rowbytes + 1);
  196709. do
  196710. {
  196711. png_ptr->pass++;
  196712. if (png_ptr->pass >= 7)
  196713. break;
  196714. png_ptr->iwidth = (png_ptr->width +
  196715. png_pass_inc[png_ptr->pass] - 1 -
  196716. png_pass_start[png_ptr->pass]) /
  196717. png_pass_inc[png_ptr->pass];
  196718. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196719. png_ptr->iwidth) + 1;
  196720. if (!(png_ptr->transformations & PNG_INTERLACE))
  196721. {
  196722. png_ptr->num_rows = (png_ptr->height +
  196723. png_pass_yinc[png_ptr->pass] - 1 -
  196724. png_pass_ystart[png_ptr->pass]) /
  196725. png_pass_yinc[png_ptr->pass];
  196726. if (!(png_ptr->num_rows))
  196727. continue;
  196728. }
  196729. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196730. break;
  196731. } while (png_ptr->iwidth == 0);
  196732. if (png_ptr->pass < 7)
  196733. return;
  196734. }
  196735. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196736. {
  196737. #ifdef PNG_USE_LOCAL_ARRAYS
  196738. PNG_CONST PNG_IDAT;
  196739. #endif
  196740. char extra;
  196741. int ret;
  196742. png_ptr->zstream.next_out = (Bytef *)&extra;
  196743. png_ptr->zstream.avail_out = (uInt)1;
  196744. for(;;)
  196745. {
  196746. if (!(png_ptr->zstream.avail_in))
  196747. {
  196748. while (!png_ptr->idat_size)
  196749. {
  196750. png_byte chunk_length[4];
  196751. png_crc_finish(png_ptr, 0);
  196752. png_read_data(png_ptr, chunk_length, 4);
  196753. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196754. png_reset_crc(png_ptr);
  196755. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196756. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196757. png_error(png_ptr, "Not enough image data");
  196758. }
  196759. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196760. png_ptr->zstream.next_in = png_ptr->zbuf;
  196761. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196762. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196763. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196764. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196765. }
  196766. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196767. if (ret == Z_STREAM_END)
  196768. {
  196769. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196770. png_ptr->idat_size)
  196771. png_warning(png_ptr, "Extra compressed data");
  196772. png_ptr->mode |= PNG_AFTER_IDAT;
  196773. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196774. break;
  196775. }
  196776. if (ret != Z_OK)
  196777. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196778. "Decompression Error");
  196779. if (!(png_ptr->zstream.avail_out))
  196780. {
  196781. png_warning(png_ptr, "Extra compressed data.");
  196782. png_ptr->mode |= PNG_AFTER_IDAT;
  196783. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196784. break;
  196785. }
  196786. }
  196787. png_ptr->zstream.avail_out = 0;
  196788. }
  196789. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196790. png_warning(png_ptr, "Extra compression data");
  196791. inflateReset(&png_ptr->zstream);
  196792. png_ptr->mode |= PNG_AFTER_IDAT;
  196793. }
  196794. void /* PRIVATE */
  196795. png_read_start_row(png_structp png_ptr)
  196796. {
  196797. #ifdef PNG_USE_LOCAL_ARRAYS
  196798. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196799. /* start of interlace block */
  196800. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196801. /* offset to next interlace block */
  196802. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196803. /* start of interlace block in the y direction */
  196804. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196805. /* offset to next interlace block in the y direction */
  196806. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196807. #endif
  196808. int max_pixel_depth;
  196809. png_uint_32 row_bytes;
  196810. png_debug(1, "in png_read_start_row\n");
  196811. png_ptr->zstream.avail_in = 0;
  196812. png_init_read_transformations(png_ptr);
  196813. if (png_ptr->interlaced)
  196814. {
  196815. if (!(png_ptr->transformations & PNG_INTERLACE))
  196816. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196817. png_pass_ystart[0]) / png_pass_yinc[0];
  196818. else
  196819. png_ptr->num_rows = png_ptr->height;
  196820. png_ptr->iwidth = (png_ptr->width +
  196821. png_pass_inc[png_ptr->pass] - 1 -
  196822. png_pass_start[png_ptr->pass]) /
  196823. png_pass_inc[png_ptr->pass];
  196824. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196825. png_ptr->irowbytes = (png_size_t)row_bytes;
  196826. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196827. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196828. }
  196829. else
  196830. {
  196831. png_ptr->num_rows = png_ptr->height;
  196832. png_ptr->iwidth = png_ptr->width;
  196833. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196834. }
  196835. max_pixel_depth = png_ptr->pixel_depth;
  196836. #if defined(PNG_READ_PACK_SUPPORTED)
  196837. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196838. max_pixel_depth = 8;
  196839. #endif
  196840. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196841. if (png_ptr->transformations & PNG_EXPAND)
  196842. {
  196843. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196844. {
  196845. if (png_ptr->num_trans)
  196846. max_pixel_depth = 32;
  196847. else
  196848. max_pixel_depth = 24;
  196849. }
  196850. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196851. {
  196852. if (max_pixel_depth < 8)
  196853. max_pixel_depth = 8;
  196854. if (png_ptr->num_trans)
  196855. max_pixel_depth *= 2;
  196856. }
  196857. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196858. {
  196859. if (png_ptr->num_trans)
  196860. {
  196861. max_pixel_depth *= 4;
  196862. max_pixel_depth /= 3;
  196863. }
  196864. }
  196865. }
  196866. #endif
  196867. #if defined(PNG_READ_FILLER_SUPPORTED)
  196868. if (png_ptr->transformations & (PNG_FILLER))
  196869. {
  196870. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196871. max_pixel_depth = 32;
  196872. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196873. {
  196874. if (max_pixel_depth <= 8)
  196875. max_pixel_depth = 16;
  196876. else
  196877. max_pixel_depth = 32;
  196878. }
  196879. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196880. {
  196881. if (max_pixel_depth <= 32)
  196882. max_pixel_depth = 32;
  196883. else
  196884. max_pixel_depth = 64;
  196885. }
  196886. }
  196887. #endif
  196888. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196889. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196890. {
  196891. if (
  196892. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196893. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196894. #endif
  196895. #if defined(PNG_READ_FILLER_SUPPORTED)
  196896. (png_ptr->transformations & (PNG_FILLER)) ||
  196897. #endif
  196898. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196899. {
  196900. if (max_pixel_depth <= 16)
  196901. max_pixel_depth = 32;
  196902. else
  196903. max_pixel_depth = 64;
  196904. }
  196905. else
  196906. {
  196907. if (max_pixel_depth <= 8)
  196908. {
  196909. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196910. max_pixel_depth = 32;
  196911. else
  196912. max_pixel_depth = 24;
  196913. }
  196914. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196915. max_pixel_depth = 64;
  196916. else
  196917. max_pixel_depth = 48;
  196918. }
  196919. }
  196920. #endif
  196921. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196922. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196923. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196924. {
  196925. int user_pixel_depth=png_ptr->user_transform_depth*
  196926. png_ptr->user_transform_channels;
  196927. if(user_pixel_depth > max_pixel_depth)
  196928. max_pixel_depth=user_pixel_depth;
  196929. }
  196930. #endif
  196931. /* align the width on the next larger 8 pixels. Mainly used
  196932. for interlacing */
  196933. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196934. /* calculate the maximum bytes needed, adding a byte and a pixel
  196935. for safety's sake */
  196936. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196937. 1 + ((max_pixel_depth + 7) >> 3);
  196938. #ifdef PNG_MAX_MALLOC_64K
  196939. if (row_bytes > (png_uint_32)65536L)
  196940. png_error(png_ptr, "This image requires a row greater than 64KB");
  196941. #endif
  196942. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196943. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196944. #ifdef PNG_MAX_MALLOC_64K
  196945. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196946. png_error(png_ptr, "This image requires a row greater than 64KB");
  196947. #endif
  196948. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196949. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196950. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196951. png_ptr->rowbytes + 1));
  196952. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196953. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196954. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196955. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196956. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196957. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196958. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196959. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196960. }
  196961. #endif /* PNG_READ_SUPPORTED */
  196962. /*** End of inlined file: pngrutil.c ***/
  196963. /*** Start of inlined file: pngset.c ***/
  196964. /* pngset.c - storage of image information into info struct
  196965. *
  196966. * Last changed in libpng 1.2.21 [October 4, 2007]
  196967. * For conditions of distribution and use, see copyright notice in png.h
  196968. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196969. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196970. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196971. *
  196972. * The functions here are used during reads to store data from the file
  196973. * into the info struct, and during writes to store application data
  196974. * into the info struct for writing into the file. This abstracts the
  196975. * info struct and allows us to change the structure in the future.
  196976. */
  196977. #define PNG_INTERNAL
  196978. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196979. #if defined(PNG_bKGD_SUPPORTED)
  196980. void PNGAPI
  196981. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196982. {
  196983. png_debug1(1, "in %s storage function\n", "bKGD");
  196984. if (png_ptr == NULL || info_ptr == NULL)
  196985. return;
  196986. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196987. info_ptr->valid |= PNG_INFO_bKGD;
  196988. }
  196989. #endif
  196990. #if defined(PNG_cHRM_SUPPORTED)
  196991. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196992. void PNGAPI
  196993. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196994. double white_x, double white_y, double red_x, double red_y,
  196995. double green_x, double green_y, double blue_x, double blue_y)
  196996. {
  196997. png_debug1(1, "in %s storage function\n", "cHRM");
  196998. if (png_ptr == NULL || info_ptr == NULL)
  196999. return;
  197000. if (white_x < 0.0 || white_y < 0.0 ||
  197001. red_x < 0.0 || red_y < 0.0 ||
  197002. green_x < 0.0 || green_y < 0.0 ||
  197003. blue_x < 0.0 || blue_y < 0.0)
  197004. {
  197005. png_warning(png_ptr,
  197006. "Ignoring attempt to set negative chromaticity value");
  197007. return;
  197008. }
  197009. if (white_x > 21474.83 || white_y > 21474.83 ||
  197010. red_x > 21474.83 || red_y > 21474.83 ||
  197011. green_x > 21474.83 || green_y > 21474.83 ||
  197012. blue_x > 21474.83 || blue_y > 21474.83)
  197013. {
  197014. png_warning(png_ptr,
  197015. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197016. return;
  197017. }
  197018. info_ptr->x_white = (float)white_x;
  197019. info_ptr->y_white = (float)white_y;
  197020. info_ptr->x_red = (float)red_x;
  197021. info_ptr->y_red = (float)red_y;
  197022. info_ptr->x_green = (float)green_x;
  197023. info_ptr->y_green = (float)green_y;
  197024. info_ptr->x_blue = (float)blue_x;
  197025. info_ptr->y_blue = (float)blue_y;
  197026. #ifdef PNG_FIXED_POINT_SUPPORTED
  197027. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197028. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197029. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197030. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197031. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197032. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197033. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197034. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197035. #endif
  197036. info_ptr->valid |= PNG_INFO_cHRM;
  197037. }
  197038. #endif
  197039. #ifdef PNG_FIXED_POINT_SUPPORTED
  197040. void PNGAPI
  197041. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197042. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197043. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197044. png_fixed_point blue_x, png_fixed_point blue_y)
  197045. {
  197046. png_debug1(1, "in %s storage function\n", "cHRM");
  197047. if (png_ptr == NULL || info_ptr == NULL)
  197048. return;
  197049. if (white_x < 0 || white_y < 0 ||
  197050. red_x < 0 || red_y < 0 ||
  197051. green_x < 0 || green_y < 0 ||
  197052. blue_x < 0 || blue_y < 0)
  197053. {
  197054. png_warning(png_ptr,
  197055. "Ignoring attempt to set negative chromaticity value");
  197056. return;
  197057. }
  197058. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197059. if (white_x > (double) PNG_UINT_31_MAX ||
  197060. white_y > (double) PNG_UINT_31_MAX ||
  197061. red_x > (double) PNG_UINT_31_MAX ||
  197062. red_y > (double) PNG_UINT_31_MAX ||
  197063. green_x > (double) PNG_UINT_31_MAX ||
  197064. green_y > (double) PNG_UINT_31_MAX ||
  197065. blue_x > (double) PNG_UINT_31_MAX ||
  197066. blue_y > (double) PNG_UINT_31_MAX)
  197067. #else
  197068. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197069. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197070. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197071. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197072. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197073. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197074. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197075. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197076. #endif
  197077. {
  197078. png_warning(png_ptr,
  197079. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197080. return;
  197081. }
  197082. info_ptr->int_x_white = white_x;
  197083. info_ptr->int_y_white = white_y;
  197084. info_ptr->int_x_red = red_x;
  197085. info_ptr->int_y_red = red_y;
  197086. info_ptr->int_x_green = green_x;
  197087. info_ptr->int_y_green = green_y;
  197088. info_ptr->int_x_blue = blue_x;
  197089. info_ptr->int_y_blue = blue_y;
  197090. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197091. info_ptr->x_white = (float)(white_x/100000.);
  197092. info_ptr->y_white = (float)(white_y/100000.);
  197093. info_ptr->x_red = (float)( red_x/100000.);
  197094. info_ptr->y_red = (float)( red_y/100000.);
  197095. info_ptr->x_green = (float)(green_x/100000.);
  197096. info_ptr->y_green = (float)(green_y/100000.);
  197097. info_ptr->x_blue = (float)( blue_x/100000.);
  197098. info_ptr->y_blue = (float)( blue_y/100000.);
  197099. #endif
  197100. info_ptr->valid |= PNG_INFO_cHRM;
  197101. }
  197102. #endif
  197103. #endif
  197104. #if defined(PNG_gAMA_SUPPORTED)
  197105. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197106. void PNGAPI
  197107. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197108. {
  197109. double gamma;
  197110. png_debug1(1, "in %s storage function\n", "gAMA");
  197111. if (png_ptr == NULL || info_ptr == NULL)
  197112. return;
  197113. /* Check for overflow */
  197114. if (file_gamma > 21474.83)
  197115. {
  197116. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197117. gamma=21474.83;
  197118. }
  197119. else
  197120. gamma=file_gamma;
  197121. info_ptr->gamma = (float)gamma;
  197122. #ifdef PNG_FIXED_POINT_SUPPORTED
  197123. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197124. #endif
  197125. info_ptr->valid |= PNG_INFO_gAMA;
  197126. if(gamma == 0.0)
  197127. png_warning(png_ptr, "Setting gamma=0");
  197128. }
  197129. #endif
  197130. void PNGAPI
  197131. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197132. int_gamma)
  197133. {
  197134. png_fixed_point gamma;
  197135. png_debug1(1, "in %s storage function\n", "gAMA");
  197136. if (png_ptr == NULL || info_ptr == NULL)
  197137. return;
  197138. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197139. {
  197140. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197141. gamma=PNG_UINT_31_MAX;
  197142. }
  197143. else
  197144. {
  197145. if (int_gamma < 0)
  197146. {
  197147. png_warning(png_ptr, "Setting negative gamma to zero");
  197148. gamma=0;
  197149. }
  197150. else
  197151. gamma=int_gamma;
  197152. }
  197153. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197154. info_ptr->gamma = (float)(gamma/100000.);
  197155. #endif
  197156. #ifdef PNG_FIXED_POINT_SUPPORTED
  197157. info_ptr->int_gamma = gamma;
  197158. #endif
  197159. info_ptr->valid |= PNG_INFO_gAMA;
  197160. if(gamma == 0)
  197161. png_warning(png_ptr, "Setting gamma=0");
  197162. }
  197163. #endif
  197164. #if defined(PNG_hIST_SUPPORTED)
  197165. void PNGAPI
  197166. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197167. {
  197168. int i;
  197169. png_debug1(1, "in %s storage function\n", "hIST");
  197170. if (png_ptr == NULL || info_ptr == NULL)
  197171. return;
  197172. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197173. > PNG_MAX_PALETTE_LENGTH)
  197174. {
  197175. png_warning(png_ptr,
  197176. "Invalid palette size, hIST allocation skipped.");
  197177. return;
  197178. }
  197179. #ifdef PNG_FREE_ME_SUPPORTED
  197180. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197181. #endif
  197182. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197183. 1.2.1 */
  197184. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197185. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197186. if (png_ptr->hist == NULL)
  197187. {
  197188. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197189. return;
  197190. }
  197191. for (i = 0; i < info_ptr->num_palette; i++)
  197192. png_ptr->hist[i] = hist[i];
  197193. info_ptr->hist = png_ptr->hist;
  197194. info_ptr->valid |= PNG_INFO_hIST;
  197195. #ifdef PNG_FREE_ME_SUPPORTED
  197196. info_ptr->free_me |= PNG_FREE_HIST;
  197197. #else
  197198. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197199. #endif
  197200. }
  197201. #endif
  197202. void PNGAPI
  197203. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197204. png_uint_32 width, png_uint_32 height, int bit_depth,
  197205. int color_type, int interlace_type, int compression_type,
  197206. int filter_type)
  197207. {
  197208. png_debug1(1, "in %s storage function\n", "IHDR");
  197209. if (png_ptr == NULL || info_ptr == NULL)
  197210. return;
  197211. /* check for width and height valid values */
  197212. if (width == 0 || height == 0)
  197213. png_error(png_ptr, "Image width or height is zero in IHDR");
  197214. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197215. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197216. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197217. #else
  197218. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197219. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197220. #endif
  197221. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197222. png_error(png_ptr, "Invalid image size in IHDR");
  197223. if ( width > (PNG_UINT_32_MAX
  197224. >> 3) /* 8-byte RGBA pixels */
  197225. - 64 /* bigrowbuf hack */
  197226. - 1 /* filter byte */
  197227. - 7*8 /* rounding of width to multiple of 8 pixels */
  197228. - 8) /* extra max_pixel_depth pad */
  197229. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197230. /* check other values */
  197231. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197232. bit_depth != 8 && bit_depth != 16)
  197233. png_error(png_ptr, "Invalid bit depth in IHDR");
  197234. if (color_type < 0 || color_type == 1 ||
  197235. color_type == 5 || color_type > 6)
  197236. png_error(png_ptr, "Invalid color type in IHDR");
  197237. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197238. ((color_type == PNG_COLOR_TYPE_RGB ||
  197239. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197240. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197241. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197242. if (interlace_type >= PNG_INTERLACE_LAST)
  197243. png_error(png_ptr, "Unknown interlace method in IHDR");
  197244. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197245. png_error(png_ptr, "Unknown compression method in IHDR");
  197246. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197247. /* Accept filter_method 64 (intrapixel differencing) only if
  197248. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197249. * 2. Libpng did not read a PNG signature (this filter_method is only
  197250. * used in PNG datastreams that are embedded in MNG datastreams) and
  197251. * 3. The application called png_permit_mng_features with a mask that
  197252. * included PNG_FLAG_MNG_FILTER_64 and
  197253. * 4. The filter_method is 64 and
  197254. * 5. The color_type is RGB or RGBA
  197255. */
  197256. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197257. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197258. if(filter_type != PNG_FILTER_TYPE_BASE)
  197259. {
  197260. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197261. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197262. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197263. (color_type == PNG_COLOR_TYPE_RGB ||
  197264. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197265. png_error(png_ptr, "Unknown filter method in IHDR");
  197266. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197267. png_warning(png_ptr, "Invalid filter method in IHDR");
  197268. }
  197269. #else
  197270. if(filter_type != PNG_FILTER_TYPE_BASE)
  197271. png_error(png_ptr, "Unknown filter method in IHDR");
  197272. #endif
  197273. info_ptr->width = width;
  197274. info_ptr->height = height;
  197275. info_ptr->bit_depth = (png_byte)bit_depth;
  197276. info_ptr->color_type =(png_byte) color_type;
  197277. info_ptr->compression_type = (png_byte)compression_type;
  197278. info_ptr->filter_type = (png_byte)filter_type;
  197279. info_ptr->interlace_type = (png_byte)interlace_type;
  197280. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197281. info_ptr->channels = 1;
  197282. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197283. info_ptr->channels = 3;
  197284. else
  197285. info_ptr->channels = 1;
  197286. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197287. info_ptr->channels++;
  197288. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197289. /* check for potential overflow */
  197290. if (width > (PNG_UINT_32_MAX
  197291. >> 3) /* 8-byte RGBA pixels */
  197292. - 64 /* bigrowbuf hack */
  197293. - 1 /* filter byte */
  197294. - 7*8 /* rounding of width to multiple of 8 pixels */
  197295. - 8) /* extra max_pixel_depth pad */
  197296. info_ptr->rowbytes = (png_size_t)0;
  197297. else
  197298. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197299. }
  197300. #if defined(PNG_oFFs_SUPPORTED)
  197301. void PNGAPI
  197302. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197303. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197304. {
  197305. png_debug1(1, "in %s storage function\n", "oFFs");
  197306. if (png_ptr == NULL || info_ptr == NULL)
  197307. return;
  197308. info_ptr->x_offset = offset_x;
  197309. info_ptr->y_offset = offset_y;
  197310. info_ptr->offset_unit_type = (png_byte)unit_type;
  197311. info_ptr->valid |= PNG_INFO_oFFs;
  197312. }
  197313. #endif
  197314. #if defined(PNG_pCAL_SUPPORTED)
  197315. void PNGAPI
  197316. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197317. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197318. png_charp units, png_charpp params)
  197319. {
  197320. png_uint_32 length;
  197321. int i;
  197322. png_debug1(1, "in %s storage function\n", "pCAL");
  197323. if (png_ptr == NULL || info_ptr == NULL)
  197324. return;
  197325. length = png_strlen(purpose) + 1;
  197326. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197327. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197328. if (info_ptr->pcal_purpose == NULL)
  197329. {
  197330. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197331. return;
  197332. }
  197333. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197334. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197335. info_ptr->pcal_X0 = X0;
  197336. info_ptr->pcal_X1 = X1;
  197337. info_ptr->pcal_type = (png_byte)type;
  197338. info_ptr->pcal_nparams = (png_byte)nparams;
  197339. length = png_strlen(units) + 1;
  197340. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197341. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197342. if (info_ptr->pcal_units == NULL)
  197343. {
  197344. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197345. return;
  197346. }
  197347. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197348. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197349. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197350. if (info_ptr->pcal_params == NULL)
  197351. {
  197352. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197353. return;
  197354. }
  197355. info_ptr->pcal_params[nparams] = NULL;
  197356. for (i = 0; i < nparams; i++)
  197357. {
  197358. length = png_strlen(params[i]) + 1;
  197359. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197360. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197361. if (info_ptr->pcal_params[i] == NULL)
  197362. {
  197363. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197364. return;
  197365. }
  197366. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197367. }
  197368. info_ptr->valid |= PNG_INFO_pCAL;
  197369. #ifdef PNG_FREE_ME_SUPPORTED
  197370. info_ptr->free_me |= PNG_FREE_PCAL;
  197371. #endif
  197372. }
  197373. #endif
  197374. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197375. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197376. void PNGAPI
  197377. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197378. int unit, double width, double height)
  197379. {
  197380. png_debug1(1, "in %s storage function\n", "sCAL");
  197381. if (png_ptr == NULL || info_ptr == NULL)
  197382. return;
  197383. info_ptr->scal_unit = (png_byte)unit;
  197384. info_ptr->scal_pixel_width = width;
  197385. info_ptr->scal_pixel_height = height;
  197386. info_ptr->valid |= PNG_INFO_sCAL;
  197387. }
  197388. #else
  197389. #ifdef PNG_FIXED_POINT_SUPPORTED
  197390. void PNGAPI
  197391. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197392. int unit, png_charp swidth, png_charp sheight)
  197393. {
  197394. png_uint_32 length;
  197395. png_debug1(1, "in %s storage function\n", "sCAL");
  197396. if (png_ptr == NULL || info_ptr == NULL)
  197397. return;
  197398. info_ptr->scal_unit = (png_byte)unit;
  197399. length = png_strlen(swidth) + 1;
  197400. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197401. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197402. if (info_ptr->scal_s_width == NULL)
  197403. {
  197404. png_warning(png_ptr,
  197405. "Memory allocation failed while processing sCAL.");
  197406. }
  197407. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197408. length = png_strlen(sheight) + 1;
  197409. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197410. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197411. if (info_ptr->scal_s_height == NULL)
  197412. {
  197413. png_free (png_ptr, info_ptr->scal_s_width);
  197414. png_warning(png_ptr,
  197415. "Memory allocation failed while processing sCAL.");
  197416. }
  197417. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197418. info_ptr->valid |= PNG_INFO_sCAL;
  197419. #ifdef PNG_FREE_ME_SUPPORTED
  197420. info_ptr->free_me |= PNG_FREE_SCAL;
  197421. #endif
  197422. }
  197423. #endif
  197424. #endif
  197425. #endif
  197426. #if defined(PNG_pHYs_SUPPORTED)
  197427. void PNGAPI
  197428. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197429. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197430. {
  197431. png_debug1(1, "in %s storage function\n", "pHYs");
  197432. if (png_ptr == NULL || info_ptr == NULL)
  197433. return;
  197434. info_ptr->x_pixels_per_unit = res_x;
  197435. info_ptr->y_pixels_per_unit = res_y;
  197436. info_ptr->phys_unit_type = (png_byte)unit_type;
  197437. info_ptr->valid |= PNG_INFO_pHYs;
  197438. }
  197439. #endif
  197440. void PNGAPI
  197441. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197442. png_colorp palette, int num_palette)
  197443. {
  197444. png_debug1(1, "in %s storage function\n", "PLTE");
  197445. if (png_ptr == NULL || info_ptr == NULL)
  197446. return;
  197447. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197448. {
  197449. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197450. png_error(png_ptr, "Invalid palette length");
  197451. else
  197452. {
  197453. png_warning(png_ptr, "Invalid palette length");
  197454. return;
  197455. }
  197456. }
  197457. /*
  197458. * It may not actually be necessary to set png_ptr->palette here;
  197459. * we do it for backward compatibility with the way the png_handle_tRNS
  197460. * function used to do the allocation.
  197461. */
  197462. #ifdef PNG_FREE_ME_SUPPORTED
  197463. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197464. #endif
  197465. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197466. of num_palette entries,
  197467. in case of an invalid PNG file that has too-large sample values. */
  197468. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197469. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197470. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197471. png_sizeof(png_color));
  197472. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197473. info_ptr->palette = png_ptr->palette;
  197474. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197475. #ifdef PNG_FREE_ME_SUPPORTED
  197476. info_ptr->free_me |= PNG_FREE_PLTE;
  197477. #else
  197478. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197479. #endif
  197480. info_ptr->valid |= PNG_INFO_PLTE;
  197481. }
  197482. #if defined(PNG_sBIT_SUPPORTED)
  197483. void PNGAPI
  197484. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197485. png_color_8p sig_bit)
  197486. {
  197487. png_debug1(1, "in %s storage function\n", "sBIT");
  197488. if (png_ptr == NULL || info_ptr == NULL)
  197489. return;
  197490. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197491. info_ptr->valid |= PNG_INFO_sBIT;
  197492. }
  197493. #endif
  197494. #if defined(PNG_sRGB_SUPPORTED)
  197495. void PNGAPI
  197496. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197497. {
  197498. png_debug1(1, "in %s storage function\n", "sRGB");
  197499. if (png_ptr == NULL || info_ptr == NULL)
  197500. return;
  197501. info_ptr->srgb_intent = (png_byte)intent;
  197502. info_ptr->valid |= PNG_INFO_sRGB;
  197503. }
  197504. void PNGAPI
  197505. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197506. int intent)
  197507. {
  197508. #if defined(PNG_gAMA_SUPPORTED)
  197509. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197510. float file_gamma;
  197511. #endif
  197512. #ifdef PNG_FIXED_POINT_SUPPORTED
  197513. png_fixed_point int_file_gamma;
  197514. #endif
  197515. #endif
  197516. #if defined(PNG_cHRM_SUPPORTED)
  197517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197518. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197519. #endif
  197520. #ifdef PNG_FIXED_POINT_SUPPORTED
  197521. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197522. int_green_y, int_blue_x, int_blue_y;
  197523. #endif
  197524. #endif
  197525. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197526. if (png_ptr == NULL || info_ptr == NULL)
  197527. return;
  197528. png_set_sRGB(png_ptr, info_ptr, intent);
  197529. #if defined(PNG_gAMA_SUPPORTED)
  197530. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197531. file_gamma = (float).45455;
  197532. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197533. #endif
  197534. #ifdef PNG_FIXED_POINT_SUPPORTED
  197535. int_file_gamma = 45455L;
  197536. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197537. #endif
  197538. #endif
  197539. #if defined(PNG_cHRM_SUPPORTED)
  197540. #ifdef PNG_FIXED_POINT_SUPPORTED
  197541. int_white_x = 31270L;
  197542. int_white_y = 32900L;
  197543. int_red_x = 64000L;
  197544. int_red_y = 33000L;
  197545. int_green_x = 30000L;
  197546. int_green_y = 60000L;
  197547. int_blue_x = 15000L;
  197548. int_blue_y = 6000L;
  197549. png_set_cHRM_fixed(png_ptr, info_ptr,
  197550. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197551. int_blue_x, int_blue_y);
  197552. #endif
  197553. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197554. white_x = (float).3127;
  197555. white_y = (float).3290;
  197556. red_x = (float).64;
  197557. red_y = (float).33;
  197558. green_x = (float).30;
  197559. green_y = (float).60;
  197560. blue_x = (float).15;
  197561. blue_y = (float).06;
  197562. png_set_cHRM(png_ptr, info_ptr,
  197563. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197564. #endif
  197565. #endif
  197566. }
  197567. #endif
  197568. #if defined(PNG_iCCP_SUPPORTED)
  197569. void PNGAPI
  197570. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197571. png_charp name, int compression_type,
  197572. png_charp profile, png_uint_32 proflen)
  197573. {
  197574. png_charp new_iccp_name;
  197575. png_charp new_iccp_profile;
  197576. png_debug1(1, "in %s storage function\n", "iCCP");
  197577. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197578. return;
  197579. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197580. if (new_iccp_name == NULL)
  197581. {
  197582. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197583. return;
  197584. }
  197585. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197586. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197587. if (new_iccp_profile == NULL)
  197588. {
  197589. png_free (png_ptr, new_iccp_name);
  197590. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197591. return;
  197592. }
  197593. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197594. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197595. info_ptr->iccp_proflen = proflen;
  197596. info_ptr->iccp_name = new_iccp_name;
  197597. info_ptr->iccp_profile = new_iccp_profile;
  197598. /* Compression is always zero but is here so the API and info structure
  197599. * does not have to change if we introduce multiple compression types */
  197600. info_ptr->iccp_compression = (png_byte)compression_type;
  197601. #ifdef PNG_FREE_ME_SUPPORTED
  197602. info_ptr->free_me |= PNG_FREE_ICCP;
  197603. #endif
  197604. info_ptr->valid |= PNG_INFO_iCCP;
  197605. }
  197606. #endif
  197607. #if defined(PNG_TEXT_SUPPORTED)
  197608. void PNGAPI
  197609. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197610. int num_text)
  197611. {
  197612. int ret;
  197613. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197614. if (ret)
  197615. png_error(png_ptr, "Insufficient memory to store text");
  197616. }
  197617. int /* PRIVATE */
  197618. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197619. int num_text)
  197620. {
  197621. int i;
  197622. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197623. "text" : (png_const_charp)png_ptr->chunk_name));
  197624. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197625. return(0);
  197626. /* Make sure we have enough space in the "text" array in info_struct
  197627. * to hold all of the incoming text_ptr objects.
  197628. */
  197629. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197630. {
  197631. if (info_ptr->text != NULL)
  197632. {
  197633. png_textp old_text;
  197634. int old_max;
  197635. old_max = info_ptr->max_text;
  197636. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197637. old_text = info_ptr->text;
  197638. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197639. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197640. if (info_ptr->text == NULL)
  197641. {
  197642. png_free(png_ptr, old_text);
  197643. return(1);
  197644. }
  197645. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197646. png_sizeof(png_text)));
  197647. png_free(png_ptr, old_text);
  197648. }
  197649. else
  197650. {
  197651. info_ptr->max_text = num_text + 8;
  197652. info_ptr->num_text = 0;
  197653. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197654. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197655. if (info_ptr->text == NULL)
  197656. return(1);
  197657. #ifdef PNG_FREE_ME_SUPPORTED
  197658. info_ptr->free_me |= PNG_FREE_TEXT;
  197659. #endif
  197660. }
  197661. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197662. info_ptr->max_text);
  197663. }
  197664. for (i = 0; i < num_text; i++)
  197665. {
  197666. png_size_t text_length,key_len;
  197667. png_size_t lang_len,lang_key_len;
  197668. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197669. if (text_ptr[i].key == NULL)
  197670. continue;
  197671. key_len = png_strlen(text_ptr[i].key);
  197672. if(text_ptr[i].compression <= 0)
  197673. {
  197674. lang_len = 0;
  197675. lang_key_len = 0;
  197676. }
  197677. else
  197678. #ifdef PNG_iTXt_SUPPORTED
  197679. {
  197680. /* set iTXt data */
  197681. if (text_ptr[i].lang != NULL)
  197682. lang_len = png_strlen(text_ptr[i].lang);
  197683. else
  197684. lang_len = 0;
  197685. if (text_ptr[i].lang_key != NULL)
  197686. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197687. else
  197688. lang_key_len = 0;
  197689. }
  197690. #else
  197691. {
  197692. png_warning(png_ptr, "iTXt chunk not supported.");
  197693. continue;
  197694. }
  197695. #endif
  197696. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197697. {
  197698. text_length = 0;
  197699. #ifdef PNG_iTXt_SUPPORTED
  197700. if(text_ptr[i].compression > 0)
  197701. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197702. else
  197703. #endif
  197704. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197705. }
  197706. else
  197707. {
  197708. text_length = png_strlen(text_ptr[i].text);
  197709. textp->compression = text_ptr[i].compression;
  197710. }
  197711. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197712. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197713. if (textp->key == NULL)
  197714. return(1);
  197715. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197716. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197717. (int)textp->key);
  197718. png_memcpy(textp->key, text_ptr[i].key,
  197719. (png_size_t)(key_len));
  197720. *(textp->key+key_len) = '\0';
  197721. #ifdef PNG_iTXt_SUPPORTED
  197722. if (text_ptr[i].compression > 0)
  197723. {
  197724. textp->lang=textp->key + key_len + 1;
  197725. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197726. *(textp->lang+lang_len) = '\0';
  197727. textp->lang_key=textp->lang + lang_len + 1;
  197728. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197729. *(textp->lang_key+lang_key_len) = '\0';
  197730. textp->text=textp->lang_key + lang_key_len + 1;
  197731. }
  197732. else
  197733. #endif
  197734. {
  197735. #ifdef PNG_iTXt_SUPPORTED
  197736. textp->lang=NULL;
  197737. textp->lang_key=NULL;
  197738. #endif
  197739. textp->text=textp->key + key_len + 1;
  197740. }
  197741. if(text_length)
  197742. png_memcpy(textp->text, text_ptr[i].text,
  197743. (png_size_t)(text_length));
  197744. *(textp->text+text_length) = '\0';
  197745. #ifdef PNG_iTXt_SUPPORTED
  197746. if(textp->compression > 0)
  197747. {
  197748. textp->text_length = 0;
  197749. textp->itxt_length = text_length;
  197750. }
  197751. else
  197752. #endif
  197753. {
  197754. textp->text_length = text_length;
  197755. #ifdef PNG_iTXt_SUPPORTED
  197756. textp->itxt_length = 0;
  197757. #endif
  197758. }
  197759. info_ptr->num_text++;
  197760. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197761. }
  197762. return(0);
  197763. }
  197764. #endif
  197765. #if defined(PNG_tIME_SUPPORTED)
  197766. void PNGAPI
  197767. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197768. {
  197769. png_debug1(1, "in %s storage function\n", "tIME");
  197770. if (png_ptr == NULL || info_ptr == NULL ||
  197771. (png_ptr->mode & PNG_WROTE_tIME))
  197772. return;
  197773. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197774. info_ptr->valid |= PNG_INFO_tIME;
  197775. }
  197776. #endif
  197777. #if defined(PNG_tRNS_SUPPORTED)
  197778. void PNGAPI
  197779. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197780. png_bytep trans, int num_trans, png_color_16p trans_values)
  197781. {
  197782. png_debug1(1, "in %s storage function\n", "tRNS");
  197783. if (png_ptr == NULL || info_ptr == NULL)
  197784. return;
  197785. if (trans != NULL)
  197786. {
  197787. /*
  197788. * It may not actually be necessary to set png_ptr->trans here;
  197789. * we do it for backward compatibility with the way the png_handle_tRNS
  197790. * function used to do the allocation.
  197791. */
  197792. #ifdef PNG_FREE_ME_SUPPORTED
  197793. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197794. #endif
  197795. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197796. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197797. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197798. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197799. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197800. #ifdef PNG_FREE_ME_SUPPORTED
  197801. info_ptr->free_me |= PNG_FREE_TRNS;
  197802. #else
  197803. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197804. #endif
  197805. }
  197806. if (trans_values != NULL)
  197807. {
  197808. png_memcpy(&(info_ptr->trans_values), trans_values,
  197809. png_sizeof(png_color_16));
  197810. if (num_trans == 0)
  197811. num_trans = 1;
  197812. }
  197813. info_ptr->num_trans = (png_uint_16)num_trans;
  197814. info_ptr->valid |= PNG_INFO_tRNS;
  197815. }
  197816. #endif
  197817. #if defined(PNG_sPLT_SUPPORTED)
  197818. void PNGAPI
  197819. png_set_sPLT(png_structp png_ptr,
  197820. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197821. {
  197822. png_sPLT_tp np;
  197823. int i;
  197824. if (png_ptr == NULL || info_ptr == NULL)
  197825. return;
  197826. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197827. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197828. if (np == NULL)
  197829. {
  197830. png_warning(png_ptr, "No memory for sPLT palettes.");
  197831. return;
  197832. }
  197833. png_memcpy(np, info_ptr->splt_palettes,
  197834. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197835. png_free(png_ptr, info_ptr->splt_palettes);
  197836. info_ptr->splt_palettes=NULL;
  197837. for (i = 0; i < nentries; i++)
  197838. {
  197839. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197840. png_sPLT_tp from = entries + i;
  197841. to->name = (png_charp)png_malloc_warn(png_ptr,
  197842. png_strlen(from->name) + 1);
  197843. if (to->name == NULL)
  197844. {
  197845. png_warning(png_ptr,
  197846. "Out of memory while processing sPLT chunk");
  197847. }
  197848. /* TODO: use png_malloc_warn */
  197849. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197850. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197851. from->nentries * png_sizeof(png_sPLT_entry));
  197852. /* TODO: use png_malloc_warn */
  197853. png_memcpy(to->entries, from->entries,
  197854. from->nentries * png_sizeof(png_sPLT_entry));
  197855. if (to->entries == NULL)
  197856. {
  197857. png_warning(png_ptr,
  197858. "Out of memory while processing sPLT chunk");
  197859. png_free(png_ptr,to->name);
  197860. to->name = NULL;
  197861. }
  197862. to->nentries = from->nentries;
  197863. to->depth = from->depth;
  197864. }
  197865. info_ptr->splt_palettes = np;
  197866. info_ptr->splt_palettes_num += nentries;
  197867. info_ptr->valid |= PNG_INFO_sPLT;
  197868. #ifdef PNG_FREE_ME_SUPPORTED
  197869. info_ptr->free_me |= PNG_FREE_SPLT;
  197870. #endif
  197871. }
  197872. #endif /* PNG_sPLT_SUPPORTED */
  197873. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197874. void PNGAPI
  197875. png_set_unknown_chunks(png_structp png_ptr,
  197876. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197877. {
  197878. png_unknown_chunkp np;
  197879. int i;
  197880. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197881. return;
  197882. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197883. (info_ptr->unknown_chunks_num + num_unknowns) *
  197884. png_sizeof(png_unknown_chunk));
  197885. if (np == NULL)
  197886. {
  197887. png_warning(png_ptr,
  197888. "Out of memory while processing unknown chunk.");
  197889. return;
  197890. }
  197891. png_memcpy(np, info_ptr->unknown_chunks,
  197892. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197893. png_free(png_ptr, info_ptr->unknown_chunks);
  197894. info_ptr->unknown_chunks=NULL;
  197895. for (i = 0; i < num_unknowns; i++)
  197896. {
  197897. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197898. png_unknown_chunkp from = unknowns + i;
  197899. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197900. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197901. if (to->data == NULL)
  197902. {
  197903. png_warning(png_ptr,
  197904. "Out of memory while processing unknown chunk.");
  197905. }
  197906. else
  197907. {
  197908. png_memcpy(to->data, from->data, from->size);
  197909. to->size = from->size;
  197910. /* note our location in the read or write sequence */
  197911. to->location = (png_byte)(png_ptr->mode & 0xff);
  197912. }
  197913. }
  197914. info_ptr->unknown_chunks = np;
  197915. info_ptr->unknown_chunks_num += num_unknowns;
  197916. #ifdef PNG_FREE_ME_SUPPORTED
  197917. info_ptr->free_me |= PNG_FREE_UNKN;
  197918. #endif
  197919. }
  197920. void PNGAPI
  197921. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197922. int chunk, int location)
  197923. {
  197924. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197925. (int)info_ptr->unknown_chunks_num)
  197926. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197927. }
  197928. #endif
  197929. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197930. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197931. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197932. void PNGAPI
  197933. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197934. {
  197935. /* This function is deprecated in favor of png_permit_mng_features()
  197936. and will be removed from libpng-1.3.0 */
  197937. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197938. if (png_ptr == NULL)
  197939. return;
  197940. png_ptr->mng_features_permitted = (png_byte)
  197941. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197942. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197943. }
  197944. #endif
  197945. #endif
  197946. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197947. png_uint_32 PNGAPI
  197948. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197949. {
  197950. png_debug(1, "in png_permit_mng_features\n");
  197951. if (png_ptr == NULL)
  197952. return (png_uint_32)0;
  197953. png_ptr->mng_features_permitted =
  197954. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197955. return (png_uint_32)png_ptr->mng_features_permitted;
  197956. }
  197957. #endif
  197958. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197959. void PNGAPI
  197960. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197961. chunk_list, int num_chunks)
  197962. {
  197963. png_bytep new_list, p;
  197964. int i, old_num_chunks;
  197965. if (png_ptr == NULL)
  197966. return;
  197967. if (num_chunks == 0)
  197968. {
  197969. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197970. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197971. else
  197972. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197973. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197974. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197975. else
  197976. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197977. return;
  197978. }
  197979. if (chunk_list == NULL)
  197980. return;
  197981. old_num_chunks=png_ptr->num_chunk_list;
  197982. new_list=(png_bytep)png_malloc(png_ptr,
  197983. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197984. if(png_ptr->chunk_list != NULL)
  197985. {
  197986. png_memcpy(new_list, png_ptr->chunk_list,
  197987. (png_size_t)(5*old_num_chunks));
  197988. png_free(png_ptr, png_ptr->chunk_list);
  197989. png_ptr->chunk_list=NULL;
  197990. }
  197991. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197992. (png_size_t)(5*num_chunks));
  197993. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197994. *p=(png_byte)keep;
  197995. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197996. png_ptr->chunk_list=new_list;
  197997. #ifdef PNG_FREE_ME_SUPPORTED
  197998. png_ptr->free_me |= PNG_FREE_LIST;
  197999. #endif
  198000. }
  198001. #endif
  198002. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198003. void PNGAPI
  198004. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198005. png_user_chunk_ptr read_user_chunk_fn)
  198006. {
  198007. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198008. if (png_ptr == NULL)
  198009. return;
  198010. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198011. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198012. }
  198013. #endif
  198014. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198015. void PNGAPI
  198016. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198017. {
  198018. png_debug1(1, "in %s storage function\n", "rows");
  198019. if (png_ptr == NULL || info_ptr == NULL)
  198020. return;
  198021. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198022. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198023. info_ptr->row_pointers = row_pointers;
  198024. if(row_pointers)
  198025. info_ptr->valid |= PNG_INFO_IDAT;
  198026. }
  198027. #endif
  198028. #ifdef PNG_WRITE_SUPPORTED
  198029. void PNGAPI
  198030. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198031. {
  198032. if (png_ptr == NULL)
  198033. return;
  198034. if(png_ptr->zbuf)
  198035. png_free(png_ptr, png_ptr->zbuf);
  198036. png_ptr->zbuf_size = (png_size_t)size;
  198037. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198038. png_ptr->zstream.next_out = png_ptr->zbuf;
  198039. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198040. }
  198041. #endif
  198042. void PNGAPI
  198043. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198044. {
  198045. if (png_ptr && info_ptr)
  198046. info_ptr->valid &= ~(mask);
  198047. }
  198048. #ifndef PNG_1_0_X
  198049. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198050. /* function was added to libpng 1.2.0 and should always exist by default */
  198051. void PNGAPI
  198052. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198053. {
  198054. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198055. if (png_ptr != NULL)
  198056. png_ptr->asm_flags = 0;
  198057. }
  198058. /* this function was added to libpng 1.2.0 */
  198059. void PNGAPI
  198060. png_set_mmx_thresholds (png_structp png_ptr,
  198061. png_byte,
  198062. png_uint_32)
  198063. {
  198064. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198065. if (png_ptr == NULL)
  198066. return;
  198067. }
  198068. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198069. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198070. /* this function was added to libpng 1.2.6 */
  198071. void PNGAPI
  198072. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198073. png_uint_32 user_height_max)
  198074. {
  198075. /* Images with dimensions larger than these limits will be
  198076. * rejected by png_set_IHDR(). To accept any PNG datastream
  198077. * regardless of dimensions, set both limits to 0x7ffffffL.
  198078. */
  198079. if(png_ptr == NULL) return;
  198080. png_ptr->user_width_max = user_width_max;
  198081. png_ptr->user_height_max = user_height_max;
  198082. }
  198083. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198084. #endif /* ?PNG_1_0_X */
  198085. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198086. /*** End of inlined file: pngset.c ***/
  198087. /*** Start of inlined file: pngtrans.c ***/
  198088. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198089. *
  198090. * Last changed in libpng 1.2.17 May 15, 2007
  198091. * For conditions of distribution and use, see copyright notice in png.h
  198092. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198093. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198094. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198095. */
  198096. #define PNG_INTERNAL
  198097. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198098. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198099. /* turn on BGR-to-RGB mapping */
  198100. void PNGAPI
  198101. png_set_bgr(png_structp png_ptr)
  198102. {
  198103. png_debug(1, "in png_set_bgr\n");
  198104. if(png_ptr == NULL) return;
  198105. png_ptr->transformations |= PNG_BGR;
  198106. }
  198107. #endif
  198108. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198109. /* turn on 16 bit byte swapping */
  198110. void PNGAPI
  198111. png_set_swap(png_structp png_ptr)
  198112. {
  198113. png_debug(1, "in png_set_swap\n");
  198114. if(png_ptr == NULL) return;
  198115. if (png_ptr->bit_depth == 16)
  198116. png_ptr->transformations |= PNG_SWAP_BYTES;
  198117. }
  198118. #endif
  198119. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198120. /* turn on pixel packing */
  198121. void PNGAPI
  198122. png_set_packing(png_structp png_ptr)
  198123. {
  198124. png_debug(1, "in png_set_packing\n");
  198125. if(png_ptr == NULL) return;
  198126. if (png_ptr->bit_depth < 8)
  198127. {
  198128. png_ptr->transformations |= PNG_PACK;
  198129. png_ptr->usr_bit_depth = 8;
  198130. }
  198131. }
  198132. #endif
  198133. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198134. /* turn on packed pixel swapping */
  198135. void PNGAPI
  198136. png_set_packswap(png_structp png_ptr)
  198137. {
  198138. png_debug(1, "in png_set_packswap\n");
  198139. if(png_ptr == NULL) return;
  198140. if (png_ptr->bit_depth < 8)
  198141. png_ptr->transformations |= PNG_PACKSWAP;
  198142. }
  198143. #endif
  198144. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198145. void PNGAPI
  198146. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198147. {
  198148. png_debug(1, "in png_set_shift\n");
  198149. if(png_ptr == NULL) return;
  198150. png_ptr->transformations |= PNG_SHIFT;
  198151. png_ptr->shift = *true_bits;
  198152. }
  198153. #endif
  198154. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198155. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198156. int PNGAPI
  198157. png_set_interlace_handling(png_structp png_ptr)
  198158. {
  198159. png_debug(1, "in png_set_interlace handling\n");
  198160. if (png_ptr && png_ptr->interlaced)
  198161. {
  198162. png_ptr->transformations |= PNG_INTERLACE;
  198163. return (7);
  198164. }
  198165. return (1);
  198166. }
  198167. #endif
  198168. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198169. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198170. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198171. * for 48-bit input data, as well as to avoid problems with some compilers
  198172. * that don't like bytes as parameters.
  198173. */
  198174. void PNGAPI
  198175. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198176. {
  198177. png_debug(1, "in png_set_filler\n");
  198178. if(png_ptr == NULL) return;
  198179. png_ptr->transformations |= PNG_FILLER;
  198180. png_ptr->filler = (png_byte)filler;
  198181. if (filler_loc == PNG_FILLER_AFTER)
  198182. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198183. else
  198184. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198185. /* This should probably go in the "do_read_filler" routine.
  198186. * I attempted to do that in libpng-1.0.1a but that caused problems
  198187. * so I restored it in libpng-1.0.2a
  198188. */
  198189. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198190. {
  198191. png_ptr->usr_channels = 4;
  198192. }
  198193. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198194. * a less-than-8-bit grayscale to GA? */
  198195. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198196. {
  198197. png_ptr->usr_channels = 2;
  198198. }
  198199. }
  198200. #if !defined(PNG_1_0_X)
  198201. /* Added to libpng-1.2.7 */
  198202. void PNGAPI
  198203. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198204. {
  198205. png_debug(1, "in png_set_add_alpha\n");
  198206. if(png_ptr == NULL) return;
  198207. png_set_filler(png_ptr, filler, filler_loc);
  198208. png_ptr->transformations |= PNG_ADD_ALPHA;
  198209. }
  198210. #endif
  198211. #endif
  198212. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198213. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198214. void PNGAPI
  198215. png_set_swap_alpha(png_structp png_ptr)
  198216. {
  198217. png_debug(1, "in png_set_swap_alpha\n");
  198218. if(png_ptr == NULL) return;
  198219. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198220. }
  198221. #endif
  198222. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198223. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198224. void PNGAPI
  198225. png_set_invert_alpha(png_structp png_ptr)
  198226. {
  198227. png_debug(1, "in png_set_invert_alpha\n");
  198228. if(png_ptr == NULL) return;
  198229. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198230. }
  198231. #endif
  198232. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198233. void PNGAPI
  198234. png_set_invert_mono(png_structp png_ptr)
  198235. {
  198236. png_debug(1, "in png_set_invert_mono\n");
  198237. if(png_ptr == NULL) return;
  198238. png_ptr->transformations |= PNG_INVERT_MONO;
  198239. }
  198240. /* invert monochrome grayscale data */
  198241. void /* PRIVATE */
  198242. png_do_invert(png_row_infop row_info, png_bytep row)
  198243. {
  198244. png_debug(1, "in png_do_invert\n");
  198245. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198246. * if (row_info->bit_depth == 1 &&
  198247. */
  198248. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198249. if (row == NULL || row_info == NULL)
  198250. return;
  198251. #endif
  198252. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198253. {
  198254. png_bytep rp = row;
  198255. png_uint_32 i;
  198256. png_uint_32 istop = row_info->rowbytes;
  198257. for (i = 0; i < istop; i++)
  198258. {
  198259. *rp = (png_byte)(~(*rp));
  198260. rp++;
  198261. }
  198262. }
  198263. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198264. row_info->bit_depth == 8)
  198265. {
  198266. png_bytep rp = row;
  198267. png_uint_32 i;
  198268. png_uint_32 istop = row_info->rowbytes;
  198269. for (i = 0; i < istop; i+=2)
  198270. {
  198271. *rp = (png_byte)(~(*rp));
  198272. rp+=2;
  198273. }
  198274. }
  198275. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198276. row_info->bit_depth == 16)
  198277. {
  198278. png_bytep rp = row;
  198279. png_uint_32 i;
  198280. png_uint_32 istop = row_info->rowbytes;
  198281. for (i = 0; i < istop; i+=4)
  198282. {
  198283. *rp = (png_byte)(~(*rp));
  198284. *(rp+1) = (png_byte)(~(*(rp+1)));
  198285. rp+=4;
  198286. }
  198287. }
  198288. }
  198289. #endif
  198290. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198291. /* swaps byte order on 16 bit depth images */
  198292. void /* PRIVATE */
  198293. png_do_swap(png_row_infop row_info, png_bytep row)
  198294. {
  198295. png_debug(1, "in png_do_swap\n");
  198296. if (
  198297. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198298. row != NULL && row_info != NULL &&
  198299. #endif
  198300. row_info->bit_depth == 16)
  198301. {
  198302. png_bytep rp = row;
  198303. png_uint_32 i;
  198304. png_uint_32 istop= row_info->width * row_info->channels;
  198305. for (i = 0; i < istop; i++, rp += 2)
  198306. {
  198307. png_byte t = *rp;
  198308. *rp = *(rp + 1);
  198309. *(rp + 1) = t;
  198310. }
  198311. }
  198312. }
  198313. #endif
  198314. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198315. static PNG_CONST png_byte onebppswaptable[256] = {
  198316. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198317. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198318. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198319. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198320. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198321. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198322. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198323. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198324. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198325. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198326. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198327. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198328. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198329. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198330. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198331. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198332. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198333. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198334. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198335. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198336. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198337. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198338. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198339. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198340. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198341. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198342. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198343. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198344. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198345. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198346. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198347. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198348. };
  198349. static PNG_CONST png_byte twobppswaptable[256] = {
  198350. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198351. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198352. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198353. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198354. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198355. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198356. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198357. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198358. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198359. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198360. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198361. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198362. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198363. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198364. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198365. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198366. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198367. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198368. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198369. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198370. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198371. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198372. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198373. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198374. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198375. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198376. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198377. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198378. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198379. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198380. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198381. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198382. };
  198383. static PNG_CONST png_byte fourbppswaptable[256] = {
  198384. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198385. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198386. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198387. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198388. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198389. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198390. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198391. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198392. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198393. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198394. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198395. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198396. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198397. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198398. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198399. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198400. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198401. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198402. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198403. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198404. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198405. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198406. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198407. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198408. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198409. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198410. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198411. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198412. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198413. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198414. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198415. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198416. };
  198417. /* swaps pixel packing order within bytes */
  198418. void /* PRIVATE */
  198419. png_do_packswap(png_row_infop row_info, png_bytep row)
  198420. {
  198421. png_debug(1, "in png_do_packswap\n");
  198422. if (
  198423. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198424. row != NULL && row_info != NULL &&
  198425. #endif
  198426. row_info->bit_depth < 8)
  198427. {
  198428. png_bytep rp, end, table;
  198429. end = row + row_info->rowbytes;
  198430. if (row_info->bit_depth == 1)
  198431. table = (png_bytep)onebppswaptable;
  198432. else if (row_info->bit_depth == 2)
  198433. table = (png_bytep)twobppswaptable;
  198434. else if (row_info->bit_depth == 4)
  198435. table = (png_bytep)fourbppswaptable;
  198436. else
  198437. return;
  198438. for (rp = row; rp < end; rp++)
  198439. *rp = table[*rp];
  198440. }
  198441. }
  198442. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198443. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198444. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198445. /* remove filler or alpha byte(s) */
  198446. void /* PRIVATE */
  198447. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198448. {
  198449. png_debug(1, "in png_do_strip_filler\n");
  198450. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198451. if (row != NULL && row_info != NULL)
  198452. #endif
  198453. {
  198454. png_bytep sp=row;
  198455. png_bytep dp=row;
  198456. png_uint_32 row_width=row_info->width;
  198457. png_uint_32 i;
  198458. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198459. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198460. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198461. row_info->channels == 4)
  198462. {
  198463. if (row_info->bit_depth == 8)
  198464. {
  198465. /* This converts from RGBX or RGBA to RGB */
  198466. if (flags & PNG_FLAG_FILLER_AFTER)
  198467. {
  198468. dp+=3; sp+=4;
  198469. for (i = 1; i < row_width; i++)
  198470. {
  198471. *dp++ = *sp++;
  198472. *dp++ = *sp++;
  198473. *dp++ = *sp++;
  198474. sp++;
  198475. }
  198476. }
  198477. /* This converts from XRGB or ARGB to RGB */
  198478. else
  198479. {
  198480. for (i = 0; i < row_width; i++)
  198481. {
  198482. sp++;
  198483. *dp++ = *sp++;
  198484. *dp++ = *sp++;
  198485. *dp++ = *sp++;
  198486. }
  198487. }
  198488. row_info->pixel_depth = 24;
  198489. row_info->rowbytes = row_width * 3;
  198490. }
  198491. else /* if (row_info->bit_depth == 16) */
  198492. {
  198493. if (flags & PNG_FLAG_FILLER_AFTER)
  198494. {
  198495. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198496. sp += 8; dp += 6;
  198497. for (i = 1; i < row_width; i++)
  198498. {
  198499. /* This could be (although png_memcpy is probably slower):
  198500. png_memcpy(dp, sp, 6);
  198501. sp += 8;
  198502. dp += 6;
  198503. */
  198504. *dp++ = *sp++;
  198505. *dp++ = *sp++;
  198506. *dp++ = *sp++;
  198507. *dp++ = *sp++;
  198508. *dp++ = *sp++;
  198509. *dp++ = *sp++;
  198510. sp += 2;
  198511. }
  198512. }
  198513. else
  198514. {
  198515. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198516. for (i = 0; i < row_width; i++)
  198517. {
  198518. /* This could be (although png_memcpy is probably slower):
  198519. png_memcpy(dp, sp, 6);
  198520. sp += 8;
  198521. dp += 6;
  198522. */
  198523. sp+=2;
  198524. *dp++ = *sp++;
  198525. *dp++ = *sp++;
  198526. *dp++ = *sp++;
  198527. *dp++ = *sp++;
  198528. *dp++ = *sp++;
  198529. *dp++ = *sp++;
  198530. }
  198531. }
  198532. row_info->pixel_depth = 48;
  198533. row_info->rowbytes = row_width * 6;
  198534. }
  198535. row_info->channels = 3;
  198536. }
  198537. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198538. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198539. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198540. row_info->channels == 2)
  198541. {
  198542. if (row_info->bit_depth == 8)
  198543. {
  198544. /* This converts from GX or GA to G */
  198545. if (flags & PNG_FLAG_FILLER_AFTER)
  198546. {
  198547. for (i = 0; i < row_width; i++)
  198548. {
  198549. *dp++ = *sp++;
  198550. sp++;
  198551. }
  198552. }
  198553. /* This converts from XG or AG to G */
  198554. else
  198555. {
  198556. for (i = 0; i < row_width; i++)
  198557. {
  198558. sp++;
  198559. *dp++ = *sp++;
  198560. }
  198561. }
  198562. row_info->pixel_depth = 8;
  198563. row_info->rowbytes = row_width;
  198564. }
  198565. else /* if (row_info->bit_depth == 16) */
  198566. {
  198567. if (flags & PNG_FLAG_FILLER_AFTER)
  198568. {
  198569. /* This converts from GGXX or GGAA to GG */
  198570. sp += 4; dp += 2;
  198571. for (i = 1; i < row_width; i++)
  198572. {
  198573. *dp++ = *sp++;
  198574. *dp++ = *sp++;
  198575. sp += 2;
  198576. }
  198577. }
  198578. else
  198579. {
  198580. /* This converts from XXGG or AAGG to GG */
  198581. for (i = 0; i < row_width; i++)
  198582. {
  198583. sp += 2;
  198584. *dp++ = *sp++;
  198585. *dp++ = *sp++;
  198586. }
  198587. }
  198588. row_info->pixel_depth = 16;
  198589. row_info->rowbytes = row_width * 2;
  198590. }
  198591. row_info->channels = 1;
  198592. }
  198593. if (flags & PNG_FLAG_STRIP_ALPHA)
  198594. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198595. }
  198596. }
  198597. #endif
  198598. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198599. /* swaps red and blue bytes within a pixel */
  198600. void /* PRIVATE */
  198601. png_do_bgr(png_row_infop row_info, png_bytep row)
  198602. {
  198603. png_debug(1, "in png_do_bgr\n");
  198604. if (
  198605. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198606. row != NULL && row_info != NULL &&
  198607. #endif
  198608. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198609. {
  198610. png_uint_32 row_width = row_info->width;
  198611. if (row_info->bit_depth == 8)
  198612. {
  198613. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198614. {
  198615. png_bytep rp;
  198616. png_uint_32 i;
  198617. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198618. {
  198619. png_byte save = *rp;
  198620. *rp = *(rp + 2);
  198621. *(rp + 2) = save;
  198622. }
  198623. }
  198624. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198625. {
  198626. png_bytep rp;
  198627. png_uint_32 i;
  198628. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198629. {
  198630. png_byte save = *rp;
  198631. *rp = *(rp + 2);
  198632. *(rp + 2) = save;
  198633. }
  198634. }
  198635. }
  198636. else if (row_info->bit_depth == 16)
  198637. {
  198638. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198639. {
  198640. png_bytep rp;
  198641. png_uint_32 i;
  198642. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198643. {
  198644. png_byte save = *rp;
  198645. *rp = *(rp + 4);
  198646. *(rp + 4) = save;
  198647. save = *(rp + 1);
  198648. *(rp + 1) = *(rp + 5);
  198649. *(rp + 5) = save;
  198650. }
  198651. }
  198652. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198653. {
  198654. png_bytep rp;
  198655. png_uint_32 i;
  198656. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198657. {
  198658. png_byte save = *rp;
  198659. *rp = *(rp + 4);
  198660. *(rp + 4) = save;
  198661. save = *(rp + 1);
  198662. *(rp + 1) = *(rp + 5);
  198663. *(rp + 5) = save;
  198664. }
  198665. }
  198666. }
  198667. }
  198668. }
  198669. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198670. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198671. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198672. defined(PNG_LEGACY_SUPPORTED)
  198673. void PNGAPI
  198674. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198675. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198676. {
  198677. png_debug(1, "in png_set_user_transform_info\n");
  198678. if(png_ptr == NULL) return;
  198679. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198680. png_ptr->user_transform_ptr = user_transform_ptr;
  198681. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198682. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198683. #else
  198684. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198685. png_warning(png_ptr,
  198686. "This version of libpng does not support user transform info");
  198687. #endif
  198688. }
  198689. #endif
  198690. /* This function returns a pointer to the user_transform_ptr associated with
  198691. * the user transform functions. The application should free any memory
  198692. * associated with this pointer before png_write_destroy and png_read_destroy
  198693. * are called.
  198694. */
  198695. png_voidp PNGAPI
  198696. png_get_user_transform_ptr(png_structp png_ptr)
  198697. {
  198698. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198699. if (png_ptr == NULL) return (NULL);
  198700. return ((png_voidp)png_ptr->user_transform_ptr);
  198701. #else
  198702. return (NULL);
  198703. #endif
  198704. }
  198705. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198706. /*** End of inlined file: pngtrans.c ***/
  198707. /*** Start of inlined file: pngwio.c ***/
  198708. /* pngwio.c - functions for data output
  198709. *
  198710. * Last changed in libpng 1.2.13 November 13, 2006
  198711. * For conditions of distribution and use, see copyright notice in png.h
  198712. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198713. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198714. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198715. *
  198716. * This file provides a location for all output. Users who need
  198717. * special handling are expected to write functions that have the same
  198718. * arguments as these and perform similar functions, but that possibly
  198719. * use different output methods. Note that you shouldn't change these
  198720. * functions, but rather write replacement functions and then change
  198721. * them at run time with png_set_write_fn(...).
  198722. */
  198723. #define PNG_INTERNAL
  198724. #ifdef PNG_WRITE_SUPPORTED
  198725. /* Write the data to whatever output you are using. The default routine
  198726. writes to a file pointer. Note that this routine sometimes gets called
  198727. with very small lengths, so you should implement some kind of simple
  198728. buffering if you are using unbuffered writes. This should never be asked
  198729. to write more than 64K on a 16 bit machine. */
  198730. void /* PRIVATE */
  198731. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198732. {
  198733. if (png_ptr->write_data_fn != NULL )
  198734. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198735. else
  198736. png_error(png_ptr, "Call to NULL write function");
  198737. }
  198738. #if !defined(PNG_NO_STDIO)
  198739. /* This is the function that does the actual writing of data. If you are
  198740. not writing to a standard C stream, you should create a replacement
  198741. write_data function and use it at run time with png_set_write_fn(), rather
  198742. than changing the library. */
  198743. #ifndef USE_FAR_KEYWORD
  198744. void PNGAPI
  198745. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198746. {
  198747. png_uint_32 check;
  198748. if(png_ptr == NULL) return;
  198749. #if defined(_WIN32_WCE)
  198750. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198751. check = 0;
  198752. #else
  198753. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198754. #endif
  198755. if (check != length)
  198756. png_error(png_ptr, "Write Error");
  198757. }
  198758. #else
  198759. /* this is the model-independent version. Since the standard I/O library
  198760. can't handle far buffers in the medium and small models, we have to copy
  198761. the data.
  198762. */
  198763. #define NEAR_BUF_SIZE 1024
  198764. #define MIN(a,b) (a <= b ? a : b)
  198765. void PNGAPI
  198766. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198767. {
  198768. png_uint_32 check;
  198769. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198770. png_FILE_p io_ptr;
  198771. if(png_ptr == NULL) return;
  198772. /* Check if data really is near. If so, use usual code. */
  198773. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198774. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198775. if ((png_bytep)near_data == data)
  198776. {
  198777. #if defined(_WIN32_WCE)
  198778. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198779. check = 0;
  198780. #else
  198781. check = fwrite(near_data, 1, length, io_ptr);
  198782. #endif
  198783. }
  198784. else
  198785. {
  198786. png_byte buf[NEAR_BUF_SIZE];
  198787. png_size_t written, remaining, err;
  198788. check = 0;
  198789. remaining = length;
  198790. do
  198791. {
  198792. written = MIN(NEAR_BUF_SIZE, remaining);
  198793. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198794. #if defined(_WIN32_WCE)
  198795. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198796. err = 0;
  198797. #else
  198798. err = fwrite(buf, 1, written, io_ptr);
  198799. #endif
  198800. if (err != written)
  198801. break;
  198802. else
  198803. check += err;
  198804. data += written;
  198805. remaining -= written;
  198806. }
  198807. while (remaining != 0);
  198808. }
  198809. if (check != length)
  198810. png_error(png_ptr, "Write Error");
  198811. }
  198812. #endif
  198813. #endif
  198814. /* This function is called to output any data pending writing (normally
  198815. to disk). After png_flush is called, there should be no data pending
  198816. writing in any buffers. */
  198817. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198818. void /* PRIVATE */
  198819. png_flush(png_structp png_ptr)
  198820. {
  198821. if (png_ptr->output_flush_fn != NULL)
  198822. (*(png_ptr->output_flush_fn))(png_ptr);
  198823. }
  198824. #if !defined(PNG_NO_STDIO)
  198825. void PNGAPI
  198826. png_default_flush(png_structp png_ptr)
  198827. {
  198828. #if !defined(_WIN32_WCE)
  198829. png_FILE_p io_ptr;
  198830. #endif
  198831. if(png_ptr == NULL) return;
  198832. #if !defined(_WIN32_WCE)
  198833. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198834. if (io_ptr != NULL)
  198835. fflush(io_ptr);
  198836. #endif
  198837. }
  198838. #endif
  198839. #endif
  198840. /* This function allows the application to supply new output functions for
  198841. libpng if standard C streams aren't being used.
  198842. This function takes as its arguments:
  198843. png_ptr - pointer to a png output data structure
  198844. io_ptr - pointer to user supplied structure containing info about
  198845. the output functions. May be NULL.
  198846. write_data_fn - pointer to a new output function that takes as its
  198847. arguments a pointer to a png_struct, a pointer to
  198848. data to be written, and a 32-bit unsigned int that is
  198849. the number of bytes to be written. The new write
  198850. function should call png_error(png_ptr, "Error msg")
  198851. to exit and output any fatal error messages.
  198852. flush_data_fn - pointer to a new flush function that takes as its
  198853. arguments a pointer to a png_struct. After a call to
  198854. the flush function, there should be no data in any buffers
  198855. or pending transmission. If the output method doesn't do
  198856. any buffering of ouput, a function prototype must still be
  198857. supplied although it doesn't have to do anything. If
  198858. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198859. time, output_flush_fn will be ignored, although it must be
  198860. supplied for compatibility. */
  198861. void PNGAPI
  198862. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198863. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198864. {
  198865. if(png_ptr == NULL) return;
  198866. png_ptr->io_ptr = io_ptr;
  198867. #if !defined(PNG_NO_STDIO)
  198868. if (write_data_fn != NULL)
  198869. png_ptr->write_data_fn = write_data_fn;
  198870. else
  198871. png_ptr->write_data_fn = png_default_write_data;
  198872. #else
  198873. png_ptr->write_data_fn = write_data_fn;
  198874. #endif
  198875. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198876. #if !defined(PNG_NO_STDIO)
  198877. if (output_flush_fn != NULL)
  198878. png_ptr->output_flush_fn = output_flush_fn;
  198879. else
  198880. png_ptr->output_flush_fn = png_default_flush;
  198881. #else
  198882. png_ptr->output_flush_fn = output_flush_fn;
  198883. #endif
  198884. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198885. /* It is an error to read while writing a png file */
  198886. if (png_ptr->read_data_fn != NULL)
  198887. {
  198888. png_ptr->read_data_fn = NULL;
  198889. png_warning(png_ptr,
  198890. "Attempted to set both read_data_fn and write_data_fn in");
  198891. png_warning(png_ptr,
  198892. "the same structure. Resetting read_data_fn to NULL.");
  198893. }
  198894. }
  198895. #if defined(USE_FAR_KEYWORD)
  198896. #if defined(_MSC_VER)
  198897. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198898. {
  198899. void *near_ptr;
  198900. void FAR *far_ptr;
  198901. FP_OFF(near_ptr) = FP_OFF(ptr);
  198902. far_ptr = (void FAR *)near_ptr;
  198903. if(check != 0)
  198904. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198905. png_error(png_ptr,"segment lost in conversion");
  198906. return(near_ptr);
  198907. }
  198908. # else
  198909. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198910. {
  198911. void *near_ptr;
  198912. void FAR *far_ptr;
  198913. near_ptr = (void FAR *)ptr;
  198914. far_ptr = (void FAR *)near_ptr;
  198915. if(check != 0)
  198916. if(far_ptr != ptr)
  198917. png_error(png_ptr,"segment lost in conversion");
  198918. return(near_ptr);
  198919. }
  198920. # endif
  198921. # endif
  198922. #endif /* PNG_WRITE_SUPPORTED */
  198923. /*** End of inlined file: pngwio.c ***/
  198924. /*** Start of inlined file: pngwrite.c ***/
  198925. /* pngwrite.c - general routines to write a PNG file
  198926. *
  198927. * Last changed in libpng 1.2.15 January 5, 2007
  198928. * For conditions of distribution and use, see copyright notice in png.h
  198929. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198930. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198931. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198932. */
  198933. /* get internal access to png.h */
  198934. #define PNG_INTERNAL
  198935. #ifdef PNG_WRITE_SUPPORTED
  198936. /* Writes all the PNG information. This is the suggested way to use the
  198937. * library. If you have a new chunk to add, make a function to write it,
  198938. * and put it in the correct location here. If you want the chunk written
  198939. * after the image data, put it in png_write_end(). I strongly encourage
  198940. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198941. * the chunk, as that will keep the code from breaking if you want to just
  198942. * write a plain PNG file. If you have long comments, I suggest writing
  198943. * them in png_write_end(), and compressing them.
  198944. */
  198945. void PNGAPI
  198946. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198947. {
  198948. png_debug(1, "in png_write_info_before_PLTE\n");
  198949. if (png_ptr == NULL || info_ptr == NULL)
  198950. return;
  198951. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198952. {
  198953. png_write_sig(png_ptr); /* write PNG signature */
  198954. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198955. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198956. {
  198957. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198958. png_ptr->mng_features_permitted=0;
  198959. }
  198960. #endif
  198961. /* write IHDR information. */
  198962. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198963. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198964. info_ptr->filter_type,
  198965. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198966. info_ptr->interlace_type);
  198967. #else
  198968. 0);
  198969. #endif
  198970. /* the rest of these check to see if the valid field has the appropriate
  198971. flag set, and if it does, writes the chunk. */
  198972. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198973. if (info_ptr->valid & PNG_INFO_gAMA)
  198974. {
  198975. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198976. png_write_gAMA(png_ptr, info_ptr->gamma);
  198977. #else
  198978. #ifdef PNG_FIXED_POINT_SUPPORTED
  198979. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198980. # endif
  198981. #endif
  198982. }
  198983. #endif
  198984. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198985. if (info_ptr->valid & PNG_INFO_sRGB)
  198986. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198987. #endif
  198988. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198989. if (info_ptr->valid & PNG_INFO_iCCP)
  198990. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198991. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198992. #endif
  198993. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198994. if (info_ptr->valid & PNG_INFO_sBIT)
  198995. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198996. #endif
  198997. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198998. if (info_ptr->valid & PNG_INFO_cHRM)
  198999. {
  199000. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199001. png_write_cHRM(png_ptr,
  199002. info_ptr->x_white, info_ptr->y_white,
  199003. info_ptr->x_red, info_ptr->y_red,
  199004. info_ptr->x_green, info_ptr->y_green,
  199005. info_ptr->x_blue, info_ptr->y_blue);
  199006. #else
  199007. # ifdef PNG_FIXED_POINT_SUPPORTED
  199008. png_write_cHRM_fixed(png_ptr,
  199009. info_ptr->int_x_white, info_ptr->int_y_white,
  199010. info_ptr->int_x_red, info_ptr->int_y_red,
  199011. info_ptr->int_x_green, info_ptr->int_y_green,
  199012. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199013. # endif
  199014. #endif
  199015. }
  199016. #endif
  199017. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199018. if (info_ptr->unknown_chunks_num)
  199019. {
  199020. png_unknown_chunk *up;
  199021. png_debug(5, "writing extra chunks\n");
  199022. for (up = info_ptr->unknown_chunks;
  199023. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199024. up++)
  199025. {
  199026. int keep=png_handle_as_unknown(png_ptr, up->name);
  199027. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199028. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199029. !(up->location & PNG_HAVE_IDAT) &&
  199030. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199031. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199032. {
  199033. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199034. }
  199035. }
  199036. }
  199037. #endif
  199038. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199039. }
  199040. }
  199041. void PNGAPI
  199042. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199043. {
  199044. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199045. int i;
  199046. #endif
  199047. png_debug(1, "in png_write_info\n");
  199048. if (png_ptr == NULL || info_ptr == NULL)
  199049. return;
  199050. png_write_info_before_PLTE(png_ptr, info_ptr);
  199051. if (info_ptr->valid & PNG_INFO_PLTE)
  199052. png_write_PLTE(png_ptr, info_ptr->palette,
  199053. (png_uint_32)info_ptr->num_palette);
  199054. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199055. png_error(png_ptr, "Valid palette required for paletted images");
  199056. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199057. if (info_ptr->valid & PNG_INFO_tRNS)
  199058. {
  199059. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199060. /* invert the alpha channel (in tRNS) */
  199061. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199062. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199063. {
  199064. int j;
  199065. for (j=0; j<(int)info_ptr->num_trans; j++)
  199066. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199067. }
  199068. #endif
  199069. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199070. info_ptr->num_trans, info_ptr->color_type);
  199071. }
  199072. #endif
  199073. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199074. if (info_ptr->valid & PNG_INFO_bKGD)
  199075. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199076. #endif
  199077. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199078. if (info_ptr->valid & PNG_INFO_hIST)
  199079. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199080. #endif
  199081. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199082. if (info_ptr->valid & PNG_INFO_oFFs)
  199083. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199084. info_ptr->offset_unit_type);
  199085. #endif
  199086. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199087. if (info_ptr->valid & PNG_INFO_pCAL)
  199088. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199089. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199090. info_ptr->pcal_units, info_ptr->pcal_params);
  199091. #endif
  199092. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199093. if (info_ptr->valid & PNG_INFO_sCAL)
  199094. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199095. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199096. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199097. #else
  199098. #ifdef PNG_FIXED_POINT_SUPPORTED
  199099. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199100. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199101. #else
  199102. png_warning(png_ptr,
  199103. "png_write_sCAL not supported; sCAL chunk not written.");
  199104. #endif
  199105. #endif
  199106. #endif
  199107. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199108. if (info_ptr->valid & PNG_INFO_pHYs)
  199109. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199110. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199111. #endif
  199112. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199113. if (info_ptr->valid & PNG_INFO_tIME)
  199114. {
  199115. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199116. png_ptr->mode |= PNG_WROTE_tIME;
  199117. }
  199118. #endif
  199119. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199120. if (info_ptr->valid & PNG_INFO_sPLT)
  199121. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199122. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199123. #endif
  199124. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199125. /* Check to see if we need to write text chunks */
  199126. for (i = 0; i < info_ptr->num_text; i++)
  199127. {
  199128. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199129. info_ptr->text[i].compression);
  199130. /* an internationalized chunk? */
  199131. if (info_ptr->text[i].compression > 0)
  199132. {
  199133. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199134. /* write international chunk */
  199135. png_write_iTXt(png_ptr,
  199136. info_ptr->text[i].compression,
  199137. info_ptr->text[i].key,
  199138. info_ptr->text[i].lang,
  199139. info_ptr->text[i].lang_key,
  199140. info_ptr->text[i].text);
  199141. #else
  199142. png_warning(png_ptr, "Unable to write international text");
  199143. #endif
  199144. /* Mark this chunk as written */
  199145. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199146. }
  199147. /* If we want a compressed text chunk */
  199148. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199149. {
  199150. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199151. /* write compressed chunk */
  199152. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199153. info_ptr->text[i].text, 0,
  199154. info_ptr->text[i].compression);
  199155. #else
  199156. png_warning(png_ptr, "Unable to write compressed text");
  199157. #endif
  199158. /* Mark this chunk as written */
  199159. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199160. }
  199161. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199162. {
  199163. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199164. /* write uncompressed chunk */
  199165. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199166. info_ptr->text[i].text,
  199167. 0);
  199168. #else
  199169. png_warning(png_ptr, "Unable to write uncompressed text");
  199170. #endif
  199171. /* Mark this chunk as written */
  199172. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199173. }
  199174. }
  199175. #endif
  199176. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199177. if (info_ptr->unknown_chunks_num)
  199178. {
  199179. png_unknown_chunk *up;
  199180. png_debug(5, "writing extra chunks\n");
  199181. for (up = info_ptr->unknown_chunks;
  199182. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199183. up++)
  199184. {
  199185. int keep=png_handle_as_unknown(png_ptr, up->name);
  199186. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199187. up->location && (up->location & PNG_HAVE_PLTE) &&
  199188. !(up->location & PNG_HAVE_IDAT) &&
  199189. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199190. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199191. {
  199192. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199193. }
  199194. }
  199195. }
  199196. #endif
  199197. }
  199198. /* Writes the end of the PNG file. If you don't want to write comments or
  199199. * time information, you can pass NULL for info. If you already wrote these
  199200. * in png_write_info(), do not write them again here. If you have long
  199201. * comments, I suggest writing them here, and compressing them.
  199202. */
  199203. void PNGAPI
  199204. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199205. {
  199206. png_debug(1, "in png_write_end\n");
  199207. if (png_ptr == NULL)
  199208. return;
  199209. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199210. png_error(png_ptr, "No IDATs written into file");
  199211. /* see if user wants us to write information chunks */
  199212. if (info_ptr != NULL)
  199213. {
  199214. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199215. int i; /* local index variable */
  199216. #endif
  199217. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199218. /* check to see if user has supplied a time chunk */
  199219. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199220. !(png_ptr->mode & PNG_WROTE_tIME))
  199221. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199222. #endif
  199223. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199224. /* loop through comment chunks */
  199225. for (i = 0; i < info_ptr->num_text; i++)
  199226. {
  199227. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199228. info_ptr->text[i].compression);
  199229. /* an internationalized chunk? */
  199230. if (info_ptr->text[i].compression > 0)
  199231. {
  199232. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199233. /* write international chunk */
  199234. png_write_iTXt(png_ptr,
  199235. info_ptr->text[i].compression,
  199236. info_ptr->text[i].key,
  199237. info_ptr->text[i].lang,
  199238. info_ptr->text[i].lang_key,
  199239. info_ptr->text[i].text);
  199240. #else
  199241. png_warning(png_ptr, "Unable to write international text");
  199242. #endif
  199243. /* Mark this chunk as written */
  199244. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199245. }
  199246. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199247. {
  199248. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199249. /* write compressed chunk */
  199250. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199251. info_ptr->text[i].text, 0,
  199252. info_ptr->text[i].compression);
  199253. #else
  199254. png_warning(png_ptr, "Unable to write compressed text");
  199255. #endif
  199256. /* Mark this chunk as written */
  199257. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199258. }
  199259. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199260. {
  199261. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199262. /* write uncompressed chunk */
  199263. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199264. info_ptr->text[i].text, 0);
  199265. #else
  199266. png_warning(png_ptr, "Unable to write uncompressed text");
  199267. #endif
  199268. /* Mark this chunk as written */
  199269. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199270. }
  199271. }
  199272. #endif
  199273. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199274. if (info_ptr->unknown_chunks_num)
  199275. {
  199276. png_unknown_chunk *up;
  199277. png_debug(5, "writing extra chunks\n");
  199278. for (up = info_ptr->unknown_chunks;
  199279. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199280. up++)
  199281. {
  199282. int keep=png_handle_as_unknown(png_ptr, up->name);
  199283. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199284. up->location && (up->location & PNG_AFTER_IDAT) &&
  199285. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199286. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199287. {
  199288. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199289. }
  199290. }
  199291. }
  199292. #endif
  199293. }
  199294. png_ptr->mode |= PNG_AFTER_IDAT;
  199295. /* write end of PNG file */
  199296. png_write_IEND(png_ptr);
  199297. }
  199298. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199299. #if !defined(_WIN32_WCE)
  199300. /* "time.h" functions are not supported on WindowsCE */
  199301. void PNGAPI
  199302. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199303. {
  199304. png_debug(1, "in png_convert_from_struct_tm\n");
  199305. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199306. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199307. ptime->day = (png_byte)ttime->tm_mday;
  199308. ptime->hour = (png_byte)ttime->tm_hour;
  199309. ptime->minute = (png_byte)ttime->tm_min;
  199310. ptime->second = (png_byte)ttime->tm_sec;
  199311. }
  199312. void PNGAPI
  199313. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199314. {
  199315. struct tm *tbuf;
  199316. png_debug(1, "in png_convert_from_time_t\n");
  199317. tbuf = gmtime(&ttime);
  199318. png_convert_from_struct_tm(ptime, tbuf);
  199319. }
  199320. #endif
  199321. #endif
  199322. /* Initialize png_ptr structure, and allocate any memory needed */
  199323. png_structp PNGAPI
  199324. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199325. png_error_ptr error_fn, png_error_ptr warn_fn)
  199326. {
  199327. #ifdef PNG_USER_MEM_SUPPORTED
  199328. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199329. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199330. }
  199331. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199332. png_structp PNGAPI
  199333. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199334. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199335. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199336. {
  199337. #endif /* PNG_USER_MEM_SUPPORTED */
  199338. png_structp png_ptr;
  199339. #ifdef PNG_SETJMP_SUPPORTED
  199340. #ifdef USE_FAR_KEYWORD
  199341. jmp_buf jmpbuf;
  199342. #endif
  199343. #endif
  199344. int i;
  199345. png_debug(1, "in png_create_write_struct\n");
  199346. #ifdef PNG_USER_MEM_SUPPORTED
  199347. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199348. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199349. #else
  199350. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199351. #endif /* PNG_USER_MEM_SUPPORTED */
  199352. if (png_ptr == NULL)
  199353. return (NULL);
  199354. /* added at libpng-1.2.6 */
  199355. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199356. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199357. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199358. #endif
  199359. #ifdef PNG_SETJMP_SUPPORTED
  199360. #ifdef USE_FAR_KEYWORD
  199361. if (setjmp(jmpbuf))
  199362. #else
  199363. if (setjmp(png_ptr->jmpbuf))
  199364. #endif
  199365. {
  199366. png_free(png_ptr, png_ptr->zbuf);
  199367. png_ptr->zbuf=NULL;
  199368. png_destroy_struct(png_ptr);
  199369. return (NULL);
  199370. }
  199371. #ifdef USE_FAR_KEYWORD
  199372. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199373. #endif
  199374. #endif
  199375. #ifdef PNG_USER_MEM_SUPPORTED
  199376. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199377. #endif /* PNG_USER_MEM_SUPPORTED */
  199378. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199379. i=0;
  199380. do
  199381. {
  199382. if(user_png_ver[i] != png_libpng_ver[i])
  199383. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199384. } while (png_libpng_ver[i++]);
  199385. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199386. {
  199387. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199388. * we must recompile any applications that use any older library version.
  199389. * For versions after libpng 1.0, we will be compatible, so we need
  199390. * only check the first digit.
  199391. */
  199392. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199393. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199394. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199395. {
  199396. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199397. char msg[80];
  199398. if (user_png_ver)
  199399. {
  199400. png_snprintf(msg, 80,
  199401. "Application was compiled with png.h from libpng-%.20s",
  199402. user_png_ver);
  199403. png_warning(png_ptr, msg);
  199404. }
  199405. png_snprintf(msg, 80,
  199406. "Application is running with png.c from libpng-%.20s",
  199407. png_libpng_ver);
  199408. png_warning(png_ptr, msg);
  199409. #endif
  199410. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199411. png_ptr->flags=0;
  199412. #endif
  199413. png_error(png_ptr,
  199414. "Incompatible libpng version in application and library");
  199415. }
  199416. }
  199417. /* initialize zbuf - compression buffer */
  199418. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199419. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199420. (png_uint_32)png_ptr->zbuf_size);
  199421. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199422. png_flush_ptr_NULL);
  199423. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199424. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199425. 1, png_doublep_NULL, png_doublep_NULL);
  199426. #endif
  199427. #ifdef PNG_SETJMP_SUPPORTED
  199428. /* Applications that neglect to set up their own setjmp() and then encounter
  199429. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199430. abort instead of returning. */
  199431. #ifdef USE_FAR_KEYWORD
  199432. if (setjmp(jmpbuf))
  199433. PNG_ABORT();
  199434. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199435. #else
  199436. if (setjmp(png_ptr->jmpbuf))
  199437. PNG_ABORT();
  199438. #endif
  199439. #endif
  199440. return (png_ptr);
  199441. }
  199442. /* Initialize png_ptr structure, and allocate any memory needed */
  199443. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199444. /* Deprecated. */
  199445. #undef png_write_init
  199446. void PNGAPI
  199447. png_write_init(png_structp png_ptr)
  199448. {
  199449. /* We only come here via pre-1.0.7-compiled applications */
  199450. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199451. }
  199452. void PNGAPI
  199453. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199454. png_size_t png_struct_size, png_size_t png_info_size)
  199455. {
  199456. /* We only come here via pre-1.0.12-compiled applications */
  199457. if(png_ptr == NULL) return;
  199458. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199459. if(png_sizeof(png_struct) > png_struct_size ||
  199460. png_sizeof(png_info) > png_info_size)
  199461. {
  199462. char msg[80];
  199463. png_ptr->warning_fn=NULL;
  199464. if (user_png_ver)
  199465. {
  199466. png_snprintf(msg, 80,
  199467. "Application was compiled with png.h from libpng-%.20s",
  199468. user_png_ver);
  199469. png_warning(png_ptr, msg);
  199470. }
  199471. png_snprintf(msg, 80,
  199472. "Application is running with png.c from libpng-%.20s",
  199473. png_libpng_ver);
  199474. png_warning(png_ptr, msg);
  199475. }
  199476. #endif
  199477. if(png_sizeof(png_struct) > png_struct_size)
  199478. {
  199479. png_ptr->error_fn=NULL;
  199480. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199481. png_ptr->flags=0;
  199482. #endif
  199483. png_error(png_ptr,
  199484. "The png struct allocated by the application for writing is too small.");
  199485. }
  199486. if(png_sizeof(png_info) > png_info_size)
  199487. {
  199488. png_ptr->error_fn=NULL;
  199489. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199490. png_ptr->flags=0;
  199491. #endif
  199492. png_error(png_ptr,
  199493. "The info struct allocated by the application for writing is too small.");
  199494. }
  199495. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199496. }
  199497. #endif /* PNG_1_0_X || PNG_1_2_X */
  199498. void PNGAPI
  199499. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199500. png_size_t png_struct_size)
  199501. {
  199502. png_structp png_ptr=*ptr_ptr;
  199503. #ifdef PNG_SETJMP_SUPPORTED
  199504. jmp_buf tmp_jmp; /* to save current jump buffer */
  199505. #endif
  199506. int i = 0;
  199507. if (png_ptr == NULL)
  199508. return;
  199509. do
  199510. {
  199511. if (user_png_ver[i] != png_libpng_ver[i])
  199512. {
  199513. #ifdef PNG_LEGACY_SUPPORTED
  199514. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199515. #else
  199516. png_ptr->warning_fn=NULL;
  199517. png_warning(png_ptr,
  199518. "Application uses deprecated png_write_init() and should be recompiled.");
  199519. break;
  199520. #endif
  199521. }
  199522. } while (png_libpng_ver[i++]);
  199523. png_debug(1, "in png_write_init_3\n");
  199524. #ifdef PNG_SETJMP_SUPPORTED
  199525. /* save jump buffer and error functions */
  199526. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199527. #endif
  199528. if (png_sizeof(png_struct) > png_struct_size)
  199529. {
  199530. png_destroy_struct(png_ptr);
  199531. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199532. *ptr_ptr = png_ptr;
  199533. }
  199534. /* reset all variables to 0 */
  199535. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199536. /* added at libpng-1.2.6 */
  199537. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199538. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199539. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199540. #endif
  199541. #ifdef PNG_SETJMP_SUPPORTED
  199542. /* restore jump buffer */
  199543. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199544. #endif
  199545. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199546. png_flush_ptr_NULL);
  199547. /* initialize zbuf - compression buffer */
  199548. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199549. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199550. (png_uint_32)png_ptr->zbuf_size);
  199551. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199552. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199553. 1, png_doublep_NULL, png_doublep_NULL);
  199554. #endif
  199555. }
  199556. /* Write a few rows of image data. If the image is interlaced,
  199557. * either you will have to write the 7 sub images, or, if you
  199558. * have called png_set_interlace_handling(), you will have to
  199559. * "write" the image seven times.
  199560. */
  199561. void PNGAPI
  199562. png_write_rows(png_structp png_ptr, png_bytepp row,
  199563. png_uint_32 num_rows)
  199564. {
  199565. png_uint_32 i; /* row counter */
  199566. png_bytepp rp; /* row pointer */
  199567. png_debug(1, "in png_write_rows\n");
  199568. if (png_ptr == NULL)
  199569. return;
  199570. /* loop through the rows */
  199571. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199572. {
  199573. png_write_row(png_ptr, *rp);
  199574. }
  199575. }
  199576. /* Write the image. You only need to call this function once, even
  199577. * if you are writing an interlaced image.
  199578. */
  199579. void PNGAPI
  199580. png_write_image(png_structp png_ptr, png_bytepp image)
  199581. {
  199582. png_uint_32 i; /* row index */
  199583. int pass, num_pass; /* pass variables */
  199584. png_bytepp rp; /* points to current row */
  199585. if (png_ptr == NULL)
  199586. return;
  199587. png_debug(1, "in png_write_image\n");
  199588. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199589. /* intialize interlace handling. If image is not interlaced,
  199590. this will set pass to 1 */
  199591. num_pass = png_set_interlace_handling(png_ptr);
  199592. #else
  199593. num_pass = 1;
  199594. #endif
  199595. /* loop through passes */
  199596. for (pass = 0; pass < num_pass; pass++)
  199597. {
  199598. /* loop through image */
  199599. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199600. {
  199601. png_write_row(png_ptr, *rp);
  199602. }
  199603. }
  199604. }
  199605. /* called by user to write a row of image data */
  199606. void PNGAPI
  199607. png_write_row(png_structp png_ptr, png_bytep row)
  199608. {
  199609. if (png_ptr == NULL)
  199610. return;
  199611. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199612. png_ptr->row_number, png_ptr->pass);
  199613. /* initialize transformations and other stuff if first time */
  199614. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199615. {
  199616. /* make sure we wrote the header info */
  199617. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199618. png_error(png_ptr,
  199619. "png_write_info was never called before png_write_row.");
  199620. /* check for transforms that have been set but were defined out */
  199621. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199622. if (png_ptr->transformations & PNG_INVERT_MONO)
  199623. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199624. #endif
  199625. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199626. if (png_ptr->transformations & PNG_FILLER)
  199627. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199628. #endif
  199629. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199630. if (png_ptr->transformations & PNG_PACKSWAP)
  199631. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199632. #endif
  199633. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199634. if (png_ptr->transformations & PNG_PACK)
  199635. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199636. #endif
  199637. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199638. if (png_ptr->transformations & PNG_SHIFT)
  199639. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199640. #endif
  199641. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199642. if (png_ptr->transformations & PNG_BGR)
  199643. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199644. #endif
  199645. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199646. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199647. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199648. #endif
  199649. png_write_start_row(png_ptr);
  199650. }
  199651. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199652. /* if interlaced and not interested in row, return */
  199653. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199654. {
  199655. switch (png_ptr->pass)
  199656. {
  199657. case 0:
  199658. if (png_ptr->row_number & 0x07)
  199659. {
  199660. png_write_finish_row(png_ptr);
  199661. return;
  199662. }
  199663. break;
  199664. case 1:
  199665. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199666. {
  199667. png_write_finish_row(png_ptr);
  199668. return;
  199669. }
  199670. break;
  199671. case 2:
  199672. if ((png_ptr->row_number & 0x07) != 4)
  199673. {
  199674. png_write_finish_row(png_ptr);
  199675. return;
  199676. }
  199677. break;
  199678. case 3:
  199679. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199680. {
  199681. png_write_finish_row(png_ptr);
  199682. return;
  199683. }
  199684. break;
  199685. case 4:
  199686. if ((png_ptr->row_number & 0x03) != 2)
  199687. {
  199688. png_write_finish_row(png_ptr);
  199689. return;
  199690. }
  199691. break;
  199692. case 5:
  199693. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199694. {
  199695. png_write_finish_row(png_ptr);
  199696. return;
  199697. }
  199698. break;
  199699. case 6:
  199700. if (!(png_ptr->row_number & 0x01))
  199701. {
  199702. png_write_finish_row(png_ptr);
  199703. return;
  199704. }
  199705. break;
  199706. }
  199707. }
  199708. #endif
  199709. /* set up row info for transformations */
  199710. png_ptr->row_info.color_type = png_ptr->color_type;
  199711. png_ptr->row_info.width = png_ptr->usr_width;
  199712. png_ptr->row_info.channels = png_ptr->usr_channels;
  199713. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199714. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199715. png_ptr->row_info.channels);
  199716. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199717. png_ptr->row_info.width);
  199718. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199719. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199720. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199721. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199722. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199723. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199724. /* Copy user's row into buffer, leaving room for filter byte. */
  199725. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199726. png_ptr->row_info.rowbytes);
  199727. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199728. /* handle interlacing */
  199729. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199730. (png_ptr->transformations & PNG_INTERLACE))
  199731. {
  199732. png_do_write_interlace(&(png_ptr->row_info),
  199733. png_ptr->row_buf + 1, png_ptr->pass);
  199734. /* this should always get caught above, but still ... */
  199735. if (!(png_ptr->row_info.width))
  199736. {
  199737. png_write_finish_row(png_ptr);
  199738. return;
  199739. }
  199740. }
  199741. #endif
  199742. /* handle other transformations */
  199743. if (png_ptr->transformations)
  199744. png_do_write_transformations(png_ptr);
  199745. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199746. /* Write filter_method 64 (intrapixel differencing) only if
  199747. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199748. * 2. Libpng did not write a PNG signature (this filter_method is only
  199749. * used in PNG datastreams that are embedded in MNG datastreams) and
  199750. * 3. The application called png_permit_mng_features with a mask that
  199751. * included PNG_FLAG_MNG_FILTER_64 and
  199752. * 4. The filter_method is 64 and
  199753. * 5. The color_type is RGB or RGBA
  199754. */
  199755. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199756. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199757. {
  199758. /* Intrapixel differencing */
  199759. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199760. }
  199761. #endif
  199762. /* Find a filter if necessary, filter the row and write it out. */
  199763. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199764. if (png_ptr->write_row_fn != NULL)
  199765. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199766. }
  199767. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199768. /* Set the automatic flush interval or 0 to turn flushing off */
  199769. void PNGAPI
  199770. png_set_flush(png_structp png_ptr, int nrows)
  199771. {
  199772. png_debug(1, "in png_set_flush\n");
  199773. if (png_ptr == NULL)
  199774. return;
  199775. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199776. }
  199777. /* flush the current output buffers now */
  199778. void PNGAPI
  199779. png_write_flush(png_structp png_ptr)
  199780. {
  199781. int wrote_IDAT;
  199782. png_debug(1, "in png_write_flush\n");
  199783. if (png_ptr == NULL)
  199784. return;
  199785. /* We have already written out all of the data */
  199786. if (png_ptr->row_number >= png_ptr->num_rows)
  199787. return;
  199788. do
  199789. {
  199790. int ret;
  199791. /* compress the data */
  199792. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199793. wrote_IDAT = 0;
  199794. /* check for compression errors */
  199795. if (ret != Z_OK)
  199796. {
  199797. if (png_ptr->zstream.msg != NULL)
  199798. png_error(png_ptr, png_ptr->zstream.msg);
  199799. else
  199800. png_error(png_ptr, "zlib error");
  199801. }
  199802. if (!(png_ptr->zstream.avail_out))
  199803. {
  199804. /* write the IDAT and reset the zlib output buffer */
  199805. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199806. png_ptr->zbuf_size);
  199807. png_ptr->zstream.next_out = png_ptr->zbuf;
  199808. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199809. wrote_IDAT = 1;
  199810. }
  199811. } while(wrote_IDAT == 1);
  199812. /* If there is any data left to be output, write it into a new IDAT */
  199813. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199814. {
  199815. /* write the IDAT and reset the zlib output buffer */
  199816. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199817. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199818. png_ptr->zstream.next_out = png_ptr->zbuf;
  199819. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199820. }
  199821. png_ptr->flush_rows = 0;
  199822. png_flush(png_ptr);
  199823. }
  199824. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199825. /* free all memory used by the write */
  199826. void PNGAPI
  199827. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199828. {
  199829. png_structp png_ptr = NULL;
  199830. png_infop info_ptr = NULL;
  199831. #ifdef PNG_USER_MEM_SUPPORTED
  199832. png_free_ptr free_fn = NULL;
  199833. png_voidp mem_ptr = NULL;
  199834. #endif
  199835. png_debug(1, "in png_destroy_write_struct\n");
  199836. if (png_ptr_ptr != NULL)
  199837. {
  199838. png_ptr = *png_ptr_ptr;
  199839. #ifdef PNG_USER_MEM_SUPPORTED
  199840. free_fn = png_ptr->free_fn;
  199841. mem_ptr = png_ptr->mem_ptr;
  199842. #endif
  199843. }
  199844. if (info_ptr_ptr != NULL)
  199845. info_ptr = *info_ptr_ptr;
  199846. if (info_ptr != NULL)
  199847. {
  199848. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199849. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199850. if (png_ptr->num_chunk_list)
  199851. {
  199852. png_free(png_ptr, png_ptr->chunk_list);
  199853. png_ptr->chunk_list=NULL;
  199854. png_ptr->num_chunk_list=0;
  199855. }
  199856. #endif
  199857. #ifdef PNG_USER_MEM_SUPPORTED
  199858. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199859. (png_voidp)mem_ptr);
  199860. #else
  199861. png_destroy_struct((png_voidp)info_ptr);
  199862. #endif
  199863. *info_ptr_ptr = NULL;
  199864. }
  199865. if (png_ptr != NULL)
  199866. {
  199867. png_write_destroy(png_ptr);
  199868. #ifdef PNG_USER_MEM_SUPPORTED
  199869. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199870. (png_voidp)mem_ptr);
  199871. #else
  199872. png_destroy_struct((png_voidp)png_ptr);
  199873. #endif
  199874. *png_ptr_ptr = NULL;
  199875. }
  199876. }
  199877. /* Free any memory used in png_ptr struct (old method) */
  199878. void /* PRIVATE */
  199879. png_write_destroy(png_structp png_ptr)
  199880. {
  199881. #ifdef PNG_SETJMP_SUPPORTED
  199882. jmp_buf tmp_jmp; /* save jump buffer */
  199883. #endif
  199884. png_error_ptr error_fn;
  199885. png_error_ptr warning_fn;
  199886. png_voidp error_ptr;
  199887. #ifdef PNG_USER_MEM_SUPPORTED
  199888. png_free_ptr free_fn;
  199889. #endif
  199890. png_debug(1, "in png_write_destroy\n");
  199891. /* free any memory zlib uses */
  199892. deflateEnd(&png_ptr->zstream);
  199893. /* free our memory. png_free checks NULL for us. */
  199894. png_free(png_ptr, png_ptr->zbuf);
  199895. png_free(png_ptr, png_ptr->row_buf);
  199896. png_free(png_ptr, png_ptr->prev_row);
  199897. png_free(png_ptr, png_ptr->sub_row);
  199898. png_free(png_ptr, png_ptr->up_row);
  199899. png_free(png_ptr, png_ptr->avg_row);
  199900. png_free(png_ptr, png_ptr->paeth_row);
  199901. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199902. png_free(png_ptr, png_ptr->time_buffer);
  199903. #endif
  199904. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199905. png_free(png_ptr, png_ptr->prev_filters);
  199906. png_free(png_ptr, png_ptr->filter_weights);
  199907. png_free(png_ptr, png_ptr->inv_filter_weights);
  199908. png_free(png_ptr, png_ptr->filter_costs);
  199909. png_free(png_ptr, png_ptr->inv_filter_costs);
  199910. #endif
  199911. #ifdef PNG_SETJMP_SUPPORTED
  199912. /* reset structure */
  199913. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199914. #endif
  199915. error_fn = png_ptr->error_fn;
  199916. warning_fn = png_ptr->warning_fn;
  199917. error_ptr = png_ptr->error_ptr;
  199918. #ifdef PNG_USER_MEM_SUPPORTED
  199919. free_fn = png_ptr->free_fn;
  199920. #endif
  199921. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199922. png_ptr->error_fn = error_fn;
  199923. png_ptr->warning_fn = warning_fn;
  199924. png_ptr->error_ptr = error_ptr;
  199925. #ifdef PNG_USER_MEM_SUPPORTED
  199926. png_ptr->free_fn = free_fn;
  199927. #endif
  199928. #ifdef PNG_SETJMP_SUPPORTED
  199929. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199930. #endif
  199931. }
  199932. /* Allow the application to select one or more row filters to use. */
  199933. void PNGAPI
  199934. png_set_filter(png_structp png_ptr, int method, int filters)
  199935. {
  199936. png_debug(1, "in png_set_filter\n");
  199937. if (png_ptr == NULL)
  199938. return;
  199939. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199940. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199941. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199942. method = PNG_FILTER_TYPE_BASE;
  199943. #endif
  199944. if (method == PNG_FILTER_TYPE_BASE)
  199945. {
  199946. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199947. {
  199948. #ifndef PNG_NO_WRITE_FILTER
  199949. case 5:
  199950. case 6:
  199951. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199952. #endif /* PNG_NO_WRITE_FILTER */
  199953. case PNG_FILTER_VALUE_NONE:
  199954. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199955. #ifndef PNG_NO_WRITE_FILTER
  199956. case PNG_FILTER_VALUE_SUB:
  199957. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199958. case PNG_FILTER_VALUE_UP:
  199959. png_ptr->do_filter=PNG_FILTER_UP; break;
  199960. case PNG_FILTER_VALUE_AVG:
  199961. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199962. case PNG_FILTER_VALUE_PAETH:
  199963. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199964. default: png_ptr->do_filter = (png_byte)filters; break;
  199965. #else
  199966. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199967. #endif /* PNG_NO_WRITE_FILTER */
  199968. }
  199969. /* If we have allocated the row_buf, this means we have already started
  199970. * with the image and we should have allocated all of the filter buffers
  199971. * that have been selected. If prev_row isn't already allocated, then
  199972. * it is too late to start using the filters that need it, since we
  199973. * will be missing the data in the previous row. If an application
  199974. * wants to start and stop using particular filters during compression,
  199975. * it should start out with all of the filters, and then add and
  199976. * remove them after the start of compression.
  199977. */
  199978. if (png_ptr->row_buf != NULL)
  199979. {
  199980. #ifndef PNG_NO_WRITE_FILTER
  199981. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199982. {
  199983. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199984. (png_ptr->rowbytes + 1));
  199985. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199986. }
  199987. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199988. {
  199989. if (png_ptr->prev_row == NULL)
  199990. {
  199991. png_warning(png_ptr, "Can't add Up filter after starting");
  199992. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199993. }
  199994. else
  199995. {
  199996. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199997. (png_ptr->rowbytes + 1));
  199998. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199999. }
  200000. }
  200001. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200002. {
  200003. if (png_ptr->prev_row == NULL)
  200004. {
  200005. png_warning(png_ptr, "Can't add Average filter after starting");
  200006. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200007. }
  200008. else
  200009. {
  200010. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200011. (png_ptr->rowbytes + 1));
  200012. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200013. }
  200014. }
  200015. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200016. png_ptr->paeth_row == NULL)
  200017. {
  200018. if (png_ptr->prev_row == NULL)
  200019. {
  200020. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200021. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200022. }
  200023. else
  200024. {
  200025. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200026. (png_ptr->rowbytes + 1));
  200027. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200028. }
  200029. }
  200030. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200031. #endif /* PNG_NO_WRITE_FILTER */
  200032. png_ptr->do_filter = PNG_FILTER_NONE;
  200033. }
  200034. }
  200035. else
  200036. png_error(png_ptr, "Unknown custom filter method");
  200037. }
  200038. /* This allows us to influence the way in which libpng chooses the "best"
  200039. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200040. * differences metric is relatively fast and effective, there is some
  200041. * question as to whether it can be improved upon by trying to keep the
  200042. * filtered data going to zlib more consistent, hopefully resulting in
  200043. * better compression.
  200044. */
  200045. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200046. void PNGAPI
  200047. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200048. int num_weights, png_doublep filter_weights,
  200049. png_doublep filter_costs)
  200050. {
  200051. int i;
  200052. png_debug(1, "in png_set_filter_heuristics\n");
  200053. if (png_ptr == NULL)
  200054. return;
  200055. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200056. {
  200057. png_warning(png_ptr, "Unknown filter heuristic method");
  200058. return;
  200059. }
  200060. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200061. {
  200062. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200063. }
  200064. if (num_weights < 0 || filter_weights == NULL ||
  200065. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200066. {
  200067. num_weights = 0;
  200068. }
  200069. png_ptr->num_prev_filters = (png_byte)num_weights;
  200070. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200071. if (num_weights > 0)
  200072. {
  200073. if (png_ptr->prev_filters == NULL)
  200074. {
  200075. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200076. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200077. /* To make sure that the weighting starts out fairly */
  200078. for (i = 0; i < num_weights; i++)
  200079. {
  200080. png_ptr->prev_filters[i] = 255;
  200081. }
  200082. }
  200083. if (png_ptr->filter_weights == NULL)
  200084. {
  200085. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200086. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200087. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200088. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200089. for (i = 0; i < num_weights; i++)
  200090. {
  200091. png_ptr->inv_filter_weights[i] =
  200092. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200093. }
  200094. }
  200095. for (i = 0; i < num_weights; i++)
  200096. {
  200097. if (filter_weights[i] < 0.0)
  200098. {
  200099. png_ptr->inv_filter_weights[i] =
  200100. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200101. }
  200102. else
  200103. {
  200104. png_ptr->inv_filter_weights[i] =
  200105. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200106. png_ptr->filter_weights[i] =
  200107. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200108. }
  200109. }
  200110. }
  200111. /* If, in the future, there are other filter methods, this would
  200112. * need to be based on png_ptr->filter.
  200113. */
  200114. if (png_ptr->filter_costs == NULL)
  200115. {
  200116. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200117. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200118. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200119. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200120. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200121. {
  200122. png_ptr->inv_filter_costs[i] =
  200123. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200124. }
  200125. }
  200126. /* Here is where we set the relative costs of the different filters. We
  200127. * should take the desired compression level into account when setting
  200128. * the costs, so that Paeth, for instance, has a high relative cost at low
  200129. * compression levels, while it has a lower relative cost at higher
  200130. * compression settings. The filter types are in order of increasing
  200131. * relative cost, so it would be possible to do this with an algorithm.
  200132. */
  200133. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200134. {
  200135. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200136. {
  200137. png_ptr->inv_filter_costs[i] =
  200138. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200139. }
  200140. else if (filter_costs[i] >= 1.0)
  200141. {
  200142. png_ptr->inv_filter_costs[i] =
  200143. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200144. png_ptr->filter_costs[i] =
  200145. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200146. }
  200147. }
  200148. }
  200149. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200150. void PNGAPI
  200151. png_set_compression_level(png_structp png_ptr, int level)
  200152. {
  200153. png_debug(1, "in png_set_compression_level\n");
  200154. if (png_ptr == NULL)
  200155. return;
  200156. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200157. png_ptr->zlib_level = level;
  200158. }
  200159. void PNGAPI
  200160. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200161. {
  200162. png_debug(1, "in png_set_compression_mem_level\n");
  200163. if (png_ptr == NULL)
  200164. return;
  200165. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200166. png_ptr->zlib_mem_level = mem_level;
  200167. }
  200168. void PNGAPI
  200169. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200170. {
  200171. png_debug(1, "in png_set_compression_strategy\n");
  200172. if (png_ptr == NULL)
  200173. return;
  200174. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200175. png_ptr->zlib_strategy = strategy;
  200176. }
  200177. void PNGAPI
  200178. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200179. {
  200180. if (png_ptr == NULL)
  200181. return;
  200182. if (window_bits > 15)
  200183. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200184. else if (window_bits < 8)
  200185. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200186. #ifndef WBITS_8_OK
  200187. /* avoid libpng bug with 256-byte windows */
  200188. if (window_bits == 8)
  200189. {
  200190. png_warning(png_ptr, "Compression window is being reset to 512");
  200191. window_bits=9;
  200192. }
  200193. #endif
  200194. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200195. png_ptr->zlib_window_bits = window_bits;
  200196. }
  200197. void PNGAPI
  200198. png_set_compression_method(png_structp png_ptr, int method)
  200199. {
  200200. png_debug(1, "in png_set_compression_method\n");
  200201. if (png_ptr == NULL)
  200202. return;
  200203. if (method != 8)
  200204. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200205. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200206. png_ptr->zlib_method = method;
  200207. }
  200208. void PNGAPI
  200209. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200210. {
  200211. if (png_ptr == NULL)
  200212. return;
  200213. png_ptr->write_row_fn = write_row_fn;
  200214. }
  200215. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200216. void PNGAPI
  200217. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200218. write_user_transform_fn)
  200219. {
  200220. png_debug(1, "in png_set_write_user_transform_fn\n");
  200221. if (png_ptr == NULL)
  200222. return;
  200223. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200224. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200225. }
  200226. #endif
  200227. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200228. void PNGAPI
  200229. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200230. int transforms, voidp params)
  200231. {
  200232. if (png_ptr == NULL || info_ptr == NULL)
  200233. return;
  200234. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200235. /* invert the alpha channel from opacity to transparency */
  200236. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200237. png_set_invert_alpha(png_ptr);
  200238. #endif
  200239. /* Write the file header information. */
  200240. png_write_info(png_ptr, info_ptr);
  200241. /* ------ these transformations don't touch the info structure ------- */
  200242. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200243. /* invert monochrome pixels */
  200244. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200245. png_set_invert_mono(png_ptr);
  200246. #endif
  200247. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200248. /* Shift the pixels up to a legal bit depth and fill in
  200249. * as appropriate to correctly scale the image.
  200250. */
  200251. if ((transforms & PNG_TRANSFORM_SHIFT)
  200252. && (info_ptr->valid & PNG_INFO_sBIT))
  200253. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200254. #endif
  200255. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200256. /* pack pixels into bytes */
  200257. if (transforms & PNG_TRANSFORM_PACKING)
  200258. png_set_packing(png_ptr);
  200259. #endif
  200260. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200261. /* swap location of alpha bytes from ARGB to RGBA */
  200262. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200263. png_set_swap_alpha(png_ptr);
  200264. #endif
  200265. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200266. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200267. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200268. */
  200269. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200270. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200271. #endif
  200272. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200273. /* flip BGR pixels to RGB */
  200274. if (transforms & PNG_TRANSFORM_BGR)
  200275. png_set_bgr(png_ptr);
  200276. #endif
  200277. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200278. /* swap bytes of 16-bit files to most significant byte first */
  200279. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200280. png_set_swap(png_ptr);
  200281. #endif
  200282. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200283. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200284. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200285. png_set_packswap(png_ptr);
  200286. #endif
  200287. /* ----------------------- end of transformations ------------------- */
  200288. /* write the bits */
  200289. if (info_ptr->valid & PNG_INFO_IDAT)
  200290. png_write_image(png_ptr, info_ptr->row_pointers);
  200291. /* It is REQUIRED to call this to finish writing the rest of the file */
  200292. png_write_end(png_ptr, info_ptr);
  200293. transforms = transforms; /* quiet compiler warnings */
  200294. params = params;
  200295. }
  200296. #endif
  200297. #endif /* PNG_WRITE_SUPPORTED */
  200298. /*** End of inlined file: pngwrite.c ***/
  200299. /*** Start of inlined file: pngwtran.c ***/
  200300. /* pngwtran.c - transforms the data in a row for PNG writers
  200301. *
  200302. * Last changed in libpng 1.2.9 April 14, 2006
  200303. * For conditions of distribution and use, see copyright notice in png.h
  200304. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200305. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200306. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200307. */
  200308. #define PNG_INTERNAL
  200309. #ifdef PNG_WRITE_SUPPORTED
  200310. /* Transform the data according to the user's wishes. The order of
  200311. * transformations is significant.
  200312. */
  200313. void /* PRIVATE */
  200314. png_do_write_transformations(png_structp png_ptr)
  200315. {
  200316. png_debug(1, "in png_do_write_transformations\n");
  200317. if (png_ptr == NULL)
  200318. return;
  200319. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200320. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200321. if(png_ptr->write_user_transform_fn != NULL)
  200322. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200323. (png_ptr, /* png_ptr */
  200324. &(png_ptr->row_info), /* row_info: */
  200325. /* png_uint_32 width; width of row */
  200326. /* png_uint_32 rowbytes; number of bytes in row */
  200327. /* png_byte color_type; color type of pixels */
  200328. /* png_byte bit_depth; bit depth of samples */
  200329. /* png_byte channels; number of channels (1-4) */
  200330. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200331. png_ptr->row_buf + 1); /* start of pixel data for row */
  200332. #endif
  200333. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200334. if (png_ptr->transformations & PNG_FILLER)
  200335. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200336. png_ptr->flags);
  200337. #endif
  200338. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200339. if (png_ptr->transformations & PNG_PACKSWAP)
  200340. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200341. #endif
  200342. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200343. if (png_ptr->transformations & PNG_PACK)
  200344. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200345. (png_uint_32)png_ptr->bit_depth);
  200346. #endif
  200347. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200348. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200349. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200350. #endif
  200351. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200352. if (png_ptr->transformations & PNG_SHIFT)
  200353. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200354. &(png_ptr->shift));
  200355. #endif
  200356. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200357. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200358. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200359. #endif
  200360. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200361. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200362. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200363. #endif
  200364. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200365. if (png_ptr->transformations & PNG_BGR)
  200366. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200367. #endif
  200368. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200369. if (png_ptr->transformations & PNG_INVERT_MONO)
  200370. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200371. #endif
  200372. }
  200373. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200374. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200375. * row_info bit depth should be 8 (one pixel per byte). The channels
  200376. * should be 1 (this only happens on grayscale and paletted images).
  200377. */
  200378. void /* PRIVATE */
  200379. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200380. {
  200381. png_debug(1, "in png_do_pack\n");
  200382. if (row_info->bit_depth == 8 &&
  200383. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200384. row != NULL && row_info != NULL &&
  200385. #endif
  200386. row_info->channels == 1)
  200387. {
  200388. switch ((int)bit_depth)
  200389. {
  200390. case 1:
  200391. {
  200392. png_bytep sp, dp;
  200393. int mask, v;
  200394. png_uint_32 i;
  200395. png_uint_32 row_width = row_info->width;
  200396. sp = row;
  200397. dp = row;
  200398. mask = 0x80;
  200399. v = 0;
  200400. for (i = 0; i < row_width; i++)
  200401. {
  200402. if (*sp != 0)
  200403. v |= mask;
  200404. sp++;
  200405. if (mask > 1)
  200406. mask >>= 1;
  200407. else
  200408. {
  200409. mask = 0x80;
  200410. *dp = (png_byte)v;
  200411. dp++;
  200412. v = 0;
  200413. }
  200414. }
  200415. if (mask != 0x80)
  200416. *dp = (png_byte)v;
  200417. break;
  200418. }
  200419. case 2:
  200420. {
  200421. png_bytep sp, dp;
  200422. int shift, v;
  200423. png_uint_32 i;
  200424. png_uint_32 row_width = row_info->width;
  200425. sp = row;
  200426. dp = row;
  200427. shift = 6;
  200428. v = 0;
  200429. for (i = 0; i < row_width; i++)
  200430. {
  200431. png_byte value;
  200432. value = (png_byte)(*sp & 0x03);
  200433. v |= (value << shift);
  200434. if (shift == 0)
  200435. {
  200436. shift = 6;
  200437. *dp = (png_byte)v;
  200438. dp++;
  200439. v = 0;
  200440. }
  200441. else
  200442. shift -= 2;
  200443. sp++;
  200444. }
  200445. if (shift != 6)
  200446. *dp = (png_byte)v;
  200447. break;
  200448. }
  200449. case 4:
  200450. {
  200451. png_bytep sp, dp;
  200452. int shift, v;
  200453. png_uint_32 i;
  200454. png_uint_32 row_width = row_info->width;
  200455. sp = row;
  200456. dp = row;
  200457. shift = 4;
  200458. v = 0;
  200459. for (i = 0; i < row_width; i++)
  200460. {
  200461. png_byte value;
  200462. value = (png_byte)(*sp & 0x0f);
  200463. v |= (value << shift);
  200464. if (shift == 0)
  200465. {
  200466. shift = 4;
  200467. *dp = (png_byte)v;
  200468. dp++;
  200469. v = 0;
  200470. }
  200471. else
  200472. shift -= 4;
  200473. sp++;
  200474. }
  200475. if (shift != 4)
  200476. *dp = (png_byte)v;
  200477. break;
  200478. }
  200479. }
  200480. row_info->bit_depth = (png_byte)bit_depth;
  200481. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200482. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200483. row_info->width);
  200484. }
  200485. }
  200486. #endif
  200487. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200488. /* Shift pixel values to take advantage of whole range. Pass the
  200489. * true number of bits in bit_depth. The row should be packed
  200490. * according to row_info->bit_depth. Thus, if you had a row of
  200491. * bit depth 4, but the pixels only had values from 0 to 7, you
  200492. * would pass 3 as bit_depth, and this routine would translate the
  200493. * data to 0 to 15.
  200494. */
  200495. void /* PRIVATE */
  200496. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200497. {
  200498. png_debug(1, "in png_do_shift\n");
  200499. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200500. if (row != NULL && row_info != NULL &&
  200501. #else
  200502. if (
  200503. #endif
  200504. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200505. {
  200506. int shift_start[4], shift_dec[4];
  200507. int channels = 0;
  200508. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200509. {
  200510. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200511. shift_dec[channels] = bit_depth->red;
  200512. channels++;
  200513. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200514. shift_dec[channels] = bit_depth->green;
  200515. channels++;
  200516. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200517. shift_dec[channels] = bit_depth->blue;
  200518. channels++;
  200519. }
  200520. else
  200521. {
  200522. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200523. shift_dec[channels] = bit_depth->gray;
  200524. channels++;
  200525. }
  200526. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200527. {
  200528. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200529. shift_dec[channels] = bit_depth->alpha;
  200530. channels++;
  200531. }
  200532. /* with low row depths, could only be grayscale, so one channel */
  200533. if (row_info->bit_depth < 8)
  200534. {
  200535. png_bytep bp = row;
  200536. png_uint_32 i;
  200537. png_byte mask;
  200538. png_uint_32 row_bytes = row_info->rowbytes;
  200539. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200540. mask = 0x55;
  200541. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200542. mask = 0x11;
  200543. else
  200544. mask = 0xff;
  200545. for (i = 0; i < row_bytes; i++, bp++)
  200546. {
  200547. png_uint_16 v;
  200548. int j;
  200549. v = *bp;
  200550. *bp = 0;
  200551. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200552. {
  200553. if (j > 0)
  200554. *bp |= (png_byte)((v << j) & 0xff);
  200555. else
  200556. *bp |= (png_byte)((v >> (-j)) & mask);
  200557. }
  200558. }
  200559. }
  200560. else if (row_info->bit_depth == 8)
  200561. {
  200562. png_bytep bp = row;
  200563. png_uint_32 i;
  200564. png_uint_32 istop = channels * row_info->width;
  200565. for (i = 0; i < istop; i++, bp++)
  200566. {
  200567. png_uint_16 v;
  200568. int j;
  200569. int c = (int)(i%channels);
  200570. v = *bp;
  200571. *bp = 0;
  200572. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200573. {
  200574. if (j > 0)
  200575. *bp |= (png_byte)((v << j) & 0xff);
  200576. else
  200577. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200578. }
  200579. }
  200580. }
  200581. else
  200582. {
  200583. png_bytep bp;
  200584. png_uint_32 i;
  200585. png_uint_32 istop = channels * row_info->width;
  200586. for (bp = row, i = 0; i < istop; i++)
  200587. {
  200588. int c = (int)(i%channels);
  200589. png_uint_16 value, v;
  200590. int j;
  200591. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200592. value = 0;
  200593. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200594. {
  200595. if (j > 0)
  200596. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200597. else
  200598. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200599. }
  200600. *bp++ = (png_byte)(value >> 8);
  200601. *bp++ = (png_byte)(value & 0xff);
  200602. }
  200603. }
  200604. }
  200605. }
  200606. #endif
  200607. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200608. void /* PRIVATE */
  200609. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200610. {
  200611. png_debug(1, "in png_do_write_swap_alpha\n");
  200612. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200613. if (row != NULL && row_info != NULL)
  200614. #endif
  200615. {
  200616. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200617. {
  200618. /* This converts from ARGB to RGBA */
  200619. if (row_info->bit_depth == 8)
  200620. {
  200621. png_bytep sp, dp;
  200622. png_uint_32 i;
  200623. png_uint_32 row_width = row_info->width;
  200624. for (i = 0, sp = dp = row; i < row_width; i++)
  200625. {
  200626. png_byte save = *(sp++);
  200627. *(dp++) = *(sp++);
  200628. *(dp++) = *(sp++);
  200629. *(dp++) = *(sp++);
  200630. *(dp++) = save;
  200631. }
  200632. }
  200633. /* This converts from AARRGGBB to RRGGBBAA */
  200634. else
  200635. {
  200636. png_bytep sp, dp;
  200637. png_uint_32 i;
  200638. png_uint_32 row_width = row_info->width;
  200639. for (i = 0, sp = dp = row; i < row_width; i++)
  200640. {
  200641. png_byte save[2];
  200642. save[0] = *(sp++);
  200643. save[1] = *(sp++);
  200644. *(dp++) = *(sp++);
  200645. *(dp++) = *(sp++);
  200646. *(dp++) = *(sp++);
  200647. *(dp++) = *(sp++);
  200648. *(dp++) = *(sp++);
  200649. *(dp++) = *(sp++);
  200650. *(dp++) = save[0];
  200651. *(dp++) = save[1];
  200652. }
  200653. }
  200654. }
  200655. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200656. {
  200657. /* This converts from AG to GA */
  200658. if (row_info->bit_depth == 8)
  200659. {
  200660. png_bytep sp, dp;
  200661. png_uint_32 i;
  200662. png_uint_32 row_width = row_info->width;
  200663. for (i = 0, sp = dp = row; i < row_width; i++)
  200664. {
  200665. png_byte save = *(sp++);
  200666. *(dp++) = *(sp++);
  200667. *(dp++) = save;
  200668. }
  200669. }
  200670. /* This converts from AAGG to GGAA */
  200671. else
  200672. {
  200673. png_bytep sp, dp;
  200674. png_uint_32 i;
  200675. png_uint_32 row_width = row_info->width;
  200676. for (i = 0, sp = dp = row; i < row_width; i++)
  200677. {
  200678. png_byte save[2];
  200679. save[0] = *(sp++);
  200680. save[1] = *(sp++);
  200681. *(dp++) = *(sp++);
  200682. *(dp++) = *(sp++);
  200683. *(dp++) = save[0];
  200684. *(dp++) = save[1];
  200685. }
  200686. }
  200687. }
  200688. }
  200689. }
  200690. #endif
  200691. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200692. void /* PRIVATE */
  200693. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200694. {
  200695. png_debug(1, "in png_do_write_invert_alpha\n");
  200696. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200697. if (row != NULL && row_info != NULL)
  200698. #endif
  200699. {
  200700. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200701. {
  200702. /* This inverts the alpha channel in RGBA */
  200703. if (row_info->bit_depth == 8)
  200704. {
  200705. png_bytep sp, dp;
  200706. png_uint_32 i;
  200707. png_uint_32 row_width = row_info->width;
  200708. for (i = 0, sp = dp = row; i < row_width; i++)
  200709. {
  200710. /* does nothing
  200711. *(dp++) = *(sp++);
  200712. *(dp++) = *(sp++);
  200713. *(dp++) = *(sp++);
  200714. */
  200715. sp+=3; dp = sp;
  200716. *(dp++) = (png_byte)(255 - *(sp++));
  200717. }
  200718. }
  200719. /* This inverts the alpha channel in RRGGBBAA */
  200720. else
  200721. {
  200722. png_bytep sp, dp;
  200723. png_uint_32 i;
  200724. png_uint_32 row_width = row_info->width;
  200725. for (i = 0, sp = dp = row; i < row_width; i++)
  200726. {
  200727. /* does nothing
  200728. *(dp++) = *(sp++);
  200729. *(dp++) = *(sp++);
  200730. *(dp++) = *(sp++);
  200731. *(dp++) = *(sp++);
  200732. *(dp++) = *(sp++);
  200733. *(dp++) = *(sp++);
  200734. */
  200735. sp+=6; dp = sp;
  200736. *(dp++) = (png_byte)(255 - *(sp++));
  200737. *(dp++) = (png_byte)(255 - *(sp++));
  200738. }
  200739. }
  200740. }
  200741. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200742. {
  200743. /* This inverts the alpha channel in GA */
  200744. if (row_info->bit_depth == 8)
  200745. {
  200746. png_bytep sp, dp;
  200747. png_uint_32 i;
  200748. png_uint_32 row_width = row_info->width;
  200749. for (i = 0, sp = dp = row; i < row_width; i++)
  200750. {
  200751. *(dp++) = *(sp++);
  200752. *(dp++) = (png_byte)(255 - *(sp++));
  200753. }
  200754. }
  200755. /* This inverts the alpha channel in GGAA */
  200756. else
  200757. {
  200758. png_bytep sp, dp;
  200759. png_uint_32 i;
  200760. png_uint_32 row_width = row_info->width;
  200761. for (i = 0, sp = dp = row; i < row_width; i++)
  200762. {
  200763. /* does nothing
  200764. *(dp++) = *(sp++);
  200765. *(dp++) = *(sp++);
  200766. */
  200767. sp+=2; dp = sp;
  200768. *(dp++) = (png_byte)(255 - *(sp++));
  200769. *(dp++) = (png_byte)(255 - *(sp++));
  200770. }
  200771. }
  200772. }
  200773. }
  200774. }
  200775. #endif
  200776. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200777. /* undoes intrapixel differencing */
  200778. void /* PRIVATE */
  200779. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200780. {
  200781. png_debug(1, "in png_do_write_intrapixel\n");
  200782. if (
  200783. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200784. row != NULL && row_info != NULL &&
  200785. #endif
  200786. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200787. {
  200788. int bytes_per_pixel;
  200789. png_uint_32 row_width = row_info->width;
  200790. if (row_info->bit_depth == 8)
  200791. {
  200792. png_bytep rp;
  200793. png_uint_32 i;
  200794. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200795. bytes_per_pixel = 3;
  200796. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200797. bytes_per_pixel = 4;
  200798. else
  200799. return;
  200800. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200801. {
  200802. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200803. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200804. }
  200805. }
  200806. else if (row_info->bit_depth == 16)
  200807. {
  200808. png_bytep rp;
  200809. png_uint_32 i;
  200810. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200811. bytes_per_pixel = 6;
  200812. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200813. bytes_per_pixel = 8;
  200814. else
  200815. return;
  200816. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200817. {
  200818. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200819. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200820. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200821. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200822. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200823. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200824. *(rp+1) = (png_byte)(red & 0xff);
  200825. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200826. *(rp+5) = (png_byte)(blue & 0xff);
  200827. }
  200828. }
  200829. }
  200830. }
  200831. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200832. #endif /* PNG_WRITE_SUPPORTED */
  200833. /*** End of inlined file: pngwtran.c ***/
  200834. /*** Start of inlined file: pngwutil.c ***/
  200835. /* pngwutil.c - utilities to write a PNG file
  200836. *
  200837. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200838. * For conditions of distribution and use, see copyright notice in png.h
  200839. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200840. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200841. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200842. */
  200843. #define PNG_INTERNAL
  200844. #ifdef PNG_WRITE_SUPPORTED
  200845. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200846. * with unsigned numbers for convenience, although one supported
  200847. * ancillary chunk uses signed (two's complement) numbers.
  200848. */
  200849. void PNGAPI
  200850. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200851. {
  200852. buf[0] = (png_byte)((i >> 24) & 0xff);
  200853. buf[1] = (png_byte)((i >> 16) & 0xff);
  200854. buf[2] = (png_byte)((i >> 8) & 0xff);
  200855. buf[3] = (png_byte)(i & 0xff);
  200856. }
  200857. /* The png_save_int_32 function assumes integers are stored in two's
  200858. * complement format. If this isn't the case, then this routine needs to
  200859. * be modified to write data in two's complement format.
  200860. */
  200861. void PNGAPI
  200862. png_save_int_32(png_bytep buf, png_int_32 i)
  200863. {
  200864. buf[0] = (png_byte)((i >> 24) & 0xff);
  200865. buf[1] = (png_byte)((i >> 16) & 0xff);
  200866. buf[2] = (png_byte)((i >> 8) & 0xff);
  200867. buf[3] = (png_byte)(i & 0xff);
  200868. }
  200869. /* Place a 16-bit number into a buffer in PNG byte order.
  200870. * The parameter is declared unsigned int, not png_uint_16,
  200871. * just to avoid potential problems on pre-ANSI C compilers.
  200872. */
  200873. void PNGAPI
  200874. png_save_uint_16(png_bytep buf, unsigned int i)
  200875. {
  200876. buf[0] = (png_byte)((i >> 8) & 0xff);
  200877. buf[1] = (png_byte)(i & 0xff);
  200878. }
  200879. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200880. * representing the chunk name. The array must be at least 4 bytes in
  200881. * length, and does not need to be null terminated. To be safe, pass the
  200882. * pre-defined chunk names here, and if you need a new one, define it
  200883. * where the others are defined. The length is the length of the data.
  200884. * All the data must be present. If that is not possible, use the
  200885. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200886. * functions instead.
  200887. */
  200888. void PNGAPI
  200889. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200890. png_bytep data, png_size_t length)
  200891. {
  200892. if(png_ptr == NULL) return;
  200893. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200894. png_write_chunk_data(png_ptr, data, length);
  200895. png_write_chunk_end(png_ptr);
  200896. }
  200897. /* Write the start of a PNG chunk. The type is the chunk type.
  200898. * The total_length is the sum of the lengths of all the data you will be
  200899. * passing in png_write_chunk_data().
  200900. */
  200901. void PNGAPI
  200902. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200903. png_uint_32 length)
  200904. {
  200905. png_byte buf[4];
  200906. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200907. if(png_ptr == NULL) return;
  200908. /* write the length */
  200909. png_save_uint_32(buf, length);
  200910. png_write_data(png_ptr, buf, (png_size_t)4);
  200911. /* write the chunk name */
  200912. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200913. /* reset the crc and run it over the chunk name */
  200914. png_reset_crc(png_ptr);
  200915. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200916. }
  200917. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200918. * Note that multiple calls to this function are allowed, and that the
  200919. * sum of the lengths from these calls *must* add up to the total_length
  200920. * given to png_write_chunk_start().
  200921. */
  200922. void PNGAPI
  200923. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200924. {
  200925. /* write the data, and run the CRC over it */
  200926. if(png_ptr == NULL) return;
  200927. if (data != NULL && length > 0)
  200928. {
  200929. png_calculate_crc(png_ptr, data, length);
  200930. png_write_data(png_ptr, data, length);
  200931. }
  200932. }
  200933. /* Finish a chunk started with png_write_chunk_start(). */
  200934. void PNGAPI
  200935. png_write_chunk_end(png_structp png_ptr)
  200936. {
  200937. png_byte buf[4];
  200938. if(png_ptr == NULL) return;
  200939. /* write the crc */
  200940. png_save_uint_32(buf, png_ptr->crc);
  200941. png_write_data(png_ptr, buf, (png_size_t)4);
  200942. }
  200943. /* Simple function to write the signature. If we have already written
  200944. * the magic bytes of the signature, or more likely, the PNG stream is
  200945. * being embedded into another stream and doesn't need its own signature,
  200946. * we should call png_set_sig_bytes() to tell libpng how many of the
  200947. * bytes have already been written.
  200948. */
  200949. void /* PRIVATE */
  200950. png_write_sig(png_structp png_ptr)
  200951. {
  200952. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200953. /* write the rest of the 8 byte signature */
  200954. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200955. (png_size_t)8 - png_ptr->sig_bytes);
  200956. if(png_ptr->sig_bytes < 3)
  200957. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200958. }
  200959. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200960. /*
  200961. * This pair of functions encapsulates the operation of (a) compressing a
  200962. * text string, and (b) issuing it later as a series of chunk data writes.
  200963. * The compression_state structure is shared context for these functions
  200964. * set up by the caller in order to make the whole mess thread-safe.
  200965. */
  200966. typedef struct
  200967. {
  200968. char *input; /* the uncompressed input data */
  200969. int input_len; /* its length */
  200970. int num_output_ptr; /* number of output pointers used */
  200971. int max_output_ptr; /* size of output_ptr */
  200972. png_charpp output_ptr; /* array of pointers to output */
  200973. } compression_state;
  200974. /* compress given text into storage in the png_ptr structure */
  200975. static int /* PRIVATE */
  200976. png_text_compress(png_structp png_ptr,
  200977. png_charp text, png_size_t text_len, int compression,
  200978. compression_state *comp)
  200979. {
  200980. int ret;
  200981. comp->num_output_ptr = 0;
  200982. comp->max_output_ptr = 0;
  200983. comp->output_ptr = NULL;
  200984. comp->input = NULL;
  200985. comp->input_len = 0;
  200986. /* we may just want to pass the text right through */
  200987. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200988. {
  200989. comp->input = text;
  200990. comp->input_len = text_len;
  200991. return((int)text_len);
  200992. }
  200993. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200994. {
  200995. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200996. char msg[50];
  200997. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200998. png_warning(png_ptr, msg);
  200999. #else
  201000. png_warning(png_ptr, "Unknown compression type");
  201001. #endif
  201002. }
  201003. /* We can't write the chunk until we find out how much data we have,
  201004. * which means we need to run the compressor first and save the
  201005. * output. This shouldn't be a problem, as the vast majority of
  201006. * comments should be reasonable, but we will set up an array of
  201007. * malloc'd pointers to be sure.
  201008. *
  201009. * If we knew the application was well behaved, we could simplify this
  201010. * greatly by assuming we can always malloc an output buffer large
  201011. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201012. * and malloc this directly. The only time this would be a bad idea is
  201013. * if we can't malloc more than 64K and we have 64K of random input
  201014. * data, or if the input string is incredibly large (although this
  201015. * wouldn't cause a failure, just a slowdown due to swapping).
  201016. */
  201017. /* set up the compression buffers */
  201018. png_ptr->zstream.avail_in = (uInt)text_len;
  201019. png_ptr->zstream.next_in = (Bytef *)text;
  201020. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201021. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201022. /* this is the same compression loop as in png_write_row() */
  201023. do
  201024. {
  201025. /* compress the data */
  201026. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201027. if (ret != Z_OK)
  201028. {
  201029. /* error */
  201030. if (png_ptr->zstream.msg != NULL)
  201031. png_error(png_ptr, png_ptr->zstream.msg);
  201032. else
  201033. png_error(png_ptr, "zlib error");
  201034. }
  201035. /* check to see if we need more room */
  201036. if (!(png_ptr->zstream.avail_out))
  201037. {
  201038. /* make sure the output array has room */
  201039. if (comp->num_output_ptr >= comp->max_output_ptr)
  201040. {
  201041. int old_max;
  201042. old_max = comp->max_output_ptr;
  201043. comp->max_output_ptr = comp->num_output_ptr + 4;
  201044. if (comp->output_ptr != NULL)
  201045. {
  201046. png_charpp old_ptr;
  201047. old_ptr = comp->output_ptr;
  201048. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201049. (png_uint_32)(comp->max_output_ptr *
  201050. png_sizeof (png_charpp)));
  201051. png_memcpy(comp->output_ptr, old_ptr, old_max
  201052. * png_sizeof (png_charp));
  201053. png_free(png_ptr, old_ptr);
  201054. }
  201055. else
  201056. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201057. (png_uint_32)(comp->max_output_ptr *
  201058. png_sizeof (png_charp)));
  201059. }
  201060. /* save the data */
  201061. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201062. (png_uint_32)png_ptr->zbuf_size);
  201063. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201064. png_ptr->zbuf_size);
  201065. comp->num_output_ptr++;
  201066. /* and reset the buffer */
  201067. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201068. png_ptr->zstream.next_out = png_ptr->zbuf;
  201069. }
  201070. /* continue until we don't have any more to compress */
  201071. } while (png_ptr->zstream.avail_in);
  201072. /* finish the compression */
  201073. do
  201074. {
  201075. /* tell zlib we are finished */
  201076. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201077. if (ret == Z_OK)
  201078. {
  201079. /* check to see if we need more room */
  201080. if (!(png_ptr->zstream.avail_out))
  201081. {
  201082. /* check to make sure our output array has room */
  201083. if (comp->num_output_ptr >= comp->max_output_ptr)
  201084. {
  201085. int old_max;
  201086. old_max = comp->max_output_ptr;
  201087. comp->max_output_ptr = comp->num_output_ptr + 4;
  201088. if (comp->output_ptr != NULL)
  201089. {
  201090. png_charpp old_ptr;
  201091. old_ptr = comp->output_ptr;
  201092. /* This could be optimized to realloc() */
  201093. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201094. (png_uint_32)(comp->max_output_ptr *
  201095. png_sizeof (png_charpp)));
  201096. png_memcpy(comp->output_ptr, old_ptr,
  201097. old_max * png_sizeof (png_charp));
  201098. png_free(png_ptr, old_ptr);
  201099. }
  201100. else
  201101. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201102. (png_uint_32)(comp->max_output_ptr *
  201103. png_sizeof (png_charp)));
  201104. }
  201105. /* save off the data */
  201106. comp->output_ptr[comp->num_output_ptr] =
  201107. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201108. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201109. png_ptr->zbuf_size);
  201110. comp->num_output_ptr++;
  201111. /* and reset the buffer pointers */
  201112. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201113. png_ptr->zstream.next_out = png_ptr->zbuf;
  201114. }
  201115. }
  201116. else if (ret != Z_STREAM_END)
  201117. {
  201118. /* we got an error */
  201119. if (png_ptr->zstream.msg != NULL)
  201120. png_error(png_ptr, png_ptr->zstream.msg);
  201121. else
  201122. png_error(png_ptr, "zlib error");
  201123. }
  201124. } while (ret != Z_STREAM_END);
  201125. /* text length is number of buffers plus last buffer */
  201126. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201127. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201128. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201129. return((int)text_len);
  201130. }
  201131. /* ship the compressed text out via chunk writes */
  201132. static void /* PRIVATE */
  201133. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201134. {
  201135. int i;
  201136. /* handle the no-compression case */
  201137. if (comp->input)
  201138. {
  201139. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201140. (png_size_t)comp->input_len);
  201141. return;
  201142. }
  201143. /* write saved output buffers, if any */
  201144. for (i = 0; i < comp->num_output_ptr; i++)
  201145. {
  201146. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201147. png_ptr->zbuf_size);
  201148. png_free(png_ptr, comp->output_ptr[i]);
  201149. comp->output_ptr[i]=NULL;
  201150. }
  201151. if (comp->max_output_ptr != 0)
  201152. png_free(png_ptr, comp->output_ptr);
  201153. comp->output_ptr=NULL;
  201154. /* write anything left in zbuf */
  201155. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201156. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201157. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201158. /* reset zlib for another zTXt/iTXt or image data */
  201159. deflateReset(&png_ptr->zstream);
  201160. png_ptr->zstream.data_type = Z_BINARY;
  201161. }
  201162. #endif
  201163. /* Write the IHDR chunk, and update the png_struct with the necessary
  201164. * information. Note that the rest of this code depends upon this
  201165. * information being correct.
  201166. */
  201167. void /* PRIVATE */
  201168. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201169. int bit_depth, int color_type, int compression_type, int filter_type,
  201170. int interlace_type)
  201171. {
  201172. #ifdef PNG_USE_LOCAL_ARRAYS
  201173. PNG_IHDR;
  201174. #endif
  201175. png_byte buf[13]; /* buffer to store the IHDR info */
  201176. png_debug(1, "in png_write_IHDR\n");
  201177. /* Check that we have valid input data from the application info */
  201178. switch (color_type)
  201179. {
  201180. case PNG_COLOR_TYPE_GRAY:
  201181. switch (bit_depth)
  201182. {
  201183. case 1:
  201184. case 2:
  201185. case 4:
  201186. case 8:
  201187. case 16: png_ptr->channels = 1; break;
  201188. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201189. }
  201190. break;
  201191. case PNG_COLOR_TYPE_RGB:
  201192. if (bit_depth != 8 && bit_depth != 16)
  201193. png_error(png_ptr, "Invalid bit depth for RGB image");
  201194. png_ptr->channels = 3;
  201195. break;
  201196. case PNG_COLOR_TYPE_PALETTE:
  201197. switch (bit_depth)
  201198. {
  201199. case 1:
  201200. case 2:
  201201. case 4:
  201202. case 8: png_ptr->channels = 1; break;
  201203. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201204. }
  201205. break;
  201206. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201207. if (bit_depth != 8 && bit_depth != 16)
  201208. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201209. png_ptr->channels = 2;
  201210. break;
  201211. case PNG_COLOR_TYPE_RGB_ALPHA:
  201212. if (bit_depth != 8 && bit_depth != 16)
  201213. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201214. png_ptr->channels = 4;
  201215. break;
  201216. default:
  201217. png_error(png_ptr, "Invalid image color type specified");
  201218. }
  201219. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201220. {
  201221. png_warning(png_ptr, "Invalid compression type specified");
  201222. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201223. }
  201224. /* Write filter_method 64 (intrapixel differencing) only if
  201225. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201226. * 2. Libpng did not write a PNG signature (this filter_method is only
  201227. * used in PNG datastreams that are embedded in MNG datastreams) and
  201228. * 3. The application called png_permit_mng_features with a mask that
  201229. * included PNG_FLAG_MNG_FILTER_64 and
  201230. * 4. The filter_method is 64 and
  201231. * 5. The color_type is RGB or RGBA
  201232. */
  201233. if (
  201234. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201235. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201236. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201237. (color_type == PNG_COLOR_TYPE_RGB ||
  201238. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201239. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201240. #endif
  201241. filter_type != PNG_FILTER_TYPE_BASE)
  201242. {
  201243. png_warning(png_ptr, "Invalid filter type specified");
  201244. filter_type = PNG_FILTER_TYPE_BASE;
  201245. }
  201246. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201247. if (interlace_type != PNG_INTERLACE_NONE &&
  201248. interlace_type != PNG_INTERLACE_ADAM7)
  201249. {
  201250. png_warning(png_ptr, "Invalid interlace type specified");
  201251. interlace_type = PNG_INTERLACE_ADAM7;
  201252. }
  201253. #else
  201254. interlace_type=PNG_INTERLACE_NONE;
  201255. #endif
  201256. /* save off the relevent information */
  201257. png_ptr->bit_depth = (png_byte)bit_depth;
  201258. png_ptr->color_type = (png_byte)color_type;
  201259. png_ptr->interlaced = (png_byte)interlace_type;
  201260. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201261. png_ptr->filter_type = (png_byte)filter_type;
  201262. #endif
  201263. png_ptr->compression_type = (png_byte)compression_type;
  201264. png_ptr->width = width;
  201265. png_ptr->height = height;
  201266. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201267. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201268. /* set the usr info, so any transformations can modify it */
  201269. png_ptr->usr_width = png_ptr->width;
  201270. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201271. png_ptr->usr_channels = png_ptr->channels;
  201272. /* pack the header information into the buffer */
  201273. png_save_uint_32(buf, width);
  201274. png_save_uint_32(buf + 4, height);
  201275. buf[8] = (png_byte)bit_depth;
  201276. buf[9] = (png_byte)color_type;
  201277. buf[10] = (png_byte)compression_type;
  201278. buf[11] = (png_byte)filter_type;
  201279. buf[12] = (png_byte)interlace_type;
  201280. /* write the chunk */
  201281. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201282. /* initialize zlib with PNG info */
  201283. png_ptr->zstream.zalloc = png_zalloc;
  201284. png_ptr->zstream.zfree = png_zfree;
  201285. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201286. if (!(png_ptr->do_filter))
  201287. {
  201288. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201289. png_ptr->bit_depth < 8)
  201290. png_ptr->do_filter = PNG_FILTER_NONE;
  201291. else
  201292. png_ptr->do_filter = PNG_ALL_FILTERS;
  201293. }
  201294. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201295. {
  201296. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201297. png_ptr->zlib_strategy = Z_FILTERED;
  201298. else
  201299. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201300. }
  201301. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201302. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201303. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201304. png_ptr->zlib_mem_level = 8;
  201305. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201306. png_ptr->zlib_window_bits = 15;
  201307. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201308. png_ptr->zlib_method = 8;
  201309. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201310. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201311. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201312. png_error(png_ptr, "zlib failed to initialize compressor");
  201313. png_ptr->zstream.next_out = png_ptr->zbuf;
  201314. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201315. /* libpng is not interested in zstream.data_type */
  201316. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201317. png_ptr->zstream.data_type = Z_BINARY;
  201318. png_ptr->mode = PNG_HAVE_IHDR;
  201319. }
  201320. /* write the palette. We are careful not to trust png_color to be in the
  201321. * correct order for PNG, so people can redefine it to any convenient
  201322. * structure.
  201323. */
  201324. void /* PRIVATE */
  201325. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201326. {
  201327. #ifdef PNG_USE_LOCAL_ARRAYS
  201328. PNG_PLTE;
  201329. #endif
  201330. png_uint_32 i;
  201331. png_colorp pal_ptr;
  201332. png_byte buf[3];
  201333. png_debug(1, "in png_write_PLTE\n");
  201334. if ((
  201335. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201336. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201337. #endif
  201338. num_pal == 0) || num_pal > 256)
  201339. {
  201340. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201341. {
  201342. png_error(png_ptr, "Invalid number of colors in palette");
  201343. }
  201344. else
  201345. {
  201346. png_warning(png_ptr, "Invalid number of colors in palette");
  201347. return;
  201348. }
  201349. }
  201350. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201351. {
  201352. png_warning(png_ptr,
  201353. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201354. return;
  201355. }
  201356. png_ptr->num_palette = (png_uint_16)num_pal;
  201357. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201358. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201359. #ifndef PNG_NO_POINTER_INDEXING
  201360. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201361. {
  201362. buf[0] = pal_ptr->red;
  201363. buf[1] = pal_ptr->green;
  201364. buf[2] = pal_ptr->blue;
  201365. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201366. }
  201367. #else
  201368. /* This is a little slower but some buggy compilers need to do this instead */
  201369. pal_ptr=palette;
  201370. for (i = 0; i < num_pal; i++)
  201371. {
  201372. buf[0] = pal_ptr[i].red;
  201373. buf[1] = pal_ptr[i].green;
  201374. buf[2] = pal_ptr[i].blue;
  201375. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201376. }
  201377. #endif
  201378. png_write_chunk_end(png_ptr);
  201379. png_ptr->mode |= PNG_HAVE_PLTE;
  201380. }
  201381. /* write an IDAT chunk */
  201382. void /* PRIVATE */
  201383. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201384. {
  201385. #ifdef PNG_USE_LOCAL_ARRAYS
  201386. PNG_IDAT;
  201387. #endif
  201388. png_debug(1, "in png_write_IDAT\n");
  201389. /* Optimize the CMF field in the zlib stream. */
  201390. /* This hack of the zlib stream is compliant to the stream specification. */
  201391. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201392. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201393. {
  201394. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201395. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201396. {
  201397. /* Avoid memory underflows and multiplication overflows. */
  201398. /* The conditions below are practically always satisfied;
  201399. however, they still must be checked. */
  201400. if (length >= 2 &&
  201401. png_ptr->height < 16384 && png_ptr->width < 16384)
  201402. {
  201403. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201404. ((png_ptr->width *
  201405. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201406. unsigned int z_cinfo = z_cmf >> 4;
  201407. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201408. while (uncompressed_idat_size <= half_z_window_size &&
  201409. half_z_window_size >= 256)
  201410. {
  201411. z_cinfo--;
  201412. half_z_window_size >>= 1;
  201413. }
  201414. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201415. if (data[0] != (png_byte)z_cmf)
  201416. {
  201417. data[0] = (png_byte)z_cmf;
  201418. data[1] &= 0xe0;
  201419. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201420. }
  201421. }
  201422. }
  201423. else
  201424. png_error(png_ptr,
  201425. "Invalid zlib compression method or flags in IDAT");
  201426. }
  201427. png_write_chunk(png_ptr, png_IDAT, data, length);
  201428. png_ptr->mode |= PNG_HAVE_IDAT;
  201429. }
  201430. /* write an IEND chunk */
  201431. void /* PRIVATE */
  201432. png_write_IEND(png_structp png_ptr)
  201433. {
  201434. #ifdef PNG_USE_LOCAL_ARRAYS
  201435. PNG_IEND;
  201436. #endif
  201437. png_debug(1, "in png_write_IEND\n");
  201438. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201439. (png_size_t)0);
  201440. png_ptr->mode |= PNG_HAVE_IEND;
  201441. }
  201442. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201443. /* write a gAMA chunk */
  201444. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201445. void /* PRIVATE */
  201446. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201447. {
  201448. #ifdef PNG_USE_LOCAL_ARRAYS
  201449. PNG_gAMA;
  201450. #endif
  201451. png_uint_32 igamma;
  201452. png_byte buf[4];
  201453. png_debug(1, "in png_write_gAMA\n");
  201454. /* file_gamma is saved in 1/100,000ths */
  201455. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201456. png_save_uint_32(buf, igamma);
  201457. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201458. }
  201459. #endif
  201460. #ifdef PNG_FIXED_POINT_SUPPORTED
  201461. void /* PRIVATE */
  201462. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201463. {
  201464. #ifdef PNG_USE_LOCAL_ARRAYS
  201465. PNG_gAMA;
  201466. #endif
  201467. png_byte buf[4];
  201468. png_debug(1, "in png_write_gAMA\n");
  201469. /* file_gamma is saved in 1/100,000ths */
  201470. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201471. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201472. }
  201473. #endif
  201474. #endif
  201475. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201476. /* write a sRGB chunk */
  201477. void /* PRIVATE */
  201478. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201479. {
  201480. #ifdef PNG_USE_LOCAL_ARRAYS
  201481. PNG_sRGB;
  201482. #endif
  201483. png_byte buf[1];
  201484. png_debug(1, "in png_write_sRGB\n");
  201485. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201486. png_warning(png_ptr,
  201487. "Invalid sRGB rendering intent specified");
  201488. buf[0]=(png_byte)srgb_intent;
  201489. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201490. }
  201491. #endif
  201492. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201493. /* write an iCCP chunk */
  201494. void /* PRIVATE */
  201495. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201496. png_charp profile, int profile_len)
  201497. {
  201498. #ifdef PNG_USE_LOCAL_ARRAYS
  201499. PNG_iCCP;
  201500. #endif
  201501. png_size_t name_len;
  201502. png_charp new_name;
  201503. compression_state comp;
  201504. int embedded_profile_len = 0;
  201505. png_debug(1, "in png_write_iCCP\n");
  201506. comp.num_output_ptr = 0;
  201507. comp.max_output_ptr = 0;
  201508. comp.output_ptr = NULL;
  201509. comp.input = NULL;
  201510. comp.input_len = 0;
  201511. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201512. &new_name)) == 0)
  201513. {
  201514. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201515. return;
  201516. }
  201517. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201518. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201519. if (profile == NULL)
  201520. profile_len = 0;
  201521. if (profile_len > 3)
  201522. embedded_profile_len =
  201523. ((*( (png_bytep)profile ))<<24) |
  201524. ((*( (png_bytep)profile+1))<<16) |
  201525. ((*( (png_bytep)profile+2))<< 8) |
  201526. ((*( (png_bytep)profile+3)) );
  201527. if (profile_len < embedded_profile_len)
  201528. {
  201529. png_warning(png_ptr,
  201530. "Embedded profile length too large in iCCP chunk");
  201531. return;
  201532. }
  201533. if (profile_len > embedded_profile_len)
  201534. {
  201535. png_warning(png_ptr,
  201536. "Truncating profile to actual length in iCCP chunk");
  201537. profile_len = embedded_profile_len;
  201538. }
  201539. if (profile_len)
  201540. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201541. PNG_COMPRESSION_TYPE_BASE, &comp);
  201542. /* make sure we include the NULL after the name and the compression type */
  201543. png_write_chunk_start(png_ptr, png_iCCP,
  201544. (png_uint_32)name_len+profile_len+2);
  201545. new_name[name_len+1]=0x00;
  201546. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201547. if (profile_len)
  201548. png_write_compressed_data_out(png_ptr, &comp);
  201549. png_write_chunk_end(png_ptr);
  201550. png_free(png_ptr, new_name);
  201551. }
  201552. #endif
  201553. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201554. /* write a sPLT chunk */
  201555. void /* PRIVATE */
  201556. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201557. {
  201558. #ifdef PNG_USE_LOCAL_ARRAYS
  201559. PNG_sPLT;
  201560. #endif
  201561. png_size_t name_len;
  201562. png_charp new_name;
  201563. png_byte entrybuf[10];
  201564. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201565. int palette_size = entry_size * spalette->nentries;
  201566. png_sPLT_entryp ep;
  201567. #ifdef PNG_NO_POINTER_INDEXING
  201568. int i;
  201569. #endif
  201570. png_debug(1, "in png_write_sPLT\n");
  201571. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201572. spalette->name, &new_name))==0)
  201573. {
  201574. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201575. return;
  201576. }
  201577. /* make sure we include the NULL after the name */
  201578. png_write_chunk_start(png_ptr, png_sPLT,
  201579. (png_uint_32)(name_len + 2 + palette_size));
  201580. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201581. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201582. /* loop through each palette entry, writing appropriately */
  201583. #ifndef PNG_NO_POINTER_INDEXING
  201584. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201585. {
  201586. if (spalette->depth == 8)
  201587. {
  201588. entrybuf[0] = (png_byte)ep->red;
  201589. entrybuf[1] = (png_byte)ep->green;
  201590. entrybuf[2] = (png_byte)ep->blue;
  201591. entrybuf[3] = (png_byte)ep->alpha;
  201592. png_save_uint_16(entrybuf + 4, ep->frequency);
  201593. }
  201594. else
  201595. {
  201596. png_save_uint_16(entrybuf + 0, ep->red);
  201597. png_save_uint_16(entrybuf + 2, ep->green);
  201598. png_save_uint_16(entrybuf + 4, ep->blue);
  201599. png_save_uint_16(entrybuf + 6, ep->alpha);
  201600. png_save_uint_16(entrybuf + 8, ep->frequency);
  201601. }
  201602. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201603. }
  201604. #else
  201605. ep=spalette->entries;
  201606. for (i=0; i>spalette->nentries; i++)
  201607. {
  201608. if (spalette->depth == 8)
  201609. {
  201610. entrybuf[0] = (png_byte)ep[i].red;
  201611. entrybuf[1] = (png_byte)ep[i].green;
  201612. entrybuf[2] = (png_byte)ep[i].blue;
  201613. entrybuf[3] = (png_byte)ep[i].alpha;
  201614. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201615. }
  201616. else
  201617. {
  201618. png_save_uint_16(entrybuf + 0, ep[i].red);
  201619. png_save_uint_16(entrybuf + 2, ep[i].green);
  201620. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201621. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201622. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201623. }
  201624. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201625. }
  201626. #endif
  201627. png_write_chunk_end(png_ptr);
  201628. png_free(png_ptr, new_name);
  201629. }
  201630. #endif
  201631. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201632. /* write the sBIT chunk */
  201633. void /* PRIVATE */
  201634. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201635. {
  201636. #ifdef PNG_USE_LOCAL_ARRAYS
  201637. PNG_sBIT;
  201638. #endif
  201639. png_byte buf[4];
  201640. png_size_t size;
  201641. png_debug(1, "in png_write_sBIT\n");
  201642. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201643. if (color_type & PNG_COLOR_MASK_COLOR)
  201644. {
  201645. png_byte maxbits;
  201646. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201647. png_ptr->usr_bit_depth);
  201648. if (sbit->red == 0 || sbit->red > maxbits ||
  201649. sbit->green == 0 || sbit->green > maxbits ||
  201650. sbit->blue == 0 || sbit->blue > maxbits)
  201651. {
  201652. png_warning(png_ptr, "Invalid sBIT depth specified");
  201653. return;
  201654. }
  201655. buf[0] = sbit->red;
  201656. buf[1] = sbit->green;
  201657. buf[2] = sbit->blue;
  201658. size = 3;
  201659. }
  201660. else
  201661. {
  201662. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201663. {
  201664. png_warning(png_ptr, "Invalid sBIT depth specified");
  201665. return;
  201666. }
  201667. buf[0] = sbit->gray;
  201668. size = 1;
  201669. }
  201670. if (color_type & PNG_COLOR_MASK_ALPHA)
  201671. {
  201672. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201673. {
  201674. png_warning(png_ptr, "Invalid sBIT depth specified");
  201675. return;
  201676. }
  201677. buf[size++] = sbit->alpha;
  201678. }
  201679. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201680. }
  201681. #endif
  201682. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201683. /* write the cHRM chunk */
  201684. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201685. void /* PRIVATE */
  201686. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201687. double red_x, double red_y, double green_x, double green_y,
  201688. double blue_x, double blue_y)
  201689. {
  201690. #ifdef PNG_USE_LOCAL_ARRAYS
  201691. PNG_cHRM;
  201692. #endif
  201693. png_byte buf[32];
  201694. png_uint_32 itemp;
  201695. png_debug(1, "in png_write_cHRM\n");
  201696. /* each value is saved in 1/100,000ths */
  201697. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201698. white_x + white_y > 1.0)
  201699. {
  201700. png_warning(png_ptr, "Invalid cHRM white point specified");
  201701. #if !defined(PNG_NO_CONSOLE_IO)
  201702. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201703. #endif
  201704. return;
  201705. }
  201706. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201707. png_save_uint_32(buf, itemp);
  201708. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201709. png_save_uint_32(buf + 4, itemp);
  201710. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201711. {
  201712. png_warning(png_ptr, "Invalid cHRM red point specified");
  201713. return;
  201714. }
  201715. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201716. png_save_uint_32(buf + 8, itemp);
  201717. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201718. png_save_uint_32(buf + 12, itemp);
  201719. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201720. {
  201721. png_warning(png_ptr, "Invalid cHRM green point specified");
  201722. return;
  201723. }
  201724. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201725. png_save_uint_32(buf + 16, itemp);
  201726. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201727. png_save_uint_32(buf + 20, itemp);
  201728. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201729. {
  201730. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201731. return;
  201732. }
  201733. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201734. png_save_uint_32(buf + 24, itemp);
  201735. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201736. png_save_uint_32(buf + 28, itemp);
  201737. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201738. }
  201739. #endif
  201740. #ifdef PNG_FIXED_POINT_SUPPORTED
  201741. void /* PRIVATE */
  201742. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201743. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201744. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201745. png_fixed_point blue_y)
  201746. {
  201747. #ifdef PNG_USE_LOCAL_ARRAYS
  201748. PNG_cHRM;
  201749. #endif
  201750. png_byte buf[32];
  201751. png_debug(1, "in png_write_cHRM\n");
  201752. /* each value is saved in 1/100,000ths */
  201753. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201754. {
  201755. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201756. #if !defined(PNG_NO_CONSOLE_IO)
  201757. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201758. #endif
  201759. return;
  201760. }
  201761. png_save_uint_32(buf, (png_uint_32)white_x);
  201762. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201763. if (red_x + red_y > 100000L)
  201764. {
  201765. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201766. return;
  201767. }
  201768. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201769. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201770. if (green_x + green_y > 100000L)
  201771. {
  201772. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201773. return;
  201774. }
  201775. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201776. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201777. if (blue_x + blue_y > 100000L)
  201778. {
  201779. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201780. return;
  201781. }
  201782. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201783. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201784. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201785. }
  201786. #endif
  201787. #endif
  201788. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201789. /* write the tRNS chunk */
  201790. void /* PRIVATE */
  201791. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201792. int num_trans, int color_type)
  201793. {
  201794. #ifdef PNG_USE_LOCAL_ARRAYS
  201795. PNG_tRNS;
  201796. #endif
  201797. png_byte buf[6];
  201798. png_debug(1, "in png_write_tRNS\n");
  201799. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201800. {
  201801. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201802. {
  201803. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201804. return;
  201805. }
  201806. /* write the chunk out as it is */
  201807. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201808. }
  201809. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201810. {
  201811. /* one 16 bit value */
  201812. if(tran->gray >= (1 << png_ptr->bit_depth))
  201813. {
  201814. png_warning(png_ptr,
  201815. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201816. return;
  201817. }
  201818. png_save_uint_16(buf, tran->gray);
  201819. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201820. }
  201821. else if (color_type == PNG_COLOR_TYPE_RGB)
  201822. {
  201823. /* three 16 bit values */
  201824. png_save_uint_16(buf, tran->red);
  201825. png_save_uint_16(buf + 2, tran->green);
  201826. png_save_uint_16(buf + 4, tran->blue);
  201827. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201828. {
  201829. png_warning(png_ptr,
  201830. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201831. return;
  201832. }
  201833. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201834. }
  201835. else
  201836. {
  201837. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201838. }
  201839. }
  201840. #endif
  201841. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201842. /* write the background chunk */
  201843. void /* PRIVATE */
  201844. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201845. {
  201846. #ifdef PNG_USE_LOCAL_ARRAYS
  201847. PNG_bKGD;
  201848. #endif
  201849. png_byte buf[6];
  201850. png_debug(1, "in png_write_bKGD\n");
  201851. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201852. {
  201853. if (
  201854. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201855. (png_ptr->num_palette ||
  201856. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201857. #endif
  201858. back->index > png_ptr->num_palette)
  201859. {
  201860. png_warning(png_ptr, "Invalid background palette index");
  201861. return;
  201862. }
  201863. buf[0] = back->index;
  201864. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201865. }
  201866. else if (color_type & PNG_COLOR_MASK_COLOR)
  201867. {
  201868. png_save_uint_16(buf, back->red);
  201869. png_save_uint_16(buf + 2, back->green);
  201870. png_save_uint_16(buf + 4, back->blue);
  201871. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201872. {
  201873. png_warning(png_ptr,
  201874. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201875. return;
  201876. }
  201877. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201878. }
  201879. else
  201880. {
  201881. if(back->gray >= (1 << png_ptr->bit_depth))
  201882. {
  201883. png_warning(png_ptr,
  201884. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201885. return;
  201886. }
  201887. png_save_uint_16(buf, back->gray);
  201888. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201889. }
  201890. }
  201891. #endif
  201892. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201893. /* write the histogram */
  201894. void /* PRIVATE */
  201895. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201896. {
  201897. #ifdef PNG_USE_LOCAL_ARRAYS
  201898. PNG_hIST;
  201899. #endif
  201900. int i;
  201901. png_byte buf[3];
  201902. png_debug(1, "in png_write_hIST\n");
  201903. if (num_hist > (int)png_ptr->num_palette)
  201904. {
  201905. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201906. png_ptr->num_palette);
  201907. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201908. return;
  201909. }
  201910. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201911. for (i = 0; i < num_hist; i++)
  201912. {
  201913. png_save_uint_16(buf, hist[i]);
  201914. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201915. }
  201916. png_write_chunk_end(png_ptr);
  201917. }
  201918. #endif
  201919. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201920. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201921. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201922. * and if invalid, correct the keyword rather than discarding the entire
  201923. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201924. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201925. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201926. *
  201927. * The new_key is allocated to hold the corrected keyword and must be freed
  201928. * by the calling routine. This avoids problems with trying to write to
  201929. * static keywords without having to have duplicate copies of the strings.
  201930. */
  201931. png_size_t /* PRIVATE */
  201932. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201933. {
  201934. png_size_t key_len;
  201935. png_charp kp, dp;
  201936. int kflag;
  201937. int kwarn=0;
  201938. png_debug(1, "in png_check_keyword\n");
  201939. *new_key = NULL;
  201940. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201941. {
  201942. png_warning(png_ptr, "zero length keyword");
  201943. return ((png_size_t)0);
  201944. }
  201945. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201946. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201947. if (*new_key == NULL)
  201948. {
  201949. png_warning(png_ptr, "Out of memory while procesing keyword");
  201950. return ((png_size_t)0);
  201951. }
  201952. /* Replace non-printing characters with a blank and print a warning */
  201953. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201954. {
  201955. if ((png_byte)*kp < 0x20 ||
  201956. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201957. {
  201958. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201959. char msg[40];
  201960. png_snprintf(msg, 40,
  201961. "invalid keyword character 0x%02X", (png_byte)*kp);
  201962. png_warning(png_ptr, msg);
  201963. #else
  201964. png_warning(png_ptr, "invalid character in keyword");
  201965. #endif
  201966. *dp = ' ';
  201967. }
  201968. else
  201969. {
  201970. *dp = *kp;
  201971. }
  201972. }
  201973. *dp = '\0';
  201974. /* Remove any trailing white space. */
  201975. kp = *new_key + key_len - 1;
  201976. if (*kp == ' ')
  201977. {
  201978. png_warning(png_ptr, "trailing spaces removed from keyword");
  201979. while (*kp == ' ')
  201980. {
  201981. *(kp--) = '\0';
  201982. key_len--;
  201983. }
  201984. }
  201985. /* Remove any leading white space. */
  201986. kp = *new_key;
  201987. if (*kp == ' ')
  201988. {
  201989. png_warning(png_ptr, "leading spaces removed from keyword");
  201990. while (*kp == ' ')
  201991. {
  201992. kp++;
  201993. key_len--;
  201994. }
  201995. }
  201996. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201997. /* Remove multiple internal spaces. */
  201998. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201999. {
  202000. if (*kp == ' ' && kflag == 0)
  202001. {
  202002. *(dp++) = *kp;
  202003. kflag = 1;
  202004. }
  202005. else if (*kp == ' ')
  202006. {
  202007. key_len--;
  202008. kwarn=1;
  202009. }
  202010. else
  202011. {
  202012. *(dp++) = *kp;
  202013. kflag = 0;
  202014. }
  202015. }
  202016. *dp = '\0';
  202017. if(kwarn)
  202018. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202019. if (key_len == 0)
  202020. {
  202021. png_free(png_ptr, *new_key);
  202022. *new_key=NULL;
  202023. png_warning(png_ptr, "Zero length keyword");
  202024. }
  202025. if (key_len > 79)
  202026. {
  202027. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202028. new_key[79] = '\0';
  202029. key_len = 79;
  202030. }
  202031. return (key_len);
  202032. }
  202033. #endif
  202034. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202035. /* write a tEXt chunk */
  202036. void /* PRIVATE */
  202037. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202038. png_size_t text_len)
  202039. {
  202040. #ifdef PNG_USE_LOCAL_ARRAYS
  202041. PNG_tEXt;
  202042. #endif
  202043. png_size_t key_len;
  202044. png_charp new_key;
  202045. png_debug(1, "in png_write_tEXt\n");
  202046. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202047. {
  202048. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202049. return;
  202050. }
  202051. if (text == NULL || *text == '\0')
  202052. text_len = 0;
  202053. else
  202054. text_len = png_strlen(text);
  202055. /* make sure we include the 0 after the key */
  202056. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202057. /*
  202058. * We leave it to the application to meet PNG-1.0 requirements on the
  202059. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202060. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202061. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202062. */
  202063. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202064. if (text_len)
  202065. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202066. png_write_chunk_end(png_ptr);
  202067. png_free(png_ptr, new_key);
  202068. }
  202069. #endif
  202070. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202071. /* write a compressed text chunk */
  202072. void /* PRIVATE */
  202073. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202074. png_size_t text_len, int compression)
  202075. {
  202076. #ifdef PNG_USE_LOCAL_ARRAYS
  202077. PNG_zTXt;
  202078. #endif
  202079. png_size_t key_len;
  202080. char buf[1];
  202081. png_charp new_key;
  202082. compression_state comp;
  202083. png_debug(1, "in png_write_zTXt\n");
  202084. comp.num_output_ptr = 0;
  202085. comp.max_output_ptr = 0;
  202086. comp.output_ptr = NULL;
  202087. comp.input = NULL;
  202088. comp.input_len = 0;
  202089. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202090. {
  202091. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202092. return;
  202093. }
  202094. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202095. {
  202096. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202097. png_free(png_ptr, new_key);
  202098. return;
  202099. }
  202100. text_len = png_strlen(text);
  202101. /* compute the compressed data; do it now for the length */
  202102. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202103. &comp);
  202104. /* write start of chunk */
  202105. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202106. (key_len+text_len+2));
  202107. /* write key */
  202108. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202109. png_free(png_ptr, new_key);
  202110. buf[0] = (png_byte)compression;
  202111. /* write compression */
  202112. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202113. /* write the compressed data */
  202114. png_write_compressed_data_out(png_ptr, &comp);
  202115. /* close the chunk */
  202116. png_write_chunk_end(png_ptr);
  202117. }
  202118. #endif
  202119. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202120. /* write an iTXt chunk */
  202121. void /* PRIVATE */
  202122. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202123. png_charp lang, png_charp lang_key, png_charp text)
  202124. {
  202125. #ifdef PNG_USE_LOCAL_ARRAYS
  202126. PNG_iTXt;
  202127. #endif
  202128. png_size_t lang_len, key_len, lang_key_len, text_len;
  202129. png_charp new_lang, new_key;
  202130. png_byte cbuf[2];
  202131. compression_state comp;
  202132. png_debug(1, "in png_write_iTXt\n");
  202133. comp.num_output_ptr = 0;
  202134. comp.max_output_ptr = 0;
  202135. comp.output_ptr = NULL;
  202136. comp.input = NULL;
  202137. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202138. {
  202139. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202140. return;
  202141. }
  202142. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202143. {
  202144. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202145. new_lang = NULL;
  202146. lang_len = 0;
  202147. }
  202148. if (lang_key == NULL)
  202149. lang_key_len = 0;
  202150. else
  202151. lang_key_len = png_strlen(lang_key);
  202152. if (text == NULL)
  202153. text_len = 0;
  202154. else
  202155. text_len = png_strlen(text);
  202156. /* compute the compressed data; do it now for the length */
  202157. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202158. &comp);
  202159. /* make sure we include the compression flag, the compression byte,
  202160. * and the NULs after the key, lang, and lang_key parts */
  202161. png_write_chunk_start(png_ptr, png_iTXt,
  202162. (png_uint_32)(
  202163. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202164. + key_len
  202165. + lang_len
  202166. + lang_key_len
  202167. + text_len));
  202168. /*
  202169. * We leave it to the application to meet PNG-1.0 requirements on the
  202170. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202171. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202172. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202173. */
  202174. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202175. /* set the compression flag */
  202176. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202177. compression == PNG_TEXT_COMPRESSION_NONE)
  202178. cbuf[0] = 0;
  202179. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202180. cbuf[0] = 1;
  202181. /* set the compression method */
  202182. cbuf[1] = 0;
  202183. png_write_chunk_data(png_ptr, cbuf, 2);
  202184. cbuf[0] = 0;
  202185. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202186. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202187. png_write_compressed_data_out(png_ptr, &comp);
  202188. png_write_chunk_end(png_ptr);
  202189. png_free(png_ptr, new_key);
  202190. if (new_lang)
  202191. png_free(png_ptr, new_lang);
  202192. }
  202193. #endif
  202194. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202195. /* write the oFFs chunk */
  202196. void /* PRIVATE */
  202197. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202198. int unit_type)
  202199. {
  202200. #ifdef PNG_USE_LOCAL_ARRAYS
  202201. PNG_oFFs;
  202202. #endif
  202203. png_byte buf[9];
  202204. png_debug(1, "in png_write_oFFs\n");
  202205. if (unit_type >= PNG_OFFSET_LAST)
  202206. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202207. png_save_int_32(buf, x_offset);
  202208. png_save_int_32(buf + 4, y_offset);
  202209. buf[8] = (png_byte)unit_type;
  202210. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202211. }
  202212. #endif
  202213. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202214. /* write the pCAL chunk (described in the PNG extensions document) */
  202215. void /* PRIVATE */
  202216. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202217. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202218. {
  202219. #ifdef PNG_USE_LOCAL_ARRAYS
  202220. PNG_pCAL;
  202221. #endif
  202222. png_size_t purpose_len, units_len, total_len;
  202223. png_uint_32p params_len;
  202224. png_byte buf[10];
  202225. png_charp new_purpose;
  202226. int i;
  202227. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202228. if (type >= PNG_EQUATION_LAST)
  202229. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202230. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202231. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202232. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202233. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202234. total_len = purpose_len + units_len + 10;
  202235. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202236. *png_sizeof(png_uint_32)));
  202237. /* Find the length of each parameter, making sure we don't count the
  202238. null terminator for the last parameter. */
  202239. for (i = 0; i < nparams; i++)
  202240. {
  202241. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202242. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202243. total_len += (png_size_t)params_len[i];
  202244. }
  202245. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202246. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202247. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202248. png_save_int_32(buf, X0);
  202249. png_save_int_32(buf + 4, X1);
  202250. buf[8] = (png_byte)type;
  202251. buf[9] = (png_byte)nparams;
  202252. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202253. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202254. png_free(png_ptr, new_purpose);
  202255. for (i = 0; i < nparams; i++)
  202256. {
  202257. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202258. (png_size_t)params_len[i]);
  202259. }
  202260. png_free(png_ptr, params_len);
  202261. png_write_chunk_end(png_ptr);
  202262. }
  202263. #endif
  202264. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202265. /* write the sCAL chunk */
  202266. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202267. void /* PRIVATE */
  202268. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202269. {
  202270. #ifdef PNG_USE_LOCAL_ARRAYS
  202271. PNG_sCAL;
  202272. #endif
  202273. char buf[64];
  202274. png_size_t total_len;
  202275. png_debug(1, "in png_write_sCAL\n");
  202276. buf[0] = (char)unit;
  202277. #if defined(_WIN32_WCE)
  202278. /* sprintf() function is not supported on WindowsCE */
  202279. {
  202280. wchar_t wc_buf[32];
  202281. size_t wc_len;
  202282. swprintf(wc_buf, TEXT("%12.12e"), width);
  202283. wc_len = wcslen(wc_buf);
  202284. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202285. total_len = wc_len + 2;
  202286. swprintf(wc_buf, TEXT("%12.12e"), height);
  202287. wc_len = wcslen(wc_buf);
  202288. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202289. NULL, NULL);
  202290. total_len += wc_len;
  202291. }
  202292. #else
  202293. png_snprintf(buf + 1, 63, "%12.12e", width);
  202294. total_len = 1 + png_strlen(buf + 1) + 1;
  202295. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202296. total_len += png_strlen(buf + total_len);
  202297. #endif
  202298. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202299. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202300. }
  202301. #else
  202302. #ifdef PNG_FIXED_POINT_SUPPORTED
  202303. void /* PRIVATE */
  202304. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202305. png_charp height)
  202306. {
  202307. #ifdef PNG_USE_LOCAL_ARRAYS
  202308. PNG_sCAL;
  202309. #endif
  202310. png_byte buf[64];
  202311. png_size_t wlen, hlen, total_len;
  202312. png_debug(1, "in png_write_sCAL_s\n");
  202313. wlen = png_strlen(width);
  202314. hlen = png_strlen(height);
  202315. total_len = wlen + hlen + 2;
  202316. if (total_len > 64)
  202317. {
  202318. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202319. return;
  202320. }
  202321. buf[0] = (png_byte)unit;
  202322. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202323. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202324. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202325. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202326. }
  202327. #endif
  202328. #endif
  202329. #endif
  202330. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202331. /* write the pHYs chunk */
  202332. void /* PRIVATE */
  202333. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202334. png_uint_32 y_pixels_per_unit,
  202335. int unit_type)
  202336. {
  202337. #ifdef PNG_USE_LOCAL_ARRAYS
  202338. PNG_pHYs;
  202339. #endif
  202340. png_byte buf[9];
  202341. png_debug(1, "in png_write_pHYs\n");
  202342. if (unit_type >= PNG_RESOLUTION_LAST)
  202343. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202344. png_save_uint_32(buf, x_pixels_per_unit);
  202345. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202346. buf[8] = (png_byte)unit_type;
  202347. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202348. }
  202349. #endif
  202350. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202351. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202352. * or png_convert_from_time_t(), or fill in the structure yourself.
  202353. */
  202354. void /* PRIVATE */
  202355. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202356. {
  202357. #ifdef PNG_USE_LOCAL_ARRAYS
  202358. PNG_tIME;
  202359. #endif
  202360. png_byte buf[7];
  202361. png_debug(1, "in png_write_tIME\n");
  202362. if (mod_time->month > 12 || mod_time->month < 1 ||
  202363. mod_time->day > 31 || mod_time->day < 1 ||
  202364. mod_time->hour > 23 || mod_time->second > 60)
  202365. {
  202366. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202367. return;
  202368. }
  202369. png_save_uint_16(buf, mod_time->year);
  202370. buf[2] = mod_time->month;
  202371. buf[3] = mod_time->day;
  202372. buf[4] = mod_time->hour;
  202373. buf[5] = mod_time->minute;
  202374. buf[6] = mod_time->second;
  202375. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202376. }
  202377. #endif
  202378. /* initializes the row writing capability of libpng */
  202379. void /* PRIVATE */
  202380. png_write_start_row(png_structp png_ptr)
  202381. {
  202382. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202383. #ifdef PNG_USE_LOCAL_ARRAYS
  202384. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202385. /* start of interlace block */
  202386. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202387. /* offset to next interlace block */
  202388. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202389. /* start of interlace block in the y direction */
  202390. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202391. /* offset to next interlace block in the y direction */
  202392. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202393. #endif
  202394. #endif
  202395. png_size_t buf_size;
  202396. png_debug(1, "in png_write_start_row\n");
  202397. buf_size = (png_size_t)(PNG_ROWBYTES(
  202398. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202399. /* set up row buffer */
  202400. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202401. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202402. #ifndef PNG_NO_WRITE_FILTERING
  202403. /* set up filtering buffer, if using this filter */
  202404. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202405. {
  202406. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202407. (png_ptr->rowbytes + 1));
  202408. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202409. }
  202410. /* We only need to keep the previous row if we are using one of these. */
  202411. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202412. {
  202413. /* set up previous row buffer */
  202414. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202415. png_memset(png_ptr->prev_row, 0, buf_size);
  202416. if (png_ptr->do_filter & PNG_FILTER_UP)
  202417. {
  202418. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202419. (png_ptr->rowbytes + 1));
  202420. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202421. }
  202422. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202423. {
  202424. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202425. (png_ptr->rowbytes + 1));
  202426. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202427. }
  202428. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202429. {
  202430. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202431. (png_ptr->rowbytes + 1));
  202432. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202433. }
  202434. #endif /* PNG_NO_WRITE_FILTERING */
  202435. }
  202436. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202437. /* if interlaced, we need to set up width and height of pass */
  202438. if (png_ptr->interlaced)
  202439. {
  202440. if (!(png_ptr->transformations & PNG_INTERLACE))
  202441. {
  202442. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202443. png_pass_ystart[0]) / png_pass_yinc[0];
  202444. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202445. png_pass_start[0]) / png_pass_inc[0];
  202446. }
  202447. else
  202448. {
  202449. png_ptr->num_rows = png_ptr->height;
  202450. png_ptr->usr_width = png_ptr->width;
  202451. }
  202452. }
  202453. else
  202454. #endif
  202455. {
  202456. png_ptr->num_rows = png_ptr->height;
  202457. png_ptr->usr_width = png_ptr->width;
  202458. }
  202459. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202460. png_ptr->zstream.next_out = png_ptr->zbuf;
  202461. }
  202462. /* Internal use only. Called when finished processing a row of data. */
  202463. void /* PRIVATE */
  202464. png_write_finish_row(png_structp png_ptr)
  202465. {
  202466. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202467. #ifdef PNG_USE_LOCAL_ARRAYS
  202468. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202469. /* start of interlace block */
  202470. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202471. /* offset to next interlace block */
  202472. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202473. /* start of interlace block in the y direction */
  202474. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202475. /* offset to next interlace block in the y direction */
  202476. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202477. #endif
  202478. #endif
  202479. int ret;
  202480. png_debug(1, "in png_write_finish_row\n");
  202481. /* next row */
  202482. png_ptr->row_number++;
  202483. /* see if we are done */
  202484. if (png_ptr->row_number < png_ptr->num_rows)
  202485. return;
  202486. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202487. /* if interlaced, go to next pass */
  202488. if (png_ptr->interlaced)
  202489. {
  202490. png_ptr->row_number = 0;
  202491. if (png_ptr->transformations & PNG_INTERLACE)
  202492. {
  202493. png_ptr->pass++;
  202494. }
  202495. else
  202496. {
  202497. /* loop until we find a non-zero width or height pass */
  202498. do
  202499. {
  202500. png_ptr->pass++;
  202501. if (png_ptr->pass >= 7)
  202502. break;
  202503. png_ptr->usr_width = (png_ptr->width +
  202504. png_pass_inc[png_ptr->pass] - 1 -
  202505. png_pass_start[png_ptr->pass]) /
  202506. png_pass_inc[png_ptr->pass];
  202507. png_ptr->num_rows = (png_ptr->height +
  202508. png_pass_yinc[png_ptr->pass] - 1 -
  202509. png_pass_ystart[png_ptr->pass]) /
  202510. png_pass_yinc[png_ptr->pass];
  202511. if (png_ptr->transformations & PNG_INTERLACE)
  202512. break;
  202513. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202514. }
  202515. /* reset the row above the image for the next pass */
  202516. if (png_ptr->pass < 7)
  202517. {
  202518. if (png_ptr->prev_row != NULL)
  202519. png_memset(png_ptr->prev_row, 0,
  202520. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202521. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202522. return;
  202523. }
  202524. }
  202525. #endif
  202526. /* if we get here, we've just written the last row, so we need
  202527. to flush the compressor */
  202528. do
  202529. {
  202530. /* tell the compressor we are done */
  202531. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202532. /* check for an error */
  202533. if (ret == Z_OK)
  202534. {
  202535. /* check to see if we need more room */
  202536. if (!(png_ptr->zstream.avail_out))
  202537. {
  202538. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202539. png_ptr->zstream.next_out = png_ptr->zbuf;
  202540. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202541. }
  202542. }
  202543. else if (ret != Z_STREAM_END)
  202544. {
  202545. if (png_ptr->zstream.msg != NULL)
  202546. png_error(png_ptr, png_ptr->zstream.msg);
  202547. else
  202548. png_error(png_ptr, "zlib error");
  202549. }
  202550. } while (ret != Z_STREAM_END);
  202551. /* write any extra space */
  202552. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202553. {
  202554. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202555. png_ptr->zstream.avail_out);
  202556. }
  202557. deflateReset(&png_ptr->zstream);
  202558. png_ptr->zstream.data_type = Z_BINARY;
  202559. }
  202560. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202561. /* Pick out the correct pixels for the interlace pass.
  202562. * The basic idea here is to go through the row with a source
  202563. * pointer and a destination pointer (sp and dp), and copy the
  202564. * correct pixels for the pass. As the row gets compacted,
  202565. * sp will always be >= dp, so we should never overwrite anything.
  202566. * See the default: case for the easiest code to understand.
  202567. */
  202568. void /* PRIVATE */
  202569. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202570. {
  202571. #ifdef PNG_USE_LOCAL_ARRAYS
  202572. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202573. /* start of interlace block */
  202574. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202575. /* offset to next interlace block */
  202576. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202577. #endif
  202578. png_debug(1, "in png_do_write_interlace\n");
  202579. /* we don't have to do anything on the last pass (6) */
  202580. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202581. if (row != NULL && row_info != NULL && pass < 6)
  202582. #else
  202583. if (pass < 6)
  202584. #endif
  202585. {
  202586. /* each pixel depth is handled separately */
  202587. switch (row_info->pixel_depth)
  202588. {
  202589. case 1:
  202590. {
  202591. png_bytep sp;
  202592. png_bytep dp;
  202593. int shift;
  202594. int d;
  202595. int value;
  202596. png_uint_32 i;
  202597. png_uint_32 row_width = row_info->width;
  202598. dp = row;
  202599. d = 0;
  202600. shift = 7;
  202601. for (i = png_pass_start[pass]; i < row_width;
  202602. i += png_pass_inc[pass])
  202603. {
  202604. sp = row + (png_size_t)(i >> 3);
  202605. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202606. d |= (value << shift);
  202607. if (shift == 0)
  202608. {
  202609. shift = 7;
  202610. *dp++ = (png_byte)d;
  202611. d = 0;
  202612. }
  202613. else
  202614. shift--;
  202615. }
  202616. if (shift != 7)
  202617. *dp = (png_byte)d;
  202618. break;
  202619. }
  202620. case 2:
  202621. {
  202622. png_bytep sp;
  202623. png_bytep dp;
  202624. int shift;
  202625. int d;
  202626. int value;
  202627. png_uint_32 i;
  202628. png_uint_32 row_width = row_info->width;
  202629. dp = row;
  202630. shift = 6;
  202631. d = 0;
  202632. for (i = png_pass_start[pass]; i < row_width;
  202633. i += png_pass_inc[pass])
  202634. {
  202635. sp = row + (png_size_t)(i >> 2);
  202636. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202637. d |= (value << shift);
  202638. if (shift == 0)
  202639. {
  202640. shift = 6;
  202641. *dp++ = (png_byte)d;
  202642. d = 0;
  202643. }
  202644. else
  202645. shift -= 2;
  202646. }
  202647. if (shift != 6)
  202648. *dp = (png_byte)d;
  202649. break;
  202650. }
  202651. case 4:
  202652. {
  202653. png_bytep sp;
  202654. png_bytep dp;
  202655. int shift;
  202656. int d;
  202657. int value;
  202658. png_uint_32 i;
  202659. png_uint_32 row_width = row_info->width;
  202660. dp = row;
  202661. shift = 4;
  202662. d = 0;
  202663. for (i = png_pass_start[pass]; i < row_width;
  202664. i += png_pass_inc[pass])
  202665. {
  202666. sp = row + (png_size_t)(i >> 1);
  202667. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202668. d |= (value << shift);
  202669. if (shift == 0)
  202670. {
  202671. shift = 4;
  202672. *dp++ = (png_byte)d;
  202673. d = 0;
  202674. }
  202675. else
  202676. shift -= 4;
  202677. }
  202678. if (shift != 4)
  202679. *dp = (png_byte)d;
  202680. break;
  202681. }
  202682. default:
  202683. {
  202684. png_bytep sp;
  202685. png_bytep dp;
  202686. png_uint_32 i;
  202687. png_uint_32 row_width = row_info->width;
  202688. png_size_t pixel_bytes;
  202689. /* start at the beginning */
  202690. dp = row;
  202691. /* find out how many bytes each pixel takes up */
  202692. pixel_bytes = (row_info->pixel_depth >> 3);
  202693. /* loop through the row, only looking at the pixels that
  202694. matter */
  202695. for (i = png_pass_start[pass]; i < row_width;
  202696. i += png_pass_inc[pass])
  202697. {
  202698. /* find out where the original pixel is */
  202699. sp = row + (png_size_t)i * pixel_bytes;
  202700. /* move the pixel */
  202701. if (dp != sp)
  202702. png_memcpy(dp, sp, pixel_bytes);
  202703. /* next pixel */
  202704. dp += pixel_bytes;
  202705. }
  202706. break;
  202707. }
  202708. }
  202709. /* set new row width */
  202710. row_info->width = (row_info->width +
  202711. png_pass_inc[pass] - 1 -
  202712. png_pass_start[pass]) /
  202713. png_pass_inc[pass];
  202714. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202715. row_info->width);
  202716. }
  202717. }
  202718. #endif
  202719. /* This filters the row, chooses which filter to use, if it has not already
  202720. * been specified by the application, and then writes the row out with the
  202721. * chosen filter.
  202722. */
  202723. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202724. #define PNG_HISHIFT 10
  202725. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202726. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202727. void /* PRIVATE */
  202728. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202729. {
  202730. png_bytep best_row;
  202731. #ifndef PNG_NO_WRITE_FILTER
  202732. png_bytep prev_row, row_buf;
  202733. png_uint_32 mins, bpp;
  202734. png_byte filter_to_do = png_ptr->do_filter;
  202735. png_uint_32 row_bytes = row_info->rowbytes;
  202736. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202737. int num_p_filters = (int)png_ptr->num_prev_filters;
  202738. #endif
  202739. png_debug(1, "in png_write_find_filter\n");
  202740. /* find out how many bytes offset each pixel is */
  202741. bpp = (row_info->pixel_depth + 7) >> 3;
  202742. prev_row = png_ptr->prev_row;
  202743. #endif
  202744. best_row = png_ptr->row_buf;
  202745. #ifndef PNG_NO_WRITE_FILTER
  202746. row_buf = best_row;
  202747. mins = PNG_MAXSUM;
  202748. /* The prediction method we use is to find which method provides the
  202749. * smallest value when summing the absolute values of the distances
  202750. * from zero, using anything >= 128 as negative numbers. This is known
  202751. * as the "minimum sum of absolute differences" heuristic. Other
  202752. * heuristics are the "weighted minimum sum of absolute differences"
  202753. * (experimental and can in theory improve compression), and the "zlib
  202754. * predictive" method (not implemented yet), which does test compressions
  202755. * of lines using different filter methods, and then chooses the
  202756. * (series of) filter(s) that give minimum compressed data size (VERY
  202757. * computationally expensive).
  202758. *
  202759. * GRR 980525: consider also
  202760. * (1) minimum sum of absolute differences from running average (i.e.,
  202761. * keep running sum of non-absolute differences & count of bytes)
  202762. * [track dispersion, too? restart average if dispersion too large?]
  202763. * (1b) minimum sum of absolute differences from sliding average, probably
  202764. * with window size <= deflate window (usually 32K)
  202765. * (2) minimum sum of squared differences from zero or running average
  202766. * (i.e., ~ root-mean-square approach)
  202767. */
  202768. /* We don't need to test the 'no filter' case if this is the only filter
  202769. * that has been chosen, as it doesn't actually do anything to the data.
  202770. */
  202771. if ((filter_to_do & PNG_FILTER_NONE) &&
  202772. filter_to_do != PNG_FILTER_NONE)
  202773. {
  202774. png_bytep rp;
  202775. png_uint_32 sum = 0;
  202776. png_uint_32 i;
  202777. int v;
  202778. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202779. {
  202780. v = *rp;
  202781. sum += (v < 128) ? v : 256 - v;
  202782. }
  202783. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202784. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202785. {
  202786. png_uint_32 sumhi, sumlo;
  202787. int j;
  202788. sumlo = sum & PNG_LOMASK;
  202789. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202790. /* Reduce the sum if we match any of the previous rows */
  202791. for (j = 0; j < num_p_filters; j++)
  202792. {
  202793. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202794. {
  202795. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202796. PNG_WEIGHT_SHIFT;
  202797. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202798. PNG_WEIGHT_SHIFT;
  202799. }
  202800. }
  202801. /* Factor in the cost of this filter (this is here for completeness,
  202802. * but it makes no sense to have a "cost" for the NONE filter, as
  202803. * it has the minimum possible computational cost - none).
  202804. */
  202805. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202806. PNG_COST_SHIFT;
  202807. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202808. PNG_COST_SHIFT;
  202809. if (sumhi > PNG_HIMASK)
  202810. sum = PNG_MAXSUM;
  202811. else
  202812. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202813. }
  202814. #endif
  202815. mins = sum;
  202816. }
  202817. /* sub filter */
  202818. if (filter_to_do == PNG_FILTER_SUB)
  202819. /* it's the only filter so no testing is needed */
  202820. {
  202821. png_bytep rp, lp, dp;
  202822. png_uint_32 i;
  202823. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202824. i++, rp++, dp++)
  202825. {
  202826. *dp = *rp;
  202827. }
  202828. for (lp = row_buf + 1; i < row_bytes;
  202829. i++, rp++, lp++, dp++)
  202830. {
  202831. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202832. }
  202833. best_row = png_ptr->sub_row;
  202834. }
  202835. else if (filter_to_do & PNG_FILTER_SUB)
  202836. {
  202837. png_bytep rp, dp, lp;
  202838. png_uint_32 sum = 0, lmins = mins;
  202839. png_uint_32 i;
  202840. int v;
  202841. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202842. /* We temporarily increase the "minimum sum" by the factor we
  202843. * would reduce the sum of this filter, so that we can do the
  202844. * early exit comparison without scaling the sum each time.
  202845. */
  202846. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202847. {
  202848. int j;
  202849. png_uint_32 lmhi, lmlo;
  202850. lmlo = lmins & PNG_LOMASK;
  202851. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202852. for (j = 0; j < num_p_filters; j++)
  202853. {
  202854. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202855. {
  202856. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202857. PNG_WEIGHT_SHIFT;
  202858. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202859. PNG_WEIGHT_SHIFT;
  202860. }
  202861. }
  202862. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202863. PNG_COST_SHIFT;
  202864. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202865. PNG_COST_SHIFT;
  202866. if (lmhi > PNG_HIMASK)
  202867. lmins = PNG_MAXSUM;
  202868. else
  202869. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202870. }
  202871. #endif
  202872. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202873. i++, rp++, dp++)
  202874. {
  202875. v = *dp = *rp;
  202876. sum += (v < 128) ? v : 256 - v;
  202877. }
  202878. for (lp = row_buf + 1; i < row_bytes;
  202879. i++, rp++, lp++, dp++)
  202880. {
  202881. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202882. sum += (v < 128) ? v : 256 - v;
  202883. if (sum > lmins) /* We are already worse, don't continue. */
  202884. break;
  202885. }
  202886. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202887. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202888. {
  202889. int j;
  202890. png_uint_32 sumhi, sumlo;
  202891. sumlo = sum & PNG_LOMASK;
  202892. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202893. for (j = 0; j < num_p_filters; j++)
  202894. {
  202895. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202896. {
  202897. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202898. PNG_WEIGHT_SHIFT;
  202899. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202900. PNG_WEIGHT_SHIFT;
  202901. }
  202902. }
  202903. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202904. PNG_COST_SHIFT;
  202905. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202906. PNG_COST_SHIFT;
  202907. if (sumhi > PNG_HIMASK)
  202908. sum = PNG_MAXSUM;
  202909. else
  202910. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202911. }
  202912. #endif
  202913. if (sum < mins)
  202914. {
  202915. mins = sum;
  202916. best_row = png_ptr->sub_row;
  202917. }
  202918. }
  202919. /* up filter */
  202920. if (filter_to_do == PNG_FILTER_UP)
  202921. {
  202922. png_bytep rp, dp, pp;
  202923. png_uint_32 i;
  202924. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202925. pp = prev_row + 1; i < row_bytes;
  202926. i++, rp++, pp++, dp++)
  202927. {
  202928. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202929. }
  202930. best_row = png_ptr->up_row;
  202931. }
  202932. else if (filter_to_do & PNG_FILTER_UP)
  202933. {
  202934. png_bytep rp, dp, pp;
  202935. png_uint_32 sum = 0, lmins = mins;
  202936. png_uint_32 i;
  202937. int v;
  202938. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202939. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202940. {
  202941. int j;
  202942. png_uint_32 lmhi, lmlo;
  202943. lmlo = lmins & PNG_LOMASK;
  202944. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202945. for (j = 0; j < num_p_filters; j++)
  202946. {
  202947. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202948. {
  202949. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202950. PNG_WEIGHT_SHIFT;
  202951. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202952. PNG_WEIGHT_SHIFT;
  202953. }
  202954. }
  202955. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202956. PNG_COST_SHIFT;
  202957. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202958. PNG_COST_SHIFT;
  202959. if (lmhi > PNG_HIMASK)
  202960. lmins = PNG_MAXSUM;
  202961. else
  202962. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202963. }
  202964. #endif
  202965. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202966. pp = prev_row + 1; i < row_bytes; i++)
  202967. {
  202968. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202969. sum += (v < 128) ? v : 256 - v;
  202970. if (sum > lmins) /* We are already worse, don't continue. */
  202971. break;
  202972. }
  202973. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202974. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202975. {
  202976. int j;
  202977. png_uint_32 sumhi, sumlo;
  202978. sumlo = sum & PNG_LOMASK;
  202979. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202980. for (j = 0; j < num_p_filters; j++)
  202981. {
  202982. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202983. {
  202984. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202985. PNG_WEIGHT_SHIFT;
  202986. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202987. PNG_WEIGHT_SHIFT;
  202988. }
  202989. }
  202990. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202991. PNG_COST_SHIFT;
  202992. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202993. PNG_COST_SHIFT;
  202994. if (sumhi > PNG_HIMASK)
  202995. sum = PNG_MAXSUM;
  202996. else
  202997. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202998. }
  202999. #endif
  203000. if (sum < mins)
  203001. {
  203002. mins = sum;
  203003. best_row = png_ptr->up_row;
  203004. }
  203005. }
  203006. /* avg filter */
  203007. if (filter_to_do == PNG_FILTER_AVG)
  203008. {
  203009. png_bytep rp, dp, pp, lp;
  203010. png_uint_32 i;
  203011. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203012. pp = prev_row + 1; i < bpp; i++)
  203013. {
  203014. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203015. }
  203016. for (lp = row_buf + 1; i < row_bytes; i++)
  203017. {
  203018. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203019. & 0xff);
  203020. }
  203021. best_row = png_ptr->avg_row;
  203022. }
  203023. else if (filter_to_do & PNG_FILTER_AVG)
  203024. {
  203025. png_bytep rp, dp, pp, lp;
  203026. png_uint_32 sum = 0, lmins = mins;
  203027. png_uint_32 i;
  203028. int v;
  203029. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203030. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203031. {
  203032. int j;
  203033. png_uint_32 lmhi, lmlo;
  203034. lmlo = lmins & PNG_LOMASK;
  203035. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203036. for (j = 0; j < num_p_filters; j++)
  203037. {
  203038. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203039. {
  203040. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203041. PNG_WEIGHT_SHIFT;
  203042. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203043. PNG_WEIGHT_SHIFT;
  203044. }
  203045. }
  203046. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203047. PNG_COST_SHIFT;
  203048. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203049. PNG_COST_SHIFT;
  203050. if (lmhi > PNG_HIMASK)
  203051. lmins = PNG_MAXSUM;
  203052. else
  203053. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203054. }
  203055. #endif
  203056. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203057. pp = prev_row + 1; i < bpp; i++)
  203058. {
  203059. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203060. sum += (v < 128) ? v : 256 - v;
  203061. }
  203062. for (lp = row_buf + 1; i < row_bytes; i++)
  203063. {
  203064. v = *dp++ =
  203065. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203066. sum += (v < 128) ? v : 256 - v;
  203067. if (sum > lmins) /* We are already worse, don't continue. */
  203068. break;
  203069. }
  203070. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203071. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203072. {
  203073. int j;
  203074. png_uint_32 sumhi, sumlo;
  203075. sumlo = sum & PNG_LOMASK;
  203076. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203077. for (j = 0; j < num_p_filters; j++)
  203078. {
  203079. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203080. {
  203081. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203082. PNG_WEIGHT_SHIFT;
  203083. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203084. PNG_WEIGHT_SHIFT;
  203085. }
  203086. }
  203087. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203088. PNG_COST_SHIFT;
  203089. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203090. PNG_COST_SHIFT;
  203091. if (sumhi > PNG_HIMASK)
  203092. sum = PNG_MAXSUM;
  203093. else
  203094. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203095. }
  203096. #endif
  203097. if (sum < mins)
  203098. {
  203099. mins = sum;
  203100. best_row = png_ptr->avg_row;
  203101. }
  203102. }
  203103. /* Paeth filter */
  203104. if (filter_to_do == PNG_FILTER_PAETH)
  203105. {
  203106. png_bytep rp, dp, pp, cp, lp;
  203107. png_uint_32 i;
  203108. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203109. pp = prev_row + 1; i < bpp; i++)
  203110. {
  203111. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203112. }
  203113. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203114. {
  203115. int a, b, c, pa, pb, pc, p;
  203116. b = *pp++;
  203117. c = *cp++;
  203118. a = *lp++;
  203119. p = b - c;
  203120. pc = a - c;
  203121. #ifdef PNG_USE_ABS
  203122. pa = abs(p);
  203123. pb = abs(pc);
  203124. pc = abs(p + pc);
  203125. #else
  203126. pa = p < 0 ? -p : p;
  203127. pb = pc < 0 ? -pc : pc;
  203128. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203129. #endif
  203130. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203131. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203132. }
  203133. best_row = png_ptr->paeth_row;
  203134. }
  203135. else if (filter_to_do & PNG_FILTER_PAETH)
  203136. {
  203137. png_bytep rp, dp, pp, cp, lp;
  203138. png_uint_32 sum = 0, lmins = mins;
  203139. png_uint_32 i;
  203140. int v;
  203141. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203142. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203143. {
  203144. int j;
  203145. png_uint_32 lmhi, lmlo;
  203146. lmlo = lmins & PNG_LOMASK;
  203147. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203148. for (j = 0; j < num_p_filters; j++)
  203149. {
  203150. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203151. {
  203152. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203153. PNG_WEIGHT_SHIFT;
  203154. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203155. PNG_WEIGHT_SHIFT;
  203156. }
  203157. }
  203158. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203159. PNG_COST_SHIFT;
  203160. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203161. PNG_COST_SHIFT;
  203162. if (lmhi > PNG_HIMASK)
  203163. lmins = PNG_MAXSUM;
  203164. else
  203165. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203166. }
  203167. #endif
  203168. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203169. pp = prev_row + 1; i < bpp; i++)
  203170. {
  203171. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203172. sum += (v < 128) ? v : 256 - v;
  203173. }
  203174. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203175. {
  203176. int a, b, c, pa, pb, pc, p;
  203177. b = *pp++;
  203178. c = *cp++;
  203179. a = *lp++;
  203180. #ifndef PNG_SLOW_PAETH
  203181. p = b - c;
  203182. pc = a - c;
  203183. #ifdef PNG_USE_ABS
  203184. pa = abs(p);
  203185. pb = abs(pc);
  203186. pc = abs(p + pc);
  203187. #else
  203188. pa = p < 0 ? -p : p;
  203189. pb = pc < 0 ? -pc : pc;
  203190. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203191. #endif
  203192. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203193. #else /* PNG_SLOW_PAETH */
  203194. p = a + b - c;
  203195. pa = abs(p - a);
  203196. pb = abs(p - b);
  203197. pc = abs(p - c);
  203198. if (pa <= pb && pa <= pc)
  203199. p = a;
  203200. else if (pb <= pc)
  203201. p = b;
  203202. else
  203203. p = c;
  203204. #endif /* PNG_SLOW_PAETH */
  203205. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203206. sum += (v < 128) ? v : 256 - v;
  203207. if (sum > lmins) /* We are already worse, don't continue. */
  203208. break;
  203209. }
  203210. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203211. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203212. {
  203213. int j;
  203214. png_uint_32 sumhi, sumlo;
  203215. sumlo = sum & PNG_LOMASK;
  203216. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203217. for (j = 0; j < num_p_filters; j++)
  203218. {
  203219. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203220. {
  203221. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203222. PNG_WEIGHT_SHIFT;
  203223. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203224. PNG_WEIGHT_SHIFT;
  203225. }
  203226. }
  203227. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203228. PNG_COST_SHIFT;
  203229. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203230. PNG_COST_SHIFT;
  203231. if (sumhi > PNG_HIMASK)
  203232. sum = PNG_MAXSUM;
  203233. else
  203234. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203235. }
  203236. #endif
  203237. if (sum < mins)
  203238. {
  203239. best_row = png_ptr->paeth_row;
  203240. }
  203241. }
  203242. #endif /* PNG_NO_WRITE_FILTER */
  203243. /* Do the actual writing of the filtered row data from the chosen filter. */
  203244. png_write_filtered_row(png_ptr, best_row);
  203245. #ifndef PNG_NO_WRITE_FILTER
  203246. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203247. /* Save the type of filter we picked this time for future calculations */
  203248. if (png_ptr->num_prev_filters > 0)
  203249. {
  203250. int j;
  203251. for (j = 1; j < num_p_filters; j++)
  203252. {
  203253. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203254. }
  203255. png_ptr->prev_filters[j] = best_row[0];
  203256. }
  203257. #endif
  203258. #endif /* PNG_NO_WRITE_FILTER */
  203259. }
  203260. /* Do the actual writing of a previously filtered row. */
  203261. void /* PRIVATE */
  203262. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203263. {
  203264. png_debug(1, "in png_write_filtered_row\n");
  203265. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203266. /* set up the zlib input buffer */
  203267. png_ptr->zstream.next_in = filtered_row;
  203268. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203269. /* repeat until we have compressed all the data */
  203270. do
  203271. {
  203272. int ret; /* return of zlib */
  203273. /* compress the data */
  203274. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203275. /* check for compression errors */
  203276. if (ret != Z_OK)
  203277. {
  203278. if (png_ptr->zstream.msg != NULL)
  203279. png_error(png_ptr, png_ptr->zstream.msg);
  203280. else
  203281. png_error(png_ptr, "zlib error");
  203282. }
  203283. /* see if it is time to write another IDAT */
  203284. if (!(png_ptr->zstream.avail_out))
  203285. {
  203286. /* write the IDAT and reset the zlib output buffer */
  203287. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203288. png_ptr->zstream.next_out = png_ptr->zbuf;
  203289. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203290. }
  203291. /* repeat until all data has been compressed */
  203292. } while (png_ptr->zstream.avail_in);
  203293. /* swap the current and previous rows */
  203294. if (png_ptr->prev_row != NULL)
  203295. {
  203296. png_bytep tptr;
  203297. tptr = png_ptr->prev_row;
  203298. png_ptr->prev_row = png_ptr->row_buf;
  203299. png_ptr->row_buf = tptr;
  203300. }
  203301. /* finish row - updates counters and flushes zlib if last row */
  203302. png_write_finish_row(png_ptr);
  203303. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203304. png_ptr->flush_rows++;
  203305. if (png_ptr->flush_dist > 0 &&
  203306. png_ptr->flush_rows >= png_ptr->flush_dist)
  203307. {
  203308. png_write_flush(png_ptr);
  203309. }
  203310. #endif
  203311. }
  203312. #endif /* PNG_WRITE_SUPPORTED */
  203313. /*** End of inlined file: pngwutil.c ***/
  203314. #else
  203315. extern "C"
  203316. {
  203317. #include <png.h>
  203318. #include <pngconf.h>
  203319. }
  203320. #endif
  203321. }
  203322. #undef max
  203323. #undef min
  203324. #if JUCE_MSVC
  203325. #pragma warning (pop)
  203326. #endif
  203327. BEGIN_JUCE_NAMESPACE
  203328. using ::calloc;
  203329. using ::malloc;
  203330. using ::free;
  203331. namespace PNGHelpers
  203332. {
  203333. using namespace pnglibNamespace;
  203334. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203335. {
  203336. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203337. }
  203338. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203339. {
  203340. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203341. }
  203342. struct PNGErrorStruct {};
  203343. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203344. {
  203345. throw PNGErrorStruct();
  203346. }
  203347. }
  203348. PNGImageFormat::PNGImageFormat() {}
  203349. PNGImageFormat::~PNGImageFormat() {}
  203350. const String PNGImageFormat::getFormatName()
  203351. {
  203352. return "PNG";
  203353. }
  203354. bool PNGImageFormat::canUnderstand (InputStream& in)
  203355. {
  203356. const int bytesNeeded = 4;
  203357. char header [bytesNeeded];
  203358. return in.read (header, bytesNeeded) == bytesNeeded
  203359. && header[1] == 'P'
  203360. && header[2] == 'N'
  203361. && header[3] == 'G';
  203362. }
  203363. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203364. const Image juce_loadWithCoreImage (InputStream& input);
  203365. #endif
  203366. const Image PNGImageFormat::decodeImage (InputStream& in)
  203367. {
  203368. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203369. return juce_loadWithCoreImage (in);
  203370. #else
  203371. using namespace pnglibNamespace;
  203372. Image image;
  203373. png_structp pngReadStruct;
  203374. png_infop pngInfoStruct;
  203375. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203376. if (pngReadStruct != 0)
  203377. {
  203378. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203379. if (pngInfoStruct == 0)
  203380. {
  203381. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203382. return Image::null;
  203383. }
  203384. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203385. // read the header..
  203386. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203387. png_uint_32 width, height;
  203388. int bitDepth, colorType, interlaceType;
  203389. png_read_info (pngReadStruct, pngInfoStruct);
  203390. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203391. &width, &height,
  203392. &bitDepth, &colorType,
  203393. &interlaceType, 0, 0);
  203394. if (bitDepth == 16)
  203395. png_set_strip_16 (pngReadStruct);
  203396. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203397. png_set_expand (pngReadStruct);
  203398. if (bitDepth < 8)
  203399. png_set_expand (pngReadStruct);
  203400. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203401. png_set_expand (pngReadStruct);
  203402. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203403. png_set_gray_to_rgb (pngReadStruct);
  203404. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203405. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203406. || pngInfoStruct->num_trans > 0;
  203407. // Load the image into a temp buffer in the pnglib format..
  203408. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203409. {
  203410. HeapBlock <png_bytep> rows (height);
  203411. for (int y = (int) height; --y >= 0;)
  203412. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203413. png_read_image (pngReadStruct, rows);
  203414. png_read_end (pngReadStruct, pngInfoStruct);
  203415. }
  203416. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203417. // now convert the data to a juce image format..
  203418. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203419. (int) width, (int) height, hasAlphaChan);
  203420. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203421. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203422. const Image::BitmapData destData (image, true);
  203423. uint8* srcRow = tempBuffer;
  203424. uint8* destRow = destData.data;
  203425. for (int y = 0; y < (int) height; ++y)
  203426. {
  203427. const uint8* src = srcRow;
  203428. srcRow += (width << 2);
  203429. uint8* dest = destRow;
  203430. destRow += destData.lineStride;
  203431. if (hasAlphaChan)
  203432. {
  203433. for (int i = (int) width; --i >= 0;)
  203434. {
  203435. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203436. ((PixelARGB*) dest)->premultiply();
  203437. dest += destData.pixelStride;
  203438. src += 4;
  203439. }
  203440. }
  203441. else
  203442. {
  203443. for (int i = (int) width; --i >= 0;)
  203444. {
  203445. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203446. dest += destData.pixelStride;
  203447. src += 4;
  203448. }
  203449. }
  203450. }
  203451. }
  203452. return image;
  203453. #endif
  203454. }
  203455. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203456. {
  203457. using namespace pnglibNamespace;
  203458. const int width = image.getWidth();
  203459. const int height = image.getHeight();
  203460. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203461. if (pngWriteStruct == 0)
  203462. return false;
  203463. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203464. if (pngInfoStruct == 0)
  203465. {
  203466. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203467. return false;
  203468. }
  203469. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203470. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203471. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203472. : PNG_COLOR_TYPE_RGB,
  203473. PNG_INTERLACE_NONE,
  203474. PNG_COMPRESSION_TYPE_BASE,
  203475. PNG_FILTER_TYPE_BASE);
  203476. HeapBlock <uint8> rowData (width * 4);
  203477. png_color_8 sig_bit;
  203478. sig_bit.red = 8;
  203479. sig_bit.green = 8;
  203480. sig_bit.blue = 8;
  203481. sig_bit.alpha = 8;
  203482. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203483. png_write_info (pngWriteStruct, pngInfoStruct);
  203484. png_set_shift (pngWriteStruct, &sig_bit);
  203485. png_set_packing (pngWriteStruct);
  203486. const Image::BitmapData srcData (image, false);
  203487. for (int y = 0; y < height; ++y)
  203488. {
  203489. uint8* dst = rowData;
  203490. const uint8* src = srcData.getLinePointer (y);
  203491. if (image.hasAlphaChannel())
  203492. {
  203493. for (int i = width; --i >= 0;)
  203494. {
  203495. PixelARGB p (*(const PixelARGB*) src);
  203496. p.unpremultiply();
  203497. *dst++ = p.getRed();
  203498. *dst++ = p.getGreen();
  203499. *dst++ = p.getBlue();
  203500. *dst++ = p.getAlpha();
  203501. src += srcData.pixelStride;
  203502. }
  203503. }
  203504. else
  203505. {
  203506. for (int i = width; --i >= 0;)
  203507. {
  203508. *dst++ = ((const PixelRGB*) src)->getRed();
  203509. *dst++ = ((const PixelRGB*) src)->getGreen();
  203510. *dst++ = ((const PixelRGB*) src)->getBlue();
  203511. src += srcData.pixelStride;
  203512. }
  203513. }
  203514. png_bytep rowPtr = rowData;
  203515. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203516. }
  203517. png_write_end (pngWriteStruct, pngInfoStruct);
  203518. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203519. out.flush();
  203520. return true;
  203521. }
  203522. END_JUCE_NAMESPACE
  203523. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203524. #endif
  203525. //==============================================================================
  203526. #if JUCE_BUILD_NATIVE
  203527. // Non-public headers that are needed by more than one platform must be included
  203528. // before the platform-specific sections..
  203529. BEGIN_JUCE_NAMESPACE
  203530. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203531. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203532. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203533. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203534. /**
  203535. Helper class that takes chunks of incoming midi bytes, packages them into
  203536. messages, and dispatches them to a midi callback.
  203537. */
  203538. class MidiDataConcatenator
  203539. {
  203540. public:
  203541. MidiDataConcatenator (const int initialBufferSize)
  203542. : pendingData (initialBufferSize),
  203543. pendingBytes (0), pendingDataTime (0)
  203544. {
  203545. }
  203546. void reset()
  203547. {
  203548. pendingBytes = 0;
  203549. pendingDataTime = 0;
  203550. }
  203551. void pushMidiData (const void* data, int numBytes, double time,
  203552. MidiInput* input, MidiInputCallback& callback)
  203553. {
  203554. const uint8* d = static_cast <const uint8*> (data);
  203555. while (numBytes > 0)
  203556. {
  203557. if (pendingBytes > 0 || d[0] == 0xf0)
  203558. {
  203559. processSysex (d, numBytes, time, input, callback);
  203560. }
  203561. else
  203562. {
  203563. int used = 0;
  203564. const MidiMessage m (d, numBytes, used, 0, time);
  203565. if (used <= 0)
  203566. break; // malformed message..
  203567. callback.handleIncomingMidiMessage (input, m);
  203568. numBytes -= used;
  203569. d += used;
  203570. }
  203571. }
  203572. }
  203573. private:
  203574. void processSysex (const uint8*& d, int& numBytes, double time,
  203575. MidiInput* input, MidiInputCallback& callback)
  203576. {
  203577. if (*d == 0xf0)
  203578. {
  203579. pendingBytes = 0;
  203580. pendingDataTime = time;
  203581. }
  203582. pendingData.ensureSize (pendingBytes + numBytes, false);
  203583. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203584. uint8* dest = totalMessage + pendingBytes;
  203585. do
  203586. {
  203587. if (pendingBytes > 0 && *d >= 0x80)
  203588. {
  203589. if (*d >= 0xfa || *d == 0xf8)
  203590. {
  203591. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203592. ++d;
  203593. --numBytes;
  203594. }
  203595. else
  203596. {
  203597. if (*d == 0xf7)
  203598. {
  203599. *dest++ = *d++;
  203600. pendingBytes++;
  203601. --numBytes;
  203602. }
  203603. break;
  203604. }
  203605. }
  203606. else
  203607. {
  203608. *dest++ = *d++;
  203609. pendingBytes++;
  203610. --numBytes;
  203611. }
  203612. }
  203613. while (numBytes > 0);
  203614. if (pendingBytes > 0)
  203615. {
  203616. if (totalMessage [pendingBytes - 1] == 0xf7)
  203617. {
  203618. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203619. pendingBytes = 0;
  203620. }
  203621. else
  203622. {
  203623. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203624. }
  203625. }
  203626. }
  203627. MemoryBlock pendingData;
  203628. int pendingBytes;
  203629. double pendingDataTime;
  203630. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203631. };
  203632. #endif
  203633. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203634. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203635. END_JUCE_NAMESPACE
  203636. #if JUCE_WINDOWS
  203637. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203638. /*
  203639. This file wraps together all the win32-specific code, so that
  203640. we can include all the native headers just once, and compile all our
  203641. platform-specific stuff in one big lump, keeping it out of the way of
  203642. the rest of the codebase.
  203643. */
  203644. #if JUCE_WINDOWS
  203645. #undef JUCE_BUILD_NATIVE
  203646. #define JUCE_BUILD_NATIVE 1
  203647. BEGIN_JUCE_NAMESPACE
  203648. #define JUCE_INCLUDED_FILE 1
  203649. // Now include the actual code files..
  203650. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203651. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203652. // compiled on its own).
  203653. #if JUCE_INCLUDED_FILE
  203654. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203655. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203656. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203657. #ifndef DOXYGEN
  203658. // use with DynamicLibraryLoader to simplify importing functions
  203659. //
  203660. // functionName: function to import
  203661. // localFunctionName: name you want to use to actually call it (must be different)
  203662. // returnType: the return type
  203663. // object: the DynamicLibraryLoader to use
  203664. // params: list of params (bracketed)
  203665. //
  203666. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203667. typedef returnType (WINAPI *type##localFunctionName) params; \
  203668. type##localFunctionName localFunctionName \
  203669. = (type##localFunctionName)object.findProcAddress (#functionName);
  203670. // loads and unloads a DLL automatically
  203671. class JUCE_API DynamicLibraryLoader
  203672. {
  203673. public:
  203674. DynamicLibraryLoader (const String& name = String::empty);
  203675. ~DynamicLibraryLoader();
  203676. bool load (const String& libraryName);
  203677. void* findProcAddress (const String& functionName);
  203678. private:
  203679. void* libHandle;
  203680. };
  203681. #endif
  203682. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203683. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203684. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203685. : libHandle (0)
  203686. {
  203687. load (name);
  203688. }
  203689. DynamicLibraryLoader::~DynamicLibraryLoader()
  203690. {
  203691. load (String::empty);
  203692. }
  203693. bool DynamicLibraryLoader::load (const String& name)
  203694. {
  203695. FreeLibrary ((HMODULE) libHandle);
  203696. libHandle = name.isNotEmpty() ? LoadLibrary (name) : 0;
  203697. return libHandle != 0;
  203698. }
  203699. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203700. {
  203701. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203702. }
  203703. #endif
  203704. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203705. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203706. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203707. // compiled on its own).
  203708. #if JUCE_INCLUDED_FILE
  203709. void Logger::outputDebugString (const String& text)
  203710. {
  203711. OutputDebugString (text + "\n");
  203712. }
  203713. static int64 hiResTicksPerSecond;
  203714. static double hiResTicksScaleFactor;
  203715. #if JUCE_USE_INTRINSICS
  203716. // CPU info functions using intrinsics...
  203717. #pragma intrinsic (__cpuid)
  203718. #pragma intrinsic (__rdtsc)
  203719. const String SystemStats::getCpuVendor()
  203720. {
  203721. int info [4];
  203722. __cpuid (info, 0);
  203723. char v [12];
  203724. memcpy (v, info + 1, 4);
  203725. memcpy (v + 4, info + 3, 4);
  203726. memcpy (v + 8, info + 2, 4);
  203727. return String (v, 12);
  203728. }
  203729. #else
  203730. // CPU info functions using old fashioned inline asm...
  203731. static void juce_getCpuVendor (char* const v)
  203732. {
  203733. int vendor[4];
  203734. zeromem (vendor, 16);
  203735. #ifdef JUCE_64BIT
  203736. #else
  203737. #ifndef __MINGW32__
  203738. __try
  203739. #endif
  203740. {
  203741. #if JUCE_GCC
  203742. unsigned int dummy = 0;
  203743. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203744. #else
  203745. __asm
  203746. {
  203747. mov eax, 0
  203748. cpuid
  203749. mov [vendor], ebx
  203750. mov [vendor + 4], edx
  203751. mov [vendor + 8], ecx
  203752. }
  203753. #endif
  203754. }
  203755. #ifndef __MINGW32__
  203756. __except (EXCEPTION_EXECUTE_HANDLER)
  203757. {
  203758. *v = 0;
  203759. }
  203760. #endif
  203761. #endif
  203762. memcpy (v, vendor, 16);
  203763. }
  203764. const String SystemStats::getCpuVendor()
  203765. {
  203766. char v [16];
  203767. juce_getCpuVendor (v);
  203768. return String (v, 16);
  203769. }
  203770. #endif
  203771. void SystemStats::initialiseStats()
  203772. {
  203773. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203774. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203775. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203776. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203777. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203778. #else
  203779. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203780. #endif
  203781. {
  203782. SYSTEM_INFO systemInfo;
  203783. GetSystemInfo (&systemInfo);
  203784. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203785. }
  203786. LARGE_INTEGER f;
  203787. QueryPerformanceFrequency (&f);
  203788. hiResTicksPerSecond = f.QuadPart;
  203789. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203790. String s (SystemStats::getJUCEVersion());
  203791. const MMRESULT res = timeBeginPeriod (1);
  203792. (void) res;
  203793. jassert (res == TIMERR_NOERROR);
  203794. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203795. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203796. #endif
  203797. }
  203798. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203799. {
  203800. OSVERSIONINFO info;
  203801. info.dwOSVersionInfoSize = sizeof (info);
  203802. GetVersionEx (&info);
  203803. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203804. {
  203805. switch (info.dwMajorVersion)
  203806. {
  203807. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203808. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203809. default: jassertfalse; break; // !! not a supported OS!
  203810. }
  203811. }
  203812. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203813. {
  203814. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203815. return Win98;
  203816. }
  203817. return UnknownOS;
  203818. }
  203819. const String SystemStats::getOperatingSystemName()
  203820. {
  203821. const char* name = "Unknown OS";
  203822. switch (getOperatingSystemType())
  203823. {
  203824. case Windows7: name = "Windows 7"; break;
  203825. case WinVista: name = "Windows Vista"; break;
  203826. case WinXP: name = "Windows XP"; break;
  203827. case Win2000: name = "Windows 2000"; break;
  203828. case Win98: name = "Windows 98"; break;
  203829. default: jassertfalse; break; // !! new type of OS?
  203830. }
  203831. return name;
  203832. }
  203833. bool SystemStats::isOperatingSystem64Bit()
  203834. {
  203835. #ifdef _WIN64
  203836. return true;
  203837. #else
  203838. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203839. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203840. BOOL isWow64 = FALSE;
  203841. return (fnIsWow64Process != 0)
  203842. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203843. && (isWow64 != FALSE);
  203844. #endif
  203845. }
  203846. int SystemStats::getMemorySizeInMegabytes()
  203847. {
  203848. MEMORYSTATUSEX mem;
  203849. mem.dwLength = sizeof (mem);
  203850. GlobalMemoryStatusEx (&mem);
  203851. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203852. }
  203853. uint32 juce_millisecondsSinceStartup() throw()
  203854. {
  203855. return (uint32) timeGetTime();
  203856. }
  203857. int64 Time::getHighResolutionTicks() throw()
  203858. {
  203859. LARGE_INTEGER ticks;
  203860. QueryPerformanceCounter (&ticks);
  203861. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203862. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203863. // fix for a very obscure PCI hardware bug that can make the counter
  203864. // sometimes jump forwards by a few seconds..
  203865. static int64 hiResTicksOffset = 0;
  203866. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203867. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203868. hiResTicksOffset = newOffset;
  203869. return ticks.QuadPart + hiResTicksOffset;
  203870. }
  203871. double Time::getMillisecondCounterHiRes() throw()
  203872. {
  203873. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203874. }
  203875. int64 Time::getHighResolutionTicksPerSecond() throw()
  203876. {
  203877. return hiResTicksPerSecond;
  203878. }
  203879. static int64 juce_getClockCycleCounter() throw()
  203880. {
  203881. #if JUCE_USE_INTRINSICS
  203882. // MS intrinsics version...
  203883. return __rdtsc();
  203884. #elif JUCE_GCC
  203885. // GNU inline asm version...
  203886. unsigned int hi = 0, lo = 0;
  203887. __asm__ __volatile__ (
  203888. "xor %%eax, %%eax \n\
  203889. xor %%edx, %%edx \n\
  203890. rdtsc \n\
  203891. movl %%eax, %[lo] \n\
  203892. movl %%edx, %[hi]"
  203893. :
  203894. : [hi] "m" (hi),
  203895. [lo] "m" (lo)
  203896. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203897. return (int64) ((((uint64) hi) << 32) | lo);
  203898. #else
  203899. // MSVC inline asm version...
  203900. unsigned int hi = 0, lo = 0;
  203901. __asm
  203902. {
  203903. xor eax, eax
  203904. xor edx, edx
  203905. rdtsc
  203906. mov lo, eax
  203907. mov hi, edx
  203908. }
  203909. return (int64) ((((uint64) hi) << 32) | lo);
  203910. #endif
  203911. }
  203912. int SystemStats::getCpuSpeedInMegaherz()
  203913. {
  203914. const int64 cycles = juce_getClockCycleCounter();
  203915. const uint32 millis = Time::getMillisecondCounter();
  203916. int lastResult = 0;
  203917. for (;;)
  203918. {
  203919. int n = 1000000;
  203920. while (--n > 0) {}
  203921. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203922. const int64 cyclesNow = juce_getClockCycleCounter();
  203923. if (millisElapsed > 80)
  203924. {
  203925. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203926. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203927. return newResult;
  203928. lastResult = newResult;
  203929. }
  203930. }
  203931. }
  203932. bool Time::setSystemTimeToThisTime() const
  203933. {
  203934. SYSTEMTIME st;
  203935. st.wDayOfWeek = 0;
  203936. st.wYear = (WORD) getYear();
  203937. st.wMonth = (WORD) (getMonth() + 1);
  203938. st.wDay = (WORD) getDayOfMonth();
  203939. st.wHour = (WORD) getHours();
  203940. st.wMinute = (WORD) getMinutes();
  203941. st.wSecond = (WORD) getSeconds();
  203942. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203943. // do this twice because of daylight saving conversion problems - the
  203944. // first one sets it up, the second one kicks it in.
  203945. return SetLocalTime (&st) != 0
  203946. && SetLocalTime (&st) != 0;
  203947. }
  203948. int SystemStats::getPageSize()
  203949. {
  203950. SYSTEM_INFO systemInfo;
  203951. GetSystemInfo (&systemInfo);
  203952. return systemInfo.dwPageSize;
  203953. }
  203954. const String SystemStats::getLogonName()
  203955. {
  203956. TCHAR text [256];
  203957. DWORD len = numElementsInArray (text) - 2;
  203958. zerostruct (text);
  203959. GetUserName (text, &len);
  203960. return String (text, len);
  203961. }
  203962. const String SystemStats::getFullUserName()
  203963. {
  203964. return getLogonName();
  203965. }
  203966. #endif
  203967. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203968. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203969. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203970. // compiled on its own).
  203971. #if JUCE_INCLUDED_FILE
  203972. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203973. extern HWND juce_messageWindowHandle;
  203974. #endif
  203975. #if ! JUCE_USE_INTRINSICS
  203976. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203977. // older ones we have to actually call the ops as win32 functions..
  203978. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203979. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203980. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203981. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203982. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203983. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203984. {
  203985. jassertfalse; // This operation isn't available in old MS compiler versions!
  203986. __int64 oldValue = *value;
  203987. if (oldValue == valueToCompare)
  203988. *value = newValue;
  203989. return oldValue;
  203990. }
  203991. #endif
  203992. CriticalSection::CriticalSection() throw()
  203993. {
  203994. // (just to check the MS haven't changed this structure and broken things...)
  203995. #if JUCE_VC7_OR_EARLIER
  203996. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203997. #else
  203998. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203999. #endif
  204000. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  204001. }
  204002. CriticalSection::~CriticalSection() throw()
  204003. {
  204004. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  204005. }
  204006. void CriticalSection::enter() const throw()
  204007. {
  204008. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  204009. }
  204010. bool CriticalSection::tryEnter() const throw()
  204011. {
  204012. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  204013. }
  204014. void CriticalSection::exit() const throw()
  204015. {
  204016. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  204017. }
  204018. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  204019. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  204020. {
  204021. }
  204022. WaitableEvent::~WaitableEvent() throw()
  204023. {
  204024. CloseHandle (internal);
  204025. }
  204026. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  204027. {
  204028. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204029. }
  204030. void WaitableEvent::signal() const throw()
  204031. {
  204032. SetEvent (internal);
  204033. }
  204034. void WaitableEvent::reset() const throw()
  204035. {
  204036. ResetEvent (internal);
  204037. }
  204038. void JUCE_API juce_threadEntryPoint (void*);
  204039. static unsigned int __stdcall threadEntryProc (void* userData)
  204040. {
  204041. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204042. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204043. GetCurrentThreadId(), TRUE);
  204044. #endif
  204045. juce_threadEntryPoint (userData);
  204046. _endthreadex (0);
  204047. return 0;
  204048. }
  204049. void Thread::launchThread()
  204050. {
  204051. unsigned int newThreadId;
  204052. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  204053. threadId_ = (ThreadID) newThreadId;
  204054. }
  204055. void Thread::closeThreadHandle()
  204056. {
  204057. CloseHandle ((HANDLE) threadHandle_);
  204058. threadId_ = 0;
  204059. threadHandle_ = 0;
  204060. }
  204061. void Thread::killThread()
  204062. {
  204063. if (threadHandle_ != 0)
  204064. {
  204065. #if JUCE_DEBUG
  204066. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204067. #endif
  204068. TerminateThread (threadHandle_, 0);
  204069. }
  204070. }
  204071. void Thread::setCurrentThreadName (const String& name)
  204072. {
  204073. #if JUCE_DEBUG && JUCE_MSVC
  204074. struct
  204075. {
  204076. DWORD dwType;
  204077. LPCSTR szName;
  204078. DWORD dwThreadID;
  204079. DWORD dwFlags;
  204080. } info;
  204081. info.dwType = 0x1000;
  204082. info.szName = name.toCString();
  204083. info.dwThreadID = GetCurrentThreadId();
  204084. info.dwFlags = 0;
  204085. __try
  204086. {
  204087. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204088. }
  204089. __except (EXCEPTION_CONTINUE_EXECUTION)
  204090. {}
  204091. #else
  204092. (void) name;
  204093. #endif
  204094. }
  204095. Thread::ThreadID Thread::getCurrentThreadId()
  204096. {
  204097. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204098. }
  204099. bool Thread::setThreadPriority (void* handle, int priority)
  204100. {
  204101. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204102. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204103. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204104. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204105. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204106. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204107. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204108. if (handle == 0)
  204109. handle = GetCurrentThread();
  204110. return SetThreadPriority (handle, pri) != FALSE;
  204111. }
  204112. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204113. {
  204114. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204115. }
  204116. struct SleepEvent
  204117. {
  204118. SleepEvent()
  204119. : handle (CreateEvent (0, 0, 0,
  204120. #if JUCE_DEBUG
  204121. _T("Juce Sleep Event")))
  204122. #else
  204123. 0))
  204124. #endif
  204125. {
  204126. }
  204127. HANDLE handle;
  204128. };
  204129. static SleepEvent sleepEvent;
  204130. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204131. {
  204132. if (millisecs >= 10)
  204133. {
  204134. Sleep (millisecs);
  204135. }
  204136. else
  204137. {
  204138. // unlike Sleep() this is guaranteed to return to the current thread after
  204139. // the time expires, so we'll use this for short waits, which are more likely
  204140. // to need to be accurate
  204141. WaitForSingleObject (sleepEvent.handle, millisecs);
  204142. }
  204143. }
  204144. void Thread::yield()
  204145. {
  204146. Sleep (0);
  204147. }
  204148. static int lastProcessPriority = -1;
  204149. // called by WindowDriver because Windows does wierd things to process priority
  204150. // when you swap apps, and this forces an update when the app is brought to the front.
  204151. void juce_repeatLastProcessPriority()
  204152. {
  204153. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204154. {
  204155. DWORD p;
  204156. switch (lastProcessPriority)
  204157. {
  204158. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204159. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204160. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204161. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204162. default: jassertfalse; return; // bad priority value
  204163. }
  204164. SetPriorityClass (GetCurrentProcess(), p);
  204165. }
  204166. }
  204167. void Process::setPriority (ProcessPriority prior)
  204168. {
  204169. if (lastProcessPriority != (int) prior)
  204170. {
  204171. lastProcessPriority = (int) prior;
  204172. juce_repeatLastProcessPriority();
  204173. }
  204174. }
  204175. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204176. {
  204177. return IsDebuggerPresent() != FALSE;
  204178. }
  204179. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204180. {
  204181. return juce_isRunningUnderDebugger();
  204182. }
  204183. void Process::raisePrivilege()
  204184. {
  204185. jassertfalse; // xxx not implemented
  204186. }
  204187. void Process::lowerPrivilege()
  204188. {
  204189. jassertfalse; // xxx not implemented
  204190. }
  204191. void Process::terminate()
  204192. {
  204193. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204194. _CrtDumpMemoryLeaks();
  204195. #endif
  204196. // bullet in the head in case there's a problem shutting down..
  204197. ExitProcess (0);
  204198. }
  204199. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204200. {
  204201. void* result = 0;
  204202. JUCE_TRY
  204203. {
  204204. result = LoadLibrary (name);
  204205. }
  204206. JUCE_CATCH_ALL
  204207. return result;
  204208. }
  204209. void PlatformUtilities::freeDynamicLibrary (void* h)
  204210. {
  204211. JUCE_TRY
  204212. {
  204213. if (h != 0)
  204214. FreeLibrary ((HMODULE) h);
  204215. }
  204216. JUCE_CATCH_ALL
  204217. }
  204218. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204219. {
  204220. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204221. }
  204222. class InterProcessLock::Pimpl
  204223. {
  204224. public:
  204225. Pimpl (const String& name, const int timeOutMillisecs)
  204226. : handle (0), refCount (1)
  204227. {
  204228. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204229. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204230. {
  204231. if (timeOutMillisecs == 0)
  204232. {
  204233. close();
  204234. return;
  204235. }
  204236. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204237. {
  204238. case WAIT_OBJECT_0:
  204239. case WAIT_ABANDONED:
  204240. break;
  204241. case WAIT_TIMEOUT:
  204242. default:
  204243. close();
  204244. break;
  204245. }
  204246. }
  204247. }
  204248. ~Pimpl()
  204249. {
  204250. close();
  204251. }
  204252. void close()
  204253. {
  204254. if (handle != 0)
  204255. {
  204256. ReleaseMutex (handle);
  204257. CloseHandle (handle);
  204258. handle = 0;
  204259. }
  204260. }
  204261. HANDLE handle;
  204262. int refCount;
  204263. };
  204264. InterProcessLock::InterProcessLock (const String& name_)
  204265. : name (name_)
  204266. {
  204267. }
  204268. InterProcessLock::~InterProcessLock()
  204269. {
  204270. }
  204271. bool InterProcessLock::enter (const int timeOutMillisecs)
  204272. {
  204273. const ScopedLock sl (lock);
  204274. if (pimpl == 0)
  204275. {
  204276. pimpl = new Pimpl (name, timeOutMillisecs);
  204277. if (pimpl->handle == 0)
  204278. pimpl = 0;
  204279. }
  204280. else
  204281. {
  204282. pimpl->refCount++;
  204283. }
  204284. return pimpl != 0;
  204285. }
  204286. void InterProcessLock::exit()
  204287. {
  204288. const ScopedLock sl (lock);
  204289. // Trying to release the lock too many times!
  204290. jassert (pimpl != 0);
  204291. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204292. pimpl = 0;
  204293. }
  204294. #endif
  204295. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204296. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204297. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204298. // compiled on its own).
  204299. #if JUCE_INCLUDED_FILE
  204300. #ifndef CSIDL_MYMUSIC
  204301. #define CSIDL_MYMUSIC 0x000d
  204302. #endif
  204303. #ifndef CSIDL_MYVIDEO
  204304. #define CSIDL_MYVIDEO 0x000e
  204305. #endif
  204306. #ifndef INVALID_FILE_ATTRIBUTES
  204307. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204308. #endif
  204309. namespace WindowsFileHelpers
  204310. {
  204311. int64 fileTimeToTime (const FILETIME* const ft)
  204312. {
  204313. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204314. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204315. }
  204316. void timeToFileTime (const int64 time, FILETIME* const ft)
  204317. {
  204318. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204319. }
  204320. const String getDriveFromPath (const String& path)
  204321. {
  204322. if (path.isNotEmpty() && path[1] == ':')
  204323. return path.substring (0, 2) + '\\';
  204324. return path;
  204325. }
  204326. int64 getDiskSpaceInfo (const String& path, const bool total)
  204327. {
  204328. ULARGE_INTEGER spc, tot, totFree;
  204329. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204330. return total ? (int64) tot.QuadPart
  204331. : (int64) spc.QuadPart;
  204332. return 0;
  204333. }
  204334. unsigned int getWindowsDriveType (const String& path)
  204335. {
  204336. return GetDriveType (getDriveFromPath (path));
  204337. }
  204338. const File getSpecialFolderPath (int type)
  204339. {
  204340. WCHAR path [MAX_PATH + 256];
  204341. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204342. return File (String (path));
  204343. return File::nonexistent;
  204344. }
  204345. }
  204346. const juce_wchar File::separator = '\\';
  204347. const String File::separatorString ("\\");
  204348. bool File::exists() const
  204349. {
  204350. return fullPath.isNotEmpty()
  204351. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204352. }
  204353. bool File::existsAsFile() const
  204354. {
  204355. return fullPath.isNotEmpty()
  204356. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204357. }
  204358. bool File::isDirectory() const
  204359. {
  204360. const DWORD attr = GetFileAttributes (fullPath);
  204361. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204362. }
  204363. bool File::hasWriteAccess() const
  204364. {
  204365. if (exists())
  204366. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204367. // on windows, it seems that even read-only directories can still be written into,
  204368. // so checking the parent directory's permissions would return the wrong result..
  204369. return true;
  204370. }
  204371. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204372. {
  204373. DWORD attr = GetFileAttributes (fullPath);
  204374. if (attr == INVALID_FILE_ATTRIBUTES)
  204375. return false;
  204376. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204377. return true;
  204378. if (shouldBeReadOnly)
  204379. attr |= FILE_ATTRIBUTE_READONLY;
  204380. else
  204381. attr &= ~FILE_ATTRIBUTE_READONLY;
  204382. return SetFileAttributes (fullPath, attr) != FALSE;
  204383. }
  204384. bool File::isHidden() const
  204385. {
  204386. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204387. }
  204388. bool File::deleteFile() const
  204389. {
  204390. if (! exists())
  204391. return true;
  204392. else if (isDirectory())
  204393. return RemoveDirectory (fullPath) != 0;
  204394. else
  204395. return DeleteFile (fullPath) != 0;
  204396. }
  204397. bool File::moveToTrash() const
  204398. {
  204399. if (! exists())
  204400. return true;
  204401. SHFILEOPSTRUCT fos;
  204402. zerostruct (fos);
  204403. // The string we pass in must be double null terminated..
  204404. String doubleNullTermPath (getFullPathName() + " ");
  204405. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204406. p [getFullPathName().length()] = 0;
  204407. fos.wFunc = FO_DELETE;
  204408. fos.pFrom = p;
  204409. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204410. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204411. return SHFileOperation (&fos) == 0;
  204412. }
  204413. bool File::copyInternal (const File& dest) const
  204414. {
  204415. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204416. }
  204417. bool File::moveInternal (const File& dest) const
  204418. {
  204419. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204420. }
  204421. void File::createDirectoryInternal (const String& fileName) const
  204422. {
  204423. CreateDirectory (fileName, 0);
  204424. }
  204425. int64 juce_fileSetPosition (void* handle, int64 pos)
  204426. {
  204427. LARGE_INTEGER li;
  204428. li.QuadPart = pos;
  204429. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204430. return li.QuadPart;
  204431. }
  204432. void FileInputStream::openHandle()
  204433. {
  204434. totalSize = file.getSize();
  204435. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204436. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204437. if (h != INVALID_HANDLE_VALUE)
  204438. fileHandle = (void*) h;
  204439. }
  204440. void FileInputStream::closeHandle()
  204441. {
  204442. CloseHandle ((HANDLE) fileHandle);
  204443. }
  204444. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204445. {
  204446. if (fileHandle != 0)
  204447. {
  204448. DWORD actualNum = 0;
  204449. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204450. return (size_t) actualNum;
  204451. }
  204452. return 0;
  204453. }
  204454. void FileOutputStream::openHandle()
  204455. {
  204456. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204457. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204458. if (h != INVALID_HANDLE_VALUE)
  204459. {
  204460. LARGE_INTEGER li;
  204461. li.QuadPart = 0;
  204462. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204463. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204464. {
  204465. fileHandle = (void*) h;
  204466. currentPosition = li.QuadPart;
  204467. }
  204468. }
  204469. }
  204470. void FileOutputStream::closeHandle()
  204471. {
  204472. CloseHandle ((HANDLE) fileHandle);
  204473. }
  204474. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204475. {
  204476. if (fileHandle != 0)
  204477. {
  204478. DWORD actualNum = 0;
  204479. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204480. return (int) actualNum;
  204481. }
  204482. return 0;
  204483. }
  204484. void FileOutputStream::flushInternal()
  204485. {
  204486. if (fileHandle != 0)
  204487. FlushFileBuffers ((HANDLE) fileHandle);
  204488. }
  204489. int64 File::getSize() const
  204490. {
  204491. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204492. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204493. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204494. return 0;
  204495. }
  204496. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204497. {
  204498. using namespace WindowsFileHelpers;
  204499. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204500. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204501. {
  204502. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204503. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204504. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204505. }
  204506. else
  204507. {
  204508. creationTime = accessTime = modificationTime = 0;
  204509. }
  204510. }
  204511. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204512. {
  204513. using namespace WindowsFileHelpers;
  204514. bool ok = false;
  204515. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204516. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204517. if (h != INVALID_HANDLE_VALUE)
  204518. {
  204519. FILETIME m, a, c;
  204520. timeToFileTime (modificationTime, &m);
  204521. timeToFileTime (accessTime, &a);
  204522. timeToFileTime (creationTime, &c);
  204523. ok = SetFileTime (h,
  204524. creationTime > 0 ? &c : 0,
  204525. accessTime > 0 ? &a : 0,
  204526. modificationTime > 0 ? &m : 0) != 0;
  204527. CloseHandle (h);
  204528. }
  204529. return ok;
  204530. }
  204531. void File::findFileSystemRoots (Array<File>& destArray)
  204532. {
  204533. TCHAR buffer [2048];
  204534. buffer[0] = 0;
  204535. buffer[1] = 0;
  204536. GetLogicalDriveStrings (2048, buffer);
  204537. const TCHAR* n = buffer;
  204538. StringArray roots;
  204539. while (*n != 0)
  204540. {
  204541. roots.add (String (n));
  204542. while (*n++ != 0)
  204543. {}
  204544. }
  204545. roots.sort (true);
  204546. for (int i = 0; i < roots.size(); ++i)
  204547. destArray.add (roots [i]);
  204548. }
  204549. const String File::getVolumeLabel() const
  204550. {
  204551. TCHAR dest[64];
  204552. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204553. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204554. dest[0] = 0;
  204555. return dest;
  204556. }
  204557. int File::getVolumeSerialNumber() const
  204558. {
  204559. TCHAR dest[64];
  204560. DWORD serialNum;
  204561. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204562. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204563. return 0;
  204564. return (int) serialNum;
  204565. }
  204566. int64 File::getBytesFreeOnVolume() const
  204567. {
  204568. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204569. }
  204570. int64 File::getVolumeTotalSize() const
  204571. {
  204572. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204573. }
  204574. bool File::isOnCDRomDrive() const
  204575. {
  204576. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204577. }
  204578. bool File::isOnHardDisk() const
  204579. {
  204580. if (fullPath.isEmpty())
  204581. return false;
  204582. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204583. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204584. return n != DRIVE_REMOVABLE;
  204585. else
  204586. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204587. }
  204588. bool File::isOnRemovableDrive() const
  204589. {
  204590. if (fullPath.isEmpty())
  204591. return false;
  204592. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204593. return n == DRIVE_CDROM
  204594. || n == DRIVE_REMOTE
  204595. || n == DRIVE_REMOVABLE
  204596. || n == DRIVE_RAMDISK;
  204597. }
  204598. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204599. {
  204600. int csidlType = 0;
  204601. switch (type)
  204602. {
  204603. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204604. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204605. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204606. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204607. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204608. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204609. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204610. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204611. case tempDirectory:
  204612. {
  204613. WCHAR dest [2048];
  204614. dest[0] = 0;
  204615. GetTempPath (numElementsInArray (dest), dest);
  204616. return File (String (dest));
  204617. }
  204618. case invokedExecutableFile:
  204619. case currentExecutableFile:
  204620. case currentApplicationFile:
  204621. {
  204622. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204623. WCHAR dest [MAX_PATH + 256];
  204624. dest[0] = 0;
  204625. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204626. return File (String (dest));
  204627. }
  204628. case hostApplicationPath:
  204629. {
  204630. WCHAR dest [MAX_PATH + 256];
  204631. dest[0] = 0;
  204632. GetModuleFileName (0, dest, numElementsInArray (dest));
  204633. return File (String (dest));
  204634. }
  204635. default:
  204636. jassertfalse; // unknown type?
  204637. return File::nonexistent;
  204638. }
  204639. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204640. }
  204641. const File File::getCurrentWorkingDirectory()
  204642. {
  204643. WCHAR dest [MAX_PATH + 256];
  204644. dest[0] = 0;
  204645. GetCurrentDirectory (numElementsInArray (dest), dest);
  204646. return File (String (dest));
  204647. }
  204648. bool File::setAsCurrentWorkingDirectory() const
  204649. {
  204650. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204651. }
  204652. const String File::getVersion() const
  204653. {
  204654. String result;
  204655. DWORD handle = 0;
  204656. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204657. HeapBlock<char> buffer;
  204658. buffer.calloc (bufferSize);
  204659. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204660. {
  204661. VS_FIXEDFILEINFO* vffi;
  204662. UINT len = 0;
  204663. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204664. {
  204665. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204666. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204667. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204668. << (int) LOWORD (vffi->dwFileVersionLS);
  204669. }
  204670. }
  204671. return result;
  204672. }
  204673. const File File::getLinkedTarget() const
  204674. {
  204675. File result (*this);
  204676. String p (getFullPathName());
  204677. if (! exists())
  204678. p += ".lnk";
  204679. else if (getFileExtension() != ".lnk")
  204680. return result;
  204681. ComSmartPtr <IShellLink> shellLink;
  204682. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204683. {
  204684. ComSmartPtr <IPersistFile> persistFile;
  204685. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204686. {
  204687. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204688. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204689. {
  204690. WIN32_FIND_DATA winFindData;
  204691. WCHAR resolvedPath [MAX_PATH];
  204692. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204693. result = File (resolvedPath);
  204694. }
  204695. }
  204696. }
  204697. return result;
  204698. }
  204699. class DirectoryIterator::NativeIterator::Pimpl
  204700. {
  204701. public:
  204702. Pimpl (const File& directory, const String& wildCard)
  204703. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204704. handle (INVALID_HANDLE_VALUE)
  204705. {
  204706. }
  204707. ~Pimpl()
  204708. {
  204709. if (handle != INVALID_HANDLE_VALUE)
  204710. FindClose (handle);
  204711. }
  204712. bool next (String& filenameFound,
  204713. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204714. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204715. {
  204716. using namespace WindowsFileHelpers;
  204717. WIN32_FIND_DATA findData;
  204718. if (handle == INVALID_HANDLE_VALUE)
  204719. {
  204720. handle = FindFirstFile (directoryWithWildCard, &findData);
  204721. if (handle == INVALID_HANDLE_VALUE)
  204722. return false;
  204723. }
  204724. else
  204725. {
  204726. if (FindNextFile (handle, &findData) == 0)
  204727. return false;
  204728. }
  204729. filenameFound = findData.cFileName;
  204730. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204731. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204732. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204733. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204734. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204735. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204736. return true;
  204737. }
  204738. private:
  204739. const String directoryWithWildCard;
  204740. HANDLE handle;
  204741. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204742. };
  204743. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204744. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204745. {
  204746. }
  204747. DirectoryIterator::NativeIterator::~NativeIterator()
  204748. {
  204749. }
  204750. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204751. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204752. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204753. {
  204754. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204755. }
  204756. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204757. {
  204758. HINSTANCE hInstance = 0;
  204759. JUCE_TRY
  204760. {
  204761. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204762. }
  204763. JUCE_CATCH_ALL
  204764. return hInstance > (HINSTANCE) 32;
  204765. }
  204766. void File::revealToUser() const
  204767. {
  204768. if (isDirectory())
  204769. startAsProcess();
  204770. else if (getParentDirectory().exists())
  204771. getParentDirectory().startAsProcess();
  204772. }
  204773. class NamedPipeInternal
  204774. {
  204775. public:
  204776. NamedPipeInternal (const String& file, const bool isPipe_)
  204777. : pipeH (0),
  204778. cancelEvent (0),
  204779. connected (false),
  204780. isPipe (isPipe_)
  204781. {
  204782. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204783. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204784. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204785. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204786. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204787. }
  204788. ~NamedPipeInternal()
  204789. {
  204790. disconnectPipe();
  204791. if (pipeH != 0)
  204792. CloseHandle (pipeH);
  204793. CloseHandle (cancelEvent);
  204794. }
  204795. bool connect (const int timeOutMs)
  204796. {
  204797. if (! isPipe)
  204798. return true;
  204799. if (! connected)
  204800. {
  204801. OVERLAPPED over;
  204802. zerostruct (over);
  204803. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204804. if (ConnectNamedPipe (pipeH, &over))
  204805. {
  204806. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204807. }
  204808. else
  204809. {
  204810. const int err = GetLastError();
  204811. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204812. {
  204813. HANDLE handles[] = { over.hEvent, cancelEvent };
  204814. if (WaitForMultipleObjects (2, handles, FALSE,
  204815. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204816. connected = true;
  204817. }
  204818. else if (err == ERROR_PIPE_CONNECTED)
  204819. {
  204820. connected = true;
  204821. }
  204822. }
  204823. CloseHandle (over.hEvent);
  204824. }
  204825. return connected;
  204826. }
  204827. void disconnectPipe()
  204828. {
  204829. if (connected)
  204830. {
  204831. DisconnectNamedPipe (pipeH);
  204832. connected = false;
  204833. }
  204834. }
  204835. HANDLE pipeH;
  204836. HANDLE cancelEvent;
  204837. bool connected, isPipe;
  204838. };
  204839. void NamedPipe::close()
  204840. {
  204841. cancelPendingReads();
  204842. const ScopedLock sl (lock);
  204843. delete static_cast<NamedPipeInternal*> (internal);
  204844. internal = 0;
  204845. }
  204846. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204847. {
  204848. close();
  204849. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204850. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204851. {
  204852. internal = intern.release();
  204853. return true;
  204854. }
  204855. return false;
  204856. }
  204857. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204858. {
  204859. const ScopedLock sl (lock);
  204860. int bytesRead = -1;
  204861. bool waitAgain = true;
  204862. while (waitAgain && internal != 0)
  204863. {
  204864. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204865. waitAgain = false;
  204866. if (! intern->connect (timeOutMilliseconds))
  204867. break;
  204868. if (maxBytesToRead <= 0)
  204869. return 0;
  204870. OVERLAPPED over;
  204871. zerostruct (over);
  204872. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204873. unsigned long numRead;
  204874. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204875. {
  204876. bytesRead = (int) numRead;
  204877. }
  204878. else if (GetLastError() == ERROR_IO_PENDING)
  204879. {
  204880. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204881. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204882. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204883. : INFINITE);
  204884. if (waitResult != WAIT_OBJECT_0)
  204885. {
  204886. // if the operation timed out, let's cancel it...
  204887. CancelIo (intern->pipeH);
  204888. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204889. }
  204890. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204891. {
  204892. bytesRead = (int) numRead;
  204893. }
  204894. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204895. {
  204896. intern->disconnectPipe();
  204897. waitAgain = true;
  204898. }
  204899. }
  204900. else
  204901. {
  204902. waitAgain = internal != 0;
  204903. Sleep (5);
  204904. }
  204905. CloseHandle (over.hEvent);
  204906. }
  204907. return bytesRead;
  204908. }
  204909. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204910. {
  204911. int bytesWritten = -1;
  204912. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204913. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204914. {
  204915. if (numBytesToWrite <= 0)
  204916. return 0;
  204917. OVERLAPPED over;
  204918. zerostruct (over);
  204919. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204920. unsigned long numWritten;
  204921. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204922. {
  204923. bytesWritten = (int) numWritten;
  204924. }
  204925. else if (GetLastError() == ERROR_IO_PENDING)
  204926. {
  204927. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204928. DWORD waitResult;
  204929. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204930. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204931. : INFINITE);
  204932. if (waitResult != WAIT_OBJECT_0)
  204933. {
  204934. CancelIo (intern->pipeH);
  204935. WaitForSingleObject (over.hEvent, INFINITE);
  204936. }
  204937. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204938. {
  204939. bytesWritten = (int) numWritten;
  204940. }
  204941. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204942. {
  204943. intern->disconnectPipe();
  204944. }
  204945. }
  204946. CloseHandle (over.hEvent);
  204947. }
  204948. return bytesWritten;
  204949. }
  204950. void NamedPipe::cancelPendingReads()
  204951. {
  204952. if (internal != 0)
  204953. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204954. }
  204955. #endif
  204956. /*** End of inlined file: juce_win32_Files.cpp ***/
  204957. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204958. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204959. // compiled on its own).
  204960. #if JUCE_INCLUDED_FILE
  204961. #ifndef INTERNET_FLAG_NEED_FILE
  204962. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204963. #endif
  204964. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204965. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204966. #endif
  204967. static HINTERNET sessionHandle = 0;
  204968. #ifndef WORKAROUND_TIMEOUT_BUG
  204969. //#define WORKAROUND_TIMEOUT_BUG 1
  204970. #endif
  204971. #if WORKAROUND_TIMEOUT_BUG
  204972. // Required because of a Microsoft bug in setting a timeout
  204973. class InternetConnectThread : public Thread
  204974. {
  204975. public:
  204976. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204977. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204978. {
  204979. startThread();
  204980. }
  204981. ~InternetConnectThread()
  204982. {
  204983. stopThread (60000);
  204984. }
  204985. void run()
  204986. {
  204987. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204988. uc.nPort, _T(""), _T(""),
  204989. isFtp ? INTERNET_SERVICE_FTP
  204990. : INTERNET_SERVICE_HTTP,
  204991. 0, 0);
  204992. notify();
  204993. }
  204994. private:
  204995. URL_COMPONENTS& uc;
  204996. HINTERNET& connection;
  204997. const bool isFtp;
  204998. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204999. };
  205000. #endif
  205001. class WebInputStream : public InputStream
  205002. {
  205003. public:
  205004. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  205005. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205006. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  205007. : connection (0), request (0),
  205008. address (address_), headers (headers_), postData (postData_), position (0),
  205009. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  205010. {
  205011. createConnection (progressCallback, progressCallbackContext);
  205012. if (responseHeaders != 0 && ! isError())
  205013. {
  205014. DWORD bufferSizeBytes = 4096;
  205015. for (;;)
  205016. {
  205017. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205018. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205019. {
  205020. StringArray headersArray;
  205021. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205022. for (int i = 0; i < headersArray.size(); ++i)
  205023. {
  205024. const String& header = headersArray[i];
  205025. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205026. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205027. const String previousValue ((*responseHeaders) [key]);
  205028. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205029. }
  205030. break;
  205031. }
  205032. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205033. break;
  205034. }
  205035. }
  205036. }
  205037. ~WebInputStream()
  205038. {
  205039. close();
  205040. }
  205041. bool isError() const { return request == 0; }
  205042. bool isExhausted() { return finished; }
  205043. int64 getPosition() { return position; }
  205044. int64 getTotalLength()
  205045. {
  205046. if (! isError())
  205047. {
  205048. DWORD index = 0, result = 0, size = sizeof (result);
  205049. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205050. return (int64) result;
  205051. }
  205052. return -1;
  205053. }
  205054. int read (void* buffer, int bytesToRead)
  205055. {
  205056. DWORD bytesRead = 0;
  205057. if (! (finished || isError()))
  205058. {
  205059. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  205060. position += bytesRead;
  205061. if (bytesRead == 0)
  205062. finished = true;
  205063. }
  205064. return (int) bytesRead;
  205065. }
  205066. bool setPosition (int64 wantedPos)
  205067. {
  205068. if (isError())
  205069. return false;
  205070. if (wantedPos != position)
  205071. {
  205072. finished = false;
  205073. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  205074. if (position == wantedPos)
  205075. return true;
  205076. if (wantedPos < position)
  205077. {
  205078. close();
  205079. position = 0;
  205080. createConnection (0, 0);
  205081. }
  205082. skipNextBytes (wantedPos - position);
  205083. }
  205084. return true;
  205085. }
  205086. private:
  205087. HINTERNET connection, request;
  205088. String address, headers;
  205089. MemoryBlock postData;
  205090. int64 position;
  205091. bool finished;
  205092. const bool isPost;
  205093. int timeOutMs;
  205094. void close()
  205095. {
  205096. if (request != 0)
  205097. {
  205098. InternetCloseHandle (request);
  205099. request = 0;
  205100. }
  205101. if (connection != 0)
  205102. {
  205103. InternetCloseHandle (connection);
  205104. connection = 0;
  205105. }
  205106. }
  205107. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  205108. void* progressCallbackContext)
  205109. {
  205110. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  205111. close();
  205112. if (sessionHandle != 0)
  205113. {
  205114. // break up the url..
  205115. TCHAR file[1024], server[1024];
  205116. URL_COMPONENTS uc;
  205117. zerostruct (uc);
  205118. uc.dwStructSize = sizeof (uc);
  205119. uc.dwUrlPathLength = sizeof (file);
  205120. uc.dwHostNameLength = sizeof (server);
  205121. uc.lpszUrlPath = file;
  205122. uc.lpszHostName = server;
  205123. if (InternetCrackUrl (address, 0, 0, &uc))
  205124. {
  205125. int disable = 1;
  205126. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  205127. if (timeOutMs == 0)
  205128. timeOutMs = 30000;
  205129. else if (timeOutMs < 0)
  205130. timeOutMs = -1;
  205131. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205132. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  205133. #if WORKAROUND_TIMEOUT_BUG
  205134. connection = 0;
  205135. {
  205136. InternetConnectThread connectThread (uc, connection, isFtp);
  205137. connectThread.wait (timeOutMs);
  205138. if (connection == 0)
  205139. {
  205140. InternetCloseHandle (sessionHandle);
  205141. sessionHandle = 0;
  205142. }
  205143. }
  205144. #else
  205145. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  205146. _T(""), _T(""),
  205147. isFtp ? INTERNET_SERVICE_FTP
  205148. : INTERNET_SERVICE_HTTP,
  205149. 0, 0);
  205150. #endif
  205151. if (connection != 0)
  205152. {
  205153. if (isFtp)
  205154. {
  205155. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  205156. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  205157. }
  205158. else
  205159. {
  205160. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205161. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205162. if (address.startsWithIgnoreCase ("https:"))
  205163. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205164. // IE7 seems to automatically work out when it's https)
  205165. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  205166. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  205167. if (request != 0)
  205168. {
  205169. INTERNET_BUFFERS buffers;
  205170. zerostruct (buffers);
  205171. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205172. buffers.lpcszHeader = static_cast <LPCTSTR> (headers);
  205173. buffers.dwHeadersLength = headers.length();
  205174. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205175. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205176. {
  205177. int bytesSent = 0;
  205178. for (;;)
  205179. {
  205180. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205181. DWORD bytesDone = 0;
  205182. if (bytesToDo > 0
  205183. && ! InternetWriteFile (request,
  205184. static_cast <const char*> (postData.getData()) + bytesSent,
  205185. bytesToDo, &bytesDone))
  205186. {
  205187. break;
  205188. }
  205189. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205190. {
  205191. if (HttpEndRequest (request, 0, 0, 0))
  205192. return;
  205193. break;
  205194. }
  205195. bytesSent += bytesDone;
  205196. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  205197. break;
  205198. }
  205199. }
  205200. }
  205201. close();
  205202. }
  205203. }
  205204. }
  205205. }
  205206. }
  205207. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  205208. };
  205209. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  205210. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  205211. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  205212. {
  205213. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  205214. progressCallback, progressCallbackContext,
  205215. headers, timeOutMs, responseHeaders));
  205216. return wi->isError() ? 0 : wi.release();
  205217. }
  205218. namespace MACAddressHelpers
  205219. {
  205220. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  205221. {
  205222. DynamicLibraryLoader dll ("iphlpapi.dll");
  205223. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205224. if (getAdaptersInfo != 0)
  205225. {
  205226. ULONG len = sizeof (IP_ADAPTER_INFO);
  205227. MemoryBlock mb;
  205228. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205229. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205230. {
  205231. mb.setSize (len);
  205232. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205233. }
  205234. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205235. {
  205236. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  205237. {
  205238. if (adapter->AddressLength >= 6)
  205239. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  205240. }
  205241. }
  205242. }
  205243. }
  205244. void getViaNetBios (Array<MACAddress>& result)
  205245. {
  205246. DynamicLibraryLoader dll ("netapi32.dll");
  205247. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205248. if (NetbiosCall != 0)
  205249. {
  205250. NCB ncb;
  205251. zerostruct (ncb);
  205252. struct ASTAT
  205253. {
  205254. ADAPTER_STATUS adapt;
  205255. NAME_BUFFER NameBuff [30];
  205256. };
  205257. ASTAT astat;
  205258. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205259. LANA_ENUM enums;
  205260. zerostruct (enums);
  205261. ncb.ncb_command = NCBENUM;
  205262. ncb.ncb_buffer = (unsigned char*) &enums;
  205263. ncb.ncb_length = sizeof (LANA_ENUM);
  205264. NetbiosCall (&ncb);
  205265. for (int i = 0; i < enums.length; ++i)
  205266. {
  205267. zerostruct (ncb);
  205268. ncb.ncb_command = NCBRESET;
  205269. ncb.ncb_lana_num = enums.lana[i];
  205270. if (NetbiosCall (&ncb) == 0)
  205271. {
  205272. zerostruct (ncb);
  205273. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205274. ncb.ncb_command = NCBASTAT;
  205275. ncb.ncb_lana_num = enums.lana[i];
  205276. ncb.ncb_buffer = (unsigned char*) &astat;
  205277. ncb.ncb_length = sizeof (ASTAT);
  205278. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  205279. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  205280. }
  205281. }
  205282. }
  205283. }
  205284. }
  205285. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  205286. {
  205287. MACAddressHelpers::getViaGetAdaptersInfo (result);
  205288. MACAddressHelpers::getViaNetBios (result);
  205289. }
  205290. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205291. const String& emailSubject,
  205292. const String& bodyText,
  205293. const StringArray& filesToAttach)
  205294. {
  205295. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205296. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205297. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205298. bool ok = false;
  205299. if (mapiSendMail != 0)
  205300. {
  205301. MapiMessage message;
  205302. zerostruct (message);
  205303. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205304. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205305. MapiRecipDesc recip;
  205306. zerostruct (recip);
  205307. recip.ulRecipClass = MAPI_TO;
  205308. String targetEmailAddress_ (targetEmailAddress);
  205309. if (targetEmailAddress_.isEmpty())
  205310. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205311. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205312. message.nRecipCount = 1;
  205313. message.lpRecips = &recip;
  205314. HeapBlock <MapiFileDesc> files;
  205315. files.calloc (filesToAttach.size());
  205316. message.nFileCount = filesToAttach.size();
  205317. message.lpFiles = files;
  205318. for (int i = 0; i < filesToAttach.size(); ++i)
  205319. {
  205320. files[i].nPosition = (ULONG) -1;
  205321. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205322. }
  205323. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205324. }
  205325. FreeLibrary (h);
  205326. return ok;
  205327. }
  205328. #endif
  205329. /*** End of inlined file: juce_win32_Network.cpp ***/
  205330. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205331. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205332. // compiled on its own).
  205333. #if JUCE_INCLUDED_FILE
  205334. namespace
  205335. {
  205336. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205337. {
  205338. HKEY rootKey = 0;
  205339. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205340. rootKey = HKEY_CURRENT_USER;
  205341. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205342. rootKey = HKEY_LOCAL_MACHINE;
  205343. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205344. rootKey = HKEY_CLASSES_ROOT;
  205345. if (rootKey != 0)
  205346. {
  205347. name = name.substring (name.indexOfChar ('\\') + 1);
  205348. const int lastSlash = name.lastIndexOfChar ('\\');
  205349. valueName = name.substring (lastSlash + 1);
  205350. name = name.substring (0, lastSlash);
  205351. HKEY key;
  205352. DWORD result;
  205353. if (createForWriting)
  205354. {
  205355. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205356. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205357. return key;
  205358. }
  205359. else
  205360. {
  205361. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205362. return key;
  205363. }
  205364. }
  205365. return 0;
  205366. }
  205367. }
  205368. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205369. const String& defaultValue)
  205370. {
  205371. String valueName, result (defaultValue);
  205372. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205373. if (k != 0)
  205374. {
  205375. WCHAR buffer [2048];
  205376. unsigned long bufferSize = sizeof (buffer);
  205377. DWORD type = REG_SZ;
  205378. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205379. {
  205380. if (type == REG_SZ)
  205381. result = buffer;
  205382. else if (type == REG_DWORD)
  205383. result = String ((int) *(DWORD*) buffer);
  205384. }
  205385. RegCloseKey (k);
  205386. }
  205387. return result;
  205388. }
  205389. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205390. const String& value)
  205391. {
  205392. String valueName;
  205393. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205394. if (k != 0)
  205395. {
  205396. RegSetValueEx (k, valueName, 0, REG_SZ,
  205397. (const BYTE*) (const WCHAR*) value,
  205398. sizeof (WCHAR) * (value.length() + 1));
  205399. RegCloseKey (k);
  205400. }
  205401. }
  205402. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205403. {
  205404. bool exists = false;
  205405. String valueName;
  205406. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205407. if (k != 0)
  205408. {
  205409. unsigned char buffer [2048];
  205410. unsigned long bufferSize = sizeof (buffer);
  205411. DWORD type = 0;
  205412. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205413. exists = true;
  205414. RegCloseKey (k);
  205415. }
  205416. return exists;
  205417. }
  205418. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205419. {
  205420. String valueName;
  205421. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205422. if (k != 0)
  205423. {
  205424. RegDeleteValue (k, valueName);
  205425. RegCloseKey (k);
  205426. }
  205427. }
  205428. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205429. {
  205430. String valueName;
  205431. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205432. if (k != 0)
  205433. {
  205434. RegDeleteKey (k, valueName);
  205435. RegCloseKey (k);
  205436. }
  205437. }
  205438. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205439. const String& symbolicDescription,
  205440. const String& fullDescription,
  205441. const File& targetExecutable,
  205442. int iconResourceNumber)
  205443. {
  205444. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205445. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205446. if (iconResourceNumber != 0)
  205447. setRegistryValue (key + "\\DefaultIcon\\",
  205448. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205449. setRegistryValue (key + "\\", fullDescription);
  205450. setRegistryValue (key + "\\shell\\open\\command\\",
  205451. targetExecutable.getFullPathName() + " %1");
  205452. }
  205453. bool juce_IsRunningInWine()
  205454. {
  205455. HKEY key;
  205456. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205457. {
  205458. RegCloseKey (key);
  205459. return true;
  205460. }
  205461. return false;
  205462. }
  205463. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205464. {
  205465. String s (::GetCommandLineW());
  205466. StringArray tokens;
  205467. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205468. return tokens.joinIntoString (" ", 1);
  205469. }
  205470. static void* currentModuleHandle = 0;
  205471. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205472. {
  205473. if (currentModuleHandle == 0)
  205474. currentModuleHandle = GetModuleHandle (0);
  205475. return currentModuleHandle;
  205476. }
  205477. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205478. {
  205479. currentModuleHandle = newHandle;
  205480. }
  205481. void PlatformUtilities::fpuReset()
  205482. {
  205483. #if JUCE_MSVC
  205484. _clearfp();
  205485. #endif
  205486. }
  205487. void PlatformUtilities::beep()
  205488. {
  205489. MessageBeep (MB_OK);
  205490. }
  205491. #endif
  205492. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205493. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205494. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205495. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205496. // compiled on its own).
  205497. #if JUCE_INCLUDED_FILE
  205498. static const unsigned int specialId = WM_APP + 0x4400;
  205499. static const unsigned int broadcastId = WM_APP + 0x4403;
  205500. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205501. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205502. HWND juce_messageWindowHandle = 0;
  205503. extern long improbableWindowNumber; // defined in windowing.cpp
  205504. #ifndef WM_APPCOMMAND
  205505. #define WM_APPCOMMAND 0x0319
  205506. #endif
  205507. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205508. const UINT message,
  205509. const WPARAM wParam,
  205510. const LPARAM lParam) throw()
  205511. {
  205512. JUCE_TRY
  205513. {
  205514. if (h == juce_messageWindowHandle)
  205515. {
  205516. if (message == specialCallbackId)
  205517. {
  205518. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205519. return (LRESULT) (*func) ((void*) lParam);
  205520. }
  205521. else if (message == specialId)
  205522. {
  205523. // these are trapped early in the dispatch call, but must also be checked
  205524. // here in case there are windows modal dialog boxes doing their own
  205525. // dispatch loop and not calling our version
  205526. Message* const message = reinterpret_cast <Message*> (lParam);
  205527. MessageManager::getInstance()->deliverMessage (message);
  205528. message->decReferenceCount();
  205529. return 0;
  205530. }
  205531. else if (message == broadcastId)
  205532. {
  205533. const ScopedPointer <String> messageString ((String*) lParam);
  205534. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205535. return 0;
  205536. }
  205537. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205538. {
  205539. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205540. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205541. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205542. return 0;
  205543. }
  205544. }
  205545. }
  205546. JUCE_CATCH_EXCEPTION
  205547. return DefWindowProc (h, message, wParam, lParam);
  205548. }
  205549. static bool isEventBlockedByModalComps (MSG& m)
  205550. {
  205551. if (Component::getNumCurrentlyModalComponents() == 0
  205552. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205553. return false;
  205554. switch (m.message)
  205555. {
  205556. case WM_MOUSEMOVE:
  205557. case WM_NCMOUSEMOVE:
  205558. case 0x020A: /* WM_MOUSEWHEEL */
  205559. case 0x020E: /* WM_MOUSEHWHEEL */
  205560. case WM_KEYUP:
  205561. case WM_SYSKEYUP:
  205562. case WM_CHAR:
  205563. case WM_APPCOMMAND:
  205564. case WM_LBUTTONUP:
  205565. case WM_MBUTTONUP:
  205566. case WM_RBUTTONUP:
  205567. case WM_MOUSEACTIVATE:
  205568. case WM_NCMOUSEHOVER:
  205569. case WM_MOUSEHOVER:
  205570. return true;
  205571. case WM_NCLBUTTONDOWN:
  205572. case WM_NCLBUTTONDBLCLK:
  205573. case WM_NCRBUTTONDOWN:
  205574. case WM_NCRBUTTONDBLCLK:
  205575. case WM_NCMBUTTONDOWN:
  205576. case WM_NCMBUTTONDBLCLK:
  205577. case WM_LBUTTONDOWN:
  205578. case WM_LBUTTONDBLCLK:
  205579. case WM_MBUTTONDOWN:
  205580. case WM_MBUTTONDBLCLK:
  205581. case WM_RBUTTONDOWN:
  205582. case WM_RBUTTONDBLCLK:
  205583. case WM_KEYDOWN:
  205584. case WM_SYSKEYDOWN:
  205585. {
  205586. Component* const modal = Component::getCurrentlyModalComponent (0);
  205587. if (modal != 0)
  205588. modal->inputAttemptWhenModal();
  205589. return true;
  205590. }
  205591. default:
  205592. break;
  205593. }
  205594. return false;
  205595. }
  205596. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205597. {
  205598. MSG m;
  205599. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205600. return false;
  205601. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205602. {
  205603. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205604. {
  205605. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205606. MessageManager::getInstance()->deliverMessage (message);
  205607. message->decReferenceCount();
  205608. }
  205609. else if (m.message == WM_QUIT)
  205610. {
  205611. if (JUCEApplication::getInstance() != 0)
  205612. JUCEApplication::getInstance()->systemRequestedQuit();
  205613. }
  205614. else if (! isEventBlockedByModalComps (m))
  205615. {
  205616. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205617. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205618. {
  205619. // if it's someone else's window being clicked on, and the focus is
  205620. // currently on a juce window, pass the kb focus over..
  205621. HWND currentFocus = GetFocus();
  205622. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205623. SetFocus (m.hwnd);
  205624. }
  205625. TranslateMessage (&m);
  205626. DispatchMessage (&m);
  205627. }
  205628. }
  205629. return true;
  205630. }
  205631. bool juce_postMessageToSystemQueue (Message* message)
  205632. {
  205633. message->incReferenceCount();
  205634. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205635. }
  205636. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205637. void* userData)
  205638. {
  205639. if (MessageManager::getInstance()->isThisTheMessageThread())
  205640. {
  205641. return (*callback) (userData);
  205642. }
  205643. else
  205644. {
  205645. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205646. // deadlock because the message manager is blocked from running, and can't
  205647. // call your function..
  205648. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205649. return (void*) SendMessage (juce_messageWindowHandle,
  205650. specialCallbackId,
  205651. (WPARAM) callback,
  205652. (LPARAM) userData);
  205653. }
  205654. }
  205655. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205656. {
  205657. if (hwnd != juce_messageWindowHandle)
  205658. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205659. return TRUE;
  205660. }
  205661. void MessageManager::broadcastMessage (const String& value)
  205662. {
  205663. Array<void*> windows;
  205664. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205665. const String localCopy (value);
  205666. COPYDATASTRUCT data;
  205667. data.dwData = broadcastId;
  205668. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205669. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205670. for (int i = windows.size(); --i >= 0;)
  205671. {
  205672. HWND hwnd = (HWND) windows.getUnchecked(i);
  205673. TCHAR windowName [64]; // no need to read longer strings than this
  205674. GetWindowText (hwnd, windowName, 64);
  205675. windowName [63] = 0;
  205676. if (String (windowName) == messageWindowName)
  205677. {
  205678. DWORD_PTR result;
  205679. SendMessageTimeout (hwnd, WM_COPYDATA,
  205680. (WPARAM) juce_messageWindowHandle,
  205681. (LPARAM) &data,
  205682. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205683. 8000,
  205684. &result);
  205685. }
  205686. }
  205687. }
  205688. static const String getMessageWindowClassName()
  205689. {
  205690. // this name has to be different for each app/dll instance because otherwise
  205691. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205692. // window class).
  205693. static int number = 0;
  205694. if (number == 0)
  205695. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205696. return "JUCEcs_" + String (number);
  205697. }
  205698. void MessageManager::doPlatformSpecificInitialisation()
  205699. {
  205700. OleInitialize (0);
  205701. const String className (getMessageWindowClassName());
  205702. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205703. WNDCLASSEX wc;
  205704. zerostruct (wc);
  205705. wc.cbSize = sizeof (wc);
  205706. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205707. wc.cbWndExtra = 4;
  205708. wc.hInstance = hmod;
  205709. wc.lpszClassName = className;
  205710. RegisterClassEx (&wc);
  205711. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205712. messageWindowName,
  205713. 0, 0, 0, 0, 0, 0, 0,
  205714. hmod, 0);
  205715. }
  205716. void MessageManager::doPlatformSpecificShutdown()
  205717. {
  205718. DestroyWindow (juce_messageWindowHandle);
  205719. UnregisterClass (getMessageWindowClassName(), 0);
  205720. OleUninitialize();
  205721. }
  205722. #endif
  205723. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205724. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205725. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205726. // compiled on its own).
  205727. #if JUCE_INCLUDED_FILE
  205728. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205729. NEWTEXTMETRICEXW*,
  205730. int type,
  205731. LPARAM lParam)
  205732. {
  205733. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205734. {
  205735. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205736. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205737. }
  205738. return 1;
  205739. }
  205740. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205741. NEWTEXTMETRICEXW*,
  205742. int type,
  205743. LPARAM lParam)
  205744. {
  205745. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205746. {
  205747. LOGFONTW lf;
  205748. zerostruct (lf);
  205749. lf.lfWeight = FW_DONTCARE;
  205750. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205751. lf.lfQuality = DEFAULT_QUALITY;
  205752. lf.lfCharSet = DEFAULT_CHARSET;
  205753. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205754. lf.lfPitchAndFamily = FF_DONTCARE;
  205755. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205756. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205757. HDC dc = CreateCompatibleDC (0);
  205758. EnumFontFamiliesEx (dc, &lf,
  205759. (FONTENUMPROCW) &wfontEnum2,
  205760. lParam, 0);
  205761. DeleteDC (dc);
  205762. }
  205763. return 1;
  205764. }
  205765. const StringArray Font::findAllTypefaceNames()
  205766. {
  205767. StringArray results;
  205768. HDC dc = CreateCompatibleDC (0);
  205769. {
  205770. LOGFONTW lf;
  205771. zerostruct (lf);
  205772. lf.lfWeight = FW_DONTCARE;
  205773. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205774. lf.lfQuality = DEFAULT_QUALITY;
  205775. lf.lfCharSet = DEFAULT_CHARSET;
  205776. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205777. lf.lfPitchAndFamily = FF_DONTCARE;
  205778. lf.lfFaceName[0] = 0;
  205779. EnumFontFamiliesEx (dc, &lf,
  205780. (FONTENUMPROCW) &wfontEnum1,
  205781. (LPARAM) &results, 0);
  205782. }
  205783. DeleteDC (dc);
  205784. results.sort (true);
  205785. return results;
  205786. }
  205787. extern bool juce_IsRunningInWine();
  205788. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205789. {
  205790. if (juce_IsRunningInWine())
  205791. {
  205792. // If we're running in Wine, then use fonts that might be available on Linux..
  205793. defaultSans = "Bitstream Vera Sans";
  205794. defaultSerif = "Bitstream Vera Serif";
  205795. defaultFixed = "Bitstream Vera Sans Mono";
  205796. }
  205797. else
  205798. {
  205799. defaultSans = "Verdana";
  205800. defaultSerif = "Times";
  205801. defaultFixed = "Lucida Console";
  205802. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205803. }
  205804. }
  205805. class FontDCHolder : private DeletedAtShutdown
  205806. {
  205807. public:
  205808. FontDCHolder()
  205809. : dc (0), numKPs (0), size (0),
  205810. bold (false), italic (false)
  205811. {
  205812. }
  205813. ~FontDCHolder()
  205814. {
  205815. if (dc != 0)
  205816. {
  205817. DeleteDC (dc);
  205818. DeleteObject (fontH);
  205819. }
  205820. clearSingletonInstance();
  205821. }
  205822. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205823. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205824. {
  205825. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205826. {
  205827. fontName = fontName_;
  205828. bold = bold_;
  205829. italic = italic_;
  205830. size = size_;
  205831. if (dc != 0)
  205832. {
  205833. DeleteDC (dc);
  205834. DeleteObject (fontH);
  205835. kps.free();
  205836. }
  205837. fontH = 0;
  205838. dc = CreateCompatibleDC (0);
  205839. SetMapperFlags (dc, 0);
  205840. SetMapMode (dc, MM_TEXT);
  205841. LOGFONTW lfw;
  205842. zerostruct (lfw);
  205843. lfw.lfCharSet = DEFAULT_CHARSET;
  205844. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205845. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205846. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205847. lfw.lfQuality = PROOF_QUALITY;
  205848. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205849. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205850. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205851. lfw.lfHeight = size > 0 ? size : -256;
  205852. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205853. if (standardSizedFont != 0)
  205854. {
  205855. if (SelectObject (dc, standardSizedFont) != 0)
  205856. {
  205857. fontH = standardSizedFont;
  205858. if (size == 0)
  205859. {
  205860. OUTLINETEXTMETRIC otm;
  205861. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205862. {
  205863. lfw.lfHeight = -(int) otm.otmEMSquare;
  205864. fontH = CreateFontIndirect (&lfw);
  205865. SelectObject (dc, fontH);
  205866. DeleteObject (standardSizedFont);
  205867. }
  205868. }
  205869. }
  205870. else
  205871. {
  205872. jassertfalse;
  205873. }
  205874. }
  205875. else
  205876. {
  205877. jassertfalse;
  205878. }
  205879. }
  205880. return dc;
  205881. }
  205882. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205883. {
  205884. if (kps == 0)
  205885. {
  205886. numKPs = GetKerningPairs (dc, 0, 0);
  205887. kps.calloc (numKPs);
  205888. GetKerningPairs (dc, numKPs, kps);
  205889. }
  205890. numKPs_ = numKPs;
  205891. return kps;
  205892. }
  205893. private:
  205894. HFONT fontH;
  205895. HDC dc;
  205896. String fontName;
  205897. HeapBlock <KERNINGPAIR> kps;
  205898. int numKPs, size;
  205899. bool bold, italic;
  205900. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205901. };
  205902. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205903. class WindowsTypeface : public CustomTypeface
  205904. {
  205905. public:
  205906. WindowsTypeface (const Font& font)
  205907. {
  205908. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205909. font.isBold(), font.isItalic(), 0);
  205910. TEXTMETRIC tm;
  205911. tm.tmAscent = tm.tmHeight = 1;
  205912. tm.tmDefaultChar = 0;
  205913. GetTextMetrics (dc, &tm);
  205914. setCharacteristics (font.getTypefaceName(),
  205915. tm.tmAscent / (float) tm.tmHeight,
  205916. font.isBold(), font.isItalic(),
  205917. tm.tmDefaultChar);
  205918. }
  205919. bool loadGlyphIfPossible (juce_wchar character)
  205920. {
  205921. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205922. GLYPHMETRICS gm;
  205923. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205924. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205925. // gets correctly created later on.
  205926. if (! isFallbackFont)
  205927. {
  205928. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205929. WORD index = 0;
  205930. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205931. && index == 0xffff)
  205932. {
  205933. return false;
  205934. }
  205935. }
  205936. Path glyphPath;
  205937. TEXTMETRIC tm;
  205938. if (! GetTextMetrics (dc, &tm))
  205939. {
  205940. addGlyph (character, glyphPath, 0);
  205941. return true;
  205942. }
  205943. const float height = (float) tm.tmHeight;
  205944. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205945. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205946. &gm, 0, 0, &identityMatrix);
  205947. if (bufSize > 0)
  205948. {
  205949. HeapBlock<char> data (bufSize);
  205950. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205951. bufSize, data, &identityMatrix);
  205952. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205953. const float scaleX = 1.0f / height;
  205954. const float scaleY = -1.0f / height;
  205955. while ((char*) pheader < data + bufSize)
  205956. {
  205957. float x = scaleX * pheader->pfxStart.x.value;
  205958. float y = scaleY * pheader->pfxStart.y.value;
  205959. glyphPath.startNewSubPath (x, y);
  205960. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205961. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205962. while ((const char*) curve < curveEnd)
  205963. {
  205964. if (curve->wType == TT_PRIM_LINE)
  205965. {
  205966. for (int i = 0; i < curve->cpfx; ++i)
  205967. {
  205968. x = scaleX * curve->apfx[i].x.value;
  205969. y = scaleY * curve->apfx[i].y.value;
  205970. glyphPath.lineTo (x, y);
  205971. }
  205972. }
  205973. else if (curve->wType == TT_PRIM_QSPLINE)
  205974. {
  205975. for (int i = 0; i < curve->cpfx - 1; ++i)
  205976. {
  205977. const float x2 = scaleX * curve->apfx[i].x.value;
  205978. const float y2 = scaleY * curve->apfx[i].y.value;
  205979. float x3, y3;
  205980. if (i < curve->cpfx - 2)
  205981. {
  205982. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205983. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205984. }
  205985. else
  205986. {
  205987. x3 = scaleX * curve->apfx[i + 1].x.value;
  205988. y3 = scaleY * curve->apfx[i + 1].y.value;
  205989. }
  205990. glyphPath.quadraticTo (x2, y2, x3, y3);
  205991. x = x3;
  205992. y = y3;
  205993. }
  205994. }
  205995. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205996. }
  205997. pheader = (const TTPOLYGONHEADER*) curve;
  205998. glyphPath.closeSubPath();
  205999. }
  206000. }
  206001. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206002. int numKPs;
  206003. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206004. for (int i = 0; i < numKPs; ++i)
  206005. {
  206006. if (kps[i].wFirst == character)
  206007. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206008. kps[i].iKernAmount / height);
  206009. }
  206010. return true;
  206011. }
  206012. private:
  206013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  206014. };
  206015. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206016. {
  206017. return new WindowsTypeface (font);
  206018. }
  206019. #endif
  206020. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206021. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206022. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206023. // compiled on its own).
  206024. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  206025. class SharedD2DFactory : public DeletedAtShutdown
  206026. {
  206027. public:
  206028. SharedD2DFactory()
  206029. {
  206030. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  206031. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  206032. if (directWriteFactory != 0)
  206033. directWriteFactory->GetSystemFontCollection (&systemFonts);
  206034. }
  206035. ~SharedD2DFactory()
  206036. {
  206037. clearSingletonInstance();
  206038. }
  206039. juce_DeclareSingleton (SharedD2DFactory, false);
  206040. ComSmartPtr <ID2D1Factory> d2dFactory;
  206041. ComSmartPtr <IDWriteFactory> directWriteFactory;
  206042. ComSmartPtr <IDWriteFontCollection> systemFonts;
  206043. };
  206044. juce_ImplementSingleton (SharedD2DFactory)
  206045. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  206046. {
  206047. public:
  206048. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  206049. : hwnd (hwnd_),
  206050. currentState (0)
  206051. {
  206052. RECT windowRect;
  206053. GetClientRect (hwnd, &windowRect);
  206054. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206055. bounds.setSize (size.width, size.height);
  206056. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  206057. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206058. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  206059. // xxx check for error
  206060. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  206061. }
  206062. ~Direct2DLowLevelGraphicsContext()
  206063. {
  206064. states.clear();
  206065. }
  206066. void resized()
  206067. {
  206068. RECT windowRect;
  206069. GetClientRect (hwnd, &windowRect);
  206070. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206071. renderingTarget->Resize (size);
  206072. bounds.setSize (size.width, size.height);
  206073. }
  206074. void clear()
  206075. {
  206076. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206077. }
  206078. void start()
  206079. {
  206080. renderingTarget->BeginDraw();
  206081. saveState();
  206082. }
  206083. void end()
  206084. {
  206085. states.clear();
  206086. currentState = 0;
  206087. renderingTarget->EndDraw();
  206088. renderingTarget->CheckWindowState();
  206089. }
  206090. bool isVectorDevice() const { return false; }
  206091. void setOrigin (int x, int y)
  206092. {
  206093. currentState->origin.addXY (x, y);
  206094. }
  206095. void addTransform (const AffineTransform& transform)
  206096. {
  206097. //xxx todo
  206098. jassertfalse;
  206099. }
  206100. float getScaleFactor()
  206101. {
  206102. jassertfalse; //xxx
  206103. return 1.0f;
  206104. }
  206105. bool clipToRectangle (const Rectangle<int>& r)
  206106. {
  206107. currentState->clipToRectangle (r);
  206108. return ! isClipEmpty();
  206109. }
  206110. bool clipToRectangleList (const RectangleList& clipRegion)
  206111. {
  206112. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206113. return ! isClipEmpty();
  206114. }
  206115. void excludeClipRectangle (const Rectangle<int>&)
  206116. {
  206117. //xxx
  206118. }
  206119. void clipToPath (const Path& path, const AffineTransform& transform)
  206120. {
  206121. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206122. }
  206123. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206124. {
  206125. currentState->clipToImage (sourceImage,transform);
  206126. }
  206127. bool clipRegionIntersects (const Rectangle<int>& r)
  206128. {
  206129. const Rectangle<int> r2 (r + currentState->origin);
  206130. return currentState->clipRect.intersects (r2);
  206131. }
  206132. const Rectangle<int> getClipBounds() const
  206133. {
  206134. // xxx could this take into account complex clip regions?
  206135. return currentState->clipRect - currentState->origin;
  206136. }
  206137. bool isClipEmpty() const
  206138. {
  206139. return currentState->clipRect.isEmpty();
  206140. }
  206141. void saveState()
  206142. {
  206143. states.add (new SavedState (*this));
  206144. currentState = states.getLast();
  206145. }
  206146. void restoreState()
  206147. {
  206148. jassert (states.size() > 1) //you should never pop the last state!
  206149. states.removeLast (1);
  206150. currentState = states.getLast();
  206151. }
  206152. void beginTransparencyLayer (float opacity)
  206153. {
  206154. jassertfalse; //xxx todo
  206155. }
  206156. void endTransparencyLayer()
  206157. {
  206158. jassertfalse; //xxx todo
  206159. }
  206160. void setFill (const FillType& fillType)
  206161. {
  206162. currentState->setFill (fillType);
  206163. }
  206164. void setOpacity (float newOpacity)
  206165. {
  206166. currentState->setOpacity (newOpacity);
  206167. }
  206168. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206169. {
  206170. }
  206171. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206172. {
  206173. currentState->createBrush();
  206174. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206175. }
  206176. void fillPath (const Path& p, const AffineTransform& transform)
  206177. {
  206178. currentState->createBrush();
  206179. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206180. if (renderingTarget != 0)
  206181. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206182. }
  206183. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206184. {
  206185. const int x = currentState->origin.getX();
  206186. const int y = currentState->origin.getY();
  206187. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206188. D2D1_SIZE_U size;
  206189. size.width = image.getWidth();
  206190. size.height = image.getHeight();
  206191. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206192. Image img (image.convertedToFormat (Image::ARGB));
  206193. Image::BitmapData bd (img, false);
  206194. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206195. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206196. {
  206197. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206198. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206199. if (tempBitmap != 0)
  206200. renderingTarget->DrawBitmap (tempBitmap);
  206201. }
  206202. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206203. }
  206204. void drawLine (const Line <float>& line)
  206205. {
  206206. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206207. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206208. line.getEnd() + currentState->origin.toFloat());
  206209. currentState->createBrush();
  206210. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206211. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206212. currentState->currentBrush);
  206213. }
  206214. void drawVerticalLine (int x, float top, float bottom)
  206215. {
  206216. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206217. currentState->createBrush();
  206218. x += currentState->origin.getX();
  206219. const int y = currentState->origin.getY();
  206220. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206221. D2D1::Point2F (x, y + bottom),
  206222. currentState->currentBrush);
  206223. }
  206224. void drawHorizontalLine (int y, float left, float right)
  206225. {
  206226. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206227. currentState->createBrush();
  206228. y += currentState->origin.getY();
  206229. const int x = currentState->origin.getX();
  206230. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206231. D2D1::Point2F (x + right, y),
  206232. currentState->currentBrush);
  206233. }
  206234. void setFont (const Font& newFont)
  206235. {
  206236. currentState->setFont (newFont);
  206237. }
  206238. const Font getFont()
  206239. {
  206240. return currentState->font;
  206241. }
  206242. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206243. {
  206244. const float x = currentState->origin.getX();
  206245. const float y = currentState->origin.getY();
  206246. currentState->createBrush();
  206247. currentState->createFont();
  206248. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206249. float hScale = currentState->font.getHorizontalScale();
  206250. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206251. float dpiX = 0, dpiY = 0;
  206252. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206253. UINT32 glyphNum = glyphNumber;
  206254. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206255. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206256. DWRITE_GLYPH_OFFSET offset;
  206257. offset.advanceOffset = 0;
  206258. offset.ascenderOffset = 0;
  206259. float glyphAdvances = 0;
  206260. DWRITE_GLYPH_RUN glyph;
  206261. glyph.fontFace = currentState->currentFontFace;
  206262. glyph.glyphCount = 1;
  206263. glyph.glyphIndices = &glyphNum1;
  206264. glyph.isSideways = FALSE;
  206265. glyph.glyphAdvances = &glyphAdvances;
  206266. glyph.glyphOffsets = &offset;
  206267. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206268. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206269. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206270. }
  206271. class SavedState
  206272. {
  206273. public:
  206274. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206275. : owner (owner_), currentBrush (0),
  206276. fontScaling (1.0f), currentFontFace (0),
  206277. clipsRect (false), shouldClipRect (false),
  206278. clipsRectList (false), shouldClipRectList (false),
  206279. clipsComplex (false), shouldClipComplex (false),
  206280. clipsBitmap (false), shouldClipBitmap (false)
  206281. {
  206282. if (owner.currentState != 0)
  206283. {
  206284. // xxx seems like a very slow way to create one of these, and this is a performance
  206285. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206286. setFill (owner.currentState->fillType);
  206287. currentBrush = owner.currentState->currentBrush;
  206288. origin = owner.currentState->origin;
  206289. clipRect = owner.currentState->clipRect;
  206290. font = owner.currentState->font;
  206291. currentFontFace = owner.currentState->currentFontFace;
  206292. }
  206293. else
  206294. {
  206295. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206296. clipRect.setSize (size.width, size.height);
  206297. setFill (FillType (Colours::black));
  206298. }
  206299. }
  206300. ~SavedState()
  206301. {
  206302. clearClip();
  206303. clearFont();
  206304. clearFill();
  206305. clearPathClip();
  206306. clearImageClip();
  206307. complexClipLayer = 0;
  206308. bitmapMaskLayer = 0;
  206309. }
  206310. void clearClip()
  206311. {
  206312. popClips();
  206313. shouldClipRect = false;
  206314. }
  206315. void clipToRectangle (const Rectangle<int>& r)
  206316. {
  206317. clearClip();
  206318. clipRect = r + origin;
  206319. shouldClipRect = true;
  206320. pushClips();
  206321. }
  206322. void clearPathClip()
  206323. {
  206324. popClips();
  206325. if (shouldClipComplex)
  206326. {
  206327. complexClipGeometry = 0;
  206328. shouldClipComplex = false;
  206329. }
  206330. }
  206331. void clipToPath (ID2D1Geometry* geometry)
  206332. {
  206333. clearPathClip();
  206334. if (complexClipLayer == 0)
  206335. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206336. complexClipGeometry = geometry;
  206337. shouldClipComplex = true;
  206338. pushClips();
  206339. }
  206340. void clearRectListClip()
  206341. {
  206342. popClips();
  206343. if (shouldClipRectList)
  206344. {
  206345. rectListGeometry = 0;
  206346. shouldClipRectList = false;
  206347. }
  206348. }
  206349. void clipToRectList (ID2D1Geometry* geometry)
  206350. {
  206351. clearRectListClip();
  206352. if (rectListLayer == 0)
  206353. owner.renderingTarget->CreateLayer (&rectListLayer);
  206354. rectListGeometry = geometry;
  206355. shouldClipRectList = true;
  206356. pushClips();
  206357. }
  206358. void clearImageClip()
  206359. {
  206360. popClips();
  206361. if (shouldClipBitmap)
  206362. {
  206363. maskBitmap = 0;
  206364. bitmapMaskBrush = 0;
  206365. shouldClipBitmap = false;
  206366. }
  206367. }
  206368. void clipToImage (const Image& image, const AffineTransform& transform)
  206369. {
  206370. clearImageClip();
  206371. if (bitmapMaskLayer == 0)
  206372. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206373. D2D1_BRUSH_PROPERTIES brushProps;
  206374. brushProps.opacity = 1;
  206375. brushProps.transform = transfromToMatrix (transform);
  206376. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206377. D2D1_SIZE_U size;
  206378. size.width = image.getWidth();
  206379. size.height = image.getHeight();
  206380. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206381. maskImage = image.convertedToFormat (Image::ARGB);
  206382. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206383. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206384. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206385. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206386. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206387. imageMaskLayerParams = D2D1::LayerParameters();
  206388. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206389. shouldClipBitmap = true;
  206390. pushClips();
  206391. }
  206392. void popClips()
  206393. {
  206394. if (clipsBitmap)
  206395. {
  206396. owner.renderingTarget->PopLayer();
  206397. clipsBitmap = false;
  206398. }
  206399. if (clipsComplex)
  206400. {
  206401. owner.renderingTarget->PopLayer();
  206402. clipsComplex = false;
  206403. }
  206404. if (clipsRectList)
  206405. {
  206406. owner.renderingTarget->PopLayer();
  206407. clipsRectList = false;
  206408. }
  206409. if (clipsRect)
  206410. {
  206411. owner.renderingTarget->PopAxisAlignedClip();
  206412. clipsRect = false;
  206413. }
  206414. }
  206415. void pushClips()
  206416. {
  206417. if (shouldClipRect && ! clipsRect)
  206418. {
  206419. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206420. clipsRect = true;
  206421. }
  206422. if (shouldClipRectList && ! clipsRectList)
  206423. {
  206424. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206425. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206426. layerParams.geometricMask = rectListGeometry;
  206427. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206428. clipsRectList = true;
  206429. }
  206430. if (shouldClipComplex && ! clipsComplex)
  206431. {
  206432. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206433. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206434. layerParams.geometricMask = complexClipGeometry;
  206435. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206436. clipsComplex = true;
  206437. }
  206438. if (shouldClipBitmap && ! clipsBitmap)
  206439. {
  206440. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206441. clipsBitmap = true;
  206442. }
  206443. }
  206444. void setFill (const FillType& newFillType)
  206445. {
  206446. if (fillType != newFillType)
  206447. {
  206448. fillType = newFillType;
  206449. clearFill();
  206450. }
  206451. }
  206452. void clearFont()
  206453. {
  206454. currentFontFace = localFontFace = 0;
  206455. }
  206456. void setFont (const Font& newFont)
  206457. {
  206458. if (font != newFont)
  206459. {
  206460. font = newFont;
  206461. clearFont();
  206462. }
  206463. }
  206464. void createFont()
  206465. {
  206466. // xxx The font shouldn't be managed by the graphics context.
  206467. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206468. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206469. // WindowsTypeface class.
  206470. if (currentFontFace == 0)
  206471. {
  206472. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206473. fontScaling = systemType->getAscent();
  206474. BOOL fontFound;
  206475. uint32 fontIndex;
  206476. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206477. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206478. if (! fontFound)
  206479. fontIndex = 0;
  206480. ComSmartPtr <IDWriteFontFamily> fontFam;
  206481. fonts->GetFontFamily (fontIndex, &fontFam);
  206482. ComSmartPtr <IDWriteFont> font;
  206483. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206484. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206485. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206486. font->CreateFontFace (&localFontFace);
  206487. currentFontFace = localFontFace;
  206488. }
  206489. }
  206490. void setOpacity (float newOpacity)
  206491. {
  206492. fillType.setOpacity (newOpacity);
  206493. if (currentBrush != 0)
  206494. currentBrush->SetOpacity (newOpacity);
  206495. }
  206496. void clearFill()
  206497. {
  206498. gradientStops = 0;
  206499. linearGradient = 0;
  206500. radialGradient = 0;
  206501. bitmap = 0;
  206502. bitmapBrush = 0;
  206503. currentBrush = 0;
  206504. }
  206505. void createBrush()
  206506. {
  206507. if (currentBrush == 0)
  206508. {
  206509. const int x = origin.getX();
  206510. const int y = origin.getY();
  206511. if (fillType.isColour())
  206512. {
  206513. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206514. owner.colourBrush->SetColor (colour);
  206515. currentBrush = owner.colourBrush;
  206516. }
  206517. else if (fillType.isTiledImage())
  206518. {
  206519. D2D1_BRUSH_PROPERTIES brushProps;
  206520. brushProps.opacity = fillType.getOpacity();
  206521. brushProps.transform = transfromToMatrix (fillType.transform);
  206522. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206523. image = fillType.image;
  206524. D2D1_SIZE_U size;
  206525. size.width = image.getWidth();
  206526. size.height = image.getHeight();
  206527. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206528. this->image = image.convertedToFormat (Image::ARGB);
  206529. Image::BitmapData bd (this->image, false);
  206530. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206531. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206532. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206533. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206534. currentBrush = bitmapBrush;
  206535. }
  206536. else if (fillType.isGradient())
  206537. {
  206538. gradientStops = 0;
  206539. D2D1_BRUSH_PROPERTIES brushProps;
  206540. brushProps.opacity = fillType.getOpacity();
  206541. brushProps.transform = transfromToMatrix (fillType.transform);
  206542. const int numColors = fillType.gradient->getNumColours();
  206543. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206544. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206545. {
  206546. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206547. stops[i].position = fillType.gradient->getColourPosition(i);
  206548. }
  206549. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206550. if (fillType.gradient->isRadial)
  206551. {
  206552. radialGradient = 0;
  206553. const Point<float>& p1 = fillType.gradient->point1;
  206554. const Point<float>& p2 = fillType.gradient->point2;
  206555. float r = p1.getDistanceFrom (p2);
  206556. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206557. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206558. D2D1::Point2F (0, 0),
  206559. r, r);
  206560. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206561. currentBrush = radialGradient;
  206562. }
  206563. else
  206564. {
  206565. linearGradient = 0;
  206566. const Point<float>& p1 = fillType.gradient->point1;
  206567. const Point<float>& p2 = fillType.gradient->point2;
  206568. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206569. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206570. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206571. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206572. currentBrush = linearGradient;
  206573. }
  206574. }
  206575. }
  206576. }
  206577. //xxx most of these members should probably be private...
  206578. Direct2DLowLevelGraphicsContext& owner;
  206579. Point<int> origin;
  206580. Font font;
  206581. float fontScaling;
  206582. IDWriteFontFace* currentFontFace;
  206583. ComSmartPtr <IDWriteFontFace> localFontFace;
  206584. FillType fillType;
  206585. Image image;
  206586. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206587. Rectangle<int> clipRect;
  206588. bool clipsRect, shouldClipRect;
  206589. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206590. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206591. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206592. bool clipsComplex, shouldClipComplex;
  206593. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206594. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206595. ComSmartPtr <ID2D1Layer> rectListLayer;
  206596. bool clipsRectList, shouldClipRectList;
  206597. Image maskImage;
  206598. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206599. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206600. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206601. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206602. bool clipsBitmap, shouldClipBitmap;
  206603. ID2D1Brush* currentBrush;
  206604. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206605. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206606. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206607. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206608. private:
  206609. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206610. };
  206611. private:
  206612. HWND hwnd;
  206613. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206614. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206615. Rectangle<int> bounds;
  206616. SavedState* currentState;
  206617. OwnedArray<SavedState> states;
  206618. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206619. {
  206620. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206621. }
  206622. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206623. {
  206624. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206625. }
  206626. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206627. {
  206628. transform.transformPoint (x, y);
  206629. return D2D1::Point2F (x, y);
  206630. }
  206631. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206632. {
  206633. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206634. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206635. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206636. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206637. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206638. }
  206639. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206640. {
  206641. ID2D1PathGeometry* p = 0;
  206642. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206643. ComSmartPtr <ID2D1GeometrySink> sink;
  206644. HRESULT hr = p->Open (&sink); // xxx handle error
  206645. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206646. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206647. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206648. hr = sink->Close();
  206649. return p;
  206650. }
  206651. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206652. {
  206653. Path::Iterator it (path);
  206654. while (it.next())
  206655. {
  206656. switch (it.elementType)
  206657. {
  206658. case Path::Iterator::cubicTo:
  206659. {
  206660. D2D1_BEZIER_SEGMENT seg;
  206661. transform.transformPoint (it.x1, it.y1);
  206662. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206663. transform.transformPoint (it.x2, it.y2);
  206664. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206665. transform.transformPoint(it.x3, it.y3);
  206666. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206667. sink->AddBezier (seg);
  206668. break;
  206669. }
  206670. case Path::Iterator::lineTo:
  206671. {
  206672. transform.transformPoint (it.x1, it.y1);
  206673. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206674. break;
  206675. }
  206676. case Path::Iterator::quadraticTo:
  206677. {
  206678. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206679. transform.transformPoint (it.x1, it.y1);
  206680. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206681. transform.transformPoint (it.x2, it.y2);
  206682. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206683. sink->AddQuadraticBezier (seg);
  206684. break;
  206685. }
  206686. case Path::Iterator::closePath:
  206687. {
  206688. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206689. break;
  206690. }
  206691. case Path::Iterator::startNewSubPath:
  206692. {
  206693. transform.transformPoint (it.x1, it.y1);
  206694. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206695. break;
  206696. }
  206697. }
  206698. }
  206699. }
  206700. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206701. {
  206702. ID2D1PathGeometry* p = 0;
  206703. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206704. ComSmartPtr <ID2D1GeometrySink> sink;
  206705. HRESULT hr = p->Open (&sink);
  206706. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206707. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206708. hr = sink->Close();
  206709. return p;
  206710. }
  206711. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206712. {
  206713. D2D1::Matrix3x2F matrix;
  206714. matrix._11 = transform.mat00;
  206715. matrix._12 = transform.mat10;
  206716. matrix._21 = transform.mat01;
  206717. matrix._22 = transform.mat11;
  206718. matrix._31 = transform.mat02;
  206719. matrix._32 = transform.mat12;
  206720. return matrix;
  206721. }
  206722. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206723. };
  206724. #endif
  206725. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206726. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206727. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206728. // compiled on its own).
  206729. #if JUCE_INCLUDED_FILE
  206730. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206731. // these are in the windows SDK, but need to be repeated here for GCC..
  206732. #ifndef GET_APPCOMMAND_LPARAM
  206733. #define FAPPCOMMAND_MASK 0xF000
  206734. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206735. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206736. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206737. #define APPCOMMAND_MEDIA_STOP 13
  206738. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206739. #define WM_APPCOMMAND 0x0319
  206740. #endif
  206741. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206742. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206743. extern bool juce_IsRunningInWine();
  206744. #ifndef ULW_ALPHA
  206745. #define ULW_ALPHA 0x00000002
  206746. #endif
  206747. #ifndef AC_SRC_ALPHA
  206748. #define AC_SRC_ALPHA 0x01
  206749. #endif
  206750. static bool shouldDeactivateTitleBar = true;
  206751. #define WM_TRAYNOTIFY WM_USER + 100
  206752. using ::abs;
  206753. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206754. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206755. bool Desktop::canUseSemiTransparentWindows() throw()
  206756. {
  206757. if (updateLayeredWindow == 0)
  206758. {
  206759. if (! juce_IsRunningInWine())
  206760. {
  206761. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206762. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206763. }
  206764. }
  206765. return updateLayeredWindow != 0;
  206766. }
  206767. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206768. {
  206769. return upright;
  206770. }
  206771. const int extendedKeyModifier = 0x10000;
  206772. const int KeyPress::spaceKey = VK_SPACE;
  206773. const int KeyPress::returnKey = VK_RETURN;
  206774. const int KeyPress::escapeKey = VK_ESCAPE;
  206775. const int KeyPress::backspaceKey = VK_BACK;
  206776. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206777. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206778. const int KeyPress::tabKey = VK_TAB;
  206779. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206780. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206781. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206782. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206783. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206784. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206785. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206786. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206787. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206788. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206789. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206790. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206791. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206792. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206793. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206794. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206795. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206796. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206797. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206798. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206799. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206800. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206801. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206802. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206803. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206804. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206805. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206806. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206807. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206808. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206809. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206810. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206811. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206812. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206813. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206814. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206815. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206816. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206817. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206818. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206819. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206820. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206821. const int KeyPress::playKey = 0x30000;
  206822. const int KeyPress::stopKey = 0x30001;
  206823. const int KeyPress::fastForwardKey = 0x30002;
  206824. const int KeyPress::rewindKey = 0x30003;
  206825. class WindowsBitmapImage : public Image::SharedImage
  206826. {
  206827. public:
  206828. HBITMAP hBitmap;
  206829. BITMAPV4HEADER bitmapInfo;
  206830. HDC hdc;
  206831. unsigned char* bitmapData;
  206832. WindowsBitmapImage (const Image::PixelFormat format_,
  206833. const int w, const int h, const bool clearImage)
  206834. : Image::SharedImage (format_, w, h)
  206835. {
  206836. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206837. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206838. zerostruct (bitmapInfo);
  206839. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206840. bitmapInfo.bV4Width = w;
  206841. bitmapInfo.bV4Height = h;
  206842. bitmapInfo.bV4Planes = 1;
  206843. bitmapInfo.bV4CSType = 1;
  206844. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206845. if (format_ == Image::ARGB)
  206846. {
  206847. bitmapInfo.bV4AlphaMask = 0xff000000;
  206848. bitmapInfo.bV4RedMask = 0xff0000;
  206849. bitmapInfo.bV4GreenMask = 0xff00;
  206850. bitmapInfo.bV4BlueMask = 0xff;
  206851. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206852. }
  206853. else
  206854. {
  206855. bitmapInfo.bV4V4Compression = BI_RGB;
  206856. }
  206857. lineStride = -((w * pixelStride + 3) & ~3);
  206858. HDC dc = GetDC (0);
  206859. hdc = CreateCompatibleDC (dc);
  206860. ReleaseDC (0, dc);
  206861. SetMapMode (hdc, MM_TEXT);
  206862. hBitmap = CreateDIBSection (hdc,
  206863. (BITMAPINFO*) &(bitmapInfo),
  206864. DIB_RGB_COLORS,
  206865. (void**) &bitmapData,
  206866. 0, 0);
  206867. SelectObject (hdc, hBitmap);
  206868. if (format_ == Image::ARGB && clearImage)
  206869. zeromem (bitmapData, abs (h * lineStride));
  206870. imageData = bitmapData - (lineStride * (h - 1));
  206871. }
  206872. ~WindowsBitmapImage()
  206873. {
  206874. DeleteDC (hdc);
  206875. DeleteObject (hBitmap);
  206876. }
  206877. Image::ImageType getType() const { return Image::NativeImage; }
  206878. LowLevelGraphicsContext* createLowLevelContext()
  206879. {
  206880. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206881. }
  206882. Image::SharedImage* clone()
  206883. {
  206884. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206885. for (int i = 0; i < height; ++i)
  206886. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206887. return im;
  206888. }
  206889. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206890. const int x, const int y,
  206891. const RectangleList& maskedRegion,
  206892. const uint8 updateLayeredWindowAlpha) throw()
  206893. {
  206894. static HDRAWDIB hdd = 0;
  206895. static bool needToCreateDrawDib = true;
  206896. if (needToCreateDrawDib)
  206897. {
  206898. needToCreateDrawDib = false;
  206899. HDC dc = GetDC (0);
  206900. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206901. ReleaseDC (0, dc);
  206902. // only open if we're not palettised
  206903. if (n > 8)
  206904. hdd = DrawDibOpen();
  206905. }
  206906. SetMapMode (dc, MM_TEXT);
  206907. if (transparent)
  206908. {
  206909. POINT p, pos;
  206910. SIZE size;
  206911. RECT windowBounds;
  206912. GetWindowRect (hwnd, &windowBounds);
  206913. p.x = -x;
  206914. p.y = -y;
  206915. pos.x = windowBounds.left;
  206916. pos.y = windowBounds.top;
  206917. size.cx = windowBounds.right - windowBounds.left;
  206918. size.cy = windowBounds.bottom - windowBounds.top;
  206919. BLENDFUNCTION bf;
  206920. bf.AlphaFormat = AC_SRC_ALPHA;
  206921. bf.BlendFlags = 0;
  206922. bf.BlendOp = AC_SRC_OVER;
  206923. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206924. if (! maskedRegion.isEmpty())
  206925. {
  206926. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206927. {
  206928. const Rectangle<int>& r = *i.getRectangle();
  206929. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206930. }
  206931. }
  206932. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206933. }
  206934. else
  206935. {
  206936. int savedDC = 0;
  206937. if (! maskedRegion.isEmpty())
  206938. {
  206939. savedDC = SaveDC (dc);
  206940. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206941. {
  206942. const Rectangle<int>& r = *i.getRectangle();
  206943. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206944. }
  206945. }
  206946. if (hdd == 0)
  206947. {
  206948. StretchDIBits (dc,
  206949. x, y, width, height,
  206950. 0, 0, width, height,
  206951. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206952. DIB_RGB_COLORS, SRCCOPY);
  206953. }
  206954. else
  206955. {
  206956. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206957. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206958. 0, 0, width, height, 0);
  206959. }
  206960. if (! maskedRegion.isEmpty())
  206961. RestoreDC (dc, savedDC);
  206962. }
  206963. }
  206964. private:
  206965. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206966. };
  206967. namespace IconConverters
  206968. {
  206969. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206970. {
  206971. Image im;
  206972. if (bitmap != 0)
  206973. {
  206974. BITMAP bm;
  206975. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206976. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206977. {
  206978. HDC tempDC = GetDC (0);
  206979. HDC dc = CreateCompatibleDC (tempDC);
  206980. ReleaseDC (0, tempDC);
  206981. SelectObject (dc, bitmap);
  206982. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206983. Image::BitmapData imageData (im, true);
  206984. for (int y = bm.bmHeight; --y >= 0;)
  206985. {
  206986. for (int x = bm.bmWidth; --x >= 0;)
  206987. {
  206988. COLORREF col = GetPixel (dc, x, y);
  206989. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206990. (uint8) GetGValue (col),
  206991. (uint8) GetBValue (col)));
  206992. }
  206993. }
  206994. DeleteDC (dc);
  206995. }
  206996. }
  206997. return im;
  206998. }
  206999. const Image createImageFromHICON (HICON icon)
  207000. {
  207001. ICONINFO info;
  207002. if (GetIconInfo (icon, &info))
  207003. {
  207004. Image mask (createImageFromHBITMAP (info.hbmMask));
  207005. Image image (createImageFromHBITMAP (info.hbmColor));
  207006. if (mask.isValid() && image.isValid())
  207007. {
  207008. for (int y = image.getHeight(); --y >= 0;)
  207009. {
  207010. for (int x = image.getWidth(); --x >= 0;)
  207011. {
  207012. const float brightness = mask.getPixelAt (x, y).getBrightness();
  207013. if (brightness > 0.0f)
  207014. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  207015. }
  207016. }
  207017. return image;
  207018. }
  207019. }
  207020. return Image::null;
  207021. }
  207022. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  207023. {
  207024. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207025. Image bitmap (nativeBitmap);
  207026. {
  207027. Graphics g (bitmap);
  207028. g.drawImageAt (image, 0, 0);
  207029. }
  207030. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207031. ICONINFO info;
  207032. info.fIcon = isIcon;
  207033. info.xHotspot = hotspotX;
  207034. info.yHotspot = hotspotY;
  207035. info.hbmMask = mask;
  207036. info.hbmColor = nativeBitmap->hBitmap;
  207037. HICON hi = CreateIconIndirect (&info);
  207038. DeleteObject (mask);
  207039. return hi;
  207040. }
  207041. }
  207042. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  207043. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  207044. {
  207045. SHORT k = (SHORT) keyCode;
  207046. if ((keyCode & extendedKeyModifier) == 0
  207047. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  207048. k += (SHORT) 'A' - (SHORT) 'a';
  207049. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  207050. (SHORT) '+', VK_OEM_PLUS,
  207051. (SHORT) '-', VK_OEM_MINUS,
  207052. (SHORT) '.', VK_OEM_PERIOD,
  207053. (SHORT) ';', VK_OEM_1,
  207054. (SHORT) ':', VK_OEM_1,
  207055. (SHORT) '/', VK_OEM_2,
  207056. (SHORT) '?', VK_OEM_2,
  207057. (SHORT) '[', VK_OEM_4,
  207058. (SHORT) ']', VK_OEM_6 };
  207059. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  207060. if (k == translatedValues [i])
  207061. k = translatedValues [i + 1];
  207062. return (GetKeyState (k) & 0x8000) != 0;
  207063. }
  207064. class Win32ComponentPeer : public ComponentPeer
  207065. {
  207066. public:
  207067. enum RenderingEngineType
  207068. {
  207069. softwareRenderingEngine = 0,
  207070. direct2DRenderingEngine
  207071. };
  207072. Win32ComponentPeer (Component* const component,
  207073. const int windowStyleFlags,
  207074. HWND parentToAddTo_)
  207075. : ComponentPeer (component, windowStyleFlags),
  207076. dontRepaint (false),
  207077. #if JUCE_DIRECT2D
  207078. currentRenderingEngine (direct2DRenderingEngine),
  207079. #else
  207080. currentRenderingEngine (softwareRenderingEngine),
  207081. #endif
  207082. fullScreen (false),
  207083. isDragging (false),
  207084. isMouseOver (false),
  207085. hasCreatedCaret (false),
  207086. constrainerIsResizing (false),
  207087. currentWindowIcon (0),
  207088. dropTarget (0),
  207089. updateLayeredWindowAlpha (255),
  207090. parentToAddTo (parentToAddTo_)
  207091. {
  207092. callFunctionIfNotLocked (&createWindowCallback, this);
  207093. setTitle (component->getName());
  207094. if ((windowStyleFlags & windowHasDropShadow) != 0
  207095. && Desktop::canUseSemiTransparentWindows())
  207096. {
  207097. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  207098. if (shadower != 0)
  207099. shadower->setOwner (component);
  207100. }
  207101. }
  207102. ~Win32ComponentPeer()
  207103. {
  207104. setTaskBarIcon (Image());
  207105. shadower = 0;
  207106. // do this before the next bit to avoid messages arriving for this window
  207107. // before it's destroyed
  207108. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  207109. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  207110. if (currentWindowIcon != 0)
  207111. DestroyIcon (currentWindowIcon);
  207112. if (dropTarget != 0)
  207113. {
  207114. dropTarget->Release();
  207115. dropTarget = 0;
  207116. }
  207117. #if JUCE_DIRECT2D
  207118. direct2DContext = 0;
  207119. #endif
  207120. }
  207121. void* getNativeHandle() const
  207122. {
  207123. return hwnd;
  207124. }
  207125. void setVisible (bool shouldBeVisible)
  207126. {
  207127. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207128. if (shouldBeVisible)
  207129. InvalidateRect (hwnd, 0, 0);
  207130. else
  207131. lastPaintTime = 0;
  207132. }
  207133. void setTitle (const String& title)
  207134. {
  207135. SetWindowText (hwnd, title);
  207136. }
  207137. void setPosition (int x, int y)
  207138. {
  207139. offsetWithinParent (x, y);
  207140. SetWindowPos (hwnd, 0,
  207141. x - windowBorder.getLeft(),
  207142. y - windowBorder.getTop(),
  207143. 0, 0,
  207144. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207145. }
  207146. void repaintNowIfTransparent()
  207147. {
  207148. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207149. handlePaintMessage();
  207150. }
  207151. void updateBorderSize()
  207152. {
  207153. WINDOWINFO info;
  207154. info.cbSize = sizeof (info);
  207155. if (GetWindowInfo (hwnd, &info))
  207156. {
  207157. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  207158. info.rcClient.left - info.rcWindow.left,
  207159. info.rcWindow.bottom - info.rcClient.bottom,
  207160. info.rcWindow.right - info.rcClient.right);
  207161. }
  207162. #if JUCE_DIRECT2D
  207163. if (direct2DContext != 0)
  207164. direct2DContext->resized();
  207165. #endif
  207166. }
  207167. void setSize (int w, int h)
  207168. {
  207169. SetWindowPos (hwnd, 0, 0, 0,
  207170. w + windowBorder.getLeftAndRight(),
  207171. h + windowBorder.getTopAndBottom(),
  207172. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207173. updateBorderSize();
  207174. repaintNowIfTransparent();
  207175. }
  207176. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207177. {
  207178. fullScreen = isNowFullScreen;
  207179. offsetWithinParent (x, y);
  207180. SetWindowPos (hwnd, 0,
  207181. x - windowBorder.getLeft(),
  207182. y - windowBorder.getTop(),
  207183. w + windowBorder.getLeftAndRight(),
  207184. h + windowBorder.getTopAndBottom(),
  207185. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207186. updateBorderSize();
  207187. repaintNowIfTransparent();
  207188. }
  207189. const Rectangle<int> getBounds() const
  207190. {
  207191. RECT r;
  207192. GetWindowRect (hwnd, &r);
  207193. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207194. HWND parentH = GetParent (hwnd);
  207195. if (parentH != 0)
  207196. {
  207197. GetWindowRect (parentH, &r);
  207198. bounds.translate (-r.left, -r.top);
  207199. }
  207200. return windowBorder.subtractedFrom (bounds);
  207201. }
  207202. const Point<int> getScreenPosition() const
  207203. {
  207204. RECT r;
  207205. GetWindowRect (hwnd, &r);
  207206. return Point<int> (r.left + windowBorder.getLeft(),
  207207. r.top + windowBorder.getTop());
  207208. }
  207209. const Point<int> localToGlobal (const Point<int>& relativePosition)
  207210. {
  207211. return relativePosition + getScreenPosition();
  207212. }
  207213. const Point<int> globalToLocal (const Point<int>& screenPosition)
  207214. {
  207215. return screenPosition - getScreenPosition();
  207216. }
  207217. void setAlpha (float newAlpha)
  207218. {
  207219. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207220. if (component->isOpaque())
  207221. {
  207222. if (newAlpha < 1.0f)
  207223. {
  207224. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207225. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207226. }
  207227. else
  207228. {
  207229. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207230. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207231. }
  207232. }
  207233. else
  207234. {
  207235. updateLayeredWindowAlpha = intAlpha;
  207236. component->repaint();
  207237. }
  207238. }
  207239. void setMinimised (bool shouldBeMinimised)
  207240. {
  207241. if (shouldBeMinimised != isMinimised())
  207242. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207243. }
  207244. bool isMinimised() const
  207245. {
  207246. WINDOWPLACEMENT wp;
  207247. wp.length = sizeof (WINDOWPLACEMENT);
  207248. GetWindowPlacement (hwnd, &wp);
  207249. return wp.showCmd == SW_SHOWMINIMIZED;
  207250. }
  207251. void setFullScreen (bool shouldBeFullScreen)
  207252. {
  207253. setMinimised (false);
  207254. if (fullScreen != shouldBeFullScreen)
  207255. {
  207256. fullScreen = shouldBeFullScreen;
  207257. const WeakReference<Component> deletionChecker (component);
  207258. if (! fullScreen)
  207259. {
  207260. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207261. if (hasTitleBar())
  207262. ShowWindow (hwnd, SW_SHOWNORMAL);
  207263. if (! boundsCopy.isEmpty())
  207264. {
  207265. setBounds (boundsCopy.getX(),
  207266. boundsCopy.getY(),
  207267. boundsCopy.getWidth(),
  207268. boundsCopy.getHeight(),
  207269. false);
  207270. }
  207271. }
  207272. else
  207273. {
  207274. if (hasTitleBar())
  207275. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207276. else
  207277. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207278. }
  207279. if (deletionChecker != 0)
  207280. handleMovedOrResized();
  207281. }
  207282. }
  207283. bool isFullScreen() const
  207284. {
  207285. if (! hasTitleBar())
  207286. return fullScreen;
  207287. WINDOWPLACEMENT wp;
  207288. wp.length = sizeof (wp);
  207289. GetWindowPlacement (hwnd, &wp);
  207290. return wp.showCmd == SW_SHOWMAXIMIZED;
  207291. }
  207292. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207293. {
  207294. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  207295. && isPositiveAndBelow (position.getY(), component->getHeight())))
  207296. return false;
  207297. RECT r;
  207298. GetWindowRect (hwnd, &r);
  207299. POINT p;
  207300. p.x = position.getX() + r.left + windowBorder.getLeft();
  207301. p.y = position.getY() + r.top + windowBorder.getTop();
  207302. HWND w = WindowFromPoint (p);
  207303. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207304. }
  207305. const BorderSize getFrameSize() const
  207306. {
  207307. return windowBorder;
  207308. }
  207309. bool setAlwaysOnTop (bool alwaysOnTop)
  207310. {
  207311. const bool oldDeactivate = shouldDeactivateTitleBar;
  207312. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207313. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207314. 0, 0, 0, 0,
  207315. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207316. shouldDeactivateTitleBar = oldDeactivate;
  207317. if (shadower != 0)
  207318. shadower->componentBroughtToFront (*component);
  207319. return true;
  207320. }
  207321. void toFront (bool makeActive)
  207322. {
  207323. setMinimised (false);
  207324. const bool oldDeactivate = shouldDeactivateTitleBar;
  207325. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207326. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207327. shouldDeactivateTitleBar = oldDeactivate;
  207328. if (! makeActive)
  207329. {
  207330. // in this case a broughttofront call won't have occured, so do it now..
  207331. handleBroughtToFront();
  207332. }
  207333. }
  207334. void toBehind (ComponentPeer* other)
  207335. {
  207336. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207337. jassert (otherPeer != 0); // wrong type of window?
  207338. if (otherPeer != 0)
  207339. {
  207340. setMinimised (false);
  207341. // must be careful not to try to put a topmost window behind a normal one, or win32
  207342. // promotes the normal one to be topmost!
  207343. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207344. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207345. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207346. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207347. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207348. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207349. }
  207350. }
  207351. bool isFocused() const
  207352. {
  207353. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207354. }
  207355. void grabFocus()
  207356. {
  207357. const bool oldDeactivate = shouldDeactivateTitleBar;
  207358. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207359. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207360. shouldDeactivateTitleBar = oldDeactivate;
  207361. }
  207362. void textInputRequired (const Point<int>&)
  207363. {
  207364. if (! hasCreatedCaret)
  207365. {
  207366. hasCreatedCaret = true;
  207367. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207368. }
  207369. ShowCaret (hwnd);
  207370. SetCaretPos (0, 0);
  207371. }
  207372. void repaint (const Rectangle<int>& area)
  207373. {
  207374. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207375. InvalidateRect (hwnd, &r, FALSE);
  207376. }
  207377. void performAnyPendingRepaintsNow()
  207378. {
  207379. MSG m;
  207380. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207381. DispatchMessage (&m);
  207382. }
  207383. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207384. {
  207385. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207386. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207387. return 0;
  207388. }
  207389. void setTaskBarIcon (const Image& image)
  207390. {
  207391. if (image.isValid())
  207392. {
  207393. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207394. if (taskBarIcon == 0)
  207395. {
  207396. taskBarIcon = new NOTIFYICONDATA();
  207397. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  207398. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207399. taskBarIcon->hWnd = (HWND) hwnd;
  207400. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207401. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207402. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207403. taskBarIcon->hIcon = hicon;
  207404. taskBarIcon->szTip[0] = 0;
  207405. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207406. }
  207407. else
  207408. {
  207409. HICON oldIcon = taskBarIcon->hIcon;
  207410. taskBarIcon->hIcon = hicon;
  207411. taskBarIcon->uFlags = NIF_ICON;
  207412. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207413. DestroyIcon (oldIcon);
  207414. }
  207415. }
  207416. else if (taskBarIcon != 0)
  207417. {
  207418. taskBarIcon->uFlags = 0;
  207419. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207420. DestroyIcon (taskBarIcon->hIcon);
  207421. taskBarIcon = 0;
  207422. }
  207423. }
  207424. void setTaskBarIconToolTip (const String& toolTip) const
  207425. {
  207426. if (taskBarIcon != 0)
  207427. {
  207428. taskBarIcon->uFlags = NIF_TIP;
  207429. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207430. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207431. }
  207432. }
  207433. void handleTaskBarEvent (const LPARAM lParam)
  207434. {
  207435. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207436. {
  207437. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207438. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207439. {
  207440. Component* const current = Component::getCurrentlyModalComponent();
  207441. if (current != 0)
  207442. current->inputAttemptWhenModal();
  207443. }
  207444. }
  207445. else
  207446. {
  207447. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  207448. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207449. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  207450. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207451. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  207452. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207453. eventMods = eventMods.withoutMouseButtons();
  207454. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  207455. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  207456. Point<int>(), Time (getMouseEventTime()), 1, false);
  207457. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207458. {
  207459. SetFocus (hwnd);
  207460. SetForegroundWindow (hwnd);
  207461. component->mouseDown (e);
  207462. }
  207463. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207464. {
  207465. component->mouseUp (e);
  207466. }
  207467. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207468. {
  207469. component->mouseDoubleClick (e);
  207470. }
  207471. else if (lParam == WM_MOUSEMOVE)
  207472. {
  207473. component->mouseMove (e);
  207474. }
  207475. }
  207476. }
  207477. bool isInside (HWND h) const
  207478. {
  207479. return GetAncestor (hwnd, GA_ROOT) == h;
  207480. }
  207481. static void updateKeyModifiers() throw()
  207482. {
  207483. int keyMods = 0;
  207484. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207485. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207486. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207487. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207488. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207489. }
  207490. static void updateModifiersFromWParam (const WPARAM wParam)
  207491. {
  207492. int mouseMods = 0;
  207493. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207494. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207495. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207496. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207497. updateKeyModifiers();
  207498. }
  207499. static int64 getMouseEventTime()
  207500. {
  207501. static int64 eventTimeOffset = 0;
  207502. static DWORD lastMessageTime = 0;
  207503. const DWORD thisMessageTime = GetMessageTime();
  207504. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207505. {
  207506. lastMessageTime = thisMessageTime;
  207507. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207508. }
  207509. return eventTimeOffset + thisMessageTime;
  207510. }
  207511. bool dontRepaint;
  207512. static ModifierKeys currentModifiers;
  207513. static ModifierKeys modifiersAtLastCallback;
  207514. private:
  207515. HWND hwnd, parentToAddTo;
  207516. ScopedPointer<DropShadower> shadower;
  207517. RenderingEngineType currentRenderingEngine;
  207518. #if JUCE_DIRECT2D
  207519. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207520. #endif
  207521. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  207522. BorderSize windowBorder;
  207523. HICON currentWindowIcon;
  207524. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207525. IDropTarget* dropTarget;
  207526. uint8 updateLayeredWindowAlpha;
  207527. class TemporaryImage : public Timer
  207528. {
  207529. public:
  207530. TemporaryImage() {}
  207531. ~TemporaryImage() {}
  207532. const Image& getImage (const bool transparent, const int w, const int h)
  207533. {
  207534. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207535. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207536. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207537. startTimer (3000);
  207538. return image;
  207539. }
  207540. void timerCallback()
  207541. {
  207542. stopTimer();
  207543. image = Image::null;
  207544. }
  207545. private:
  207546. Image image;
  207547. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207548. };
  207549. TemporaryImage offscreenImageGenerator;
  207550. class WindowClassHolder : public DeletedAtShutdown
  207551. {
  207552. public:
  207553. WindowClassHolder()
  207554. : windowClassName ("JUCE_")
  207555. {
  207556. // this name has to be different for each app/dll instance because otherwise
  207557. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207558. // window class).
  207559. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207560. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207561. TCHAR moduleFile [1024];
  207562. moduleFile[0] = 0;
  207563. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207564. WORD iconNum = 0;
  207565. WNDCLASSEX wcex;
  207566. wcex.cbSize = sizeof (wcex);
  207567. wcex.style = CS_OWNDC;
  207568. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207569. wcex.lpszClassName = windowClassName;
  207570. wcex.cbClsExtra = 0;
  207571. wcex.cbWndExtra = 32;
  207572. wcex.hInstance = moduleHandle;
  207573. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207574. iconNum = 1;
  207575. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207576. wcex.hCursor = 0;
  207577. wcex.hbrBackground = 0;
  207578. wcex.lpszMenuName = 0;
  207579. RegisterClassEx (&wcex);
  207580. }
  207581. ~WindowClassHolder()
  207582. {
  207583. if (ComponentPeer::getNumPeers() == 0)
  207584. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207585. clearSingletonInstance();
  207586. }
  207587. String windowClassName;
  207588. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207589. };
  207590. static void* createWindowCallback (void* userData)
  207591. {
  207592. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207593. return 0;
  207594. }
  207595. void createWindow()
  207596. {
  207597. DWORD exstyle = WS_EX_ACCEPTFILES;
  207598. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207599. if (hasTitleBar())
  207600. {
  207601. type |= WS_OVERLAPPED;
  207602. if ((styleFlags & windowHasCloseButton) != 0)
  207603. {
  207604. type |= WS_SYSMENU;
  207605. }
  207606. else
  207607. {
  207608. // annoyingly, windows won't let you have a min/max button without a close button
  207609. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207610. }
  207611. if ((styleFlags & windowIsResizable) != 0)
  207612. type |= WS_THICKFRAME;
  207613. }
  207614. else if (parentToAddTo != 0)
  207615. {
  207616. type |= WS_CHILD;
  207617. }
  207618. else
  207619. {
  207620. type |= WS_POPUP | WS_SYSMENU;
  207621. }
  207622. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207623. exstyle |= WS_EX_TOOLWINDOW;
  207624. else
  207625. exstyle |= WS_EX_APPWINDOW;
  207626. if ((styleFlags & windowHasMinimiseButton) != 0)
  207627. type |= WS_MINIMIZEBOX;
  207628. if ((styleFlags & windowHasMaximiseButton) != 0)
  207629. type |= WS_MAXIMIZEBOX;
  207630. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207631. exstyle |= WS_EX_TRANSPARENT;
  207632. if ((styleFlags & windowIsSemiTransparent) != 0
  207633. && Desktop::canUseSemiTransparentWindows())
  207634. exstyle |= WS_EX_LAYERED;
  207635. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207636. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207637. #if JUCE_DIRECT2D
  207638. updateDirect2DContext();
  207639. #endif
  207640. if (hwnd != 0)
  207641. {
  207642. SetWindowLongPtr (hwnd, 0, 0);
  207643. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207644. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207645. if (dropTarget == 0)
  207646. dropTarget = new JuceDropTarget (this);
  207647. RegisterDragDrop (hwnd, dropTarget);
  207648. updateBorderSize();
  207649. // Calling this function here is (for some reason) necessary to make Windows
  207650. // correctly enable the menu items that we specify in the wm_initmenu message.
  207651. GetSystemMenu (hwnd, false);
  207652. const float alpha = component->getAlpha();
  207653. if (alpha < 1.0f)
  207654. setAlpha (alpha);
  207655. }
  207656. else
  207657. {
  207658. jassertfalse;
  207659. }
  207660. }
  207661. static void* destroyWindowCallback (void* handle)
  207662. {
  207663. RevokeDragDrop ((HWND) handle);
  207664. DestroyWindow ((HWND) handle);
  207665. return 0;
  207666. }
  207667. static void* toFrontCallback1 (void* h)
  207668. {
  207669. SetForegroundWindow ((HWND) h);
  207670. return 0;
  207671. }
  207672. static void* toFrontCallback2 (void* h)
  207673. {
  207674. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207675. return 0;
  207676. }
  207677. static void* setFocusCallback (void* h)
  207678. {
  207679. SetFocus ((HWND) h);
  207680. return 0;
  207681. }
  207682. static void* getFocusCallback (void*)
  207683. {
  207684. return GetFocus();
  207685. }
  207686. void offsetWithinParent (int& x, int& y) const
  207687. {
  207688. if (isUsingUpdateLayeredWindow())
  207689. {
  207690. HWND parentHwnd = GetParent (hwnd);
  207691. if (parentHwnd != 0)
  207692. {
  207693. RECT parentRect;
  207694. GetWindowRect (parentHwnd, &parentRect);
  207695. x += parentRect.left;
  207696. y += parentRect.top;
  207697. }
  207698. }
  207699. }
  207700. bool isUsingUpdateLayeredWindow() const
  207701. {
  207702. return ! component->isOpaque();
  207703. }
  207704. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207705. void setIcon (const Image& newIcon)
  207706. {
  207707. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207708. if (hicon != 0)
  207709. {
  207710. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207711. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207712. if (currentWindowIcon != 0)
  207713. DestroyIcon (currentWindowIcon);
  207714. currentWindowIcon = hicon;
  207715. }
  207716. }
  207717. void handlePaintMessage()
  207718. {
  207719. #if JUCE_DIRECT2D
  207720. if (direct2DContext != 0)
  207721. {
  207722. RECT r;
  207723. if (GetUpdateRect (hwnd, &r, false))
  207724. {
  207725. direct2DContext->start();
  207726. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207727. handlePaint (*direct2DContext);
  207728. direct2DContext->end();
  207729. }
  207730. }
  207731. else
  207732. #endif
  207733. {
  207734. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207735. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207736. PAINTSTRUCT paintStruct;
  207737. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207738. // message and become re-entrant, but that's OK
  207739. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207740. // corrupt the image it's using to paint into, so do a check here.
  207741. static bool reentrant = false;
  207742. if (reentrant)
  207743. {
  207744. DeleteObject (rgn);
  207745. EndPaint (hwnd, &paintStruct);
  207746. return;
  207747. }
  207748. reentrant = true;
  207749. // this is the rectangle to update..
  207750. int x = paintStruct.rcPaint.left;
  207751. int y = paintStruct.rcPaint.top;
  207752. int w = paintStruct.rcPaint.right - x;
  207753. int h = paintStruct.rcPaint.bottom - y;
  207754. const bool transparent = isUsingUpdateLayeredWindow();
  207755. if (transparent)
  207756. {
  207757. // it's not possible to have a transparent window with a title bar at the moment!
  207758. jassert (! hasTitleBar());
  207759. RECT r;
  207760. GetWindowRect (hwnd, &r);
  207761. x = y = 0;
  207762. w = r.right - r.left;
  207763. h = r.bottom - r.top;
  207764. }
  207765. if (w > 0 && h > 0)
  207766. {
  207767. clearMaskedRegion();
  207768. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207769. RectangleList contextClip;
  207770. const Rectangle<int> clipBounds (0, 0, w, h);
  207771. bool needToPaintAll = true;
  207772. if (regionType == COMPLEXREGION && ! transparent)
  207773. {
  207774. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207775. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207776. DeleteObject (clipRgn);
  207777. char rgnData [8192];
  207778. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207779. if (res > 0 && res <= sizeof (rgnData))
  207780. {
  207781. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207782. if (hdr->iType == RDH_RECTANGLES
  207783. && hdr->rcBound.right - hdr->rcBound.left >= w
  207784. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207785. {
  207786. needToPaintAll = false;
  207787. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207788. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207789. while (--num >= 0)
  207790. {
  207791. if (rects->right <= x + w && rects->bottom <= y + h)
  207792. {
  207793. const int cx = jmax (x, (int) rects->left);
  207794. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207795. .getIntersection (clipBounds));
  207796. }
  207797. else
  207798. {
  207799. needToPaintAll = true;
  207800. break;
  207801. }
  207802. ++rects;
  207803. }
  207804. }
  207805. }
  207806. }
  207807. if (needToPaintAll)
  207808. {
  207809. contextClip.clear();
  207810. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207811. }
  207812. if (transparent)
  207813. {
  207814. RectangleList::Iterator i (contextClip);
  207815. while (i.next())
  207816. offscreenImage.clear (*i.getRectangle());
  207817. }
  207818. // if the component's not opaque, this won't draw properly unless the platform can support this
  207819. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207820. updateCurrentModifiers();
  207821. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207822. handlePaint (context);
  207823. if (! dontRepaint)
  207824. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207825. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207826. }
  207827. DeleteObject (rgn);
  207828. EndPaint (hwnd, &paintStruct);
  207829. reentrant = false;
  207830. }
  207831. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207832. _fpreset(); // because some graphics cards can unmask FP exceptions
  207833. #endif
  207834. lastPaintTime = Time::getMillisecondCounter();
  207835. }
  207836. void doMouseEvent (const Point<int>& position)
  207837. {
  207838. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207839. }
  207840. const StringArray getAvailableRenderingEngines()
  207841. {
  207842. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207843. #if JUCE_DIRECT2D
  207844. // xxx is this correct? Seems to enable it on Vista too??
  207845. OSVERSIONINFO info;
  207846. zerostruct (info);
  207847. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207848. GetVersionEx (&info);
  207849. if (info.dwMajorVersion >= 6)
  207850. s.add ("Direct2D");
  207851. #endif
  207852. return s;
  207853. }
  207854. int getCurrentRenderingEngine() throw()
  207855. {
  207856. return currentRenderingEngine;
  207857. }
  207858. #if JUCE_DIRECT2D
  207859. void updateDirect2DContext()
  207860. {
  207861. if (currentRenderingEngine != direct2DRenderingEngine)
  207862. direct2DContext = 0;
  207863. else if (direct2DContext == 0)
  207864. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207865. }
  207866. #endif
  207867. void setCurrentRenderingEngine (int index)
  207868. {
  207869. (void) index;
  207870. #if JUCE_DIRECT2D
  207871. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207872. updateDirect2DContext();
  207873. repaint (component->getLocalBounds());
  207874. #endif
  207875. }
  207876. void doMouseMove (const Point<int>& position)
  207877. {
  207878. if (! isMouseOver)
  207879. {
  207880. isMouseOver = true;
  207881. updateKeyModifiers();
  207882. TRACKMOUSEEVENT tme;
  207883. tme.cbSize = sizeof (tme);
  207884. tme.dwFlags = TME_LEAVE;
  207885. tme.hwndTrack = hwnd;
  207886. tme.dwHoverTime = 0;
  207887. if (! TrackMouseEvent (&tme))
  207888. jassertfalse;
  207889. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207890. }
  207891. else if (! isDragging)
  207892. {
  207893. if (! contains (position, false))
  207894. return;
  207895. }
  207896. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207897. static uint32 lastMouseTime = 0;
  207898. const uint32 now = Time::getMillisecondCounter();
  207899. const int maxMouseMovesPerSecond = 60;
  207900. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207901. {
  207902. lastMouseTime = now;
  207903. doMouseEvent (position);
  207904. }
  207905. }
  207906. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207907. {
  207908. if (GetCapture() != hwnd)
  207909. SetCapture (hwnd);
  207910. doMouseMove (position);
  207911. updateModifiersFromWParam (wParam);
  207912. isDragging = true;
  207913. doMouseEvent (position);
  207914. }
  207915. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207916. {
  207917. updateModifiersFromWParam (wParam);
  207918. isDragging = false;
  207919. // release the mouse capture if the user has released all buttons
  207920. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207921. ReleaseCapture();
  207922. doMouseEvent (position);
  207923. }
  207924. void doCaptureChanged()
  207925. {
  207926. if (constrainerIsResizing)
  207927. {
  207928. if (constrainer != 0)
  207929. constrainer->resizeEnd();
  207930. constrainerIsResizing = false;
  207931. }
  207932. if (isDragging)
  207933. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207934. }
  207935. void doMouseExit()
  207936. {
  207937. isMouseOver = false;
  207938. doMouseEvent (getCurrentMousePos());
  207939. }
  207940. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207941. {
  207942. updateKeyModifiers();
  207943. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207944. handleMouseWheel (0, position, getMouseEventTime(),
  207945. isVertical ? 0.0f : amount,
  207946. isVertical ? amount : 0.0f);
  207947. }
  207948. void sendModifierKeyChangeIfNeeded()
  207949. {
  207950. if (modifiersAtLastCallback != currentModifiers)
  207951. {
  207952. modifiersAtLastCallback = currentModifiers;
  207953. handleModifierKeysChange();
  207954. }
  207955. }
  207956. bool doKeyUp (const WPARAM key)
  207957. {
  207958. updateKeyModifiers();
  207959. switch (key)
  207960. {
  207961. case VK_SHIFT:
  207962. case VK_CONTROL:
  207963. case VK_MENU:
  207964. case VK_CAPITAL:
  207965. case VK_LWIN:
  207966. case VK_RWIN:
  207967. case VK_APPS:
  207968. case VK_NUMLOCK:
  207969. case VK_SCROLL:
  207970. case VK_LSHIFT:
  207971. case VK_RSHIFT:
  207972. case VK_LCONTROL:
  207973. case VK_LMENU:
  207974. case VK_RCONTROL:
  207975. case VK_RMENU:
  207976. sendModifierKeyChangeIfNeeded();
  207977. }
  207978. return handleKeyUpOrDown (false)
  207979. || Component::getCurrentlyModalComponent() != 0;
  207980. }
  207981. bool doKeyDown (const WPARAM key)
  207982. {
  207983. updateKeyModifiers();
  207984. bool used = false;
  207985. switch (key)
  207986. {
  207987. case VK_SHIFT:
  207988. case VK_LSHIFT:
  207989. case VK_RSHIFT:
  207990. case VK_CONTROL:
  207991. case VK_LCONTROL:
  207992. case VK_RCONTROL:
  207993. case VK_MENU:
  207994. case VK_LMENU:
  207995. case VK_RMENU:
  207996. case VK_LWIN:
  207997. case VK_RWIN:
  207998. case VK_CAPITAL:
  207999. case VK_NUMLOCK:
  208000. case VK_SCROLL:
  208001. case VK_APPS:
  208002. sendModifierKeyChangeIfNeeded();
  208003. break;
  208004. case VK_LEFT:
  208005. case VK_RIGHT:
  208006. case VK_UP:
  208007. case VK_DOWN:
  208008. case VK_PRIOR:
  208009. case VK_NEXT:
  208010. case VK_HOME:
  208011. case VK_END:
  208012. case VK_DELETE:
  208013. case VK_INSERT:
  208014. case VK_F1:
  208015. case VK_F2:
  208016. case VK_F3:
  208017. case VK_F4:
  208018. case VK_F5:
  208019. case VK_F6:
  208020. case VK_F7:
  208021. case VK_F8:
  208022. case VK_F9:
  208023. case VK_F10:
  208024. case VK_F11:
  208025. case VK_F12:
  208026. case VK_F13:
  208027. case VK_F14:
  208028. case VK_F15:
  208029. case VK_F16:
  208030. used = handleKeyUpOrDown (true);
  208031. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  208032. break;
  208033. case VK_ADD:
  208034. case VK_SUBTRACT:
  208035. case VK_MULTIPLY:
  208036. case VK_DIVIDE:
  208037. case VK_SEPARATOR:
  208038. case VK_DECIMAL:
  208039. used = handleKeyUpOrDown (true);
  208040. break;
  208041. default:
  208042. used = handleKeyUpOrDown (true);
  208043. {
  208044. MSG msg;
  208045. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  208046. {
  208047. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  208048. // manually generate the key-press event that matches this key-down.
  208049. const UINT keyChar = MapVirtualKey (key, 2);
  208050. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  208051. }
  208052. }
  208053. break;
  208054. }
  208055. if (Component::getCurrentlyModalComponent() != 0)
  208056. used = true;
  208057. return used;
  208058. }
  208059. bool doKeyChar (int key, const LPARAM flags)
  208060. {
  208061. updateKeyModifiers();
  208062. juce_wchar textChar = (juce_wchar) key;
  208063. const int virtualScanCode = (flags >> 16) & 0xff;
  208064. if (key >= '0' && key <= '9')
  208065. {
  208066. switch (virtualScanCode) // check for a numeric keypad scan-code
  208067. {
  208068. case 0x52:
  208069. case 0x4f:
  208070. case 0x50:
  208071. case 0x51:
  208072. case 0x4b:
  208073. case 0x4c:
  208074. case 0x4d:
  208075. case 0x47:
  208076. case 0x48:
  208077. case 0x49:
  208078. key = (key - '0') + KeyPress::numberPad0;
  208079. break;
  208080. default:
  208081. break;
  208082. }
  208083. }
  208084. else
  208085. {
  208086. // convert the scan code to an unmodified character code..
  208087. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  208088. UINT keyChar = MapVirtualKey (virtualKey, 2);
  208089. keyChar = LOWORD (keyChar);
  208090. if (keyChar != 0)
  208091. key = (int) keyChar;
  208092. // avoid sending junk text characters for some control-key combinations
  208093. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  208094. textChar = 0;
  208095. }
  208096. return handleKeyPress (key, textChar);
  208097. }
  208098. bool doAppCommand (const LPARAM lParam)
  208099. {
  208100. int key = 0;
  208101. switch (GET_APPCOMMAND_LPARAM (lParam))
  208102. {
  208103. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  208104. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  208105. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  208106. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  208107. default: break;
  208108. }
  208109. if (key != 0)
  208110. {
  208111. updateKeyModifiers();
  208112. if (hwnd == GetActiveWindow())
  208113. {
  208114. handleKeyPress (key, 0);
  208115. return true;
  208116. }
  208117. }
  208118. return false;
  208119. }
  208120. bool isConstrainedNativeWindow() const
  208121. {
  208122. return constrainer != 0
  208123. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  208124. }
  208125. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  208126. {
  208127. if (isConstrainedNativeWindow())
  208128. {
  208129. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208130. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208131. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208132. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208133. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208134. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208135. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208136. r->left = pos.getX();
  208137. r->top = pos.getY();
  208138. r->right = pos.getRight();
  208139. r->bottom = pos.getBottom();
  208140. }
  208141. return TRUE;
  208142. }
  208143. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  208144. {
  208145. if (isConstrainedNativeWindow())
  208146. {
  208147. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208148. && ! Component::isMouseButtonDownAnywhere())
  208149. {
  208150. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208151. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208152. constrainer->checkBounds (pos, current,
  208153. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208154. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208155. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208156. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208157. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208158. wp->x = pos.getX();
  208159. wp->y = pos.getY();
  208160. wp->cx = pos.getWidth();
  208161. wp->cy = pos.getHeight();
  208162. }
  208163. }
  208164. return 0;
  208165. }
  208166. void handleAppActivation (const WPARAM wParam)
  208167. {
  208168. modifiersAtLastCallback = -1;
  208169. updateKeyModifiers();
  208170. if (isMinimised())
  208171. {
  208172. component->repaint();
  208173. handleMovedOrResized();
  208174. if (! ComponentPeer::isValidPeer (this))
  208175. return;
  208176. }
  208177. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  208178. {
  208179. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  208180. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208181. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208182. }
  208183. else
  208184. {
  208185. handleBroughtToFront();
  208186. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208187. Component::getCurrentlyModalComponent()->toFront (true);
  208188. }
  208189. }
  208190. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  208191. {
  208192. public:
  208193. JuceDropTarget (Win32ComponentPeer* const owner_)
  208194. : owner (owner_)
  208195. {
  208196. }
  208197. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208198. {
  208199. updateFileList (pDataObject);
  208200. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208201. *pdwEffect = DROPEFFECT_COPY;
  208202. return S_OK;
  208203. }
  208204. HRESULT __stdcall DragLeave()
  208205. {
  208206. owner->handleFileDragExit (files);
  208207. return S_OK;
  208208. }
  208209. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208210. {
  208211. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208212. *pdwEffect = DROPEFFECT_COPY;
  208213. return S_OK;
  208214. }
  208215. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208216. {
  208217. updateFileList (pDataObject);
  208218. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  208219. *pdwEffect = DROPEFFECT_COPY;
  208220. return S_OK;
  208221. }
  208222. private:
  208223. Win32ComponentPeer* const owner;
  208224. StringArray files;
  208225. void updateFileList (IDataObject* const pDataObject)
  208226. {
  208227. files.clear();
  208228. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208229. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208230. if (pDataObject->GetData (&format, &medium) == S_OK)
  208231. {
  208232. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208233. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208234. unsigned int i = 0;
  208235. if (pDropFiles->fWide)
  208236. {
  208237. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  208238. for (;;)
  208239. {
  208240. unsigned int len = 0;
  208241. while (i + len < totalLen && fname [i + len] != 0)
  208242. ++len;
  208243. if (len == 0)
  208244. break;
  208245. files.add (String (fname + i, len));
  208246. i += len + 1;
  208247. }
  208248. }
  208249. else
  208250. {
  208251. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  208252. for (;;)
  208253. {
  208254. unsigned int len = 0;
  208255. while (i + len < totalLen && fname [i + len] != 0)
  208256. ++len;
  208257. if (len == 0)
  208258. break;
  208259. files.add (String (fname + i, len));
  208260. i += len + 1;
  208261. }
  208262. }
  208263. GlobalUnlock (medium.hGlobal);
  208264. }
  208265. }
  208266. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  208267. };
  208268. void doSettingChange()
  208269. {
  208270. Desktop::getInstance().refreshMonitorSizes();
  208271. if (fullScreen && ! isMinimised())
  208272. {
  208273. const Rectangle<int> r (component->getParentMonitorArea());
  208274. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208275. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208276. }
  208277. }
  208278. public:
  208279. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208280. {
  208281. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208282. if (peer != 0)
  208283. {
  208284. jassert (isValidPeer (peer));
  208285. return peer->peerWindowProc (h, message, wParam, lParam);
  208286. }
  208287. return DefWindowProcW (h, message, wParam, lParam);
  208288. }
  208289. private:
  208290. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208291. {
  208292. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208293. return callback (userData);
  208294. else
  208295. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208296. }
  208297. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208298. {
  208299. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208300. }
  208301. const Point<int> getCurrentMousePos() throw()
  208302. {
  208303. RECT wr;
  208304. GetWindowRect (hwnd, &wr);
  208305. const DWORD mp = GetMessagePos();
  208306. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208307. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208308. }
  208309. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208310. {
  208311. switch (message)
  208312. {
  208313. case WM_NCHITTEST:
  208314. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208315. return HTTRANSPARENT;
  208316. else if (! hasTitleBar())
  208317. return HTCLIENT;
  208318. break;
  208319. case WM_PAINT:
  208320. handlePaintMessage();
  208321. return 0;
  208322. case WM_NCPAINT:
  208323. if (hasTitleBar())
  208324. break;
  208325. else if (wParam != 1)
  208326. handlePaintMessage();
  208327. return 0;
  208328. case WM_ERASEBKGND:
  208329. case WM_NCCALCSIZE:
  208330. if (hasTitleBar())
  208331. break;
  208332. return 1;
  208333. case WM_MOUSEMOVE:
  208334. doMouseMove (getPointFromLParam (lParam));
  208335. return 0;
  208336. case WM_MOUSELEAVE:
  208337. doMouseExit();
  208338. return 0;
  208339. case WM_LBUTTONDOWN:
  208340. case WM_MBUTTONDOWN:
  208341. case WM_RBUTTONDOWN:
  208342. doMouseDown (getPointFromLParam (lParam), wParam);
  208343. return 0;
  208344. case WM_LBUTTONUP:
  208345. case WM_MBUTTONUP:
  208346. case WM_RBUTTONUP:
  208347. doMouseUp (getPointFromLParam (lParam), wParam);
  208348. return 0;
  208349. case WM_CAPTURECHANGED:
  208350. doCaptureChanged();
  208351. return 0;
  208352. case WM_NCMOUSEMOVE:
  208353. if (hasTitleBar())
  208354. break;
  208355. return 0;
  208356. case 0x020A: /* WM_MOUSEWHEEL */
  208357. case 0x020E: /* WM_MOUSEHWHEEL */
  208358. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  208359. return 0;
  208360. case WM_SIZING:
  208361. return handleSizeConstraining ((RECT*) lParam, wParam);
  208362. case WM_WINDOWPOSCHANGING:
  208363. return handlePositionChanging ((WINDOWPOS*) lParam);
  208364. case WM_WINDOWPOSCHANGED:
  208365. {
  208366. const Point<int> pos (getCurrentMousePos());
  208367. if (contains (pos, false))
  208368. doMouseEvent (pos);
  208369. }
  208370. handleMovedOrResized();
  208371. if (dontRepaint)
  208372. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208373. return 0;
  208374. case WM_KEYDOWN:
  208375. case WM_SYSKEYDOWN:
  208376. if (doKeyDown (wParam))
  208377. return 0;
  208378. break;
  208379. case WM_KEYUP:
  208380. case WM_SYSKEYUP:
  208381. if (doKeyUp (wParam))
  208382. return 0;
  208383. break;
  208384. case WM_CHAR:
  208385. if (doKeyChar ((int) wParam, lParam))
  208386. return 0;
  208387. break;
  208388. case WM_APPCOMMAND:
  208389. if (doAppCommand (lParam))
  208390. return TRUE;
  208391. break;
  208392. case WM_SETFOCUS:
  208393. updateKeyModifiers();
  208394. handleFocusGain();
  208395. break;
  208396. case WM_KILLFOCUS:
  208397. if (hasCreatedCaret)
  208398. {
  208399. hasCreatedCaret = false;
  208400. DestroyCaret();
  208401. }
  208402. handleFocusLoss();
  208403. break;
  208404. case WM_ACTIVATEAPP:
  208405. // Windows does weird things to process priority when you swap apps,
  208406. // so this forces an update when the app is brought to the front
  208407. if (wParam != FALSE)
  208408. juce_repeatLastProcessPriority();
  208409. else
  208410. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208411. juce_CheckCurrentlyFocusedTopLevelWindow();
  208412. modifiersAtLastCallback = -1;
  208413. return 0;
  208414. case WM_ACTIVATE:
  208415. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208416. {
  208417. handleAppActivation (wParam);
  208418. return 0;
  208419. }
  208420. break;
  208421. case WM_NCACTIVATE:
  208422. // while a temporary window is being shown, prevent Windows from deactivating the
  208423. // title bars of our main windows.
  208424. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208425. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208426. break;
  208427. case WM_MOUSEACTIVATE:
  208428. if (! component->getMouseClickGrabsKeyboardFocus())
  208429. return MA_NOACTIVATE;
  208430. break;
  208431. case WM_SHOWWINDOW:
  208432. if (wParam != 0)
  208433. handleBroughtToFront();
  208434. break;
  208435. case WM_CLOSE:
  208436. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208437. handleUserClosingWindow();
  208438. return 0;
  208439. case WM_QUERYENDSESSION:
  208440. if (JUCEApplication::getInstance() != 0)
  208441. {
  208442. JUCEApplication::getInstance()->systemRequestedQuit();
  208443. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208444. }
  208445. return TRUE;
  208446. case WM_TRAYNOTIFY:
  208447. handleTaskBarEvent (lParam);
  208448. break;
  208449. case WM_SYNCPAINT:
  208450. return 0;
  208451. case WM_DISPLAYCHANGE:
  208452. InvalidateRect (h, 0, 0);
  208453. // intentional fall-through...
  208454. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208455. doSettingChange();
  208456. break;
  208457. case WM_INITMENU:
  208458. if (! hasTitleBar())
  208459. {
  208460. if (isFullScreen())
  208461. {
  208462. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208463. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208464. }
  208465. else if (! isMinimised())
  208466. {
  208467. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208468. }
  208469. }
  208470. break;
  208471. case WM_SYSCOMMAND:
  208472. switch (wParam & 0xfff0)
  208473. {
  208474. case SC_CLOSE:
  208475. if (sendInputAttemptWhenModalMessage())
  208476. return 0;
  208477. if (hasTitleBar())
  208478. {
  208479. PostMessage (h, WM_CLOSE, 0, 0);
  208480. return 0;
  208481. }
  208482. break;
  208483. case SC_KEYMENU:
  208484. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  208485. // situations that can arise if a modal loop is started from an alt-key keypress).
  208486. if (hasTitleBar() && h == GetCapture())
  208487. ReleaseCapture();
  208488. break;
  208489. case SC_MAXIMIZE:
  208490. if (! sendInputAttemptWhenModalMessage())
  208491. setFullScreen (true);
  208492. return 0;
  208493. case SC_MINIMIZE:
  208494. if (sendInputAttemptWhenModalMessage())
  208495. return 0;
  208496. if (! hasTitleBar())
  208497. {
  208498. setMinimised (true);
  208499. return 0;
  208500. }
  208501. break;
  208502. case SC_RESTORE:
  208503. if (sendInputAttemptWhenModalMessage())
  208504. return 0;
  208505. if (hasTitleBar())
  208506. {
  208507. if (isFullScreen())
  208508. {
  208509. setFullScreen (false);
  208510. return 0;
  208511. }
  208512. }
  208513. else
  208514. {
  208515. if (isMinimised())
  208516. setMinimised (false);
  208517. else if (isFullScreen())
  208518. setFullScreen (false);
  208519. return 0;
  208520. }
  208521. break;
  208522. }
  208523. break;
  208524. case WM_NCLBUTTONDOWN:
  208525. if (! sendInputAttemptWhenModalMessage())
  208526. {
  208527. switch (wParam)
  208528. {
  208529. case HTBOTTOM:
  208530. case HTBOTTOMLEFT:
  208531. case HTBOTTOMRIGHT:
  208532. case HTGROWBOX:
  208533. case HTLEFT:
  208534. case HTRIGHT:
  208535. case HTTOP:
  208536. case HTTOPLEFT:
  208537. case HTTOPRIGHT:
  208538. if (isConstrainedNativeWindow())
  208539. {
  208540. constrainerIsResizing = true;
  208541. constrainer->resizeStart();
  208542. }
  208543. break;
  208544. default:
  208545. break;
  208546. };
  208547. }
  208548. break;
  208549. case WM_NCRBUTTONDOWN:
  208550. case WM_NCMBUTTONDOWN:
  208551. sendInputAttemptWhenModalMessage();
  208552. break;
  208553. //case WM_IME_STARTCOMPOSITION;
  208554. // return 0;
  208555. case WM_GETDLGCODE:
  208556. return DLGC_WANTALLKEYS;
  208557. default:
  208558. if (taskBarIcon != 0)
  208559. {
  208560. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208561. if (message == taskbarCreatedMessage)
  208562. {
  208563. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208564. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208565. }
  208566. }
  208567. break;
  208568. }
  208569. return DefWindowProcW (h, message, wParam, lParam);
  208570. }
  208571. bool sendInputAttemptWhenModalMessage()
  208572. {
  208573. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208574. {
  208575. Component* const current = Component::getCurrentlyModalComponent();
  208576. if (current != 0)
  208577. current->inputAttemptWhenModal();
  208578. return true;
  208579. }
  208580. return false;
  208581. }
  208582. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208583. };
  208584. ModifierKeys Win32ComponentPeer::currentModifiers;
  208585. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208586. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208587. {
  208588. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208589. }
  208590. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208591. void ModifierKeys::updateCurrentModifiers() throw()
  208592. {
  208593. currentModifiers = Win32ComponentPeer::currentModifiers;
  208594. }
  208595. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208596. {
  208597. Win32ComponentPeer::updateKeyModifiers();
  208598. int mouseMods = 0;
  208599. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208600. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208601. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208602. Win32ComponentPeer::currentModifiers
  208603. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208604. return Win32ComponentPeer::currentModifiers;
  208605. }
  208606. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208607. {
  208608. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208609. if (wp != 0)
  208610. wp->setTaskBarIcon (newImage);
  208611. }
  208612. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208613. {
  208614. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208615. if (wp != 0)
  208616. wp->setTaskBarIconToolTip (tooltip);
  208617. }
  208618. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208619. {
  208620. DWORD val = GetWindowLong (h, styleType);
  208621. if (bitIsSet)
  208622. val |= feature;
  208623. else
  208624. val &= ~feature;
  208625. SetWindowLongPtr (h, styleType, val);
  208626. SetWindowPos (h, 0, 0, 0, 0, 0,
  208627. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208628. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208629. }
  208630. bool Process::isForegroundProcess()
  208631. {
  208632. HWND fg = GetForegroundWindow();
  208633. if (fg == 0)
  208634. return true;
  208635. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208636. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208637. // have to see if any of our windows are children of the foreground window
  208638. fg = GetAncestor (fg, GA_ROOT);
  208639. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208640. {
  208641. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208642. if (wp != 0 && wp->isInside (fg))
  208643. return true;
  208644. }
  208645. return false;
  208646. }
  208647. bool AlertWindow::showNativeDialogBox (const String& title,
  208648. const String& bodyText,
  208649. bool isOkCancel)
  208650. {
  208651. return MessageBox (0, bodyText, title,
  208652. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208653. : MB_OK)) == IDOK;
  208654. }
  208655. void Desktop::createMouseInputSources()
  208656. {
  208657. mouseSources.add (new MouseInputSource (0, true));
  208658. }
  208659. const Point<int> MouseInputSource::getCurrentMousePosition()
  208660. {
  208661. POINT mousePos;
  208662. GetCursorPos (&mousePos);
  208663. return Point<int> (mousePos.x, mousePos.y);
  208664. }
  208665. void Desktop::setMousePosition (const Point<int>& newPosition)
  208666. {
  208667. SetCursorPos (newPosition.getX(), newPosition.getY());
  208668. }
  208669. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208670. {
  208671. return createSoftwareImage (format, width, height, clearImage);
  208672. }
  208673. class ScreenSaverDefeater : public Timer,
  208674. public DeletedAtShutdown
  208675. {
  208676. public:
  208677. ScreenSaverDefeater()
  208678. {
  208679. startTimer (10000);
  208680. timerCallback();
  208681. }
  208682. ~ScreenSaverDefeater() {}
  208683. void timerCallback()
  208684. {
  208685. if (Process::isForegroundProcess())
  208686. {
  208687. // simulate a shift key getting pressed..
  208688. INPUT input[2];
  208689. input[0].type = INPUT_KEYBOARD;
  208690. input[0].ki.wVk = VK_SHIFT;
  208691. input[0].ki.dwFlags = 0;
  208692. input[0].ki.dwExtraInfo = 0;
  208693. input[1].type = INPUT_KEYBOARD;
  208694. input[1].ki.wVk = VK_SHIFT;
  208695. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208696. input[1].ki.dwExtraInfo = 0;
  208697. SendInput (2, input, sizeof (INPUT));
  208698. }
  208699. }
  208700. };
  208701. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208702. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208703. {
  208704. if (isEnabled)
  208705. deleteAndZero (screenSaverDefeater);
  208706. else if (screenSaverDefeater == 0)
  208707. screenSaverDefeater = new ScreenSaverDefeater();
  208708. }
  208709. bool Desktop::isScreenSaverEnabled()
  208710. {
  208711. return screenSaverDefeater == 0;
  208712. }
  208713. /* (The code below is the "correct" way to disable the screen saver, but it
  208714. completely fails on winXP when the saver is password-protected...)
  208715. static bool juce_screenSaverEnabled = true;
  208716. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208717. {
  208718. juce_screenSaverEnabled = isEnabled;
  208719. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208720. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208721. }
  208722. bool Desktop::isScreenSaverEnabled() throw()
  208723. {
  208724. return juce_screenSaverEnabled;
  208725. }
  208726. */
  208727. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208728. {
  208729. if (enableOrDisable)
  208730. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208731. }
  208732. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208733. {
  208734. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208735. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208736. return TRUE;
  208737. }
  208738. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208739. {
  208740. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208741. // make sure the first in the list is the main monitor
  208742. for (int i = 1; i < monitorCoords.size(); ++i)
  208743. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208744. monitorCoords.swap (i, 0);
  208745. if (monitorCoords.size() == 0)
  208746. {
  208747. RECT r;
  208748. GetWindowRect (GetDesktopWindow(), &r);
  208749. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208750. }
  208751. if (clipToWorkArea)
  208752. {
  208753. // clip the main monitor to the active non-taskbar area
  208754. RECT r;
  208755. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208756. Rectangle<int>& screen = monitorCoords.getReference (0);
  208757. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208758. jmax (screen.getY(), (int) r.top));
  208759. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208760. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208761. }
  208762. }
  208763. const Image juce_createIconForFile (const File& file)
  208764. {
  208765. Image image;
  208766. WCHAR filename [1024];
  208767. file.getFullPathName().copyToUnicode (filename, 1023);
  208768. WORD iconNum = 0;
  208769. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208770. filename, &iconNum);
  208771. if (icon != 0)
  208772. {
  208773. image = IconConverters::createImageFromHICON (icon);
  208774. DestroyIcon (icon);
  208775. }
  208776. return image;
  208777. }
  208778. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208779. {
  208780. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208781. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208782. Image im (image);
  208783. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208784. {
  208785. im = im.rescaled (maxW, maxH);
  208786. hotspotX = (hotspotX * maxW) / image.getWidth();
  208787. hotspotY = (hotspotY * maxH) / image.getHeight();
  208788. }
  208789. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208790. }
  208791. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208792. {
  208793. if (cursorHandle != 0 && ! isStandard)
  208794. DestroyCursor ((HCURSOR) cursorHandle);
  208795. }
  208796. enum
  208797. {
  208798. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208799. };
  208800. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208801. {
  208802. LPCTSTR cursorName = IDC_ARROW;
  208803. switch (type)
  208804. {
  208805. case NormalCursor: break;
  208806. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208807. case WaitCursor: cursorName = IDC_WAIT; break;
  208808. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208809. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208810. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208811. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208812. case LeftRightResizeCursor:
  208813. case LeftEdgeResizeCursor:
  208814. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208815. case UpDownResizeCursor:
  208816. case TopEdgeResizeCursor:
  208817. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208818. case TopLeftCornerResizeCursor:
  208819. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208820. case TopRightCornerResizeCursor:
  208821. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208822. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208823. case DraggingHandCursor:
  208824. {
  208825. static void* dragHandCursor = 0;
  208826. if (dragHandCursor == 0)
  208827. {
  208828. static const unsigned char dragHandData[] =
  208829. { 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,
  208830. 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,
  208831. 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 };
  208832. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208833. }
  208834. return dragHandCursor;
  208835. }
  208836. default:
  208837. jassertfalse; break;
  208838. }
  208839. HCURSOR cursorH = LoadCursor (0, cursorName);
  208840. if (cursorH == 0)
  208841. cursorH = LoadCursor (0, IDC_ARROW);
  208842. return cursorH;
  208843. }
  208844. void MouseCursor::showInWindow (ComponentPeer*) const
  208845. {
  208846. HCURSOR c = (HCURSOR) getHandle();
  208847. if (c == 0)
  208848. c = LoadCursor (0, IDC_ARROW);
  208849. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208850. c = 0;
  208851. SetCursor (c);
  208852. }
  208853. void MouseCursor::showInAllWindows() const
  208854. {
  208855. showInWindow (0);
  208856. }
  208857. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208858. {
  208859. public:
  208860. JuceDropSource() {}
  208861. ~JuceDropSource() {}
  208862. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208863. {
  208864. if (escapePressed)
  208865. return DRAGDROP_S_CANCEL;
  208866. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208867. return DRAGDROP_S_DROP;
  208868. return S_OK;
  208869. }
  208870. HRESULT __stdcall GiveFeedback (DWORD)
  208871. {
  208872. return DRAGDROP_S_USEDEFAULTCURSORS;
  208873. }
  208874. };
  208875. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208876. {
  208877. public:
  208878. JuceEnumFormatEtc (const FORMATETC* const format_)
  208879. : format (format_),
  208880. index (0)
  208881. {
  208882. }
  208883. ~JuceEnumFormatEtc() {}
  208884. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208885. {
  208886. if (result == 0)
  208887. return E_POINTER;
  208888. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208889. newOne->index = index;
  208890. *result = newOne;
  208891. return S_OK;
  208892. }
  208893. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208894. {
  208895. if (pceltFetched != 0)
  208896. *pceltFetched = 0;
  208897. else if (celt != 1)
  208898. return S_FALSE;
  208899. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208900. {
  208901. copyFormatEtc (lpFormatEtc [0], *format);
  208902. ++index;
  208903. if (pceltFetched != 0)
  208904. *pceltFetched = 1;
  208905. return S_OK;
  208906. }
  208907. return S_FALSE;
  208908. }
  208909. HRESULT __stdcall Skip (ULONG celt)
  208910. {
  208911. if (index + (int) celt >= 1)
  208912. return S_FALSE;
  208913. index += celt;
  208914. return S_OK;
  208915. }
  208916. HRESULT __stdcall Reset()
  208917. {
  208918. index = 0;
  208919. return S_OK;
  208920. }
  208921. private:
  208922. const FORMATETC* const format;
  208923. int index;
  208924. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208925. {
  208926. dest = source;
  208927. if (source.ptd != 0)
  208928. {
  208929. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208930. *(dest.ptd) = *(source.ptd);
  208931. }
  208932. }
  208933. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208934. };
  208935. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208936. {
  208937. public:
  208938. JuceDataObject (JuceDropSource* const dropSource_,
  208939. const FORMATETC* const format_,
  208940. const STGMEDIUM* const medium_)
  208941. : dropSource (dropSource_),
  208942. format (format_),
  208943. medium (medium_)
  208944. {
  208945. }
  208946. ~JuceDataObject()
  208947. {
  208948. jassert (refCount == 0);
  208949. }
  208950. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208951. {
  208952. if ((pFormatEtc->tymed & format->tymed) != 0
  208953. && pFormatEtc->cfFormat == format->cfFormat
  208954. && pFormatEtc->dwAspect == format->dwAspect)
  208955. {
  208956. pMedium->tymed = format->tymed;
  208957. pMedium->pUnkForRelease = 0;
  208958. if (format->tymed == TYMED_HGLOBAL)
  208959. {
  208960. const SIZE_T len = GlobalSize (medium->hGlobal);
  208961. void* const src = GlobalLock (medium->hGlobal);
  208962. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208963. memcpy (dst, src, len);
  208964. GlobalUnlock (medium->hGlobal);
  208965. pMedium->hGlobal = dst;
  208966. return S_OK;
  208967. }
  208968. }
  208969. return DV_E_FORMATETC;
  208970. }
  208971. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208972. {
  208973. if (f == 0)
  208974. return E_INVALIDARG;
  208975. if (f->tymed == format->tymed
  208976. && f->cfFormat == format->cfFormat
  208977. && f->dwAspect == format->dwAspect)
  208978. return S_OK;
  208979. return DV_E_FORMATETC;
  208980. }
  208981. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208982. {
  208983. pFormatEtcOut->ptd = 0;
  208984. return E_NOTIMPL;
  208985. }
  208986. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208987. {
  208988. if (result == 0)
  208989. return E_POINTER;
  208990. if (direction == DATADIR_GET)
  208991. {
  208992. *result = new JuceEnumFormatEtc (format);
  208993. return S_OK;
  208994. }
  208995. *result = 0;
  208996. return E_NOTIMPL;
  208997. }
  208998. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208999. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  209000. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  209001. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  209002. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  209003. private:
  209004. JuceDropSource* const dropSource;
  209005. const FORMATETC* const format;
  209006. const STGMEDIUM* const medium;
  209007. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  209008. };
  209009. static HDROP createHDrop (const StringArray& fileNames)
  209010. {
  209011. int totalChars = 0;
  209012. for (int i = fileNames.size(); --i >= 0;)
  209013. totalChars += fileNames[i].length() + 1;
  209014. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  209015. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  209016. if (hDrop != 0)
  209017. {
  209018. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  209019. pDropFiles->pFiles = sizeof (DROPFILES);
  209020. pDropFiles->fWide = true;
  209021. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  209022. for (int i = 0; i < fileNames.size(); ++i)
  209023. {
  209024. fileNames[i].copyToUnicode (fname, 2048);
  209025. fname += fileNames[i].length() + 1;
  209026. }
  209027. *fname = 0;
  209028. GlobalUnlock (hDrop);
  209029. }
  209030. return hDrop;
  209031. }
  209032. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  209033. {
  209034. JuceDropSource* const source = new JuceDropSource();
  209035. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  209036. DWORD effect;
  209037. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  209038. data->Release();
  209039. source->Release();
  209040. return res == DRAGDROP_S_DROP;
  209041. }
  209042. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  209043. {
  209044. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209045. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209046. medium.hGlobal = createHDrop (files);
  209047. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  209048. : DROPEFFECT_COPY);
  209049. }
  209050. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  209051. {
  209052. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209053. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209054. const int numChars = text.length();
  209055. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  209056. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  209057. text.copyToUnicode (data, numChars + 1);
  209058. format.cfFormat = CF_UNICODETEXT;
  209059. GlobalUnlock (medium.hGlobal);
  209060. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  209061. }
  209062. #endif
  209063. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  209064. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  209065. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209066. // compiled on its own).
  209067. #if JUCE_INCLUDED_FILE
  209068. namespace FileChooserHelpers
  209069. {
  209070. static bool areThereAnyAlwaysOnTopWindows()
  209071. {
  209072. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  209073. {
  209074. Component* c = Desktop::getInstance().getComponent (i);
  209075. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  209076. return true;
  209077. }
  209078. return false;
  209079. }
  209080. struct FileChooserCallbackInfo
  209081. {
  209082. String initialPath;
  209083. String returnedString; // need this to get non-existent pathnames from the directory chooser
  209084. ScopedPointer<Component> customComponent;
  209085. };
  209086. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  209087. {
  209088. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  209089. if (msg == BFFM_INITIALIZED)
  209090. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  209091. else if (msg == BFFM_VALIDATEFAILEDW)
  209092. info->returnedString = (LPCWSTR) lParam;
  209093. else if (msg == BFFM_VALIDATEFAILEDA)
  209094. info->returnedString = (const char*) lParam;
  209095. return 0;
  209096. }
  209097. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  209098. {
  209099. if (uiMsg == WM_INITDIALOG)
  209100. {
  209101. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  209102. HWND dialogH = GetParent (hdlg);
  209103. jassert (dialogH != 0);
  209104. if (dialogH == 0)
  209105. dialogH = hdlg;
  209106. RECT r, cr;
  209107. GetWindowRect (dialogH, &r);
  209108. GetClientRect (dialogH, &cr);
  209109. SetWindowPos (dialogH, 0,
  209110. r.left, r.top,
  209111. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  209112. jmax (150, (int) (r.bottom - r.top)),
  209113. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  209114. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  209115. customComp->addToDesktop (0, dialogH);
  209116. }
  209117. else if (uiMsg == WM_NOTIFY)
  209118. {
  209119. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  209120. if (ofn->hdr.code == CDN_SELCHANGE)
  209121. {
  209122. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  209123. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  209124. if (comp != 0)
  209125. {
  209126. WCHAR path [MAX_PATH * 2];
  209127. zerostruct (path);
  209128. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  209129. comp->selectedFileChanged (File (path));
  209130. }
  209131. }
  209132. }
  209133. return 0;
  209134. }
  209135. class CustomComponentHolder : public Component
  209136. {
  209137. public:
  209138. CustomComponentHolder (Component* customComp)
  209139. {
  209140. setVisible (true);
  209141. setOpaque (true);
  209142. addAndMakeVisible (customComp);
  209143. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  209144. }
  209145. void paint (Graphics& g)
  209146. {
  209147. g.fillAll (Colours::lightgrey);
  209148. }
  209149. void resized()
  209150. {
  209151. if (getNumChildComponents() > 0)
  209152. getChildComponent(0)->setBounds (getLocalBounds());
  209153. }
  209154. private:
  209155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  209156. };
  209157. }
  209158. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  209159. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  209160. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  209161. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  209162. {
  209163. using namespace FileChooserHelpers;
  209164. HeapBlock<WCHAR> files;
  209165. const int charsAvailableForResult = 32768;
  209166. files.calloc (charsAvailableForResult + 1);
  209167. int filenameOffset = 0;
  209168. FileChooserCallbackInfo info;
  209169. // use a modal window as the parent for this dialog box
  209170. // to block input from other app windows
  209171. Component parentWindow (String::empty);
  209172. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209173. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209174. mainMon.getY() + mainMon.getHeight() / 4,
  209175. 0, 0);
  209176. parentWindow.setOpaque (true);
  209177. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209178. parentWindow.addToDesktop (0);
  209179. if (extraInfoComponent == 0)
  209180. parentWindow.enterModalState();
  209181. if (currentFileOrDirectory.isDirectory())
  209182. {
  209183. info.initialPath = currentFileOrDirectory.getFullPathName();
  209184. }
  209185. else
  209186. {
  209187. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  209188. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209189. }
  209190. if (selectsDirectory)
  209191. {
  209192. BROWSEINFO bi;
  209193. zerostruct (bi);
  209194. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209195. bi.pszDisplayName = files;
  209196. bi.lpszTitle = title;
  209197. bi.lParam = (LPARAM) &info;
  209198. bi.lpfn = browseCallbackProc;
  209199. #ifdef BIF_USENEWUI
  209200. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209201. #else
  209202. bi.ulFlags = 0x50;
  209203. #endif
  209204. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209205. if (! SHGetPathFromIDListW (list, files))
  209206. {
  209207. files[0] = 0;
  209208. info.returnedString = String::empty;
  209209. }
  209210. LPMALLOC al;
  209211. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209212. al->Free (list);
  209213. if (info.returnedString.isNotEmpty())
  209214. {
  209215. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209216. return;
  209217. }
  209218. }
  209219. else
  209220. {
  209221. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209222. if (warnAboutOverwritingExistingFiles)
  209223. flags |= OFN_OVERWRITEPROMPT;
  209224. if (selectMultipleFiles)
  209225. flags |= OFN_ALLOWMULTISELECT;
  209226. if (extraInfoComponent != 0)
  209227. {
  209228. flags |= OFN_ENABLEHOOK;
  209229. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209230. info.customComponent->enterModalState();
  209231. }
  209232. WCHAR filters [1024];
  209233. zerostruct (filters);
  209234. filter.copyToUnicode (filters, 1024);
  209235. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  209236. OPENFILENAMEW of;
  209237. zerostruct (of);
  209238. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209239. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209240. #else
  209241. of.lStructSize = sizeof (of);
  209242. #endif
  209243. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209244. of.lpstrFilter = filters;
  209245. of.nFilterIndex = 1;
  209246. of.lpstrFile = files;
  209247. of.nMaxFile = charsAvailableForResult;
  209248. of.lpstrInitialDir = info.initialPath;
  209249. of.lpstrTitle = title;
  209250. of.Flags = flags;
  209251. of.lCustData = (LPARAM) &info;
  209252. if (extraInfoComponent != 0)
  209253. of.lpfnHook = &openCallback;
  209254. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209255. : GetOpenFileName (&of)))
  209256. return;
  209257. filenameOffset = of.nFileOffset;
  209258. }
  209259. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209260. {
  209261. const WCHAR* filename = files + filenameOffset;
  209262. while (*filename != 0)
  209263. {
  209264. results.add (File (String (files) + "\\" + String (filename)));
  209265. filename += CharacterFunctions::length (filename) + 1;
  209266. }
  209267. }
  209268. else if (files[0] != 0)
  209269. {
  209270. results.add (File (String (files)));
  209271. }
  209272. }
  209273. #endif
  209274. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209275. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209276. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209277. // compiled on its own).
  209278. #if JUCE_INCLUDED_FILE
  209279. void SystemClipboard::copyTextToClipboard (const String& text)
  209280. {
  209281. if (OpenClipboard (0) != 0)
  209282. {
  209283. if (EmptyClipboard() != 0)
  209284. {
  209285. const int len = text.length();
  209286. if (len > 0)
  209287. {
  209288. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209289. (len + 1) * sizeof (wchar_t));
  209290. if (bufH != 0)
  209291. {
  209292. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209293. text.copyToUnicode (data, len);
  209294. GlobalUnlock (bufH);
  209295. SetClipboardData (CF_UNICODETEXT, bufH);
  209296. }
  209297. }
  209298. }
  209299. CloseClipboard();
  209300. }
  209301. }
  209302. const String SystemClipboard::getTextFromClipboard()
  209303. {
  209304. String result;
  209305. if (OpenClipboard (0) != 0)
  209306. {
  209307. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209308. if (bufH != 0)
  209309. {
  209310. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209311. if (data != 0)
  209312. {
  209313. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209314. GlobalUnlock (bufH);
  209315. }
  209316. }
  209317. CloseClipboard();
  209318. }
  209319. return result;
  209320. }
  209321. #endif
  209322. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209323. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209324. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209325. // compiled on its own).
  209326. #if JUCE_INCLUDED_FILE
  209327. namespace ActiveXHelpers
  209328. {
  209329. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209330. {
  209331. public:
  209332. JuceIStorage() {}
  209333. ~JuceIStorage() {}
  209334. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209335. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209336. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209337. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209338. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209339. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209340. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209341. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209342. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209343. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209344. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209345. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209346. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209347. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209348. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209349. };
  209350. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209351. {
  209352. HWND window;
  209353. public:
  209354. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209355. ~JuceOleInPlaceFrame() {}
  209356. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209357. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209358. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209359. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209360. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209361. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209362. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209363. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209364. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209365. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209366. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209367. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209368. };
  209369. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209370. {
  209371. HWND window;
  209372. JuceOleInPlaceFrame* frame;
  209373. public:
  209374. JuceIOleInPlaceSite (HWND window_)
  209375. : window (window_),
  209376. frame (new JuceOleInPlaceFrame (window))
  209377. {}
  209378. ~JuceIOleInPlaceSite()
  209379. {
  209380. frame->Release();
  209381. }
  209382. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209383. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209384. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209385. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209386. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209387. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209388. {
  209389. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209390. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209391. */
  209392. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209393. if (lplpDoc != 0) *lplpDoc = 0;
  209394. lpFrameInfo->fMDIApp = FALSE;
  209395. lpFrameInfo->hwndFrame = window;
  209396. lpFrameInfo->haccel = 0;
  209397. lpFrameInfo->cAccelEntries = 0;
  209398. return S_OK;
  209399. }
  209400. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209401. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209402. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209403. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209404. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209405. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209406. };
  209407. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209408. {
  209409. JuceIOleInPlaceSite* inplaceSite;
  209410. public:
  209411. JuceIOleClientSite (HWND window)
  209412. : inplaceSite (new JuceIOleInPlaceSite (window))
  209413. {}
  209414. ~JuceIOleClientSite()
  209415. {
  209416. inplaceSite->Release();
  209417. }
  209418. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209419. {
  209420. if (type == IID_IOleInPlaceSite)
  209421. {
  209422. inplaceSite->AddRef();
  209423. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209424. return S_OK;
  209425. }
  209426. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209427. }
  209428. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209429. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209430. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209431. HRESULT __stdcall ShowObject() { return S_OK; }
  209432. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209433. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209434. };
  209435. static Array<ActiveXControlComponent*> activeXComps;
  209436. static HWND getHWND (const ActiveXControlComponent* const component)
  209437. {
  209438. HWND hwnd = 0;
  209439. const IID iid = IID_IOleWindow;
  209440. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209441. if (window != 0)
  209442. {
  209443. window->GetWindow (&hwnd);
  209444. window->Release();
  209445. }
  209446. return hwnd;
  209447. }
  209448. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209449. {
  209450. RECT activeXRect, peerRect;
  209451. GetWindowRect (hwnd, &activeXRect);
  209452. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209453. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209454. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209455. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209456. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209457. switch (message)
  209458. {
  209459. case WM_MOUSEMOVE:
  209460. case WM_LBUTTONDOWN:
  209461. case WM_MBUTTONDOWN:
  209462. case WM_RBUTTONDOWN:
  209463. case WM_LBUTTONUP:
  209464. case WM_MBUTTONUP:
  209465. case WM_RBUTTONUP:
  209466. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209467. break;
  209468. default:
  209469. break;
  209470. }
  209471. }
  209472. }
  209473. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209474. {
  209475. ActiveXControlComponent& owner;
  209476. bool wasShowing;
  209477. public:
  209478. HWND controlHWND;
  209479. IStorage* storage;
  209480. IOleClientSite* clientSite;
  209481. IOleObject* control;
  209482. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209483. : ComponentMovementWatcher (&owner_),
  209484. owner (owner_),
  209485. wasShowing (owner_.isShowing()),
  209486. controlHWND (0),
  209487. storage (new ActiveXHelpers::JuceIStorage()),
  209488. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209489. control (0)
  209490. {
  209491. }
  209492. ~Pimpl()
  209493. {
  209494. if (control != 0)
  209495. {
  209496. control->Close (OLECLOSE_NOSAVE);
  209497. control->Release();
  209498. }
  209499. clientSite->Release();
  209500. storage->Release();
  209501. }
  209502. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209503. {
  209504. Component* const topComp = owner.getTopLevelComponent();
  209505. if (topComp->getPeer() != 0)
  209506. {
  209507. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  209508. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209509. }
  209510. }
  209511. void componentPeerChanged()
  209512. {
  209513. const bool isShowingNow = owner.isShowing();
  209514. if (wasShowing != isShowingNow)
  209515. {
  209516. wasShowing = isShowingNow;
  209517. owner.setControlVisible (isShowingNow);
  209518. }
  209519. componentMovedOrResized (true, true);
  209520. }
  209521. void componentVisibilityChanged (Component&)
  209522. {
  209523. componentPeerChanged();
  209524. }
  209525. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209526. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209527. {
  209528. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209529. {
  209530. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209531. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209532. {
  209533. switch (message)
  209534. {
  209535. case WM_MOUSEMOVE:
  209536. case WM_LBUTTONDOWN:
  209537. case WM_MBUTTONDOWN:
  209538. case WM_RBUTTONDOWN:
  209539. case WM_LBUTTONUP:
  209540. case WM_MBUTTONUP:
  209541. case WM_RBUTTONUP:
  209542. case WM_LBUTTONDBLCLK:
  209543. case WM_MBUTTONDBLCLK:
  209544. case WM_RBUTTONDBLCLK:
  209545. if (ax->isShowing())
  209546. {
  209547. ComponentPeer* const peer = ax->getPeer();
  209548. if (peer != 0)
  209549. {
  209550. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209551. if (! ax->areMouseEventsAllowed())
  209552. return 0;
  209553. }
  209554. }
  209555. break;
  209556. default:
  209557. break;
  209558. }
  209559. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209560. }
  209561. }
  209562. return DefWindowProc (hwnd, message, wParam, lParam);
  209563. }
  209564. };
  209565. ActiveXControlComponent::ActiveXControlComponent()
  209566. : originalWndProc (0),
  209567. mouseEventsAllowed (true)
  209568. {
  209569. ActiveXHelpers::activeXComps.add (this);
  209570. }
  209571. ActiveXControlComponent::~ActiveXControlComponent()
  209572. {
  209573. deleteControl();
  209574. ActiveXHelpers::activeXComps.removeValue (this);
  209575. }
  209576. void ActiveXControlComponent::paint (Graphics& g)
  209577. {
  209578. if (control == 0)
  209579. g.fillAll (Colours::lightgrey);
  209580. }
  209581. bool ActiveXControlComponent::createControl (const void* controlIID)
  209582. {
  209583. deleteControl();
  209584. ComponentPeer* const peer = getPeer();
  209585. // the component must have already been added to a real window when you call this!
  209586. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209587. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209588. {
  209589. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209590. HWND hwnd = (HWND) peer->getNativeHandle();
  209591. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209592. HRESULT hr;
  209593. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209594. newControl->clientSite, newControl->storage,
  209595. (void**) &(newControl->control))) == S_OK)
  209596. {
  209597. newControl->control->SetHostNames (L"Juce", 0);
  209598. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209599. {
  209600. RECT rect;
  209601. rect.left = pos.getX();
  209602. rect.top = pos.getY();
  209603. rect.right = pos.getX() + getWidth();
  209604. rect.bottom = pos.getY() + getHeight();
  209605. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209606. {
  209607. control = newControl;
  209608. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209609. control->controlHWND = ActiveXHelpers::getHWND (this);
  209610. if (control->controlHWND != 0)
  209611. {
  209612. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209613. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209614. }
  209615. return true;
  209616. }
  209617. }
  209618. }
  209619. }
  209620. return false;
  209621. }
  209622. void ActiveXControlComponent::deleteControl()
  209623. {
  209624. control = 0;
  209625. originalWndProc = 0;
  209626. }
  209627. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209628. {
  209629. void* result = 0;
  209630. if (control != 0 && control->control != 0
  209631. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209632. return result;
  209633. return 0;
  209634. }
  209635. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209636. {
  209637. if (control->controlHWND != 0)
  209638. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209639. }
  209640. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209641. {
  209642. if (control->controlHWND != 0)
  209643. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209644. }
  209645. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209646. {
  209647. mouseEventsAllowed = eventsCanReachControl;
  209648. }
  209649. #endif
  209650. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209651. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209652. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209653. // compiled on its own).
  209654. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209655. using namespace QTOLibrary;
  209656. using namespace QTOControlLib;
  209657. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209658. static bool isQTAvailable = false;
  209659. class QuickTimeMovieComponent::Pimpl
  209660. {
  209661. public:
  209662. Pimpl() : dataHandle (0)
  209663. {
  209664. }
  209665. ~Pimpl()
  209666. {
  209667. clearHandle();
  209668. }
  209669. void clearHandle()
  209670. {
  209671. if (dataHandle != 0)
  209672. {
  209673. DisposeHandle (dataHandle);
  209674. dataHandle = 0;
  209675. }
  209676. }
  209677. IQTControlPtr qtControl;
  209678. IQTMoviePtr qtMovie;
  209679. Handle dataHandle;
  209680. };
  209681. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209682. : movieLoaded (false),
  209683. controllerVisible (true)
  209684. {
  209685. pimpl = new Pimpl();
  209686. setMouseEventsAllowed (false);
  209687. }
  209688. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209689. {
  209690. closeMovie();
  209691. pimpl->qtControl = 0;
  209692. deleteControl();
  209693. pimpl = 0;
  209694. }
  209695. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209696. {
  209697. if (! isQTAvailable)
  209698. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209699. return isQTAvailable;
  209700. }
  209701. void QuickTimeMovieComponent::createControlIfNeeded()
  209702. {
  209703. if (isShowing() && ! isControlCreated())
  209704. {
  209705. const IID qtIID = __uuidof (QTControl);
  209706. if (createControl (&qtIID))
  209707. {
  209708. const IID qtInterfaceIID = __uuidof (IQTControl);
  209709. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209710. if (pimpl->qtControl != 0)
  209711. {
  209712. pimpl->qtControl->Release(); // it has one ref too many at this point
  209713. pimpl->qtControl->QuickTimeInitialize();
  209714. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209715. if (movieFile != File::nonexistent)
  209716. loadMovie (movieFile, controllerVisible);
  209717. }
  209718. }
  209719. }
  209720. }
  209721. bool QuickTimeMovieComponent::isControlCreated() const
  209722. {
  209723. return isControlOpen();
  209724. }
  209725. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209726. const bool isControllerVisible)
  209727. {
  209728. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209729. movieFile = File::nonexistent;
  209730. movieLoaded = false;
  209731. pimpl->qtMovie = 0;
  209732. controllerVisible = isControllerVisible;
  209733. createControlIfNeeded();
  209734. if (isControlCreated())
  209735. {
  209736. if (pimpl->qtControl != 0)
  209737. {
  209738. pimpl->qtControl->Put_MovieHandle (0);
  209739. pimpl->clearHandle();
  209740. Movie movie;
  209741. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209742. {
  209743. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209744. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209745. if (pimpl->qtMovie != 0)
  209746. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209747. : qtMovieControllerTypeNone);
  209748. }
  209749. if (movie == 0)
  209750. pimpl->clearHandle();
  209751. }
  209752. movieLoaded = (pimpl->qtMovie != 0);
  209753. }
  209754. else
  209755. {
  209756. // You're trying to open a movie when the control hasn't yet been created, probably because
  209757. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209758. jassertfalse;
  209759. }
  209760. return movieLoaded;
  209761. }
  209762. void QuickTimeMovieComponent::closeMovie()
  209763. {
  209764. stop();
  209765. movieFile = File::nonexistent;
  209766. movieLoaded = false;
  209767. pimpl->qtMovie = 0;
  209768. if (pimpl->qtControl != 0)
  209769. pimpl->qtControl->Put_MovieHandle (0);
  209770. pimpl->clearHandle();
  209771. }
  209772. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209773. {
  209774. return movieFile;
  209775. }
  209776. bool QuickTimeMovieComponent::isMovieOpen() const
  209777. {
  209778. return movieLoaded;
  209779. }
  209780. double QuickTimeMovieComponent::getMovieDuration() const
  209781. {
  209782. if (pimpl->qtMovie != 0)
  209783. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209784. return 0.0;
  209785. }
  209786. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209787. {
  209788. if (pimpl->qtMovie != 0)
  209789. {
  209790. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209791. width = r.right - r.left;
  209792. height = r.bottom - r.top;
  209793. }
  209794. else
  209795. {
  209796. width = height = 0;
  209797. }
  209798. }
  209799. void QuickTimeMovieComponent::play()
  209800. {
  209801. if (pimpl->qtMovie != 0)
  209802. pimpl->qtMovie->Play();
  209803. }
  209804. void QuickTimeMovieComponent::stop()
  209805. {
  209806. if (pimpl->qtMovie != 0)
  209807. pimpl->qtMovie->Stop();
  209808. }
  209809. bool QuickTimeMovieComponent::isPlaying() const
  209810. {
  209811. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209812. }
  209813. void QuickTimeMovieComponent::setPosition (const double seconds)
  209814. {
  209815. if (pimpl->qtMovie != 0)
  209816. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209817. }
  209818. double QuickTimeMovieComponent::getPosition() const
  209819. {
  209820. if (pimpl->qtMovie != 0)
  209821. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209822. return 0.0;
  209823. }
  209824. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209825. {
  209826. if (pimpl->qtMovie != 0)
  209827. pimpl->qtMovie->PutRate (newSpeed);
  209828. }
  209829. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209830. {
  209831. if (pimpl->qtMovie != 0)
  209832. {
  209833. pimpl->qtMovie->PutAudioVolume (newVolume);
  209834. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209835. }
  209836. }
  209837. float QuickTimeMovieComponent::getMovieVolume() const
  209838. {
  209839. if (pimpl->qtMovie != 0)
  209840. return pimpl->qtMovie->GetAudioVolume();
  209841. return 0.0f;
  209842. }
  209843. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209844. {
  209845. if (pimpl->qtMovie != 0)
  209846. pimpl->qtMovie->PutLoop (shouldLoop);
  209847. }
  209848. bool QuickTimeMovieComponent::isLooping() const
  209849. {
  209850. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209851. }
  209852. bool QuickTimeMovieComponent::isControllerVisible() const
  209853. {
  209854. return controllerVisible;
  209855. }
  209856. void QuickTimeMovieComponent::parentHierarchyChanged()
  209857. {
  209858. createControlIfNeeded();
  209859. QTCompBaseClass::parentHierarchyChanged();
  209860. }
  209861. void QuickTimeMovieComponent::visibilityChanged()
  209862. {
  209863. createControlIfNeeded();
  209864. QTCompBaseClass::visibilityChanged();
  209865. }
  209866. void QuickTimeMovieComponent::paint (Graphics& g)
  209867. {
  209868. if (! isControlCreated())
  209869. g.fillAll (Colours::black);
  209870. }
  209871. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209872. {
  209873. Handle dataRef = 0;
  209874. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209875. if (err == noErr)
  209876. {
  209877. Str255 suffix;
  209878. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209879. StringPtr name = suffix;
  209880. err = PtrAndHand (name, dataRef, name[0] + 1);
  209881. if (err == noErr)
  209882. {
  209883. long atoms[3];
  209884. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209885. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209886. atoms[2] = EndianU32_NtoB (MovieFileType);
  209887. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209888. if (err == noErr)
  209889. return dataRef;
  209890. }
  209891. DisposeHandle (dataRef);
  209892. }
  209893. return 0;
  209894. }
  209895. static CFStringRef juceStringToCFString (const String& s)
  209896. {
  209897. const int len = s.length();
  209898. const juce_wchar* const t = s;
  209899. HeapBlock <UniChar> temp (len + 2);
  209900. for (int i = 0; i <= len; ++i)
  209901. temp[i] = t[i];
  209902. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209903. }
  209904. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209905. {
  209906. Boolean trueBool = true;
  209907. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209908. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209909. props[prop].propValueSize = sizeof (trueBool);
  209910. props[prop].propValueAddress = &trueBool;
  209911. ++prop;
  209912. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209913. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209914. props[prop].propValueSize = sizeof (trueBool);
  209915. props[prop].propValueAddress = &trueBool;
  209916. ++prop;
  209917. Boolean isActive = true;
  209918. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209919. props[prop].propID = kQTNewMoviePropertyID_Active;
  209920. props[prop].propValueSize = sizeof (isActive);
  209921. props[prop].propValueAddress = &isActive;
  209922. ++prop;
  209923. MacSetPort (0);
  209924. jassert (prop <= 5);
  209925. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209926. return err == noErr;
  209927. }
  209928. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209929. {
  209930. if (input == 0)
  209931. return false;
  209932. dataHandle = 0;
  209933. bool ok = false;
  209934. QTNewMoviePropertyElement props[5];
  209935. zeromem (props, sizeof (props));
  209936. int prop = 0;
  209937. DataReferenceRecord dr;
  209938. props[prop].propClass = kQTPropertyClass_DataLocation;
  209939. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209940. props[prop].propValueSize = sizeof (dr);
  209941. props[prop].propValueAddress = &dr;
  209942. ++prop;
  209943. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209944. if (fin != 0)
  209945. {
  209946. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209947. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209948. &dr.dataRef, &dr.dataRefType);
  209949. ok = openMovie (props, prop, movie);
  209950. DisposeHandle (dr.dataRef);
  209951. CFRelease (filePath);
  209952. }
  209953. else
  209954. {
  209955. // sanity-check because this currently needs to load the whole stream into memory..
  209956. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209957. dataHandle = NewHandle ((Size) input->getTotalLength());
  209958. HLock (dataHandle);
  209959. // read the entire stream into memory - this is a pain, but can't get it to work
  209960. // properly using a custom callback to supply the data.
  209961. input->read (*dataHandle, (int) input->getTotalLength());
  209962. HUnlock (dataHandle);
  209963. // different types to get QT to try. (We should really be a bit smarter here by
  209964. // working out in advance which one the stream contains, rather than just trying
  209965. // each one)
  209966. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209967. "\04.avi", "\04.m4a" };
  209968. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209969. {
  209970. /* // this fails for some bizarre reason - it can be bodged to work with
  209971. // movies, but can't seem to do it for other file types..
  209972. QTNewMovieUserProcRecord procInfo;
  209973. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209974. procInfo.getMovieUserProcRefcon = this;
  209975. procInfo.defaultDataRef.dataRef = dataRef;
  209976. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209977. props[prop].propClass = kQTPropertyClass_DataLocation;
  209978. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209979. props[prop].propValueSize = sizeof (procInfo);
  209980. props[prop].propValueAddress = (void*) &procInfo;
  209981. ++prop; */
  209982. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209983. dr.dataRefType = HandleDataHandlerSubType;
  209984. ok = openMovie (props, prop, movie);
  209985. DisposeHandle (dr.dataRef);
  209986. }
  209987. }
  209988. return ok;
  209989. }
  209990. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209991. const bool isControllerVisible)
  209992. {
  209993. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209994. movieFile = movieFile_;
  209995. return ok;
  209996. }
  209997. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209998. const bool isControllerVisible)
  209999. {
  210000. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  210001. }
  210002. void QuickTimeMovieComponent::goToStart()
  210003. {
  210004. setPosition (0.0);
  210005. }
  210006. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  210007. const RectanglePlacement& placement)
  210008. {
  210009. int normalWidth, normalHeight;
  210010. getMovieNormalSize (normalWidth, normalHeight);
  210011. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  210012. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  210013. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  210014. else
  210015. setBounds (spaceToFitWithin);
  210016. }
  210017. #endif
  210018. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  210019. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210020. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210021. // compiled on its own).
  210022. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  210023. class WebBrowserComponentInternal : public ActiveXControlComponent
  210024. {
  210025. public:
  210026. WebBrowserComponentInternal()
  210027. : browser (0),
  210028. connectionPoint (0),
  210029. adviseCookie (0)
  210030. {
  210031. }
  210032. ~WebBrowserComponentInternal()
  210033. {
  210034. if (connectionPoint != 0)
  210035. connectionPoint->Unadvise (adviseCookie);
  210036. if (browser != 0)
  210037. browser->Release();
  210038. }
  210039. void createBrowser()
  210040. {
  210041. createControl (&CLSID_WebBrowser);
  210042. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  210043. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  210044. if (connectionPointContainer != 0)
  210045. {
  210046. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  210047. &connectionPoint);
  210048. if (connectionPoint != 0)
  210049. {
  210050. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  210051. jassert (owner != 0);
  210052. EventHandler* handler = new EventHandler (owner);
  210053. connectionPoint->Advise (handler, &adviseCookie);
  210054. handler->Release();
  210055. }
  210056. }
  210057. }
  210058. void goToURL (const String& url,
  210059. const StringArray* headers,
  210060. const MemoryBlock* postData)
  210061. {
  210062. if (browser != 0)
  210063. {
  210064. LPSAFEARRAY sa = 0;
  210065. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  210066. VariantInit (&flags);
  210067. VariantInit (&frame);
  210068. VariantInit (&postDataVar);
  210069. VariantInit (&headersVar);
  210070. if (headers != 0)
  210071. {
  210072. V_VT (&headersVar) = VT_BSTR;
  210073. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  210074. }
  210075. if (postData != 0 && postData->getSize() > 0)
  210076. {
  210077. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210078. if (sa != 0)
  210079. {
  210080. void* data = 0;
  210081. SafeArrayAccessData (sa, &data);
  210082. jassert (data != 0);
  210083. if (data != 0)
  210084. {
  210085. postData->copyTo (data, 0, postData->getSize());
  210086. SafeArrayUnaccessData (sa);
  210087. VARIANT postDataVar2;
  210088. VariantInit (&postDataVar2);
  210089. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210090. V_ARRAY (&postDataVar2) = sa;
  210091. postDataVar = postDataVar2;
  210092. }
  210093. }
  210094. }
  210095. browser->Navigate ((BSTR) (const OLECHAR*) url,
  210096. &flags, &frame,
  210097. &postDataVar, &headersVar);
  210098. if (sa != 0)
  210099. SafeArrayDestroy (sa);
  210100. VariantClear (&flags);
  210101. VariantClear (&frame);
  210102. VariantClear (&postDataVar);
  210103. VariantClear (&headersVar);
  210104. }
  210105. }
  210106. IWebBrowser2* browser;
  210107. private:
  210108. IConnectionPoint* connectionPoint;
  210109. DWORD adviseCookie;
  210110. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210111. public ComponentMovementWatcher
  210112. {
  210113. public:
  210114. EventHandler (WebBrowserComponent* const owner_)
  210115. : ComponentMovementWatcher (owner_),
  210116. owner (owner_)
  210117. {
  210118. }
  210119. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  210120. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  210121. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  210122. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  210123. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  210124. {
  210125. switch (dispIdMember)
  210126. {
  210127. case DISPID_BEFORENAVIGATE2:
  210128. {
  210129. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210130. String url;
  210131. if ((vurl->vt & VT_BYREF) != 0)
  210132. url = *vurl->pbstrVal;
  210133. else
  210134. url = vurl->bstrVal;
  210135. *pDispParams->rgvarg->pboolVal
  210136. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  210137. : VARIANT_TRUE;
  210138. return S_OK;
  210139. }
  210140. default:
  210141. break;
  210142. }
  210143. return E_NOTIMPL;
  210144. }
  210145. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  210146. void componentPeerChanged() {}
  210147. void componentVisibilityChanged (Component&)
  210148. {
  210149. owner->visibilityChanged();
  210150. }
  210151. private:
  210152. WebBrowserComponent* const owner;
  210153. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  210154. };
  210155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  210156. };
  210157. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210158. : browser (0),
  210159. blankPageShown (false),
  210160. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210161. {
  210162. setOpaque (true);
  210163. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210164. }
  210165. WebBrowserComponent::~WebBrowserComponent()
  210166. {
  210167. delete browser;
  210168. }
  210169. void WebBrowserComponent::goToURL (const String& url,
  210170. const StringArray* headers,
  210171. const MemoryBlock* postData)
  210172. {
  210173. lastURL = url;
  210174. lastHeaders.clear();
  210175. if (headers != 0)
  210176. lastHeaders = *headers;
  210177. lastPostData.setSize (0);
  210178. if (postData != 0)
  210179. lastPostData = *postData;
  210180. blankPageShown = false;
  210181. browser->goToURL (url, headers, postData);
  210182. }
  210183. void WebBrowserComponent::stop()
  210184. {
  210185. if (browser->browser != 0)
  210186. browser->browser->Stop();
  210187. }
  210188. void WebBrowserComponent::goBack()
  210189. {
  210190. lastURL = String::empty;
  210191. blankPageShown = false;
  210192. if (browser->browser != 0)
  210193. browser->browser->GoBack();
  210194. }
  210195. void WebBrowserComponent::goForward()
  210196. {
  210197. lastURL = String::empty;
  210198. if (browser->browser != 0)
  210199. browser->browser->GoForward();
  210200. }
  210201. void WebBrowserComponent::refresh()
  210202. {
  210203. if (browser->browser != 0)
  210204. browser->browser->Refresh();
  210205. }
  210206. void WebBrowserComponent::paint (Graphics& g)
  210207. {
  210208. if (browser->browser == 0)
  210209. g.fillAll (Colours::white);
  210210. }
  210211. void WebBrowserComponent::checkWindowAssociation()
  210212. {
  210213. if (isShowing())
  210214. {
  210215. if (browser->browser == 0 && getPeer() != 0)
  210216. {
  210217. browser->createBrowser();
  210218. reloadLastURL();
  210219. }
  210220. else
  210221. {
  210222. if (blankPageShown)
  210223. goBack();
  210224. }
  210225. }
  210226. else
  210227. {
  210228. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210229. {
  210230. // when the component becomes invisible, some stuff like flash
  210231. // carries on playing audio, so we need to force it onto a blank
  210232. // page to avoid this..
  210233. blankPageShown = true;
  210234. browser->goToURL ("about:blank", 0, 0);
  210235. }
  210236. }
  210237. }
  210238. void WebBrowserComponent::reloadLastURL()
  210239. {
  210240. if (lastURL.isNotEmpty())
  210241. {
  210242. goToURL (lastURL, &lastHeaders, &lastPostData);
  210243. lastURL = String::empty;
  210244. }
  210245. }
  210246. void WebBrowserComponent::parentHierarchyChanged()
  210247. {
  210248. checkWindowAssociation();
  210249. }
  210250. void WebBrowserComponent::resized()
  210251. {
  210252. browser->setSize (getWidth(), getHeight());
  210253. }
  210254. void WebBrowserComponent::visibilityChanged()
  210255. {
  210256. checkWindowAssociation();
  210257. }
  210258. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210259. {
  210260. return true;
  210261. }
  210262. #endif
  210263. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210264. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210265. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210266. // compiled on its own).
  210267. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210268. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210269. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210270. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210271. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210272. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210273. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210274. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210275. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210276. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210277. #define WGL_ACCELERATION_ARB 0x2003
  210278. #define WGL_SWAP_METHOD_ARB 0x2007
  210279. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210280. #define WGL_PIXEL_TYPE_ARB 0x2013
  210281. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210282. #define WGL_COLOR_BITS_ARB 0x2014
  210283. #define WGL_RED_BITS_ARB 0x2015
  210284. #define WGL_GREEN_BITS_ARB 0x2017
  210285. #define WGL_BLUE_BITS_ARB 0x2019
  210286. #define WGL_ALPHA_BITS_ARB 0x201B
  210287. #define WGL_DEPTH_BITS_ARB 0x2022
  210288. #define WGL_STENCIL_BITS_ARB 0x2023
  210289. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210290. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210291. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210292. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210293. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210294. #define WGL_STEREO_ARB 0x2012
  210295. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210296. #define WGL_SAMPLES_ARB 0x2042
  210297. #define WGL_TYPE_RGBA_ARB 0x202B
  210298. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210299. {
  210300. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210301. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210302. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210303. else
  210304. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210305. }
  210306. class WindowedGLContext : public OpenGLContext
  210307. {
  210308. public:
  210309. WindowedGLContext (Component* const component_,
  210310. HGLRC contextToShareWith,
  210311. const OpenGLPixelFormat& pixelFormat)
  210312. : renderContext (0),
  210313. dc (0),
  210314. component (component_)
  210315. {
  210316. jassert (component != 0);
  210317. createNativeWindow();
  210318. // Use a default pixel format that should be supported everywhere
  210319. PIXELFORMATDESCRIPTOR pfd;
  210320. zerostruct (pfd);
  210321. pfd.nSize = sizeof (pfd);
  210322. pfd.nVersion = 1;
  210323. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210324. pfd.iPixelType = PFD_TYPE_RGBA;
  210325. pfd.cColorBits = 24;
  210326. pfd.cDepthBits = 16;
  210327. const int format = ChoosePixelFormat (dc, &pfd);
  210328. if (format != 0)
  210329. SetPixelFormat (dc, format, &pfd);
  210330. renderContext = wglCreateContext (dc);
  210331. makeActive();
  210332. setPixelFormat (pixelFormat);
  210333. if (contextToShareWith != 0 && renderContext != 0)
  210334. wglShareLists (contextToShareWith, renderContext);
  210335. }
  210336. ~WindowedGLContext()
  210337. {
  210338. deleteContext();
  210339. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210340. nativeWindow = 0;
  210341. }
  210342. void deleteContext()
  210343. {
  210344. makeInactive();
  210345. if (renderContext != 0)
  210346. {
  210347. wglDeleteContext (renderContext);
  210348. renderContext = 0;
  210349. }
  210350. }
  210351. bool makeActive() const throw()
  210352. {
  210353. jassert (renderContext != 0);
  210354. return wglMakeCurrent (dc, renderContext) != 0;
  210355. }
  210356. bool makeInactive() const throw()
  210357. {
  210358. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210359. }
  210360. bool isActive() const throw()
  210361. {
  210362. return wglGetCurrentContext() == renderContext;
  210363. }
  210364. const OpenGLPixelFormat getPixelFormat() const
  210365. {
  210366. OpenGLPixelFormat pf;
  210367. makeActive();
  210368. StringArray availableExtensions;
  210369. getWglExtensions (dc, availableExtensions);
  210370. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210371. return pf;
  210372. }
  210373. void* getRawContext() const throw()
  210374. {
  210375. return renderContext;
  210376. }
  210377. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210378. {
  210379. makeActive();
  210380. PIXELFORMATDESCRIPTOR pfd;
  210381. zerostruct (pfd);
  210382. pfd.nSize = sizeof (pfd);
  210383. pfd.nVersion = 1;
  210384. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210385. pfd.iPixelType = PFD_TYPE_RGBA;
  210386. pfd.iLayerType = PFD_MAIN_PLANE;
  210387. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210388. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210389. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210390. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210391. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210392. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210393. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210394. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210395. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210396. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210397. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210398. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210399. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210400. int format = 0;
  210401. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210402. StringArray availableExtensions;
  210403. getWglExtensions (dc, availableExtensions);
  210404. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210405. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210406. {
  210407. int attributes[64];
  210408. int n = 0;
  210409. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210410. attributes[n++] = GL_TRUE;
  210411. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210412. attributes[n++] = GL_TRUE;
  210413. attributes[n++] = WGL_ACCELERATION_ARB;
  210414. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210415. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210416. attributes[n++] = GL_TRUE;
  210417. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210418. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210419. attributes[n++] = WGL_COLOR_BITS_ARB;
  210420. attributes[n++] = pfd.cColorBits;
  210421. attributes[n++] = WGL_RED_BITS_ARB;
  210422. attributes[n++] = pixelFormat.redBits;
  210423. attributes[n++] = WGL_GREEN_BITS_ARB;
  210424. attributes[n++] = pixelFormat.greenBits;
  210425. attributes[n++] = WGL_BLUE_BITS_ARB;
  210426. attributes[n++] = pixelFormat.blueBits;
  210427. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210428. attributes[n++] = pixelFormat.alphaBits;
  210429. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210430. attributes[n++] = pixelFormat.depthBufferBits;
  210431. if (pixelFormat.stencilBufferBits > 0)
  210432. {
  210433. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210434. attributes[n++] = pixelFormat.stencilBufferBits;
  210435. }
  210436. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210437. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210438. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210439. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210440. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210441. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210442. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210443. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210444. if (availableExtensions.contains ("WGL_ARB_multisample")
  210445. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210446. {
  210447. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210448. attributes[n++] = 1;
  210449. attributes[n++] = WGL_SAMPLES_ARB;
  210450. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210451. }
  210452. attributes[n++] = 0;
  210453. UINT formatsCount;
  210454. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210455. (void) ok;
  210456. jassert (ok);
  210457. }
  210458. else
  210459. {
  210460. format = ChoosePixelFormat (dc, &pfd);
  210461. }
  210462. if (format != 0)
  210463. {
  210464. makeInactive();
  210465. // win32 can't change the pixel format of a window, so need to delete the
  210466. // old one and create a new one..
  210467. jassert (nativeWindow != 0);
  210468. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210469. nativeWindow = 0;
  210470. createNativeWindow();
  210471. if (SetPixelFormat (dc, format, &pfd))
  210472. {
  210473. wglDeleteContext (renderContext);
  210474. renderContext = wglCreateContext (dc);
  210475. jassert (renderContext != 0);
  210476. return renderContext != 0;
  210477. }
  210478. }
  210479. return false;
  210480. }
  210481. void updateWindowPosition (int x, int y, int w, int h, int)
  210482. {
  210483. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210484. x, y, w, h,
  210485. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210486. }
  210487. void repaint()
  210488. {
  210489. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210490. }
  210491. void swapBuffers()
  210492. {
  210493. SwapBuffers (dc);
  210494. }
  210495. bool setSwapInterval (int numFramesPerSwap)
  210496. {
  210497. makeActive();
  210498. StringArray availableExtensions;
  210499. getWglExtensions (dc, availableExtensions);
  210500. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210501. return availableExtensions.contains ("WGL_EXT_swap_control")
  210502. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210503. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210504. }
  210505. int getSwapInterval() const
  210506. {
  210507. makeActive();
  210508. StringArray availableExtensions;
  210509. getWglExtensions (dc, availableExtensions);
  210510. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210511. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210512. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210513. return wglGetSwapIntervalEXT();
  210514. return 0;
  210515. }
  210516. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210517. {
  210518. jassert (isActive());
  210519. StringArray availableExtensions;
  210520. getWglExtensions (dc, availableExtensions);
  210521. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210522. int numTypes = 0;
  210523. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210524. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210525. {
  210526. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210527. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210528. jassertfalse;
  210529. }
  210530. else
  210531. {
  210532. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210533. }
  210534. OpenGLPixelFormat pf;
  210535. for (int i = 0; i < numTypes; ++i)
  210536. {
  210537. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210538. {
  210539. bool alreadyListed = false;
  210540. for (int j = results.size(); --j >= 0;)
  210541. if (pf == *results.getUnchecked(j))
  210542. alreadyListed = true;
  210543. if (! alreadyListed)
  210544. results.add (new OpenGLPixelFormat (pf));
  210545. }
  210546. }
  210547. }
  210548. void* getNativeWindowHandle() const
  210549. {
  210550. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210551. }
  210552. HGLRC renderContext;
  210553. private:
  210554. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210555. Component* const component;
  210556. HDC dc;
  210557. void createNativeWindow()
  210558. {
  210559. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210560. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210561. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210562. nativeWindow->dontRepaint = true;
  210563. nativeWindow->setVisible (true);
  210564. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210565. }
  210566. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210567. OpenGLPixelFormat& result,
  210568. const StringArray& availableExtensions) const throw()
  210569. {
  210570. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210571. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210572. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210573. {
  210574. int attributes[32];
  210575. int numAttributes = 0;
  210576. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210577. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210578. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210579. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210580. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210581. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210582. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210583. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210584. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210585. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210586. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210587. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210588. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210589. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210590. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210591. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210592. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210593. int values[32];
  210594. zeromem (values, sizeof (values));
  210595. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210596. {
  210597. int n = 0;
  210598. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210599. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210600. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210601. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210602. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210603. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210604. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210605. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210606. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210607. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210608. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210609. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210610. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210611. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210612. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210613. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210614. return isValidFormat;
  210615. }
  210616. else
  210617. {
  210618. jassertfalse;
  210619. }
  210620. }
  210621. else
  210622. {
  210623. PIXELFORMATDESCRIPTOR pfd;
  210624. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210625. {
  210626. result.redBits = pfd.cRedBits;
  210627. result.greenBits = pfd.cGreenBits;
  210628. result.blueBits = pfd.cBlueBits;
  210629. result.alphaBits = pfd.cAlphaBits;
  210630. result.depthBufferBits = pfd.cDepthBits;
  210631. result.stencilBufferBits = pfd.cStencilBits;
  210632. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210633. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210634. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210635. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210636. result.fullSceneAntiAliasingNumSamples = 0;
  210637. return true;
  210638. }
  210639. else
  210640. {
  210641. jassertfalse;
  210642. }
  210643. }
  210644. return false;
  210645. }
  210646. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210647. };
  210648. OpenGLContext* OpenGLComponent::createContext()
  210649. {
  210650. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210651. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210652. preferredPixelFormat));
  210653. return (c->renderContext != 0) ? c.release() : 0;
  210654. }
  210655. void* OpenGLComponent::getNativeWindowHandle() const
  210656. {
  210657. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210658. }
  210659. void juce_glViewport (const int w, const int h)
  210660. {
  210661. glViewport (0, 0, w, h);
  210662. }
  210663. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210664. OwnedArray <OpenGLPixelFormat>& results)
  210665. {
  210666. Component tempComp;
  210667. {
  210668. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210669. wc.makeActive();
  210670. wc.findAlternativeOpenGLPixelFormats (results);
  210671. }
  210672. }
  210673. #endif
  210674. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210675. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210676. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210677. // compiled on its own).
  210678. #if JUCE_INCLUDED_FILE
  210679. #if JUCE_USE_CDREADER
  210680. namespace CDReaderHelpers
  210681. {
  210682. #define FILE_ANY_ACCESS 0
  210683. #ifndef FILE_READ_ACCESS
  210684. #define FILE_READ_ACCESS 1
  210685. #endif
  210686. #ifndef FILE_WRITE_ACCESS
  210687. #define FILE_WRITE_ACCESS 2
  210688. #endif
  210689. #define METHOD_BUFFERED 0
  210690. #define IOCTL_SCSI_BASE 4
  210691. #define SCSI_IOCTL_DATA_OUT 0
  210692. #define SCSI_IOCTL_DATA_IN 1
  210693. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210694. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210695. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210696. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210697. #define SENSE_LEN 14
  210698. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210699. #define SRB_DIR_IN 0x08
  210700. #define SRB_DIR_OUT 0x10
  210701. #define SRB_EVENT_NOTIFY 0x40
  210702. #define SC_HA_INQUIRY 0x00
  210703. #define SC_GET_DEV_TYPE 0x01
  210704. #define SC_EXEC_SCSI_CMD 0x02
  210705. #define SS_PENDING 0x00
  210706. #define SS_COMP 0x01
  210707. #define SS_ERR 0x04
  210708. enum
  210709. {
  210710. READTYPE_ANY = 0,
  210711. READTYPE_ATAPI1 = 1,
  210712. READTYPE_ATAPI2 = 2,
  210713. READTYPE_READ6 = 3,
  210714. READTYPE_READ10 = 4,
  210715. READTYPE_READ_D8 = 5,
  210716. READTYPE_READ_D4 = 6,
  210717. READTYPE_READ_D4_1 = 7,
  210718. READTYPE_READ10_2 = 8
  210719. };
  210720. struct SCSI_PASS_THROUGH
  210721. {
  210722. USHORT Length;
  210723. UCHAR ScsiStatus;
  210724. UCHAR PathId;
  210725. UCHAR TargetId;
  210726. UCHAR Lun;
  210727. UCHAR CdbLength;
  210728. UCHAR SenseInfoLength;
  210729. UCHAR DataIn;
  210730. ULONG DataTransferLength;
  210731. ULONG TimeOutValue;
  210732. ULONG DataBufferOffset;
  210733. ULONG SenseInfoOffset;
  210734. UCHAR Cdb[16];
  210735. };
  210736. struct SCSI_PASS_THROUGH_DIRECT
  210737. {
  210738. USHORT Length;
  210739. UCHAR ScsiStatus;
  210740. UCHAR PathId;
  210741. UCHAR TargetId;
  210742. UCHAR Lun;
  210743. UCHAR CdbLength;
  210744. UCHAR SenseInfoLength;
  210745. UCHAR DataIn;
  210746. ULONG DataTransferLength;
  210747. ULONG TimeOutValue;
  210748. PVOID DataBuffer;
  210749. ULONG SenseInfoOffset;
  210750. UCHAR Cdb[16];
  210751. };
  210752. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210753. {
  210754. SCSI_PASS_THROUGH_DIRECT spt;
  210755. ULONG Filler;
  210756. UCHAR ucSenseBuf[32];
  210757. };
  210758. struct SCSI_ADDRESS
  210759. {
  210760. ULONG Length;
  210761. UCHAR PortNumber;
  210762. UCHAR PathId;
  210763. UCHAR TargetId;
  210764. UCHAR Lun;
  210765. };
  210766. #pragma pack(1)
  210767. struct SRB_GDEVBlock
  210768. {
  210769. BYTE SRB_Cmd;
  210770. BYTE SRB_Status;
  210771. BYTE SRB_HaID;
  210772. BYTE SRB_Flags;
  210773. DWORD SRB_Hdr_Rsvd;
  210774. BYTE SRB_Target;
  210775. BYTE SRB_Lun;
  210776. BYTE SRB_DeviceType;
  210777. BYTE SRB_Rsvd1;
  210778. BYTE pad[68];
  210779. };
  210780. struct SRB_ExecSCSICmd
  210781. {
  210782. BYTE SRB_Cmd;
  210783. BYTE SRB_Status;
  210784. BYTE SRB_HaID;
  210785. BYTE SRB_Flags;
  210786. DWORD SRB_Hdr_Rsvd;
  210787. BYTE SRB_Target;
  210788. BYTE SRB_Lun;
  210789. WORD SRB_Rsvd1;
  210790. DWORD SRB_BufLen;
  210791. BYTE *SRB_BufPointer;
  210792. BYTE SRB_SenseLen;
  210793. BYTE SRB_CDBLen;
  210794. BYTE SRB_HaStat;
  210795. BYTE SRB_TargStat;
  210796. VOID *SRB_PostProc;
  210797. BYTE SRB_Rsvd2[20];
  210798. BYTE CDBByte[16];
  210799. BYTE SenseArea[SENSE_LEN + 2];
  210800. };
  210801. struct SRB
  210802. {
  210803. BYTE SRB_Cmd;
  210804. BYTE SRB_Status;
  210805. BYTE SRB_HaId;
  210806. BYTE SRB_Flags;
  210807. DWORD SRB_Hdr_Rsvd;
  210808. };
  210809. struct TOCTRACK
  210810. {
  210811. BYTE rsvd;
  210812. BYTE ADR;
  210813. BYTE trackNumber;
  210814. BYTE rsvd2;
  210815. BYTE addr[4];
  210816. };
  210817. struct TOC
  210818. {
  210819. WORD tocLen;
  210820. BYTE firstTrack;
  210821. BYTE lastTrack;
  210822. TOCTRACK tracks[100];
  210823. };
  210824. #pragma pack()
  210825. struct CDDeviceDescription
  210826. {
  210827. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210828. {
  210829. }
  210830. void createDescription (const char* data)
  210831. {
  210832. description << String (data + 8, 8).trim() // vendor
  210833. << ' ' << String (data + 16, 16).trim() // product id
  210834. << ' ' << String (data + 32, 4).trim(); // rev
  210835. }
  210836. String description;
  210837. BYTE ha, tgt, lun;
  210838. char scsiDriveLetter; // will be 0 if not using scsi
  210839. };
  210840. class CDReadBuffer
  210841. {
  210842. public:
  210843. CDReadBuffer (const int numberOfFrames)
  210844. : startFrame (0), numFrames (0), dataStartOffset (0),
  210845. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210846. buffer (bufferSize), wantsIndex (false)
  210847. {
  210848. }
  210849. bool isZero() const throw()
  210850. {
  210851. for (int i = 0; i < dataLength; ++i)
  210852. if (buffer [dataStartOffset + i] != 0)
  210853. return false;
  210854. return true;
  210855. }
  210856. int startFrame, numFrames, dataStartOffset;
  210857. int dataLength, bufferSize, index;
  210858. HeapBlock<BYTE> buffer;
  210859. bool wantsIndex;
  210860. };
  210861. class CDDeviceHandle;
  210862. class CDController
  210863. {
  210864. public:
  210865. CDController() : initialised (false) {}
  210866. virtual ~CDController() {}
  210867. virtual bool read (CDReadBuffer&) = 0;
  210868. virtual void shutDown() {}
  210869. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210870. int getLastIndex();
  210871. public:
  210872. CDDeviceHandle* deviceInfo;
  210873. int framesToCheck, framesOverlap;
  210874. bool initialised;
  210875. void prepare (SRB_ExecSCSICmd& s);
  210876. void perform (SRB_ExecSCSICmd& s);
  210877. void setPaused (bool paused);
  210878. };
  210879. class CDDeviceHandle
  210880. {
  210881. public:
  210882. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210883. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210884. {
  210885. }
  210886. ~CDDeviceHandle()
  210887. {
  210888. if (controller != 0)
  210889. {
  210890. controller->shutDown();
  210891. controller = 0;
  210892. }
  210893. if (scsiHandle != 0)
  210894. CloseHandle (scsiHandle);
  210895. }
  210896. bool readTOC (TOC* lpToc);
  210897. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210898. void openDrawer (bool shouldBeOpen);
  210899. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210900. CDDeviceDescription info;
  210901. HANDLE scsiHandle;
  210902. BYTE readType;
  210903. private:
  210904. ScopedPointer<CDController> controller;
  210905. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210906. };
  210907. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210908. {
  210909. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210910. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210911. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210912. if (h == INVALID_HANDLE_VALUE)
  210913. {
  210914. flags ^= GENERIC_WRITE;
  210915. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210916. }
  210917. return h;
  210918. }
  210919. void findCDDevices (Array<CDDeviceDescription>& list)
  210920. {
  210921. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210922. {
  210923. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210924. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210925. {
  210926. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210927. if (h != INVALID_HANDLE_VALUE)
  210928. {
  210929. char buffer[100];
  210930. zeromem (buffer, sizeof (buffer));
  210931. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210932. zerostruct (p);
  210933. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210934. p.spt.CdbLength = 6;
  210935. p.spt.SenseInfoLength = 24;
  210936. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210937. p.spt.DataTransferLength = sizeof (buffer);
  210938. p.spt.TimeOutValue = 2;
  210939. p.spt.DataBuffer = buffer;
  210940. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210941. p.spt.Cdb[0] = 0x12;
  210942. p.spt.Cdb[4] = 100;
  210943. DWORD bytesReturned = 0;
  210944. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210945. &p, sizeof (p), &p, sizeof (p),
  210946. &bytesReturned, 0) != 0)
  210947. {
  210948. CDDeviceDescription dev;
  210949. dev.scsiDriveLetter = driveLetter;
  210950. dev.createDescription (buffer);
  210951. SCSI_ADDRESS scsiAddr;
  210952. zerostruct (scsiAddr);
  210953. scsiAddr.Length = sizeof (scsiAddr);
  210954. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210955. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210956. &bytesReturned, 0) != 0)
  210957. {
  210958. dev.ha = scsiAddr.PortNumber;
  210959. dev.tgt = scsiAddr.TargetId;
  210960. dev.lun = scsiAddr.Lun;
  210961. list.add (dev);
  210962. }
  210963. }
  210964. CloseHandle (h);
  210965. }
  210966. }
  210967. }
  210968. }
  210969. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210970. HANDLE& deviceHandle, const bool retryOnFailure)
  210971. {
  210972. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210973. zerostruct (s);
  210974. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210975. s.spt.CdbLength = srb->SRB_CDBLen;
  210976. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210977. ? SCSI_IOCTL_DATA_IN
  210978. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210979. ? SCSI_IOCTL_DATA_OUT
  210980. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210981. s.spt.DataTransferLength = srb->SRB_BufLen;
  210982. s.spt.TimeOutValue = 5;
  210983. s.spt.DataBuffer = srb->SRB_BufPointer;
  210984. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210985. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210986. srb->SRB_Status = SS_ERR;
  210987. srb->SRB_TargStat = 0x0004;
  210988. DWORD bytesReturned = 0;
  210989. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210990. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210991. {
  210992. srb->SRB_Status = SS_COMP;
  210993. }
  210994. else if (retryOnFailure)
  210995. {
  210996. const DWORD error = GetLastError();
  210997. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210998. {
  210999. if (error != ERROR_INVALID_HANDLE)
  211000. CloseHandle (deviceHandle);
  211001. deviceHandle = createSCSIDeviceHandle (driveLetter);
  211002. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211003. }
  211004. }
  211005. return srb->SRB_Status;
  211006. }
  211007. // Controller types..
  211008. class ControllerType1 : public CDController
  211009. {
  211010. public:
  211011. ControllerType1() {}
  211012. bool read (CDReadBuffer& rb)
  211013. {
  211014. if (rb.numFrames * 2352 > rb.bufferSize)
  211015. return false;
  211016. SRB_ExecSCSICmd s;
  211017. prepare (s);
  211018. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211019. s.SRB_BufLen = rb.bufferSize;
  211020. s.SRB_BufPointer = rb.buffer;
  211021. s.SRB_CDBLen = 12;
  211022. s.CDBByte[0] = 0xBE;
  211023. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211024. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211025. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211026. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211027. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  211028. perform (s);
  211029. if (s.SRB_Status != SS_COMP)
  211030. return false;
  211031. rb.dataLength = rb.numFrames * 2352;
  211032. rb.dataStartOffset = 0;
  211033. return true;
  211034. }
  211035. };
  211036. class ControllerType2 : public CDController
  211037. {
  211038. public:
  211039. ControllerType2() {}
  211040. void shutDown()
  211041. {
  211042. if (initialised)
  211043. {
  211044. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211045. SRB_ExecSCSICmd s;
  211046. prepare (s);
  211047. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211048. s.SRB_BufLen = 0x0C;
  211049. s.SRB_BufPointer = bufPointer;
  211050. s.SRB_CDBLen = 6;
  211051. s.CDBByte[0] = 0x15;
  211052. s.CDBByte[4] = 0x0C;
  211053. perform (s);
  211054. }
  211055. }
  211056. bool init()
  211057. {
  211058. SRB_ExecSCSICmd s;
  211059. s.SRB_Status = SS_ERR;
  211060. if (deviceInfo->readType == READTYPE_READ10_2)
  211061. {
  211062. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211063. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211064. for (int i = 0; i < 2; ++i)
  211065. {
  211066. prepare (s);
  211067. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211068. s.SRB_BufLen = 0x14;
  211069. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211070. s.SRB_CDBLen = 6;
  211071. s.CDBByte[0] = 0x15;
  211072. s.CDBByte[1] = 0x10;
  211073. s.CDBByte[4] = 0x14;
  211074. perform (s);
  211075. if (s.SRB_Status != SS_COMP)
  211076. return false;
  211077. }
  211078. }
  211079. else
  211080. {
  211081. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211082. prepare (s);
  211083. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211084. s.SRB_BufLen = 0x0C;
  211085. s.SRB_BufPointer = bufPointer;
  211086. s.SRB_CDBLen = 6;
  211087. s.CDBByte[0] = 0x15;
  211088. s.CDBByte[4] = 0x0C;
  211089. perform (s);
  211090. }
  211091. return s.SRB_Status == SS_COMP;
  211092. }
  211093. bool read (CDReadBuffer& rb)
  211094. {
  211095. if (rb.numFrames * 2352 > rb.bufferSize)
  211096. return false;
  211097. if (! initialised)
  211098. {
  211099. initialised = init();
  211100. if (! initialised)
  211101. return false;
  211102. }
  211103. SRB_ExecSCSICmd s;
  211104. prepare (s);
  211105. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211106. s.SRB_BufLen = rb.bufferSize;
  211107. s.SRB_BufPointer = rb.buffer;
  211108. s.SRB_CDBLen = 10;
  211109. s.CDBByte[0] = 0x28;
  211110. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211111. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211112. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211113. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211114. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211115. perform (s);
  211116. if (s.SRB_Status != SS_COMP)
  211117. return false;
  211118. rb.dataLength = rb.numFrames * 2352;
  211119. rb.dataStartOffset = 0;
  211120. return true;
  211121. }
  211122. };
  211123. class ControllerType3 : public CDController
  211124. {
  211125. public:
  211126. ControllerType3() {}
  211127. bool read (CDReadBuffer& rb)
  211128. {
  211129. if (rb.numFrames * 2352 > rb.bufferSize)
  211130. return false;
  211131. if (! initialised)
  211132. {
  211133. setPaused (false);
  211134. initialised = true;
  211135. }
  211136. SRB_ExecSCSICmd s;
  211137. prepare (s);
  211138. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211139. s.SRB_BufLen = rb.numFrames * 2352;
  211140. s.SRB_BufPointer = rb.buffer;
  211141. s.SRB_CDBLen = 12;
  211142. s.CDBByte[0] = 0xD8;
  211143. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211144. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211145. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211146. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  211147. perform (s);
  211148. if (s.SRB_Status != SS_COMP)
  211149. return false;
  211150. rb.dataLength = rb.numFrames * 2352;
  211151. rb.dataStartOffset = 0;
  211152. return true;
  211153. }
  211154. };
  211155. class ControllerType4 : public CDController
  211156. {
  211157. public:
  211158. ControllerType4() {}
  211159. bool selectD4Mode()
  211160. {
  211161. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211162. SRB_ExecSCSICmd s;
  211163. prepare (s);
  211164. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211165. s.SRB_CDBLen = 6;
  211166. s.SRB_BufLen = 12;
  211167. s.SRB_BufPointer = bufPointer;
  211168. s.CDBByte[0] = 0x15;
  211169. s.CDBByte[1] = 0x10;
  211170. s.CDBByte[4] = 0x08;
  211171. perform (s);
  211172. return s.SRB_Status == SS_COMP;
  211173. }
  211174. bool read (CDReadBuffer& rb)
  211175. {
  211176. if (rb.numFrames * 2352 > rb.bufferSize)
  211177. return false;
  211178. if (! initialised)
  211179. {
  211180. setPaused (true);
  211181. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211182. selectD4Mode();
  211183. initialised = true;
  211184. }
  211185. SRB_ExecSCSICmd s;
  211186. prepare (s);
  211187. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211188. s.SRB_BufLen = rb.bufferSize;
  211189. s.SRB_BufPointer = rb.buffer;
  211190. s.SRB_CDBLen = 10;
  211191. s.CDBByte[0] = 0xD4;
  211192. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  211193. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  211194. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  211195. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  211196. perform (s);
  211197. if (s.SRB_Status != SS_COMP)
  211198. return false;
  211199. rb.dataLength = rb.numFrames * 2352;
  211200. rb.dataStartOffset = 0;
  211201. return true;
  211202. }
  211203. };
  211204. void CDController::prepare (SRB_ExecSCSICmd& s)
  211205. {
  211206. zerostruct (s);
  211207. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211208. s.SRB_HaID = deviceInfo->info.ha;
  211209. s.SRB_Target = deviceInfo->info.tgt;
  211210. s.SRB_Lun = deviceInfo->info.lun;
  211211. s.SRB_SenseLen = SENSE_LEN;
  211212. }
  211213. void CDController::perform (SRB_ExecSCSICmd& s)
  211214. {
  211215. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211216. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  211217. }
  211218. void CDController::setPaused (bool paused)
  211219. {
  211220. SRB_ExecSCSICmd s;
  211221. prepare (s);
  211222. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211223. s.SRB_CDBLen = 10;
  211224. s.CDBByte[0] = 0x4B;
  211225. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211226. perform (s);
  211227. }
  211228. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  211229. {
  211230. if (overlapBuffer != 0)
  211231. {
  211232. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211233. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211234. if (doJitter
  211235. && overlapBuffer->startFrame > 0
  211236. && overlapBuffer->numFrames > 0
  211237. && overlapBuffer->dataLength > 0)
  211238. {
  211239. const int numFrames = rb.numFrames;
  211240. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  211241. {
  211242. rb.startFrame -= framesOverlap;
  211243. if (framesToCheck < framesOverlap
  211244. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  211245. rb.numFrames += framesOverlap;
  211246. }
  211247. else
  211248. {
  211249. overlapBuffer->dataLength = 0;
  211250. overlapBuffer->startFrame = 0;
  211251. overlapBuffer->numFrames = 0;
  211252. }
  211253. }
  211254. if (! read (rb))
  211255. return false;
  211256. if (doJitter)
  211257. {
  211258. const int checkLen = framesToCheck * 2352;
  211259. const int maxToCheck = rb.dataLength - checkLen;
  211260. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211261. return true;
  211262. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211263. bool found = false;
  211264. for (int i = 0; i < maxToCheck; ++i)
  211265. {
  211266. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  211267. {
  211268. i += checkLen;
  211269. rb.dataStartOffset = i;
  211270. rb.dataLength -= i;
  211271. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  211272. found = true;
  211273. break;
  211274. }
  211275. }
  211276. rb.numFrames = rb.dataLength / 2352;
  211277. rb.dataLength = 2352 * rb.numFrames;
  211278. if (! found)
  211279. return false;
  211280. }
  211281. if (canDoJitter)
  211282. {
  211283. memcpy (overlapBuffer->buffer,
  211284. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  211285. 2352 * framesToCheck);
  211286. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  211287. overlapBuffer->numFrames = framesToCheck;
  211288. overlapBuffer->dataLength = 2352 * framesToCheck;
  211289. overlapBuffer->dataStartOffset = 0;
  211290. }
  211291. else
  211292. {
  211293. overlapBuffer->startFrame = 0;
  211294. overlapBuffer->numFrames = 0;
  211295. overlapBuffer->dataLength = 0;
  211296. }
  211297. return true;
  211298. }
  211299. return read (rb);
  211300. }
  211301. int CDController::getLastIndex()
  211302. {
  211303. char qdata[100];
  211304. SRB_ExecSCSICmd s;
  211305. prepare (s);
  211306. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211307. s.SRB_BufLen = sizeof (qdata);
  211308. s.SRB_BufPointer = (BYTE*) qdata;
  211309. s.SRB_CDBLen = 12;
  211310. s.CDBByte[0] = 0x42;
  211311. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  211312. s.CDBByte[2] = 64;
  211313. s.CDBByte[3] = 1; // get current position
  211314. s.CDBByte[7] = 0;
  211315. s.CDBByte[8] = (BYTE) sizeof (qdata);
  211316. perform (s);
  211317. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  211318. }
  211319. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211320. {
  211321. SRB_ExecSCSICmd s;
  211322. zerostruct (s);
  211323. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211324. s.SRB_HaID = info.ha;
  211325. s.SRB_Target = info.tgt;
  211326. s.SRB_Lun = info.lun;
  211327. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211328. s.SRB_BufLen = 0x324;
  211329. s.SRB_BufPointer = (BYTE*) lpToc;
  211330. s.SRB_SenseLen = 0x0E;
  211331. s.SRB_CDBLen = 0x0A;
  211332. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211333. s.CDBByte[0] = 0x43;
  211334. s.CDBByte[1] = 0x00;
  211335. s.CDBByte[7] = 0x03;
  211336. s.CDBByte[8] = 0x24;
  211337. performScsiCommand (s.SRB_PostProc, s);
  211338. return (s.SRB_Status == SS_COMP);
  211339. }
  211340. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  211341. {
  211342. ResetEvent (event);
  211343. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  211344. if (status == SS_PENDING)
  211345. WaitForSingleObject (event, 4000);
  211346. CloseHandle (event);
  211347. }
  211348. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  211349. {
  211350. if (controller == 0)
  211351. {
  211352. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211353. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211354. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211355. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211356. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211357. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211358. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211359. }
  211360. buffer.index = 0;
  211361. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  211362. {
  211363. if (buffer.wantsIndex)
  211364. buffer.index = controller->getLastIndex();
  211365. return true;
  211366. }
  211367. return false;
  211368. }
  211369. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211370. {
  211371. if (shouldBeOpen)
  211372. {
  211373. if (controller != 0)
  211374. {
  211375. controller->shutDown();
  211376. controller = 0;
  211377. }
  211378. if (scsiHandle != 0)
  211379. {
  211380. CloseHandle (scsiHandle);
  211381. scsiHandle = 0;
  211382. }
  211383. }
  211384. SRB_ExecSCSICmd s;
  211385. zerostruct (s);
  211386. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211387. s.SRB_HaID = info.ha;
  211388. s.SRB_Target = info.tgt;
  211389. s.SRB_Lun = info.lun;
  211390. s.SRB_SenseLen = SENSE_LEN;
  211391. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211392. s.SRB_BufLen = 0;
  211393. s.SRB_BufPointer = 0;
  211394. s.SRB_CDBLen = 12;
  211395. s.CDBByte[0] = 0x1b;
  211396. s.CDBByte[1] = (BYTE) (info.lun << 5);
  211397. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  211398. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  211399. performScsiCommand (s.SRB_PostProc, s);
  211400. }
  211401. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  211402. {
  211403. controller = newController;
  211404. readType = (BYTE) type;
  211405. controller->deviceInfo = this;
  211406. controller->framesToCheck = 1;
  211407. controller->framesOverlap = 3;
  211408. bool passed = false;
  211409. memset (rb.buffer, 0xcd, rb.bufferSize);
  211410. if (controller->read (rb))
  211411. {
  211412. passed = true;
  211413. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  211414. int wrong = 0;
  211415. for (int i = rb.dataLength / 4; --i >= 0;)
  211416. {
  211417. if (*p++ == (int) 0xcdcdcdcd)
  211418. {
  211419. if (++wrong == 4)
  211420. {
  211421. passed = false;
  211422. break;
  211423. }
  211424. }
  211425. else
  211426. {
  211427. wrong = 0;
  211428. }
  211429. }
  211430. }
  211431. if (! passed)
  211432. {
  211433. controller->shutDown();
  211434. controller = 0;
  211435. }
  211436. return passed;
  211437. }
  211438. struct CDDeviceWrapper
  211439. {
  211440. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  211441. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  211442. {
  211443. // xxx jitter never seemed to actually be enabled (??)
  211444. }
  211445. CDDeviceHandle deviceHandle;
  211446. CDReadBuffer overlapBuffer;
  211447. bool jitter;
  211448. };
  211449. int getAddressOfTrack (const TOCTRACK& t) throw()
  211450. {
  211451. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  211452. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  211453. }
  211454. const int samplesPerFrame = 44100 / 75;
  211455. const int bytesPerFrame = samplesPerFrame * 4;
  211456. const int framesPerIndexRead = 4;
  211457. }
  211458. const StringArray AudioCDReader::getAvailableCDNames()
  211459. {
  211460. using namespace CDReaderHelpers;
  211461. StringArray results;
  211462. Array<CDDeviceDescription> list;
  211463. findCDDevices (list);
  211464. for (int i = 0; i < list.size(); ++i)
  211465. {
  211466. String s;
  211467. if (list[i].scsiDriveLetter > 0)
  211468. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211469. s << list[i].description;
  211470. results.add (s);
  211471. }
  211472. return results;
  211473. }
  211474. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211475. {
  211476. using namespace CDReaderHelpers;
  211477. Array<CDDeviceDescription> list;
  211478. findCDDevices (list);
  211479. if (isPositiveAndBelow (deviceIndex, list.size()))
  211480. {
  211481. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  211482. if (h != INVALID_HANDLE_VALUE)
  211483. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  211484. }
  211485. return 0;
  211486. }
  211487. AudioCDReader::AudioCDReader (void* handle_)
  211488. : AudioFormatReader (0, "CD Audio"),
  211489. handle (handle_),
  211490. indexingEnabled (false),
  211491. lastIndex (0),
  211492. firstFrameInBuffer (0),
  211493. samplesInBuffer (0)
  211494. {
  211495. using namespace CDReaderHelpers;
  211496. jassert (handle_ != 0);
  211497. refreshTrackLengths();
  211498. sampleRate = 44100.0;
  211499. bitsPerSample = 16;
  211500. numChannels = 2;
  211501. usesFloatingPointData = false;
  211502. buffer.setSize (4 * bytesPerFrame, true);
  211503. }
  211504. AudioCDReader::~AudioCDReader()
  211505. {
  211506. using namespace CDReaderHelpers;
  211507. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211508. delete device;
  211509. }
  211510. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211511. int64 startSampleInFile, int numSamples)
  211512. {
  211513. using namespace CDReaderHelpers;
  211514. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211515. bool ok = true;
  211516. while (numSamples > 0)
  211517. {
  211518. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211519. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211520. if (startSampleInFile >= bufferStartSample
  211521. && startSampleInFile < bufferEndSample)
  211522. {
  211523. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211524. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211525. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211526. const short* src = (const short*) buffer.getData();
  211527. src += 2 * (startSampleInFile - bufferStartSample);
  211528. for (int i = 0; i < toDo; ++i)
  211529. {
  211530. l[i] = src [i << 1] << 16;
  211531. if (r != 0)
  211532. r[i] = src [(i << 1) + 1] << 16;
  211533. }
  211534. startOffsetInDestBuffer += toDo;
  211535. startSampleInFile += toDo;
  211536. numSamples -= toDo;
  211537. }
  211538. else
  211539. {
  211540. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211541. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211542. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211543. {
  211544. device->overlapBuffer.dataLength = 0;
  211545. device->overlapBuffer.startFrame = 0;
  211546. device->overlapBuffer.numFrames = 0;
  211547. device->jitter = false;
  211548. }
  211549. firstFrameInBuffer = frameNeeded;
  211550. lastIndex = 0;
  211551. CDReadBuffer readBuffer (framesInBuffer + 4);
  211552. readBuffer.wantsIndex = indexingEnabled;
  211553. int i;
  211554. for (i = 5; --i >= 0;)
  211555. {
  211556. readBuffer.startFrame = frameNeeded;
  211557. readBuffer.numFrames = framesInBuffer;
  211558. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211559. break;
  211560. else
  211561. device->overlapBuffer.dataLength = 0;
  211562. }
  211563. if (i >= 0)
  211564. {
  211565. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211566. samplesInBuffer = readBuffer.dataLength >> 2;
  211567. lastIndex = readBuffer.index;
  211568. }
  211569. else
  211570. {
  211571. int* l = destSamples[0] + startOffsetInDestBuffer;
  211572. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211573. while (--numSamples >= 0)
  211574. {
  211575. *l++ = 0;
  211576. if (r != 0)
  211577. *r++ = 0;
  211578. }
  211579. // sometimes the read fails for just the very last couple of blocks, so
  211580. // we'll ignore and errors in the last half-second of the disk..
  211581. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211582. break;
  211583. }
  211584. }
  211585. }
  211586. return ok;
  211587. }
  211588. bool AudioCDReader::isCDStillPresent() const
  211589. {
  211590. using namespace CDReaderHelpers;
  211591. TOC toc;
  211592. zerostruct (toc);
  211593. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211594. }
  211595. void AudioCDReader::refreshTrackLengths()
  211596. {
  211597. using namespace CDReaderHelpers;
  211598. trackStartSamples.clear();
  211599. zeromem (audioTracks, sizeof (audioTracks));
  211600. TOC toc;
  211601. zerostruct (toc);
  211602. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211603. {
  211604. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211605. for (int i = 0; i <= numTracks; ++i)
  211606. {
  211607. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211608. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211609. }
  211610. }
  211611. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211612. }
  211613. bool AudioCDReader::isTrackAudio (int trackNum) const
  211614. {
  211615. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211616. }
  211617. void AudioCDReader::enableIndexScanning (bool b)
  211618. {
  211619. indexingEnabled = b;
  211620. }
  211621. int AudioCDReader::getLastIndex() const
  211622. {
  211623. return lastIndex;
  211624. }
  211625. int AudioCDReader::getIndexAt (int samplePos)
  211626. {
  211627. using namespace CDReaderHelpers;
  211628. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211629. const int frameNeeded = samplePos / samplesPerFrame;
  211630. device->overlapBuffer.dataLength = 0;
  211631. device->overlapBuffer.startFrame = 0;
  211632. device->overlapBuffer.numFrames = 0;
  211633. device->jitter = false;
  211634. firstFrameInBuffer = 0;
  211635. lastIndex = 0;
  211636. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211637. readBuffer.wantsIndex = true;
  211638. int i;
  211639. for (i = 5; --i >= 0;)
  211640. {
  211641. readBuffer.startFrame = frameNeeded;
  211642. readBuffer.numFrames = framesPerIndexRead;
  211643. if (device->deviceHandle.readAudio (readBuffer))
  211644. break;
  211645. }
  211646. if (i >= 0)
  211647. return readBuffer.index;
  211648. return -1;
  211649. }
  211650. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211651. {
  211652. using namespace CDReaderHelpers;
  211653. Array <int> indexes;
  211654. const int trackStart = getPositionOfTrackStart (trackNumber);
  211655. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211656. bool needToScan = true;
  211657. if (trackEnd - trackStart > 20 * 44100)
  211658. {
  211659. // check the end of the track for indexes before scanning the whole thing
  211660. needToScan = false;
  211661. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211662. bool seenAnIndex = false;
  211663. while (pos <= trackEnd - samplesPerFrame)
  211664. {
  211665. const int index = getIndexAt (pos);
  211666. if (index == 0)
  211667. {
  211668. // lead-out, so skip back a bit if we've not found any indexes yet..
  211669. if (seenAnIndex)
  211670. break;
  211671. pos -= 44100 * 5;
  211672. if (pos < trackStart)
  211673. break;
  211674. }
  211675. else
  211676. {
  211677. if (index > 0)
  211678. seenAnIndex = true;
  211679. if (index > 1)
  211680. {
  211681. needToScan = true;
  211682. break;
  211683. }
  211684. pos += samplesPerFrame * framesPerIndexRead;
  211685. }
  211686. }
  211687. }
  211688. if (needToScan)
  211689. {
  211690. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211691. int pos = trackStart;
  211692. int last = -1;
  211693. while (pos < trackEnd - samplesPerFrame * 10)
  211694. {
  211695. const int frameNeeded = pos / samplesPerFrame;
  211696. device->overlapBuffer.dataLength = 0;
  211697. device->overlapBuffer.startFrame = 0;
  211698. device->overlapBuffer.numFrames = 0;
  211699. device->jitter = false;
  211700. firstFrameInBuffer = 0;
  211701. CDReadBuffer readBuffer (4);
  211702. readBuffer.wantsIndex = true;
  211703. int i;
  211704. for (i = 5; --i >= 0;)
  211705. {
  211706. readBuffer.startFrame = frameNeeded;
  211707. readBuffer.numFrames = framesPerIndexRead;
  211708. if (device->deviceHandle.readAudio (readBuffer))
  211709. break;
  211710. }
  211711. if (i < 0)
  211712. break;
  211713. if (readBuffer.index > last && readBuffer.index > 1)
  211714. {
  211715. last = readBuffer.index;
  211716. indexes.add (pos);
  211717. }
  211718. pos += samplesPerFrame * framesPerIndexRead;
  211719. }
  211720. indexes.removeValue (trackStart);
  211721. }
  211722. return indexes;
  211723. }
  211724. void AudioCDReader::ejectDisk()
  211725. {
  211726. using namespace CDReaderHelpers;
  211727. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211728. }
  211729. #endif
  211730. #if JUCE_USE_CDBURNER
  211731. namespace CDBurnerHelpers
  211732. {
  211733. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211734. {
  211735. CoInitialize (0);
  211736. IDiscMaster* dm;
  211737. IDiscRecorder* result = 0;
  211738. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211739. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211740. IID_IDiscMaster,
  211741. (void**) &dm)))
  211742. {
  211743. if (SUCCEEDED (dm->Open()))
  211744. {
  211745. IEnumDiscRecorders* drEnum = 0;
  211746. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211747. {
  211748. IDiscRecorder* dr = 0;
  211749. DWORD dummy;
  211750. int index = 0;
  211751. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211752. {
  211753. if (indexToOpen == index)
  211754. {
  211755. result = dr;
  211756. break;
  211757. }
  211758. else if (list != 0)
  211759. {
  211760. BSTR path;
  211761. if (SUCCEEDED (dr->GetPath (&path)))
  211762. list->add ((const WCHAR*) path);
  211763. }
  211764. ++index;
  211765. dr->Release();
  211766. }
  211767. drEnum->Release();
  211768. }
  211769. if (master == 0)
  211770. dm->Close();
  211771. }
  211772. if (master != 0)
  211773. *master = dm;
  211774. else
  211775. dm->Release();
  211776. }
  211777. return result;
  211778. }
  211779. }
  211780. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211781. public Timer
  211782. {
  211783. public:
  211784. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211785. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211786. listener (0), progress (0), shouldCancel (false)
  211787. {
  211788. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211789. jassert (SUCCEEDED (hr));
  211790. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211791. //jassert (SUCCEEDED (hr));
  211792. lastState = getDiskState();
  211793. startTimer (2000);
  211794. }
  211795. ~Pimpl() {}
  211796. void releaseObjects()
  211797. {
  211798. discRecorder->Close();
  211799. if (redbook != 0)
  211800. redbook->Release();
  211801. discRecorder->Release();
  211802. discMaster->Release();
  211803. Release();
  211804. }
  211805. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211806. {
  211807. if (listener != 0 && ! shouldCancel)
  211808. shouldCancel = listener->audioCDBurnProgress (progress);
  211809. *pbCancel = shouldCancel;
  211810. return S_OK;
  211811. }
  211812. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211813. {
  211814. progress = nCompleted / (float) nTotal;
  211815. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211816. return E_NOTIMPL;
  211817. }
  211818. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211819. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211820. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211821. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211822. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211823. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211824. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211825. class ScopedDiscOpener
  211826. {
  211827. public:
  211828. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211829. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211830. private:
  211831. Pimpl& pimpl;
  211832. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211833. };
  211834. DiskState getDiskState()
  211835. {
  211836. const ScopedDiscOpener opener (*this);
  211837. long type, flags;
  211838. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211839. if (FAILED (hr))
  211840. return unknown;
  211841. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211842. return writableDiskPresent;
  211843. if (type == 0)
  211844. return noDisc;
  211845. else
  211846. return readOnlyDiskPresent;
  211847. }
  211848. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211849. {
  211850. ComSmartPtr<IPropertyStorage> prop;
  211851. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211852. return defaultReturn;
  211853. PROPSPEC iPropSpec;
  211854. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211855. iPropSpec.lpwstr = name;
  211856. PROPVARIANT iPropVariant;
  211857. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211858. ? defaultReturn : (int) iPropVariant.lVal;
  211859. }
  211860. bool setIntProperty (const LPOLESTR name, const int value) const
  211861. {
  211862. ComSmartPtr<IPropertyStorage> prop;
  211863. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211864. return false;
  211865. PROPSPEC iPropSpec;
  211866. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211867. iPropSpec.lpwstr = name;
  211868. PROPVARIANT iPropVariant;
  211869. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211870. return false;
  211871. iPropVariant.lVal = (long) value;
  211872. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211873. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211874. }
  211875. void timerCallback()
  211876. {
  211877. const DiskState state = getDiskState();
  211878. if (state != lastState)
  211879. {
  211880. lastState = state;
  211881. owner.sendChangeMessage();
  211882. }
  211883. }
  211884. AudioCDBurner& owner;
  211885. DiskState lastState;
  211886. IDiscMaster* discMaster;
  211887. IDiscRecorder* discRecorder;
  211888. IRedbookDiscMaster* redbook;
  211889. AudioCDBurner::BurnProgressListener* listener;
  211890. float progress;
  211891. bool shouldCancel;
  211892. };
  211893. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211894. {
  211895. IDiscMaster* discMaster = 0;
  211896. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211897. if (discRecorder != 0)
  211898. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211899. }
  211900. AudioCDBurner::~AudioCDBurner()
  211901. {
  211902. if (pimpl != 0)
  211903. pimpl.release()->releaseObjects();
  211904. }
  211905. const StringArray AudioCDBurner::findAvailableDevices()
  211906. {
  211907. StringArray devs;
  211908. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211909. return devs;
  211910. }
  211911. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211912. {
  211913. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211914. if (b->pimpl == 0)
  211915. b = 0;
  211916. return b.release();
  211917. }
  211918. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211919. {
  211920. return pimpl->getDiskState();
  211921. }
  211922. bool AudioCDBurner::isDiskPresent() const
  211923. {
  211924. return getDiskState() == writableDiskPresent;
  211925. }
  211926. bool AudioCDBurner::openTray()
  211927. {
  211928. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211929. return SUCCEEDED (pimpl->discRecorder->Eject());
  211930. }
  211931. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211932. {
  211933. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211934. DiskState oldState = getDiskState();
  211935. DiskState newState = oldState;
  211936. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211937. {
  211938. newState = getDiskState();
  211939. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211940. }
  211941. return newState;
  211942. }
  211943. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211944. {
  211945. Array<int> results;
  211946. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211947. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211948. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211949. if (speeds[i] <= maxSpeed)
  211950. results.add (speeds[i]);
  211951. results.addIfNotAlreadyThere (maxSpeed);
  211952. return results;
  211953. }
  211954. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211955. {
  211956. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211957. return false;
  211958. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211959. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211960. }
  211961. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211962. {
  211963. long blocksFree = 0;
  211964. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211965. return blocksFree;
  211966. }
  211967. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211968. bool performFakeBurnForTesting, int writeSpeed)
  211969. {
  211970. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211971. pimpl->listener = listener;
  211972. pimpl->progress = 0;
  211973. pimpl->shouldCancel = false;
  211974. UINT_PTR cookie;
  211975. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211976. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211977. ejectDiscAfterwards);
  211978. String error;
  211979. if (hr != S_OK)
  211980. {
  211981. const char* e = "Couldn't open or write to the CD device";
  211982. if (hr == IMAPI_E_USERABORT)
  211983. e = "User cancelled the write operation";
  211984. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211985. e = "No Disk present";
  211986. error = e;
  211987. }
  211988. pimpl->discMaster->ProgressUnadvise (cookie);
  211989. pimpl->listener = 0;
  211990. return error;
  211991. }
  211992. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211993. {
  211994. if (audioSource == 0)
  211995. return false;
  211996. ScopedPointer<AudioSource> source (audioSource);
  211997. long bytesPerBlock;
  211998. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211999. const int samplesPerBlock = bytesPerBlock / 4;
  212000. bool ok = true;
  212001. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212002. HeapBlock <byte> buffer (bytesPerBlock);
  212003. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212004. int samplesDone = 0;
  212005. source->prepareToPlay (samplesPerBlock, 44100.0);
  212006. while (ok)
  212007. {
  212008. {
  212009. AudioSourceChannelInfo info;
  212010. info.buffer = &sourceBuffer;
  212011. info.numSamples = samplesPerBlock;
  212012. info.startSample = 0;
  212013. sourceBuffer.clear();
  212014. source->getNextAudioBlock (info);
  212015. }
  212016. zeromem (buffer, bytesPerBlock);
  212017. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212018. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212019. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212020. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212021. CDSampleFormat left (buffer, 2);
  212022. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212023. CDSampleFormat right (buffer + 2, 2);
  212024. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212025. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212026. if (FAILED (hr))
  212027. ok = false;
  212028. samplesDone += samplesPerBlock;
  212029. if (samplesDone >= numSamples)
  212030. break;
  212031. }
  212032. hr = pimpl->redbook->CloseAudioTrack();
  212033. return ok && hr == S_OK;
  212034. }
  212035. #endif
  212036. #endif
  212037. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212038. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212039. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212040. // compiled on its own).
  212041. #if JUCE_INCLUDED_FILE
  212042. class MidiInCollector
  212043. {
  212044. public:
  212045. MidiInCollector (MidiInput* const input_,
  212046. MidiInputCallback& callback_)
  212047. : deviceHandle (0),
  212048. input (input_),
  212049. callback (callback_),
  212050. concatenator (4096),
  212051. isStarted (false),
  212052. startTime (0)
  212053. {
  212054. }
  212055. ~MidiInCollector()
  212056. {
  212057. stop();
  212058. if (deviceHandle != 0)
  212059. {
  212060. int count = 5;
  212061. while (--count >= 0)
  212062. {
  212063. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212064. break;
  212065. Sleep (20);
  212066. }
  212067. }
  212068. }
  212069. void handleMessage (const uint32 message, const uint32 timeStamp)
  212070. {
  212071. if ((message & 0xff) >= 0x80 && isStarted)
  212072. {
  212073. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212074. writeFinishedBlocks();
  212075. }
  212076. }
  212077. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212078. {
  212079. if (isStarted)
  212080. {
  212081. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212082. writeFinishedBlocks();
  212083. }
  212084. }
  212085. void start()
  212086. {
  212087. jassert (deviceHandle != 0);
  212088. if (deviceHandle != 0 && ! isStarted)
  212089. {
  212090. activeMidiCollectors.addIfNotAlreadyThere (this);
  212091. for (int i = 0; i < (int) numHeaders; ++i)
  212092. headers[i].write (deviceHandle);
  212093. startTime = Time::getMillisecondCounter();
  212094. MMRESULT res = midiInStart (deviceHandle);
  212095. if (res == MMSYSERR_NOERROR)
  212096. {
  212097. concatenator.reset();
  212098. isStarted = true;
  212099. }
  212100. else
  212101. {
  212102. unprepareAllHeaders();
  212103. }
  212104. }
  212105. }
  212106. void stop()
  212107. {
  212108. if (isStarted)
  212109. {
  212110. isStarted = false;
  212111. midiInReset (deviceHandle);
  212112. midiInStop (deviceHandle);
  212113. activeMidiCollectors.removeValue (this);
  212114. unprepareAllHeaders();
  212115. concatenator.reset();
  212116. }
  212117. }
  212118. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212119. {
  212120. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212121. if (activeMidiCollectors.contains (collector))
  212122. {
  212123. if (uMsg == MIM_DATA)
  212124. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212125. else if (uMsg == MIM_LONGDATA)
  212126. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212127. }
  212128. }
  212129. HMIDIIN deviceHandle;
  212130. private:
  212131. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212132. MidiInput* input;
  212133. MidiInputCallback& callback;
  212134. MidiDataConcatenator concatenator;
  212135. bool volatile isStarted;
  212136. uint32 startTime;
  212137. class MidiHeader
  212138. {
  212139. public:
  212140. MidiHeader()
  212141. {
  212142. zerostruct (hdr);
  212143. hdr.lpData = data;
  212144. hdr.dwBufferLength = numElementsInArray (data);
  212145. }
  212146. void write (HMIDIIN deviceHandle)
  212147. {
  212148. hdr.dwBytesRecorded = 0;
  212149. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212150. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212151. }
  212152. void writeIfFinished (HMIDIIN deviceHandle)
  212153. {
  212154. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212155. {
  212156. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212157. (void) res;
  212158. write (deviceHandle);
  212159. }
  212160. }
  212161. void unprepare (HMIDIIN deviceHandle)
  212162. {
  212163. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212164. {
  212165. int c = 10;
  212166. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212167. Thread::sleep (20);
  212168. jassert (c >= 0);
  212169. }
  212170. }
  212171. private:
  212172. MIDIHDR hdr;
  212173. char data [256];
  212174. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  212175. };
  212176. enum { numHeaders = 32 };
  212177. MidiHeader headers [numHeaders];
  212178. void writeFinishedBlocks()
  212179. {
  212180. for (int i = 0; i < (int) numHeaders; ++i)
  212181. headers[i].writeIfFinished (deviceHandle);
  212182. }
  212183. void unprepareAllHeaders()
  212184. {
  212185. for (int i = 0; i < (int) numHeaders; ++i)
  212186. headers[i].unprepare (deviceHandle);
  212187. }
  212188. double convertTimeStamp (uint32 timeStamp)
  212189. {
  212190. timeStamp += startTime;
  212191. const uint32 now = Time::getMillisecondCounter();
  212192. if (timeStamp > now)
  212193. {
  212194. if (timeStamp > now + 2)
  212195. --startTime;
  212196. timeStamp = now;
  212197. }
  212198. return timeStamp * 0.001;
  212199. }
  212200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  212201. };
  212202. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212203. const StringArray MidiInput::getDevices()
  212204. {
  212205. StringArray s;
  212206. const int num = midiInGetNumDevs();
  212207. for (int i = 0; i < num; ++i)
  212208. {
  212209. MIDIINCAPS mc;
  212210. zerostruct (mc);
  212211. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212212. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212213. }
  212214. return s;
  212215. }
  212216. int MidiInput::getDefaultDeviceIndex()
  212217. {
  212218. return 0;
  212219. }
  212220. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212221. {
  212222. if (callback == 0)
  212223. return 0;
  212224. UINT deviceId = MIDI_MAPPER;
  212225. int n = 0;
  212226. String name;
  212227. const int num = midiInGetNumDevs();
  212228. for (int i = 0; i < num; ++i)
  212229. {
  212230. MIDIINCAPS mc;
  212231. zerostruct (mc);
  212232. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212233. {
  212234. if (index == n)
  212235. {
  212236. deviceId = i;
  212237. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212238. break;
  212239. }
  212240. ++n;
  212241. }
  212242. }
  212243. ScopedPointer <MidiInput> in (new MidiInput (name));
  212244. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212245. HMIDIIN h;
  212246. HRESULT err = midiInOpen (&h, deviceId,
  212247. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212248. (DWORD_PTR) (MidiInCollector*) collector,
  212249. CALLBACK_FUNCTION);
  212250. if (err == MMSYSERR_NOERROR)
  212251. {
  212252. collector->deviceHandle = h;
  212253. in->internal = collector.release();
  212254. return in.release();
  212255. }
  212256. return 0;
  212257. }
  212258. MidiInput::MidiInput (const String& name_)
  212259. : name (name_),
  212260. internal (0)
  212261. {
  212262. }
  212263. MidiInput::~MidiInput()
  212264. {
  212265. delete static_cast <MidiInCollector*> (internal);
  212266. }
  212267. void MidiInput::start()
  212268. {
  212269. static_cast <MidiInCollector*> (internal)->start();
  212270. }
  212271. void MidiInput::stop()
  212272. {
  212273. static_cast <MidiInCollector*> (internal)->stop();
  212274. }
  212275. struct MidiOutHandle
  212276. {
  212277. int refCount;
  212278. UINT deviceId;
  212279. HMIDIOUT handle;
  212280. static Array<MidiOutHandle*> activeHandles;
  212281. private:
  212282. JUCE_LEAK_DETECTOR (MidiOutHandle);
  212283. };
  212284. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212285. const StringArray MidiOutput::getDevices()
  212286. {
  212287. StringArray s;
  212288. const int num = midiOutGetNumDevs();
  212289. for (int i = 0; i < num; ++i)
  212290. {
  212291. MIDIOUTCAPS mc;
  212292. zerostruct (mc);
  212293. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212294. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212295. }
  212296. return s;
  212297. }
  212298. int MidiOutput::getDefaultDeviceIndex()
  212299. {
  212300. const int num = midiOutGetNumDevs();
  212301. int n = 0;
  212302. for (int i = 0; i < num; ++i)
  212303. {
  212304. MIDIOUTCAPS mc;
  212305. zerostruct (mc);
  212306. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212307. {
  212308. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212309. return n;
  212310. ++n;
  212311. }
  212312. }
  212313. return 0;
  212314. }
  212315. MidiOutput* MidiOutput::openDevice (int index)
  212316. {
  212317. UINT deviceId = MIDI_MAPPER;
  212318. const int num = midiOutGetNumDevs();
  212319. int i, n = 0;
  212320. for (i = 0; i < num; ++i)
  212321. {
  212322. MIDIOUTCAPS mc;
  212323. zerostruct (mc);
  212324. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212325. {
  212326. // use the microsoft sw synth as a default - best not to allow deviceId
  212327. // to be MIDI_MAPPER, or else device sharing breaks
  212328. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212329. deviceId = i;
  212330. if (index == n)
  212331. {
  212332. deviceId = i;
  212333. break;
  212334. }
  212335. ++n;
  212336. }
  212337. }
  212338. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212339. {
  212340. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212341. if (han != 0 && han->deviceId == deviceId)
  212342. {
  212343. han->refCount++;
  212344. MidiOutput* const out = new MidiOutput();
  212345. out->internal = han;
  212346. return out;
  212347. }
  212348. }
  212349. for (i = 4; --i >= 0;)
  212350. {
  212351. HMIDIOUT h = 0;
  212352. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212353. if (res == MMSYSERR_NOERROR)
  212354. {
  212355. MidiOutHandle* const han = new MidiOutHandle();
  212356. han->deviceId = deviceId;
  212357. han->refCount = 1;
  212358. han->handle = h;
  212359. MidiOutHandle::activeHandles.add (han);
  212360. MidiOutput* const out = new MidiOutput();
  212361. out->internal = han;
  212362. return out;
  212363. }
  212364. else if (res == MMSYSERR_ALLOCATED)
  212365. {
  212366. Sleep (100);
  212367. }
  212368. else
  212369. {
  212370. break;
  212371. }
  212372. }
  212373. return 0;
  212374. }
  212375. MidiOutput::~MidiOutput()
  212376. {
  212377. stopBackgroundThread();
  212378. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212379. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212380. {
  212381. midiOutClose (h->handle);
  212382. MidiOutHandle::activeHandles.removeValue (h);
  212383. delete h;
  212384. }
  212385. }
  212386. void MidiOutput::reset()
  212387. {
  212388. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212389. midiOutReset (h->handle);
  212390. }
  212391. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212392. {
  212393. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212394. DWORD n;
  212395. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212396. {
  212397. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212398. rightVol = nn[0] / (float) 0xffff;
  212399. leftVol = nn[1] / (float) 0xffff;
  212400. return true;
  212401. }
  212402. else
  212403. {
  212404. rightVol = leftVol = 1.0f;
  212405. return false;
  212406. }
  212407. }
  212408. void MidiOutput::setVolume (float leftVol, float rightVol)
  212409. {
  212410. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212411. DWORD n;
  212412. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212413. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212414. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212415. midiOutSetVolume (handle->handle, n);
  212416. }
  212417. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212418. {
  212419. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212420. if (message.getRawDataSize() > 3
  212421. || message.isSysEx())
  212422. {
  212423. MIDIHDR h;
  212424. zerostruct (h);
  212425. h.lpData = (char*) message.getRawData();
  212426. h.dwBufferLength = message.getRawDataSize();
  212427. h.dwBytesRecorded = message.getRawDataSize();
  212428. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212429. {
  212430. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212431. if (res == MMSYSERR_NOERROR)
  212432. {
  212433. while ((h.dwFlags & MHDR_DONE) == 0)
  212434. Sleep (1);
  212435. int count = 500; // 1 sec timeout
  212436. while (--count >= 0)
  212437. {
  212438. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212439. if (res == MIDIERR_STILLPLAYING)
  212440. Sleep (2);
  212441. else
  212442. break;
  212443. }
  212444. }
  212445. }
  212446. }
  212447. else
  212448. {
  212449. midiOutShortMsg (handle->handle,
  212450. *(unsigned int*) message.getRawData());
  212451. }
  212452. }
  212453. #endif
  212454. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212455. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212456. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212457. // compiled on its own).
  212458. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212459. #undef WINDOWS
  212460. // #define ASIO_DEBUGGING 1
  212461. #undef log
  212462. #if ASIO_DEBUGGING
  212463. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212464. #else
  212465. #define log(a) {}
  212466. #endif
  212467. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  212468. to be pretty random about whether or not they do this. If you hit an error using these functions
  212469. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  212470. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  212471. */
  212472. #define JUCE_ASIOCALLBACK __cdecl
  212473. namespace ASIODebugging
  212474. {
  212475. #if ASIO_DEBUGGING
  212476. static void log (const String& context, long error)
  212477. {
  212478. String err ("unknown error");
  212479. if (error == ASE_NotPresent) err = "Not Present";
  212480. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212481. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212482. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212483. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212484. else if (error == ASE_NoClock) err = "No Clock";
  212485. else if (error == ASE_NoMemory) err = "Out of memory";
  212486. log ("!!error: " + context + " - " + err);
  212487. }
  212488. #define logError(a, b) ASIODebugging::log ((a), (b))
  212489. #else
  212490. #define logError(a, b) {}
  212491. #endif
  212492. }
  212493. class ASIOAudioIODevice;
  212494. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212495. static const int maxASIOChannels = 160;
  212496. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212497. private Timer
  212498. {
  212499. public:
  212500. Component ourWindow;
  212501. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212502. const String& optionalDllForDirectLoading_)
  212503. : AudioIODevice (name_, "ASIO"),
  212504. asioObject (0),
  212505. classId (classId_),
  212506. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212507. currentBitDepth (16),
  212508. currentSampleRate (0),
  212509. isOpen_ (false),
  212510. isStarted (false),
  212511. postOutput (true),
  212512. insideControlPanelModalLoop (false),
  212513. shouldUsePreferredSize (false)
  212514. {
  212515. name = name_;
  212516. ourWindow.addToDesktop (0);
  212517. windowHandle = ourWindow.getWindowHandle();
  212518. jassert (currentASIODev [slotNumber] == 0);
  212519. currentASIODev [slotNumber] = this;
  212520. openDevice();
  212521. }
  212522. ~ASIOAudioIODevice()
  212523. {
  212524. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212525. if (currentASIODev[i] == this)
  212526. currentASIODev[i] = 0;
  212527. close();
  212528. log ("ASIO - exiting");
  212529. removeCurrentDriver();
  212530. }
  212531. void updateSampleRates()
  212532. {
  212533. // find a list of sample rates..
  212534. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212535. sampleRates.clear();
  212536. if (asioObject != 0)
  212537. {
  212538. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212539. {
  212540. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212541. if (err == 0)
  212542. {
  212543. sampleRates.add ((int) possibleSampleRates[index]);
  212544. log ("rate: " + String ((int) possibleSampleRates[index]));
  212545. }
  212546. else if (err != ASE_NoClock)
  212547. {
  212548. logError ("CanSampleRate", err);
  212549. }
  212550. }
  212551. if (sampleRates.size() == 0)
  212552. {
  212553. double cr = 0;
  212554. const long err = asioObject->getSampleRate (&cr);
  212555. log ("No sample rates supported - current rate: " + String ((int) cr));
  212556. if (err == 0)
  212557. sampleRates.add ((int) cr);
  212558. }
  212559. }
  212560. }
  212561. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212562. const StringArray getInputChannelNames() { return inputChannelNames; }
  212563. int getNumSampleRates() { return sampleRates.size(); }
  212564. double getSampleRate (int index) { return sampleRates [index]; }
  212565. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212566. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212567. int getDefaultBufferSize() { return preferredSize; }
  212568. const String open (const BigInteger& inputChannels,
  212569. const BigInteger& outputChannels,
  212570. double sr,
  212571. int bufferSizeSamples)
  212572. {
  212573. close();
  212574. currentCallback = 0;
  212575. if (bufferSizeSamples <= 0)
  212576. shouldUsePreferredSize = true;
  212577. if (asioObject == 0 || ! isASIOOpen)
  212578. {
  212579. log ("Warning: device not open");
  212580. const String err (openDevice());
  212581. if (asioObject == 0 || ! isASIOOpen)
  212582. return err;
  212583. }
  212584. isStarted = false;
  212585. bufferIndex = -1;
  212586. long err = 0;
  212587. long newPreferredSize = 0;
  212588. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212589. minSize = 0;
  212590. maxSize = 0;
  212591. newPreferredSize = 0;
  212592. granularity = 0;
  212593. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212594. {
  212595. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212596. shouldUsePreferredSize = true;
  212597. preferredSize = newPreferredSize;
  212598. }
  212599. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212600. // dynamic changes to the buffer size...
  212601. shouldUsePreferredSize = shouldUsePreferredSize
  212602. || getName().containsIgnoreCase ("Digidesign");
  212603. if (shouldUsePreferredSize)
  212604. {
  212605. log ("Using preferred size for buffer..");
  212606. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212607. {
  212608. bufferSizeSamples = preferredSize;
  212609. }
  212610. else
  212611. {
  212612. bufferSizeSamples = 1024;
  212613. logError ("GetBufferSize1", err);
  212614. }
  212615. shouldUsePreferredSize = false;
  212616. }
  212617. int sampleRate = roundDoubleToInt (sr);
  212618. currentSampleRate = sampleRate;
  212619. currentBlockSizeSamples = bufferSizeSamples;
  212620. currentChansOut.clear();
  212621. currentChansIn.clear();
  212622. zeromem (inBuffers, sizeof (inBuffers));
  212623. zeromem (outBuffers, sizeof (outBuffers));
  212624. updateSampleRates();
  212625. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212626. sampleRate = sampleRates[0];
  212627. jassert (sampleRate != 0);
  212628. if (sampleRate == 0)
  212629. sampleRate = 44100;
  212630. long numSources = 32;
  212631. ASIOClockSource clocks[32];
  212632. zeromem (clocks, sizeof (clocks));
  212633. asioObject->getClockSources (clocks, &numSources);
  212634. bool isSourceSet = false;
  212635. // careful not to remove this loop because it does more than just logging!
  212636. int i;
  212637. for (i = 0; i < numSources; ++i)
  212638. {
  212639. String s ("clock: ");
  212640. s += clocks[i].name;
  212641. if (clocks[i].isCurrentSource)
  212642. {
  212643. isSourceSet = true;
  212644. s << " (cur)";
  212645. }
  212646. log (s);
  212647. }
  212648. if (numSources > 1 && ! isSourceSet)
  212649. {
  212650. log ("setting clock source");
  212651. asioObject->setClockSource (clocks[0].index);
  212652. Thread::sleep (20);
  212653. }
  212654. else
  212655. {
  212656. if (numSources == 0)
  212657. {
  212658. log ("ASIO - no clock sources!");
  212659. }
  212660. }
  212661. double cr = 0;
  212662. err = asioObject->getSampleRate (&cr);
  212663. if (err == 0)
  212664. {
  212665. currentSampleRate = cr;
  212666. }
  212667. else
  212668. {
  212669. logError ("GetSampleRate", err);
  212670. currentSampleRate = 0;
  212671. }
  212672. error = String::empty;
  212673. needToReset = false;
  212674. isReSync = false;
  212675. err = 0;
  212676. bool buffersCreated = false;
  212677. if (currentSampleRate != sampleRate)
  212678. {
  212679. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212680. err = asioObject->setSampleRate (sampleRate);
  212681. if (err == ASE_NoClock && numSources > 0)
  212682. {
  212683. log ("trying to set a clock source..");
  212684. Thread::sleep (10);
  212685. err = asioObject->setClockSource (clocks[0].index);
  212686. if (err != 0)
  212687. {
  212688. logError ("SetClock", err);
  212689. }
  212690. Thread::sleep (10);
  212691. err = asioObject->setSampleRate (sampleRate);
  212692. }
  212693. }
  212694. if (err == 0)
  212695. {
  212696. currentSampleRate = sampleRate;
  212697. if (needToReset)
  212698. {
  212699. if (isReSync)
  212700. {
  212701. log ("Resync request");
  212702. }
  212703. log ("! Resetting ASIO after sample rate change");
  212704. removeCurrentDriver();
  212705. loadDriver();
  212706. const String error (initDriver());
  212707. if (error.isNotEmpty())
  212708. {
  212709. log ("ASIOInit: " + error);
  212710. }
  212711. needToReset = false;
  212712. isReSync = false;
  212713. }
  212714. numActiveInputChans = 0;
  212715. numActiveOutputChans = 0;
  212716. ASIOBufferInfo* info = bufferInfos;
  212717. int i;
  212718. for (i = 0; i < totalNumInputChans; ++i)
  212719. {
  212720. if (inputChannels[i])
  212721. {
  212722. currentChansIn.setBit (i);
  212723. info->isInput = 1;
  212724. info->channelNum = i;
  212725. info->buffers[0] = info->buffers[1] = 0;
  212726. ++info;
  212727. ++numActiveInputChans;
  212728. }
  212729. }
  212730. for (i = 0; i < totalNumOutputChans; ++i)
  212731. {
  212732. if (outputChannels[i])
  212733. {
  212734. currentChansOut.setBit (i);
  212735. info->isInput = 0;
  212736. info->channelNum = i;
  212737. info->buffers[0] = info->buffers[1] = 0;
  212738. ++info;
  212739. ++numActiveOutputChans;
  212740. }
  212741. }
  212742. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212743. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212744. if (currentASIODev[0] == this)
  212745. {
  212746. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212747. callbacks.asioMessage = &asioMessagesCallback0;
  212748. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212749. }
  212750. else if (currentASIODev[1] == this)
  212751. {
  212752. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212753. callbacks.asioMessage = &asioMessagesCallback1;
  212754. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212755. }
  212756. else if (currentASIODev[2] == this)
  212757. {
  212758. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212759. callbacks.asioMessage = &asioMessagesCallback2;
  212760. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212761. }
  212762. else
  212763. {
  212764. jassertfalse;
  212765. }
  212766. log ("disposing buffers");
  212767. err = asioObject->disposeBuffers();
  212768. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212769. err = asioObject->createBuffers (bufferInfos,
  212770. totalBuffers,
  212771. currentBlockSizeSamples,
  212772. &callbacks);
  212773. if (err != 0)
  212774. {
  212775. currentBlockSizeSamples = preferredSize;
  212776. logError ("create buffers 2", err);
  212777. asioObject->disposeBuffers();
  212778. err = asioObject->createBuffers (bufferInfos,
  212779. totalBuffers,
  212780. currentBlockSizeSamples,
  212781. &callbacks);
  212782. }
  212783. if (err == 0)
  212784. {
  212785. buffersCreated = true;
  212786. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212787. int n = 0;
  212788. Array <int> types;
  212789. currentBitDepth = 16;
  212790. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212791. {
  212792. if (inputChannels[i])
  212793. {
  212794. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212795. ASIOChannelInfo channelInfo;
  212796. zerostruct (channelInfo);
  212797. channelInfo.channel = i;
  212798. channelInfo.isInput = 1;
  212799. asioObject->getChannelInfo (&channelInfo);
  212800. types.addIfNotAlreadyThere (channelInfo.type);
  212801. typeToFormatParameters (channelInfo.type,
  212802. inputChannelBitDepths[n],
  212803. inputChannelBytesPerSample[n],
  212804. inputChannelIsFloat[n],
  212805. inputChannelLittleEndian[n]);
  212806. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212807. ++n;
  212808. }
  212809. }
  212810. jassert (numActiveInputChans == n);
  212811. n = 0;
  212812. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212813. {
  212814. if (outputChannels[i])
  212815. {
  212816. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212817. ASIOChannelInfo channelInfo;
  212818. zerostruct (channelInfo);
  212819. channelInfo.channel = i;
  212820. channelInfo.isInput = 0;
  212821. asioObject->getChannelInfo (&channelInfo);
  212822. types.addIfNotAlreadyThere (channelInfo.type);
  212823. typeToFormatParameters (channelInfo.type,
  212824. outputChannelBitDepths[n],
  212825. outputChannelBytesPerSample[n],
  212826. outputChannelIsFloat[n],
  212827. outputChannelLittleEndian[n]);
  212828. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212829. ++n;
  212830. }
  212831. }
  212832. jassert (numActiveOutputChans == n);
  212833. for (i = types.size(); --i >= 0;)
  212834. {
  212835. log ("channel format: " + String (types[i]));
  212836. }
  212837. jassert (n <= totalBuffers);
  212838. for (i = 0; i < numActiveOutputChans; ++i)
  212839. {
  212840. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212841. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212842. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212843. {
  212844. log ("!! Null buffers");
  212845. }
  212846. else
  212847. {
  212848. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212849. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212850. }
  212851. }
  212852. inputLatency = outputLatency = 0;
  212853. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212854. {
  212855. log ("ASIO - no latencies");
  212856. }
  212857. else
  212858. {
  212859. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212860. }
  212861. isOpen_ = true;
  212862. log ("starting ASIO");
  212863. calledback = false;
  212864. err = asioObject->start();
  212865. if (err != 0)
  212866. {
  212867. isOpen_ = false;
  212868. log ("ASIO - stop on failure");
  212869. Thread::sleep (10);
  212870. asioObject->stop();
  212871. error = "Can't start device";
  212872. Thread::sleep (10);
  212873. }
  212874. else
  212875. {
  212876. int count = 300;
  212877. while (--count > 0 && ! calledback)
  212878. Thread::sleep (10);
  212879. isStarted = true;
  212880. if (! calledback)
  212881. {
  212882. error = "Device didn't start correctly";
  212883. log ("ASIO didn't callback - stopping..");
  212884. asioObject->stop();
  212885. }
  212886. }
  212887. }
  212888. else
  212889. {
  212890. error = "Can't create i/o buffers";
  212891. }
  212892. }
  212893. else
  212894. {
  212895. error = "Can't set sample rate: ";
  212896. error << sampleRate;
  212897. }
  212898. if (error.isNotEmpty())
  212899. {
  212900. logError (error, err);
  212901. if (asioObject != 0 && buffersCreated)
  212902. asioObject->disposeBuffers();
  212903. Thread::sleep (20);
  212904. isStarted = false;
  212905. isOpen_ = false;
  212906. const String errorCopy (error);
  212907. close(); // (this resets the error string)
  212908. error = errorCopy;
  212909. }
  212910. needToReset = false;
  212911. isReSync = false;
  212912. return error;
  212913. }
  212914. void close()
  212915. {
  212916. error = String::empty;
  212917. stopTimer();
  212918. stop();
  212919. if (isASIOOpen && isOpen_)
  212920. {
  212921. const ScopedLock sl (callbackLock);
  212922. isOpen_ = false;
  212923. isStarted = false;
  212924. needToReset = false;
  212925. isReSync = false;
  212926. log ("ASIO - stopping");
  212927. if (asioObject != 0)
  212928. {
  212929. Thread::sleep (20);
  212930. asioObject->stop();
  212931. Thread::sleep (10);
  212932. asioObject->disposeBuffers();
  212933. }
  212934. Thread::sleep (10);
  212935. }
  212936. }
  212937. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212938. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212939. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212940. double getCurrentSampleRate() { return currentSampleRate; }
  212941. int getCurrentBitDepth() { return currentBitDepth; }
  212942. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212943. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212944. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212945. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212946. void start (AudioIODeviceCallback* callback)
  212947. {
  212948. if (callback != 0)
  212949. {
  212950. callback->audioDeviceAboutToStart (this);
  212951. const ScopedLock sl (callbackLock);
  212952. currentCallback = callback;
  212953. }
  212954. }
  212955. void stop()
  212956. {
  212957. AudioIODeviceCallback* const lastCallback = currentCallback;
  212958. {
  212959. const ScopedLock sl (callbackLock);
  212960. currentCallback = 0;
  212961. }
  212962. if (lastCallback != 0)
  212963. lastCallback->audioDeviceStopped();
  212964. }
  212965. const String getLastError() { return error; }
  212966. bool hasControlPanel() const { return true; }
  212967. bool showControlPanel()
  212968. {
  212969. log ("ASIO - showing control panel");
  212970. Component modalWindow (String::empty);
  212971. modalWindow.setOpaque (true);
  212972. modalWindow.addToDesktop (0);
  212973. modalWindow.enterModalState();
  212974. bool done = false;
  212975. JUCE_TRY
  212976. {
  212977. // are there are devices that need to be closed before showing their control panel?
  212978. // close();
  212979. insideControlPanelModalLoop = true;
  212980. const uint32 started = Time::getMillisecondCounter();
  212981. if (asioObject != 0)
  212982. {
  212983. asioObject->controlPanel();
  212984. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212985. log ("spent: " + String (spent));
  212986. if (spent > 300)
  212987. {
  212988. shouldUsePreferredSize = true;
  212989. done = true;
  212990. }
  212991. }
  212992. }
  212993. JUCE_CATCH_ALL
  212994. insideControlPanelModalLoop = false;
  212995. return done;
  212996. }
  212997. void resetRequest() throw()
  212998. {
  212999. needToReset = true;
  213000. }
  213001. void resyncRequest() throw()
  213002. {
  213003. needToReset = true;
  213004. isReSync = true;
  213005. }
  213006. void timerCallback()
  213007. {
  213008. if (! insideControlPanelModalLoop)
  213009. {
  213010. stopTimer();
  213011. // used to cause a reset
  213012. log ("! ASIO restart request!");
  213013. if (isOpen_)
  213014. {
  213015. AudioIODeviceCallback* const oldCallback = currentCallback;
  213016. close();
  213017. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213018. currentSampleRate, currentBlockSizeSamples);
  213019. if (oldCallback != 0)
  213020. start (oldCallback);
  213021. }
  213022. }
  213023. else
  213024. {
  213025. startTimer (100);
  213026. }
  213027. }
  213028. private:
  213029. IASIO* volatile asioObject;
  213030. ASIOCallbacks callbacks;
  213031. void* windowHandle;
  213032. CLSID classId;
  213033. const String optionalDllForDirectLoading;
  213034. String error;
  213035. long totalNumInputChans, totalNumOutputChans;
  213036. StringArray inputChannelNames, outputChannelNames;
  213037. Array<int> sampleRates, bufferSizes;
  213038. long inputLatency, outputLatency;
  213039. long minSize, maxSize, preferredSize, granularity;
  213040. int volatile currentBlockSizeSamples;
  213041. int volatile currentBitDepth;
  213042. double volatile currentSampleRate;
  213043. BigInteger currentChansOut, currentChansIn;
  213044. AudioIODeviceCallback* volatile currentCallback;
  213045. CriticalSection callbackLock;
  213046. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213047. float* inBuffers [maxASIOChannels];
  213048. float* outBuffers [maxASIOChannels];
  213049. int inputChannelBitDepths [maxASIOChannels];
  213050. int outputChannelBitDepths [maxASIOChannels];
  213051. int inputChannelBytesPerSample [maxASIOChannels];
  213052. int outputChannelBytesPerSample [maxASIOChannels];
  213053. bool inputChannelIsFloat [maxASIOChannels];
  213054. bool outputChannelIsFloat [maxASIOChannels];
  213055. bool inputChannelLittleEndian [maxASIOChannels];
  213056. bool outputChannelLittleEndian [maxASIOChannels];
  213057. WaitableEvent event1;
  213058. HeapBlock <float> tempBuffer;
  213059. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213060. bool isOpen_, isStarted;
  213061. bool volatile isASIOOpen;
  213062. bool volatile calledback;
  213063. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213064. bool volatile insideControlPanelModalLoop;
  213065. bool volatile shouldUsePreferredSize;
  213066. void removeCurrentDriver()
  213067. {
  213068. if (asioObject != 0)
  213069. {
  213070. asioObject->Release();
  213071. asioObject = 0;
  213072. }
  213073. }
  213074. bool loadDriver()
  213075. {
  213076. removeCurrentDriver();
  213077. JUCE_TRY
  213078. {
  213079. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213080. classId, (void**) &asioObject) == S_OK)
  213081. {
  213082. return true;
  213083. }
  213084. // If a class isn't registered but we have a path for it, we can fallback to
  213085. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213086. if (optionalDllForDirectLoading.isNotEmpty())
  213087. {
  213088. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213089. if (h != 0)
  213090. {
  213091. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213092. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213093. if (dllGetClassObject != 0)
  213094. {
  213095. IClassFactory* classFactory = 0;
  213096. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213097. if (classFactory != 0)
  213098. {
  213099. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213100. classFactory->Release();
  213101. }
  213102. return asioObject != 0;
  213103. }
  213104. }
  213105. }
  213106. }
  213107. JUCE_CATCH_ALL
  213108. asioObject = 0;
  213109. return false;
  213110. }
  213111. const String initDriver()
  213112. {
  213113. if (asioObject != 0)
  213114. {
  213115. char buffer [256];
  213116. zeromem (buffer, sizeof (buffer));
  213117. if (! asioObject->init (windowHandle))
  213118. {
  213119. asioObject->getErrorMessage (buffer);
  213120. return String (buffer, sizeof (buffer) - 1);
  213121. }
  213122. // just in case any daft drivers expect this to be called..
  213123. asioObject->getDriverName (buffer);
  213124. return String::empty;
  213125. }
  213126. return "No Driver";
  213127. }
  213128. const String openDevice()
  213129. {
  213130. // use this in case the driver starts opening dialog boxes..
  213131. Component modalWindow (String::empty);
  213132. modalWindow.setOpaque (true);
  213133. modalWindow.addToDesktop (0);
  213134. modalWindow.enterModalState();
  213135. // open the device and get its info..
  213136. log ("opening ASIO device: " + getName());
  213137. needToReset = false;
  213138. isReSync = false;
  213139. outputChannelNames.clear();
  213140. inputChannelNames.clear();
  213141. bufferSizes.clear();
  213142. sampleRates.clear();
  213143. isASIOOpen = false;
  213144. isOpen_ = false;
  213145. totalNumInputChans = 0;
  213146. totalNumOutputChans = 0;
  213147. numActiveInputChans = 0;
  213148. numActiveOutputChans = 0;
  213149. currentCallback = 0;
  213150. error = String::empty;
  213151. if (getName().isEmpty())
  213152. return error;
  213153. long err = 0;
  213154. if (loadDriver())
  213155. {
  213156. if ((error = initDriver()).isEmpty())
  213157. {
  213158. numActiveInputChans = 0;
  213159. numActiveOutputChans = 0;
  213160. totalNumInputChans = 0;
  213161. totalNumOutputChans = 0;
  213162. if (asioObject != 0
  213163. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213164. {
  213165. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213166. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213167. {
  213168. // find a list of buffer sizes..
  213169. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213170. if (granularity >= 0)
  213171. {
  213172. granularity = jmax (1, (int) granularity);
  213173. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213174. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213175. }
  213176. else if (granularity < 0)
  213177. {
  213178. for (int i = 0; i < 18; ++i)
  213179. {
  213180. const int s = (1 << i);
  213181. if (s >= minSize && s <= maxSize)
  213182. bufferSizes.add (s);
  213183. }
  213184. }
  213185. if (! bufferSizes.contains (preferredSize))
  213186. bufferSizes.insert (0, preferredSize);
  213187. double currentRate = 0;
  213188. asioObject->getSampleRate (&currentRate);
  213189. if (currentRate <= 0.0 || currentRate > 192001.0)
  213190. {
  213191. log ("setting sample rate");
  213192. err = asioObject->setSampleRate (44100.0);
  213193. if (err != 0)
  213194. {
  213195. logError ("setting sample rate", err);
  213196. }
  213197. asioObject->getSampleRate (&currentRate);
  213198. }
  213199. currentSampleRate = currentRate;
  213200. postOutput = (asioObject->outputReady() == 0);
  213201. if (postOutput)
  213202. {
  213203. log ("ASIO outputReady = ok");
  213204. }
  213205. updateSampleRates();
  213206. // ..because cubase does it at this point
  213207. inputLatency = outputLatency = 0;
  213208. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213209. {
  213210. log ("ASIO - no latencies");
  213211. }
  213212. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213213. // create some dummy buffers now.. because cubase does..
  213214. numActiveInputChans = 0;
  213215. numActiveOutputChans = 0;
  213216. ASIOBufferInfo* info = bufferInfos;
  213217. int i, numChans = 0;
  213218. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213219. {
  213220. info->isInput = 1;
  213221. info->channelNum = i;
  213222. info->buffers[0] = info->buffers[1] = 0;
  213223. ++info;
  213224. ++numChans;
  213225. }
  213226. const int outputBufferIndex = numChans;
  213227. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213228. {
  213229. info->isInput = 0;
  213230. info->channelNum = i;
  213231. info->buffers[0] = info->buffers[1] = 0;
  213232. ++info;
  213233. ++numChans;
  213234. }
  213235. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213236. if (currentASIODev[0] == this)
  213237. {
  213238. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213239. callbacks.asioMessage = &asioMessagesCallback0;
  213240. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213241. }
  213242. else if (currentASIODev[1] == this)
  213243. {
  213244. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213245. callbacks.asioMessage = &asioMessagesCallback1;
  213246. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213247. }
  213248. else if (currentASIODev[2] == this)
  213249. {
  213250. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213251. callbacks.asioMessage = &asioMessagesCallback2;
  213252. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213253. }
  213254. else
  213255. {
  213256. jassertfalse;
  213257. }
  213258. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213259. if (preferredSize > 0)
  213260. {
  213261. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213262. if (err != 0)
  213263. {
  213264. logError ("dummy buffers", err);
  213265. }
  213266. }
  213267. long newInps = 0, newOuts = 0;
  213268. asioObject->getChannels (&newInps, &newOuts);
  213269. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213270. {
  213271. totalNumInputChans = newInps;
  213272. totalNumOutputChans = newOuts;
  213273. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213274. }
  213275. updateSampleRates();
  213276. ASIOChannelInfo channelInfo;
  213277. channelInfo.type = 0;
  213278. for (i = 0; i < totalNumInputChans; ++i)
  213279. {
  213280. zerostruct (channelInfo);
  213281. channelInfo.channel = i;
  213282. channelInfo.isInput = 1;
  213283. asioObject->getChannelInfo (&channelInfo);
  213284. inputChannelNames.add (String (channelInfo.name));
  213285. }
  213286. for (i = 0; i < totalNumOutputChans; ++i)
  213287. {
  213288. zerostruct (channelInfo);
  213289. channelInfo.channel = i;
  213290. channelInfo.isInput = 0;
  213291. asioObject->getChannelInfo (&channelInfo);
  213292. outputChannelNames.add (String (channelInfo.name));
  213293. typeToFormatParameters (channelInfo.type,
  213294. outputChannelBitDepths[i],
  213295. outputChannelBytesPerSample[i],
  213296. outputChannelIsFloat[i],
  213297. outputChannelLittleEndian[i]);
  213298. if (i < 2)
  213299. {
  213300. // clear the channels that are used with the dummy stuff
  213301. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213302. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213303. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213304. }
  213305. }
  213306. outputChannelNames.trim();
  213307. inputChannelNames.trim();
  213308. outputChannelNames.appendNumbersToDuplicates (false, true);
  213309. inputChannelNames.appendNumbersToDuplicates (false, true);
  213310. // start and stop because cubase does it..
  213311. asioObject->getLatencies (&inputLatency, &outputLatency);
  213312. if ((err = asioObject->start()) != 0)
  213313. {
  213314. // ignore an error here, as it might start later after setting other stuff up
  213315. logError ("ASIO start", err);
  213316. }
  213317. Thread::sleep (100);
  213318. asioObject->stop();
  213319. }
  213320. else
  213321. {
  213322. error = "Can't detect buffer sizes";
  213323. }
  213324. }
  213325. else
  213326. {
  213327. error = "Can't detect asio channels";
  213328. }
  213329. }
  213330. }
  213331. else
  213332. {
  213333. error = "No such device";
  213334. }
  213335. if (error.isNotEmpty())
  213336. {
  213337. logError (error, err);
  213338. if (asioObject != 0)
  213339. asioObject->disposeBuffers();
  213340. removeCurrentDriver();
  213341. isASIOOpen = false;
  213342. }
  213343. else
  213344. {
  213345. isASIOOpen = true;
  213346. log ("ASIO device open");
  213347. }
  213348. isOpen_ = false;
  213349. needToReset = false;
  213350. isReSync = false;
  213351. return error;
  213352. }
  213353. void JUCE_ASIOCALLBACK callback (const long index)
  213354. {
  213355. if (isStarted)
  213356. {
  213357. bufferIndex = index;
  213358. processBuffer();
  213359. }
  213360. else
  213361. {
  213362. if (postOutput && (asioObject != 0))
  213363. asioObject->outputReady();
  213364. }
  213365. calledback = true;
  213366. }
  213367. void processBuffer()
  213368. {
  213369. const ASIOBufferInfo* const infos = bufferInfos;
  213370. const int bi = bufferIndex;
  213371. const ScopedLock sl (callbackLock);
  213372. if (needToReset)
  213373. {
  213374. needToReset = false;
  213375. if (isReSync)
  213376. {
  213377. log ("! ASIO resync");
  213378. isReSync = false;
  213379. }
  213380. else
  213381. {
  213382. startTimer (20);
  213383. }
  213384. }
  213385. if (bi >= 0)
  213386. {
  213387. const int samps = currentBlockSizeSamples;
  213388. if (currentCallback != 0)
  213389. {
  213390. int i;
  213391. for (i = 0; i < numActiveInputChans; ++i)
  213392. {
  213393. float* const dst = inBuffers[i];
  213394. jassert (dst != 0);
  213395. const char* const src = (const char*) (infos[i].buffers[bi]);
  213396. if (inputChannelIsFloat[i])
  213397. {
  213398. memcpy (dst, src, samps * sizeof (float));
  213399. }
  213400. else
  213401. {
  213402. jassert (dst == tempBuffer + (samps * i));
  213403. switch (inputChannelBitDepths[i])
  213404. {
  213405. case 16:
  213406. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213407. samps, inputChannelLittleEndian[i]);
  213408. break;
  213409. case 24:
  213410. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213411. samps, inputChannelLittleEndian[i]);
  213412. break;
  213413. case 32:
  213414. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213415. samps, inputChannelLittleEndian[i]);
  213416. break;
  213417. case 64:
  213418. jassertfalse;
  213419. break;
  213420. }
  213421. }
  213422. }
  213423. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213424. outBuffers, numActiveOutputChans, samps);
  213425. for (i = 0; i < numActiveOutputChans; ++i)
  213426. {
  213427. float* const src = outBuffers[i];
  213428. jassert (src != 0);
  213429. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213430. if (outputChannelIsFloat[i])
  213431. {
  213432. memcpy (dst, src, samps * sizeof (float));
  213433. }
  213434. else
  213435. {
  213436. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213437. switch (outputChannelBitDepths[i])
  213438. {
  213439. case 16:
  213440. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213441. samps, outputChannelLittleEndian[i]);
  213442. break;
  213443. case 24:
  213444. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213445. samps, outputChannelLittleEndian[i]);
  213446. break;
  213447. case 32:
  213448. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213449. samps, outputChannelLittleEndian[i]);
  213450. break;
  213451. case 64:
  213452. jassertfalse;
  213453. break;
  213454. }
  213455. }
  213456. }
  213457. }
  213458. else
  213459. {
  213460. for (int i = 0; i < numActiveOutputChans; ++i)
  213461. {
  213462. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213463. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213464. }
  213465. }
  213466. }
  213467. if (postOutput)
  213468. asioObject->outputReady();
  213469. }
  213470. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213471. {
  213472. if (currentASIODev[0] != 0)
  213473. currentASIODev[0]->callback (index);
  213474. return 0;
  213475. }
  213476. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213477. {
  213478. if (currentASIODev[1] != 0)
  213479. currentASIODev[1]->callback (index);
  213480. return 0;
  213481. }
  213482. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213483. {
  213484. if (currentASIODev[2] != 0)
  213485. currentASIODev[2]->callback (index);
  213486. return 0;
  213487. }
  213488. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  213489. {
  213490. if (currentASIODev[0] != 0)
  213491. currentASIODev[0]->callback (index);
  213492. }
  213493. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  213494. {
  213495. if (currentASIODev[1] != 0)
  213496. currentASIODev[1]->callback (index);
  213497. }
  213498. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  213499. {
  213500. if (currentASIODev[2] != 0)
  213501. currentASIODev[2]->callback (index);
  213502. }
  213503. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  213504. {
  213505. return asioMessagesCallback (selector, value, 0);
  213506. }
  213507. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  213508. {
  213509. return asioMessagesCallback (selector, value, 1);
  213510. }
  213511. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  213512. {
  213513. return asioMessagesCallback (selector, value, 2);
  213514. }
  213515. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  213516. {
  213517. switch (selector)
  213518. {
  213519. case kAsioSelectorSupported:
  213520. if (value == kAsioResetRequest
  213521. || value == kAsioEngineVersion
  213522. || value == kAsioResyncRequest
  213523. || value == kAsioLatenciesChanged
  213524. || value == kAsioSupportsInputMonitor)
  213525. return 1;
  213526. break;
  213527. case kAsioBufferSizeChange:
  213528. break;
  213529. case kAsioResetRequest:
  213530. if (currentASIODev[deviceIndex] != 0)
  213531. currentASIODev[deviceIndex]->resetRequest();
  213532. return 1;
  213533. case kAsioResyncRequest:
  213534. if (currentASIODev[deviceIndex] != 0)
  213535. currentASIODev[deviceIndex]->resyncRequest();
  213536. return 1;
  213537. case kAsioLatenciesChanged:
  213538. return 1;
  213539. case kAsioEngineVersion:
  213540. return 2;
  213541. case kAsioSupportsTimeInfo:
  213542. case kAsioSupportsTimeCode:
  213543. return 0;
  213544. }
  213545. return 0;
  213546. }
  213547. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213548. {
  213549. }
  213550. static void convertInt16ToFloat (const char* src,
  213551. float* dest,
  213552. const int srcStrideBytes,
  213553. int numSamples,
  213554. const bool littleEndian) throw()
  213555. {
  213556. const double g = 1.0 / 32768.0;
  213557. if (littleEndian)
  213558. {
  213559. while (--numSamples >= 0)
  213560. {
  213561. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213562. src += srcStrideBytes;
  213563. }
  213564. }
  213565. else
  213566. {
  213567. while (--numSamples >= 0)
  213568. {
  213569. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213570. src += srcStrideBytes;
  213571. }
  213572. }
  213573. }
  213574. static void convertFloatToInt16 (const float* src,
  213575. char* dest,
  213576. const int dstStrideBytes,
  213577. int numSamples,
  213578. const bool littleEndian) throw()
  213579. {
  213580. const double maxVal = (double) 0x7fff;
  213581. if (littleEndian)
  213582. {
  213583. while (--numSamples >= 0)
  213584. {
  213585. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213586. dest += dstStrideBytes;
  213587. }
  213588. }
  213589. else
  213590. {
  213591. while (--numSamples >= 0)
  213592. {
  213593. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213594. dest += dstStrideBytes;
  213595. }
  213596. }
  213597. }
  213598. static void convertInt24ToFloat (const char* src,
  213599. float* dest,
  213600. const int srcStrideBytes,
  213601. int numSamples,
  213602. const bool littleEndian) throw()
  213603. {
  213604. const double g = 1.0 / 0x7fffff;
  213605. if (littleEndian)
  213606. {
  213607. while (--numSamples >= 0)
  213608. {
  213609. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213610. src += srcStrideBytes;
  213611. }
  213612. }
  213613. else
  213614. {
  213615. while (--numSamples >= 0)
  213616. {
  213617. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213618. src += srcStrideBytes;
  213619. }
  213620. }
  213621. }
  213622. static void convertFloatToInt24 (const float* src,
  213623. char* dest,
  213624. const int dstStrideBytes,
  213625. int numSamples,
  213626. const bool littleEndian) throw()
  213627. {
  213628. const double maxVal = (double) 0x7fffff;
  213629. if (littleEndian)
  213630. {
  213631. while (--numSamples >= 0)
  213632. {
  213633. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213634. dest += dstStrideBytes;
  213635. }
  213636. }
  213637. else
  213638. {
  213639. while (--numSamples >= 0)
  213640. {
  213641. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213642. dest += dstStrideBytes;
  213643. }
  213644. }
  213645. }
  213646. static void convertInt32ToFloat (const char* src,
  213647. float* dest,
  213648. const int srcStrideBytes,
  213649. int numSamples,
  213650. const bool littleEndian) throw()
  213651. {
  213652. const double g = 1.0 / 0x7fffffff;
  213653. if (littleEndian)
  213654. {
  213655. while (--numSamples >= 0)
  213656. {
  213657. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213658. src += srcStrideBytes;
  213659. }
  213660. }
  213661. else
  213662. {
  213663. while (--numSamples >= 0)
  213664. {
  213665. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213666. src += srcStrideBytes;
  213667. }
  213668. }
  213669. }
  213670. static void convertFloatToInt32 (const float* src,
  213671. char* dest,
  213672. const int dstStrideBytes,
  213673. int numSamples,
  213674. const bool littleEndian) throw()
  213675. {
  213676. const double maxVal = (double) 0x7fffffff;
  213677. if (littleEndian)
  213678. {
  213679. while (--numSamples >= 0)
  213680. {
  213681. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213682. dest += dstStrideBytes;
  213683. }
  213684. }
  213685. else
  213686. {
  213687. while (--numSamples >= 0)
  213688. {
  213689. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213690. dest += dstStrideBytes;
  213691. }
  213692. }
  213693. }
  213694. static void typeToFormatParameters (const long type,
  213695. int& bitDepth,
  213696. int& byteStride,
  213697. bool& formatIsFloat,
  213698. bool& littleEndian) throw()
  213699. {
  213700. bitDepth = 0;
  213701. littleEndian = false;
  213702. formatIsFloat = false;
  213703. switch (type)
  213704. {
  213705. case ASIOSTInt16MSB:
  213706. case ASIOSTInt16LSB:
  213707. case ASIOSTInt32MSB16:
  213708. case ASIOSTInt32LSB16:
  213709. bitDepth = 16; break;
  213710. case ASIOSTFloat32MSB:
  213711. case ASIOSTFloat32LSB:
  213712. formatIsFloat = true;
  213713. bitDepth = 32; break;
  213714. case ASIOSTInt32MSB:
  213715. case ASIOSTInt32LSB:
  213716. bitDepth = 32; break;
  213717. case ASIOSTInt24MSB:
  213718. case ASIOSTInt24LSB:
  213719. case ASIOSTInt32MSB24:
  213720. case ASIOSTInt32LSB24:
  213721. case ASIOSTInt32MSB18:
  213722. case ASIOSTInt32MSB20:
  213723. case ASIOSTInt32LSB18:
  213724. case ASIOSTInt32LSB20:
  213725. bitDepth = 24; break;
  213726. case ASIOSTFloat64MSB:
  213727. case ASIOSTFloat64LSB:
  213728. default:
  213729. bitDepth = 64;
  213730. break;
  213731. }
  213732. switch (type)
  213733. {
  213734. case ASIOSTInt16MSB:
  213735. case ASIOSTInt32MSB16:
  213736. case ASIOSTFloat32MSB:
  213737. case ASIOSTFloat64MSB:
  213738. case ASIOSTInt32MSB:
  213739. case ASIOSTInt32MSB18:
  213740. case ASIOSTInt32MSB20:
  213741. case ASIOSTInt32MSB24:
  213742. case ASIOSTInt24MSB:
  213743. littleEndian = false; break;
  213744. case ASIOSTInt16LSB:
  213745. case ASIOSTInt32LSB16:
  213746. case ASIOSTFloat32LSB:
  213747. case ASIOSTFloat64LSB:
  213748. case ASIOSTInt32LSB:
  213749. case ASIOSTInt32LSB18:
  213750. case ASIOSTInt32LSB20:
  213751. case ASIOSTInt32LSB24:
  213752. case ASIOSTInt24LSB:
  213753. littleEndian = true; break;
  213754. default:
  213755. break;
  213756. }
  213757. switch (type)
  213758. {
  213759. case ASIOSTInt16LSB:
  213760. case ASIOSTInt16MSB:
  213761. byteStride = 2; break;
  213762. case ASIOSTInt24LSB:
  213763. case ASIOSTInt24MSB:
  213764. byteStride = 3; break;
  213765. case ASIOSTInt32MSB16:
  213766. case ASIOSTInt32LSB16:
  213767. case ASIOSTInt32MSB:
  213768. case ASIOSTInt32MSB18:
  213769. case ASIOSTInt32MSB20:
  213770. case ASIOSTInt32MSB24:
  213771. case ASIOSTInt32LSB:
  213772. case ASIOSTInt32LSB18:
  213773. case ASIOSTInt32LSB20:
  213774. case ASIOSTInt32LSB24:
  213775. case ASIOSTFloat32LSB:
  213776. case ASIOSTFloat32MSB:
  213777. byteStride = 4; break;
  213778. case ASIOSTFloat64MSB:
  213779. case ASIOSTFloat64LSB:
  213780. byteStride = 8; break;
  213781. default:
  213782. break;
  213783. }
  213784. }
  213785. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213786. };
  213787. class ASIOAudioIODeviceType : public AudioIODeviceType
  213788. {
  213789. public:
  213790. ASIOAudioIODeviceType()
  213791. : AudioIODeviceType ("ASIO"),
  213792. hasScanned (false)
  213793. {
  213794. CoInitialize (0);
  213795. }
  213796. ~ASIOAudioIODeviceType()
  213797. {
  213798. }
  213799. void scanForDevices()
  213800. {
  213801. hasScanned = true;
  213802. deviceNames.clear();
  213803. classIds.clear();
  213804. HKEY hk = 0;
  213805. int index = 0;
  213806. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213807. {
  213808. for (;;)
  213809. {
  213810. char name [256];
  213811. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213812. {
  213813. addDriverInfo (name, hk);
  213814. }
  213815. else
  213816. {
  213817. break;
  213818. }
  213819. }
  213820. RegCloseKey (hk);
  213821. }
  213822. }
  213823. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213824. {
  213825. jassert (hasScanned); // need to call scanForDevices() before doing this
  213826. return deviceNames;
  213827. }
  213828. int getDefaultDeviceIndex (bool) const
  213829. {
  213830. jassert (hasScanned); // need to call scanForDevices() before doing this
  213831. for (int i = deviceNames.size(); --i >= 0;)
  213832. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213833. return i; // asio4all is a safe choice for a default..
  213834. #if JUCE_DEBUG
  213835. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213836. return 1; // (the digi m-box driver crashes the app when you run
  213837. // it in the debugger, which can be a bit annoying)
  213838. #endif
  213839. return 0;
  213840. }
  213841. static int findFreeSlot()
  213842. {
  213843. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213844. if (currentASIODev[i] == 0)
  213845. return i;
  213846. jassertfalse; // unfortunately you can only have a finite number
  213847. // of ASIO devices open at the same time..
  213848. return -1;
  213849. }
  213850. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213851. {
  213852. jassert (hasScanned); // need to call scanForDevices() before doing this
  213853. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213854. }
  213855. bool hasSeparateInputsAndOutputs() const { return false; }
  213856. AudioIODevice* createDevice (const String& outputDeviceName,
  213857. const String& inputDeviceName)
  213858. {
  213859. // ASIO can't open two different devices for input and output - they must be the same one.
  213860. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213861. jassert (hasScanned); // need to call scanForDevices() before doing this
  213862. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213863. : inputDeviceName);
  213864. if (index >= 0)
  213865. {
  213866. const int freeSlot = findFreeSlot();
  213867. if (freeSlot >= 0)
  213868. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213869. }
  213870. return 0;
  213871. }
  213872. private:
  213873. StringArray deviceNames;
  213874. OwnedArray <CLSID> classIds;
  213875. bool hasScanned;
  213876. static bool checkClassIsOk (const String& classId)
  213877. {
  213878. HKEY hk = 0;
  213879. bool ok = false;
  213880. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213881. {
  213882. int index = 0;
  213883. for (;;)
  213884. {
  213885. WCHAR buf [512];
  213886. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213887. {
  213888. if (classId.equalsIgnoreCase (buf))
  213889. {
  213890. HKEY subKey, pathKey;
  213891. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213892. {
  213893. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213894. {
  213895. WCHAR pathName [1024];
  213896. DWORD dtype = REG_SZ;
  213897. DWORD dsize = sizeof (pathName);
  213898. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213899. ok = File (pathName).exists();
  213900. RegCloseKey (pathKey);
  213901. }
  213902. RegCloseKey (subKey);
  213903. }
  213904. break;
  213905. }
  213906. }
  213907. else
  213908. {
  213909. break;
  213910. }
  213911. }
  213912. RegCloseKey (hk);
  213913. }
  213914. return ok;
  213915. }
  213916. void addDriverInfo (const String& keyName, HKEY hk)
  213917. {
  213918. HKEY subKey;
  213919. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213920. {
  213921. WCHAR buf [256];
  213922. zerostruct (buf);
  213923. DWORD dtype = REG_SZ;
  213924. DWORD dsize = sizeof (buf);
  213925. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213926. {
  213927. if (dsize > 0 && checkClassIsOk (buf))
  213928. {
  213929. CLSID classId;
  213930. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213931. {
  213932. dtype = REG_SZ;
  213933. dsize = sizeof (buf);
  213934. String deviceName;
  213935. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213936. deviceName = buf;
  213937. else
  213938. deviceName = keyName;
  213939. log ("found " + deviceName);
  213940. deviceNames.add (deviceName);
  213941. classIds.add (new CLSID (classId));
  213942. }
  213943. }
  213944. RegCloseKey (subKey);
  213945. }
  213946. }
  213947. }
  213948. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213949. };
  213950. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213951. {
  213952. return new ASIOAudioIODeviceType();
  213953. }
  213954. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213955. void* guid,
  213956. const String& optionalDllForDirectLoading)
  213957. {
  213958. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213959. if (freeSlot < 0)
  213960. return 0;
  213961. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213962. }
  213963. #undef logError
  213964. #undef log
  213965. #endif
  213966. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213967. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213968. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213969. // compiled on its own).
  213970. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213971. END_JUCE_NAMESPACE
  213972. extern "C"
  213973. {
  213974. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213975. typedef struct typeDSBUFFERDESC
  213976. {
  213977. DWORD dwSize;
  213978. DWORD dwFlags;
  213979. DWORD dwBufferBytes;
  213980. DWORD dwReserved;
  213981. LPWAVEFORMATEX lpwfxFormat;
  213982. GUID guid3DAlgorithm;
  213983. } DSBUFFERDESC;
  213984. struct IDirectSoundBuffer;
  213985. #undef INTERFACE
  213986. #define INTERFACE IDirectSound
  213987. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213988. {
  213989. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213990. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213991. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213992. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213993. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213994. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213995. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213996. STDMETHOD(Compact) (THIS) PURE;
  213997. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213998. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213999. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214000. };
  214001. #undef INTERFACE
  214002. #define INTERFACE IDirectSoundBuffer
  214003. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214004. {
  214005. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214006. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214007. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214008. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214009. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214010. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214011. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214012. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214013. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214014. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214015. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214016. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214017. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214018. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214019. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214020. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214021. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214022. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214023. STDMETHOD(Stop) (THIS) PURE;
  214024. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214025. STDMETHOD(Restore) (THIS) PURE;
  214026. };
  214027. typedef struct typeDSCBUFFERDESC
  214028. {
  214029. DWORD dwSize;
  214030. DWORD dwFlags;
  214031. DWORD dwBufferBytes;
  214032. DWORD dwReserved;
  214033. LPWAVEFORMATEX lpwfxFormat;
  214034. } DSCBUFFERDESC;
  214035. struct IDirectSoundCaptureBuffer;
  214036. #undef INTERFACE
  214037. #define INTERFACE IDirectSoundCapture
  214038. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214039. {
  214040. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214041. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214042. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214043. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214044. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214045. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214046. };
  214047. #undef INTERFACE
  214048. #define INTERFACE IDirectSoundCaptureBuffer
  214049. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214050. {
  214051. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214052. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214053. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214054. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214055. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214056. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214057. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214058. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214059. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214060. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214061. STDMETHOD(Stop) (THIS) PURE;
  214062. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214063. };
  214064. };
  214065. BEGIN_JUCE_NAMESPACE
  214066. namespace
  214067. {
  214068. const String getDSErrorMessage (HRESULT hr)
  214069. {
  214070. const char* result = 0;
  214071. switch (hr)
  214072. {
  214073. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214074. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214075. case E_INVALIDARG: result = "Invalid parameter"; break;
  214076. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214077. case E_FAIL: result = "Generic error"; break;
  214078. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214079. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214080. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214081. case E_NOTIMPL: result = "Unsupported function"; break;
  214082. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214083. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214084. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214085. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214086. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214087. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214088. case E_NOINTERFACE: result = "No interface"; break;
  214089. case S_OK: result = "No error"; break;
  214090. default: return "Unknown error: " + String ((int) hr);
  214091. }
  214092. return result;
  214093. }
  214094. #define DS_DEBUGGING 1
  214095. #ifdef DS_DEBUGGING
  214096. #define CATCH JUCE_CATCH_EXCEPTION
  214097. #undef log
  214098. #define log(a) Logger::writeToLog(a);
  214099. #undef logError
  214100. #define logError(a) logDSError(a, __LINE__);
  214101. static void logDSError (HRESULT hr, int lineNum)
  214102. {
  214103. if (hr != S_OK)
  214104. {
  214105. String error ("DS error at line ");
  214106. error << lineNum << " - " << getDSErrorMessage (hr);
  214107. log (error);
  214108. }
  214109. }
  214110. #else
  214111. #define CATCH JUCE_CATCH_ALL
  214112. #define log(a)
  214113. #define logError(a)
  214114. #endif
  214115. #define DSOUND_FUNCTION(functionName, params) \
  214116. typedef HRESULT (WINAPI *type##functionName) params; \
  214117. static type##functionName ds##functionName = 0;
  214118. #define DSOUND_FUNCTION_LOAD(functionName) \
  214119. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214120. jassert (ds##functionName != 0);
  214121. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214122. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214123. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214124. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214125. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214126. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214127. void initialiseDSoundFunctions()
  214128. {
  214129. if (dsDirectSoundCreate == 0)
  214130. {
  214131. HMODULE h = LoadLibraryA ("dsound.dll");
  214132. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214133. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214134. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214135. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214136. }
  214137. }
  214138. }
  214139. class DSoundInternalOutChannel
  214140. {
  214141. public:
  214142. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  214143. int bufferSize, float* left, float* right)
  214144. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214145. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214146. pDirectSound (0), pOutputBuffer (0)
  214147. {
  214148. }
  214149. ~DSoundInternalOutChannel()
  214150. {
  214151. close();
  214152. }
  214153. void close()
  214154. {
  214155. HRESULT hr;
  214156. if (pOutputBuffer != 0)
  214157. {
  214158. log ("closing dsound out: " + name);
  214159. hr = pOutputBuffer->Stop();
  214160. logError (hr);
  214161. hr = pOutputBuffer->Release();
  214162. pOutputBuffer = 0;
  214163. logError (hr);
  214164. }
  214165. if (pDirectSound != 0)
  214166. {
  214167. hr = pDirectSound->Release();
  214168. pDirectSound = 0;
  214169. logError (hr);
  214170. }
  214171. }
  214172. const String open()
  214173. {
  214174. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214175. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214176. pDirectSound = 0;
  214177. pOutputBuffer = 0;
  214178. writeOffset = 0;
  214179. String error;
  214180. HRESULT hr = E_NOINTERFACE;
  214181. if (dsDirectSoundCreate != 0)
  214182. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214183. if (hr == S_OK)
  214184. {
  214185. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214186. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214187. const int numChannels = 2;
  214188. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214189. logError (hr);
  214190. if (hr == S_OK)
  214191. {
  214192. IDirectSoundBuffer* pPrimaryBuffer;
  214193. DSBUFFERDESC primaryDesc;
  214194. zerostruct (primaryDesc);
  214195. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214196. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214197. primaryDesc.dwBufferBytes = 0;
  214198. primaryDesc.lpwfxFormat = 0;
  214199. log ("opening dsound out step 2");
  214200. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214201. logError (hr);
  214202. if (hr == S_OK)
  214203. {
  214204. WAVEFORMATEX wfFormat;
  214205. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214206. wfFormat.nChannels = (unsigned short) numChannels;
  214207. wfFormat.nSamplesPerSec = sampleRate;
  214208. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214209. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214210. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214211. wfFormat.cbSize = 0;
  214212. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214213. logError (hr);
  214214. if (hr == S_OK)
  214215. {
  214216. DSBUFFERDESC secondaryDesc;
  214217. zerostruct (secondaryDesc);
  214218. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214219. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214220. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214221. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214222. secondaryDesc.lpwfxFormat = &wfFormat;
  214223. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214224. logError (hr);
  214225. if (hr == S_OK)
  214226. {
  214227. log ("opening dsound out step 3");
  214228. DWORD dwDataLen;
  214229. unsigned char* pDSBuffData;
  214230. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214231. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214232. logError (hr);
  214233. if (hr == S_OK)
  214234. {
  214235. zeromem (pDSBuffData, dwDataLen);
  214236. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214237. if (hr == S_OK)
  214238. {
  214239. hr = pOutputBuffer->SetCurrentPosition (0);
  214240. if (hr == S_OK)
  214241. {
  214242. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214243. if (hr == S_OK)
  214244. return String::empty;
  214245. }
  214246. }
  214247. }
  214248. }
  214249. }
  214250. }
  214251. }
  214252. }
  214253. error = getDSErrorMessage (hr);
  214254. close();
  214255. return error;
  214256. }
  214257. void synchronisePosition()
  214258. {
  214259. if (pOutputBuffer != 0)
  214260. {
  214261. DWORD playCursor;
  214262. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214263. }
  214264. }
  214265. bool service()
  214266. {
  214267. if (pOutputBuffer == 0)
  214268. return true;
  214269. DWORD playCursor, writeCursor;
  214270. for (;;)
  214271. {
  214272. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214273. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214274. {
  214275. pOutputBuffer->Restore();
  214276. continue;
  214277. }
  214278. if (hr == S_OK)
  214279. break;
  214280. logError (hr);
  214281. jassertfalse;
  214282. return true;
  214283. }
  214284. int playWriteGap = writeCursor - playCursor;
  214285. if (playWriteGap < 0)
  214286. playWriteGap += totalBytesPerBuffer;
  214287. int bytesEmpty = playCursor - writeOffset;
  214288. if (bytesEmpty < 0)
  214289. bytesEmpty += totalBytesPerBuffer;
  214290. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214291. {
  214292. writeOffset = writeCursor;
  214293. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214294. }
  214295. if (bytesEmpty >= bytesPerBuffer)
  214296. {
  214297. void* lpbuf1 = 0;
  214298. void* lpbuf2 = 0;
  214299. DWORD dwSize1 = 0;
  214300. DWORD dwSize2 = 0;
  214301. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214302. &lpbuf1, &dwSize1,
  214303. &lpbuf2, &dwSize2, 0);
  214304. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214305. {
  214306. pOutputBuffer->Restore();
  214307. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  214308. &lpbuf1, &dwSize1,
  214309. &lpbuf2, &dwSize2, 0);
  214310. }
  214311. if (hr == S_OK)
  214312. {
  214313. if (bitDepth == 16)
  214314. {
  214315. int* dest = static_cast<int*> (lpbuf1);
  214316. const float* left = leftBuffer;
  214317. const float* right = rightBuffer;
  214318. int samples1 = dwSize1 >> 2;
  214319. int samples2 = dwSize2 >> 2;
  214320. if (left == 0)
  214321. {
  214322. while (--samples1 >= 0)
  214323. *dest++ = (convertInputValue (*right++) << 16);
  214324. dest = static_cast<int*> (lpbuf2);
  214325. while (--samples2 >= 0)
  214326. *dest++ = (convertInputValue (*right++) << 16);
  214327. }
  214328. else if (right == 0)
  214329. {
  214330. while (--samples1 >= 0)
  214331. *dest++ = (0xffff & convertInputValue (*left++));
  214332. dest = static_cast<int*> (lpbuf2);
  214333. while (--samples2 >= 0)
  214334. *dest++ = (0xffff & convertInputValue (*left++));
  214335. }
  214336. else
  214337. {
  214338. while (--samples1 >= 0)
  214339. {
  214340. const int l = convertInputValue (*left++);
  214341. const int r = convertInputValue (*right++);
  214342. *dest++ = (r << 16) | (0xffff & l);
  214343. }
  214344. dest = static_cast<int*> (lpbuf2);
  214345. while (--samples2 >= 0)
  214346. {
  214347. const int l = convertInputValue (*left++);
  214348. const int r = convertInputValue (*right++);
  214349. *dest++ = (r << 16) | (0xffff & l);
  214350. }
  214351. }
  214352. }
  214353. else
  214354. {
  214355. jassertfalse;
  214356. }
  214357. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214358. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214359. }
  214360. else
  214361. {
  214362. jassertfalse;
  214363. logError (hr);
  214364. }
  214365. bytesEmpty -= bytesPerBuffer;
  214366. return true;
  214367. }
  214368. else
  214369. {
  214370. return false;
  214371. }
  214372. }
  214373. int bitDepth;
  214374. bool doneFlag;
  214375. private:
  214376. String name;
  214377. LPGUID guid;
  214378. int sampleRate, bufferSizeSamples;
  214379. float* leftBuffer;
  214380. float* rightBuffer;
  214381. IDirectSound* pDirectSound;
  214382. IDirectSoundBuffer* pOutputBuffer;
  214383. DWORD writeOffset;
  214384. int totalBytesPerBuffer, bytesPerBuffer;
  214385. unsigned int lastPlayCursor;
  214386. static inline int convertInputValue (const float v) throw()
  214387. {
  214388. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  214389. }
  214390. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  214391. };
  214392. struct DSoundInternalInChannel
  214393. {
  214394. public:
  214395. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  214396. int bufferSize, float* left, float* right)
  214397. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  214398. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  214399. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  214400. {
  214401. }
  214402. ~DSoundInternalInChannel()
  214403. {
  214404. close();
  214405. }
  214406. void close()
  214407. {
  214408. HRESULT hr;
  214409. if (pInputBuffer != 0)
  214410. {
  214411. log ("closing dsound in: " + name);
  214412. hr = pInputBuffer->Stop();
  214413. logError (hr);
  214414. hr = pInputBuffer->Release();
  214415. pInputBuffer = 0;
  214416. logError (hr);
  214417. }
  214418. if (pDirectSoundCapture != 0)
  214419. {
  214420. hr = pDirectSoundCapture->Release();
  214421. pDirectSoundCapture = 0;
  214422. logError (hr);
  214423. }
  214424. if (pDirectSound != 0)
  214425. {
  214426. hr = pDirectSound->Release();
  214427. pDirectSound = 0;
  214428. logError (hr);
  214429. }
  214430. }
  214431. const String open()
  214432. {
  214433. log ("opening dsound in device: " + name
  214434. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214435. pDirectSound = 0;
  214436. pDirectSoundCapture = 0;
  214437. pInputBuffer = 0;
  214438. readOffset = 0;
  214439. totalBytesPerBuffer = 0;
  214440. String error;
  214441. HRESULT hr = E_NOINTERFACE;
  214442. if (dsDirectSoundCaptureCreate != 0)
  214443. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214444. logError (hr);
  214445. if (hr == S_OK)
  214446. {
  214447. const int numChannels = 2;
  214448. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214449. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214450. WAVEFORMATEX wfFormat;
  214451. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214452. wfFormat.nChannels = (unsigned short)numChannels;
  214453. wfFormat.nSamplesPerSec = sampleRate;
  214454. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214455. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214456. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214457. wfFormat.cbSize = 0;
  214458. DSCBUFFERDESC captureDesc;
  214459. zerostruct (captureDesc);
  214460. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214461. captureDesc.dwFlags = 0;
  214462. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214463. captureDesc.lpwfxFormat = &wfFormat;
  214464. log ("opening dsound in step 2");
  214465. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214466. logError (hr);
  214467. if (hr == S_OK)
  214468. {
  214469. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214470. logError (hr);
  214471. if (hr == S_OK)
  214472. return String::empty;
  214473. }
  214474. }
  214475. error = getDSErrorMessage (hr);
  214476. close();
  214477. return error;
  214478. }
  214479. void synchronisePosition()
  214480. {
  214481. if (pInputBuffer != 0)
  214482. {
  214483. DWORD capturePos;
  214484. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214485. }
  214486. }
  214487. bool service()
  214488. {
  214489. if (pInputBuffer == 0)
  214490. return true;
  214491. DWORD capturePos, readPos;
  214492. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214493. logError (hr);
  214494. if (hr != S_OK)
  214495. return true;
  214496. int bytesFilled = readPos - readOffset;
  214497. if (bytesFilled < 0)
  214498. bytesFilled += totalBytesPerBuffer;
  214499. if (bytesFilled >= bytesPerBuffer)
  214500. {
  214501. LPBYTE lpbuf1 = 0;
  214502. LPBYTE lpbuf2 = 0;
  214503. DWORD dwsize1 = 0;
  214504. DWORD dwsize2 = 0;
  214505. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  214506. (void**) &lpbuf1, &dwsize1,
  214507. (void**) &lpbuf2, &dwsize2, 0);
  214508. if (hr == S_OK)
  214509. {
  214510. if (bitDepth == 16)
  214511. {
  214512. const float g = 1.0f / 32768.0f;
  214513. float* destL = leftBuffer;
  214514. float* destR = rightBuffer;
  214515. int samples1 = dwsize1 >> 2;
  214516. int samples2 = dwsize2 >> 2;
  214517. const short* src = (const short*)lpbuf1;
  214518. if (destL == 0)
  214519. {
  214520. while (--samples1 >= 0)
  214521. {
  214522. ++src;
  214523. *destR++ = *src++ * g;
  214524. }
  214525. src = (const short*)lpbuf2;
  214526. while (--samples2 >= 0)
  214527. {
  214528. ++src;
  214529. *destR++ = *src++ * g;
  214530. }
  214531. }
  214532. else if (destR == 0)
  214533. {
  214534. while (--samples1 >= 0)
  214535. {
  214536. *destL++ = *src++ * g;
  214537. ++src;
  214538. }
  214539. src = (const short*)lpbuf2;
  214540. while (--samples2 >= 0)
  214541. {
  214542. *destL++ = *src++ * g;
  214543. ++src;
  214544. }
  214545. }
  214546. else
  214547. {
  214548. while (--samples1 >= 0)
  214549. {
  214550. *destL++ = *src++ * g;
  214551. *destR++ = *src++ * g;
  214552. }
  214553. src = (const short*)lpbuf2;
  214554. while (--samples2 >= 0)
  214555. {
  214556. *destL++ = *src++ * g;
  214557. *destR++ = *src++ * g;
  214558. }
  214559. }
  214560. }
  214561. else
  214562. {
  214563. jassertfalse;
  214564. }
  214565. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214566. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214567. }
  214568. else
  214569. {
  214570. logError (hr);
  214571. jassertfalse;
  214572. }
  214573. bytesFilled -= bytesPerBuffer;
  214574. return true;
  214575. }
  214576. else
  214577. {
  214578. return false;
  214579. }
  214580. }
  214581. unsigned int readOffset;
  214582. int bytesPerBuffer, totalBytesPerBuffer;
  214583. int bitDepth;
  214584. bool doneFlag;
  214585. private:
  214586. String name;
  214587. LPGUID guid;
  214588. int sampleRate, bufferSizeSamples;
  214589. float* leftBuffer;
  214590. float* rightBuffer;
  214591. IDirectSound* pDirectSound;
  214592. IDirectSoundCapture* pDirectSoundCapture;
  214593. IDirectSoundCaptureBuffer* pInputBuffer;
  214594. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214595. };
  214596. class DSoundAudioIODevice : public AudioIODevice,
  214597. public Thread
  214598. {
  214599. public:
  214600. DSoundAudioIODevice (const String& deviceName,
  214601. const int outputDeviceIndex_,
  214602. const int inputDeviceIndex_)
  214603. : AudioIODevice (deviceName, "DirectSound"),
  214604. Thread ("Juce DSound"),
  214605. isOpen_ (false),
  214606. isStarted (false),
  214607. outputDeviceIndex (outputDeviceIndex_),
  214608. inputDeviceIndex (inputDeviceIndex_),
  214609. totalSamplesOut (0),
  214610. sampleRate (0.0),
  214611. inputBuffers (1, 1),
  214612. outputBuffers (1, 1),
  214613. callback (0),
  214614. bufferSizeSamples (0)
  214615. {
  214616. if (outputDeviceIndex_ >= 0)
  214617. {
  214618. outChannels.add (TRANS("Left"));
  214619. outChannels.add (TRANS("Right"));
  214620. }
  214621. if (inputDeviceIndex_ >= 0)
  214622. {
  214623. inChannels.add (TRANS("Left"));
  214624. inChannels.add (TRANS("Right"));
  214625. }
  214626. }
  214627. ~DSoundAudioIODevice()
  214628. {
  214629. close();
  214630. }
  214631. const String open (const BigInteger& inputChannels,
  214632. const BigInteger& outputChannels,
  214633. double sampleRate, int bufferSizeSamples)
  214634. {
  214635. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214636. isOpen_ = lastError.isEmpty();
  214637. return lastError;
  214638. }
  214639. void close()
  214640. {
  214641. stop();
  214642. if (isOpen_)
  214643. {
  214644. closeDevice();
  214645. isOpen_ = false;
  214646. }
  214647. }
  214648. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214649. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214650. double getCurrentSampleRate() { return sampleRate; }
  214651. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214652. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214653. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214654. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214655. const StringArray getOutputChannelNames() { return outChannels; }
  214656. const StringArray getInputChannelNames() { return inChannels; }
  214657. int getNumSampleRates() { return 4; }
  214658. int getDefaultBufferSize() { return 2560; }
  214659. int getNumBufferSizesAvailable() { return 50; }
  214660. double getSampleRate (int index)
  214661. {
  214662. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214663. return samps [jlimit (0, 3, index)];
  214664. }
  214665. int getBufferSizeSamples (int index)
  214666. {
  214667. int n = 64;
  214668. for (int i = 0; i < index; ++i)
  214669. n += (n < 512) ? 32
  214670. : ((n < 1024) ? 64
  214671. : ((n < 2048) ? 128 : 256));
  214672. return n;
  214673. }
  214674. int getCurrentBitDepth()
  214675. {
  214676. int i, bits = 256;
  214677. for (i = inChans.size(); --i >= 0;)
  214678. bits = jmin (bits, inChans[i]->bitDepth);
  214679. for (i = outChans.size(); --i >= 0;)
  214680. bits = jmin (bits, outChans[i]->bitDepth);
  214681. if (bits > 32)
  214682. bits = 16;
  214683. return bits;
  214684. }
  214685. void start (AudioIODeviceCallback* call)
  214686. {
  214687. if (isOpen_ && call != 0 && ! isStarted)
  214688. {
  214689. if (! isThreadRunning())
  214690. {
  214691. // something gone wrong and the thread's stopped..
  214692. isOpen_ = false;
  214693. return;
  214694. }
  214695. call->audioDeviceAboutToStart (this);
  214696. const ScopedLock sl (startStopLock);
  214697. callback = call;
  214698. isStarted = true;
  214699. }
  214700. }
  214701. void stop()
  214702. {
  214703. if (isStarted)
  214704. {
  214705. AudioIODeviceCallback* const callbackLocal = callback;
  214706. {
  214707. const ScopedLock sl (startStopLock);
  214708. isStarted = false;
  214709. }
  214710. if (callbackLocal != 0)
  214711. callbackLocal->audioDeviceStopped();
  214712. }
  214713. }
  214714. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214715. const String getLastError() { return lastError; }
  214716. StringArray inChannels, outChannels;
  214717. int outputDeviceIndex, inputDeviceIndex;
  214718. private:
  214719. bool isOpen_;
  214720. bool isStarted;
  214721. String lastError;
  214722. OwnedArray <DSoundInternalInChannel> inChans;
  214723. OwnedArray <DSoundInternalOutChannel> outChans;
  214724. WaitableEvent startEvent;
  214725. int bufferSizeSamples;
  214726. int volatile totalSamplesOut;
  214727. int64 volatile lastBlockTime;
  214728. double sampleRate;
  214729. BigInteger enabledInputs, enabledOutputs;
  214730. AudioSampleBuffer inputBuffers, outputBuffers;
  214731. AudioIODeviceCallback* callback;
  214732. CriticalSection startStopLock;
  214733. const String openDevice (const BigInteger& inputChannels,
  214734. const BigInteger& outputChannels,
  214735. double sampleRate_, int bufferSizeSamples_);
  214736. void closeDevice()
  214737. {
  214738. isStarted = false;
  214739. stopThread (5000);
  214740. inChans.clear();
  214741. outChans.clear();
  214742. inputBuffers.setSize (1, 1);
  214743. outputBuffers.setSize (1, 1);
  214744. }
  214745. void resync()
  214746. {
  214747. if (! threadShouldExit())
  214748. {
  214749. sleep (5);
  214750. int i;
  214751. for (i = 0; i < outChans.size(); ++i)
  214752. outChans.getUnchecked(i)->synchronisePosition();
  214753. for (i = 0; i < inChans.size(); ++i)
  214754. inChans.getUnchecked(i)->synchronisePosition();
  214755. }
  214756. }
  214757. public:
  214758. void run()
  214759. {
  214760. while (! threadShouldExit())
  214761. {
  214762. if (wait (100))
  214763. break;
  214764. }
  214765. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214766. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214767. while (! threadShouldExit())
  214768. {
  214769. int numToDo = 0;
  214770. uint32 startTime = Time::getMillisecondCounter();
  214771. int i;
  214772. for (i = inChans.size(); --i >= 0;)
  214773. {
  214774. inChans.getUnchecked(i)->doneFlag = false;
  214775. ++numToDo;
  214776. }
  214777. for (i = outChans.size(); --i >= 0;)
  214778. {
  214779. outChans.getUnchecked(i)->doneFlag = false;
  214780. ++numToDo;
  214781. }
  214782. if (numToDo > 0)
  214783. {
  214784. const int maxCount = 3;
  214785. int count = maxCount;
  214786. for (;;)
  214787. {
  214788. for (i = inChans.size(); --i >= 0;)
  214789. {
  214790. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214791. if ((! in->doneFlag) && in->service())
  214792. {
  214793. in->doneFlag = true;
  214794. --numToDo;
  214795. }
  214796. }
  214797. for (i = outChans.size(); --i >= 0;)
  214798. {
  214799. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214800. if ((! out->doneFlag) && out->service())
  214801. {
  214802. out->doneFlag = true;
  214803. --numToDo;
  214804. }
  214805. }
  214806. if (numToDo <= 0)
  214807. break;
  214808. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214809. {
  214810. resync();
  214811. break;
  214812. }
  214813. if (--count <= 0)
  214814. {
  214815. Sleep (1);
  214816. count = maxCount;
  214817. }
  214818. if (threadShouldExit())
  214819. return;
  214820. }
  214821. }
  214822. else
  214823. {
  214824. sleep (1);
  214825. }
  214826. const ScopedLock sl (startStopLock);
  214827. if (isStarted)
  214828. {
  214829. JUCE_TRY
  214830. {
  214831. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214832. inputBuffers.getNumChannels(),
  214833. outputBuffers.getArrayOfChannels(),
  214834. outputBuffers.getNumChannels(),
  214835. bufferSizeSamples);
  214836. }
  214837. JUCE_CATCH_EXCEPTION
  214838. totalSamplesOut += bufferSizeSamples;
  214839. }
  214840. else
  214841. {
  214842. outputBuffers.clear();
  214843. totalSamplesOut = 0;
  214844. sleep (1);
  214845. }
  214846. }
  214847. }
  214848. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214849. };
  214850. class DSoundAudioIODeviceType : public AudioIODeviceType
  214851. {
  214852. public:
  214853. DSoundAudioIODeviceType()
  214854. : AudioIODeviceType ("DirectSound"),
  214855. hasScanned (false)
  214856. {
  214857. initialiseDSoundFunctions();
  214858. }
  214859. void scanForDevices()
  214860. {
  214861. hasScanned = true;
  214862. outputDeviceNames.clear();
  214863. outputGuids.clear();
  214864. inputDeviceNames.clear();
  214865. inputGuids.clear();
  214866. if (dsDirectSoundEnumerateW != 0)
  214867. {
  214868. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214869. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214870. }
  214871. }
  214872. const StringArray getDeviceNames (bool wantInputNames) const
  214873. {
  214874. jassert (hasScanned); // need to call scanForDevices() before doing this
  214875. return wantInputNames ? inputDeviceNames
  214876. : outputDeviceNames;
  214877. }
  214878. int getDefaultDeviceIndex (bool /*forInput*/) const
  214879. {
  214880. jassert (hasScanned); // need to call scanForDevices() before doing this
  214881. return 0;
  214882. }
  214883. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214884. {
  214885. jassert (hasScanned); // need to call scanForDevices() before doing this
  214886. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214887. if (d == 0)
  214888. return -1;
  214889. return asInput ? d->inputDeviceIndex
  214890. : d->outputDeviceIndex;
  214891. }
  214892. bool hasSeparateInputsAndOutputs() const { return true; }
  214893. AudioIODevice* createDevice (const String& outputDeviceName,
  214894. const String& inputDeviceName)
  214895. {
  214896. jassert (hasScanned); // need to call scanForDevices() before doing this
  214897. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214898. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214899. if (outputIndex >= 0 || inputIndex >= 0)
  214900. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214901. : inputDeviceName,
  214902. outputIndex, inputIndex);
  214903. return 0;
  214904. }
  214905. StringArray outputDeviceNames, inputDeviceNames;
  214906. OwnedArray <GUID> outputGuids, inputGuids;
  214907. private:
  214908. bool hasScanned;
  214909. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214910. {
  214911. desc = desc.trim();
  214912. if (desc.isNotEmpty())
  214913. {
  214914. const String origDesc (desc);
  214915. int n = 2;
  214916. while (outputDeviceNames.contains (desc))
  214917. desc = origDesc + " (" + String (n++) + ")";
  214918. outputDeviceNames.add (desc);
  214919. if (lpGUID != 0)
  214920. outputGuids.add (new GUID (*lpGUID));
  214921. else
  214922. outputGuids.add (0);
  214923. }
  214924. return TRUE;
  214925. }
  214926. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214927. {
  214928. return ((DSoundAudioIODeviceType*) object)
  214929. ->outputEnumProc (lpGUID, String (description));
  214930. }
  214931. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214932. {
  214933. return ((DSoundAudioIODeviceType*) object)
  214934. ->outputEnumProc (lpGUID, String (description));
  214935. }
  214936. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214937. {
  214938. desc = desc.trim();
  214939. if (desc.isNotEmpty())
  214940. {
  214941. const String origDesc (desc);
  214942. int n = 2;
  214943. while (inputDeviceNames.contains (desc))
  214944. desc = origDesc + " (" + String (n++) + ")";
  214945. inputDeviceNames.add (desc);
  214946. if (lpGUID != 0)
  214947. inputGuids.add (new GUID (*lpGUID));
  214948. else
  214949. inputGuids.add (0);
  214950. }
  214951. return TRUE;
  214952. }
  214953. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214954. {
  214955. return ((DSoundAudioIODeviceType*) object)
  214956. ->inputEnumProc (lpGUID, String (description));
  214957. }
  214958. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214959. {
  214960. return ((DSoundAudioIODeviceType*) object)
  214961. ->inputEnumProc (lpGUID, String (description));
  214962. }
  214963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214964. };
  214965. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214966. const BigInteger& outputChannels,
  214967. double sampleRate_, int bufferSizeSamples_)
  214968. {
  214969. closeDevice();
  214970. totalSamplesOut = 0;
  214971. sampleRate = sampleRate_;
  214972. if (bufferSizeSamples_ <= 0)
  214973. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214974. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214975. DSoundAudioIODeviceType dlh;
  214976. dlh.scanForDevices();
  214977. enabledInputs = inputChannels;
  214978. enabledInputs.setRange (inChannels.size(),
  214979. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214980. false);
  214981. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214982. inputBuffers.clear();
  214983. int i, numIns = 0;
  214984. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214985. {
  214986. float* left = 0;
  214987. if (enabledInputs[i])
  214988. left = inputBuffers.getSampleData (numIns++);
  214989. float* right = 0;
  214990. if (enabledInputs[i + 1])
  214991. right = inputBuffers.getSampleData (numIns++);
  214992. if (left != 0 || right != 0)
  214993. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214994. dlh.inputGuids [inputDeviceIndex],
  214995. (int) sampleRate, bufferSizeSamples,
  214996. left, right));
  214997. }
  214998. enabledOutputs = outputChannels;
  214999. enabledOutputs.setRange (outChannels.size(),
  215000. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215001. false);
  215002. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215003. outputBuffers.clear();
  215004. int numOuts = 0;
  215005. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215006. {
  215007. float* left = 0;
  215008. if (enabledOutputs[i])
  215009. left = outputBuffers.getSampleData (numOuts++);
  215010. float* right = 0;
  215011. if (enabledOutputs[i + 1])
  215012. right = outputBuffers.getSampleData (numOuts++);
  215013. if (left != 0 || right != 0)
  215014. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215015. dlh.outputGuids [outputDeviceIndex],
  215016. (int) sampleRate, bufferSizeSamples,
  215017. left, right));
  215018. }
  215019. String error;
  215020. // boost our priority while opening the devices to try to get better sync between them
  215021. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215022. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215023. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215024. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215025. for (i = 0; i < outChans.size(); ++i)
  215026. {
  215027. error = outChans[i]->open();
  215028. if (error.isNotEmpty())
  215029. {
  215030. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215031. break;
  215032. }
  215033. }
  215034. if (error.isEmpty())
  215035. {
  215036. for (i = 0; i < inChans.size(); ++i)
  215037. {
  215038. error = inChans[i]->open();
  215039. if (error.isNotEmpty())
  215040. {
  215041. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215042. break;
  215043. }
  215044. }
  215045. }
  215046. if (error.isEmpty())
  215047. {
  215048. totalSamplesOut = 0;
  215049. for (i = 0; i < outChans.size(); ++i)
  215050. outChans.getUnchecked(i)->synchronisePosition();
  215051. for (i = 0; i < inChans.size(); ++i)
  215052. inChans.getUnchecked(i)->synchronisePosition();
  215053. startThread (9);
  215054. sleep (10);
  215055. notify();
  215056. }
  215057. else
  215058. {
  215059. log (error);
  215060. }
  215061. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215062. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215063. return error;
  215064. }
  215065. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215066. {
  215067. return new DSoundAudioIODeviceType();
  215068. }
  215069. #undef log
  215070. #endif
  215071. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215072. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215073. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215074. // compiled on its own).
  215075. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215076. #ifndef WASAPI_ENABLE_LOGGING
  215077. #define WASAPI_ENABLE_LOGGING 0
  215078. #endif
  215079. namespace WasapiClasses
  215080. {
  215081. void logFailure (HRESULT hr)
  215082. {
  215083. (void) hr;
  215084. #if WASAPI_ENABLE_LOGGING
  215085. if (FAILED (hr))
  215086. {
  215087. String e;
  215088. e << Time::getCurrentTime().toString (true, true, true, true)
  215089. << " -- WASAPI error: ";
  215090. switch (hr)
  215091. {
  215092. case E_POINTER: e << "E_POINTER"; break;
  215093. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215094. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215095. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215096. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215097. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215098. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215099. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215100. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215101. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215102. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215103. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215104. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215105. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215106. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215107. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215108. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215109. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215110. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215111. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215112. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215113. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215114. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215115. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215116. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215117. default: e << String::toHexString ((int) hr); break;
  215118. }
  215119. DBG (e);
  215120. jassertfalse;
  215121. }
  215122. #endif
  215123. }
  215124. #undef check
  215125. bool check (HRESULT hr)
  215126. {
  215127. logFailure (hr);
  215128. return SUCCEEDED (hr);
  215129. }
  215130. const String getDeviceID (IMMDevice* const device)
  215131. {
  215132. String s;
  215133. WCHAR* deviceId = 0;
  215134. if (check (device->GetId (&deviceId)))
  215135. {
  215136. s = String (deviceId);
  215137. CoTaskMemFree (deviceId);
  215138. }
  215139. return s;
  215140. }
  215141. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215142. {
  215143. EDataFlow flow = eRender;
  215144. ComSmartPtr <IMMEndpoint> endPoint;
  215145. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215146. (void) check (endPoint->GetDataFlow (&flow));
  215147. return flow;
  215148. }
  215149. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215150. {
  215151. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215152. }
  215153. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215154. {
  215155. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215156. : sizeof (WAVEFORMATEX));
  215157. }
  215158. class WASAPIDeviceBase
  215159. {
  215160. public:
  215161. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215162. : device (device_),
  215163. sampleRate (0),
  215164. numChannels (0),
  215165. actualNumChannels (0),
  215166. defaultSampleRate (0),
  215167. minBufferSize (0),
  215168. defaultBufferSize (0),
  215169. latencySamples (0),
  215170. useExclusiveMode (useExclusiveMode_)
  215171. {
  215172. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215173. ComSmartPtr <IAudioClient> tempClient (createClient());
  215174. if (tempClient == 0)
  215175. return;
  215176. REFERENCE_TIME defaultPeriod, minPeriod;
  215177. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215178. return;
  215179. WAVEFORMATEX* mixFormat = 0;
  215180. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215181. return;
  215182. WAVEFORMATEXTENSIBLE format;
  215183. copyWavFormat (format, mixFormat);
  215184. CoTaskMemFree (mixFormat);
  215185. actualNumChannels = numChannels = format.Format.nChannels;
  215186. defaultSampleRate = format.Format.nSamplesPerSec;
  215187. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215188. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215189. rates.addUsingDefaultSort (defaultSampleRate);
  215190. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215191. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215192. {
  215193. if (ratesToTest[i] == defaultSampleRate)
  215194. continue;
  215195. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215196. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215197. (WAVEFORMATEX*) &format, 0)))
  215198. if (! rates.contains (ratesToTest[i]))
  215199. rates.addUsingDefaultSort (ratesToTest[i]);
  215200. }
  215201. }
  215202. ~WASAPIDeviceBase()
  215203. {
  215204. device = 0;
  215205. CloseHandle (clientEvent);
  215206. }
  215207. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215208. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215209. {
  215210. sampleRate = newSampleRate;
  215211. channels = newChannels;
  215212. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215213. numChannels = channels.getHighestBit() + 1;
  215214. if (numChannels == 0)
  215215. return true;
  215216. client = createClient();
  215217. if (client != 0
  215218. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215219. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215220. {
  215221. channelMaps.clear();
  215222. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215223. if (channels[i])
  215224. channelMaps.add (i);
  215225. REFERENCE_TIME latency;
  215226. if (check (client->GetStreamLatency (&latency)))
  215227. latencySamples = refTimeToSamples (latency, sampleRate);
  215228. (void) check (client->GetBufferSize (&actualBufferSize));
  215229. return check (client->SetEventHandle (clientEvent));
  215230. }
  215231. return false;
  215232. }
  215233. void closeClient()
  215234. {
  215235. if (client != 0)
  215236. client->Stop();
  215237. client = 0;
  215238. ResetEvent (clientEvent);
  215239. }
  215240. ComSmartPtr <IMMDevice> device;
  215241. ComSmartPtr <IAudioClient> client;
  215242. double sampleRate, defaultSampleRate;
  215243. int numChannels, actualNumChannels;
  215244. int minBufferSize, defaultBufferSize, latencySamples;
  215245. const bool useExclusiveMode;
  215246. Array <double> rates;
  215247. HANDLE clientEvent;
  215248. BigInteger channels;
  215249. Array <int> channelMaps;
  215250. UINT32 actualBufferSize;
  215251. int bytesPerSample;
  215252. virtual void updateFormat (bool isFloat) = 0;
  215253. private:
  215254. const ComSmartPtr <IAudioClient> createClient()
  215255. {
  215256. ComSmartPtr <IAudioClient> client;
  215257. if (device != 0)
  215258. {
  215259. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215260. logFailure (hr);
  215261. }
  215262. return client;
  215263. }
  215264. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215265. {
  215266. WAVEFORMATEXTENSIBLE format;
  215267. zerostruct (format);
  215268. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215269. {
  215270. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215271. }
  215272. else
  215273. {
  215274. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215275. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215276. }
  215277. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215278. format.Format.nChannels = (WORD) numChannels;
  215279. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215280. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215281. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215282. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215283. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215284. switch (numChannels)
  215285. {
  215286. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215287. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215288. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215289. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215290. 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;
  215291. default: break;
  215292. }
  215293. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215294. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215295. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215296. logFailure (hr);
  215297. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215298. {
  215299. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215300. hr = S_OK;
  215301. }
  215302. CoTaskMemFree (nearestFormat);
  215303. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215304. if (useExclusiveMode)
  215305. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215306. GUID session;
  215307. if (hr == S_OK
  215308. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215309. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215310. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215311. {
  215312. actualNumChannels = format.Format.nChannels;
  215313. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215314. bytesPerSample = format.Format.wBitsPerSample / 8;
  215315. updateFormat (isFloat);
  215316. return true;
  215317. }
  215318. return false;
  215319. }
  215320. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  215321. };
  215322. class WASAPIInputDevice : public WASAPIDeviceBase
  215323. {
  215324. public:
  215325. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215326. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215327. reservoir (1, 1)
  215328. {
  215329. }
  215330. ~WASAPIInputDevice()
  215331. {
  215332. close();
  215333. }
  215334. bool open (const double newSampleRate, const BigInteger& newChannels)
  215335. {
  215336. reservoirSize = 0;
  215337. reservoirCapacity = 16384;
  215338. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215339. return openClient (newSampleRate, newChannels)
  215340. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  215341. (void**) captureClient.resetAndGetPointerAddress())));
  215342. }
  215343. void close()
  215344. {
  215345. closeClient();
  215346. captureClient = 0;
  215347. reservoir.setSize (0);
  215348. }
  215349. template <class SourceType>
  215350. void updateFormatWithType (SourceType*)
  215351. {
  215352. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215353. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215354. }
  215355. void updateFormat (bool isFloat)
  215356. {
  215357. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215358. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215359. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215360. else updateFormatWithType ((AudioData::Int16*) 0);
  215361. }
  215362. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215363. {
  215364. if (numChannels <= 0)
  215365. return;
  215366. int offset = 0;
  215367. while (bufferSize > 0)
  215368. {
  215369. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215370. {
  215371. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215372. for (int i = 0; i < numDestBuffers; ++i)
  215373. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215374. bufferSize -= samplesToDo;
  215375. offset += samplesToDo;
  215376. reservoirSize = 0;
  215377. }
  215378. else
  215379. {
  215380. UINT32 packetLength = 0;
  215381. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215382. break;
  215383. if (packetLength == 0)
  215384. {
  215385. if (thread.threadShouldExit()
  215386. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215387. break;
  215388. continue;
  215389. }
  215390. uint8* inputData;
  215391. UINT32 numSamplesAvailable;
  215392. DWORD flags;
  215393. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215394. {
  215395. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215396. for (int i = 0; i < numDestBuffers; ++i)
  215397. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215398. bufferSize -= samplesToDo;
  215399. offset += samplesToDo;
  215400. if (samplesToDo < (int) numSamplesAvailable)
  215401. {
  215402. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215403. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215404. bytesPerSample * actualNumChannels * reservoirSize);
  215405. }
  215406. captureClient->ReleaseBuffer (numSamplesAvailable);
  215407. }
  215408. }
  215409. }
  215410. }
  215411. ComSmartPtr <IAudioCaptureClient> captureClient;
  215412. MemoryBlock reservoir;
  215413. int reservoirSize, reservoirCapacity;
  215414. ScopedPointer <AudioData::Converter> converter;
  215415. private:
  215416. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  215417. };
  215418. class WASAPIOutputDevice : public WASAPIDeviceBase
  215419. {
  215420. public:
  215421. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215422. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215423. {
  215424. }
  215425. ~WASAPIOutputDevice()
  215426. {
  215427. close();
  215428. }
  215429. bool open (const double newSampleRate, const BigInteger& newChannels)
  215430. {
  215431. return openClient (newSampleRate, newChannels)
  215432. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215433. }
  215434. void close()
  215435. {
  215436. closeClient();
  215437. renderClient = 0;
  215438. }
  215439. template <class DestType>
  215440. void updateFormatWithType (DestType*)
  215441. {
  215442. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215443. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215444. }
  215445. void updateFormat (bool isFloat)
  215446. {
  215447. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  215448. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  215449. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  215450. else updateFormatWithType ((AudioData::Int16*) 0);
  215451. }
  215452. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215453. {
  215454. if (numChannels <= 0)
  215455. return;
  215456. int offset = 0;
  215457. while (bufferSize > 0)
  215458. {
  215459. UINT32 padding = 0;
  215460. if (! check (client->GetCurrentPadding (&padding)))
  215461. return;
  215462. int samplesToDo = useExclusiveMode ? bufferSize
  215463. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215464. if (samplesToDo <= 0)
  215465. {
  215466. if (thread.threadShouldExit()
  215467. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  215468. break;
  215469. continue;
  215470. }
  215471. uint8* outputData = 0;
  215472. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215473. {
  215474. for (int i = 0; i < numSrcBuffers; ++i)
  215475. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  215476. renderClient->ReleaseBuffer (samplesToDo, 0);
  215477. offset += samplesToDo;
  215478. bufferSize -= samplesToDo;
  215479. }
  215480. }
  215481. }
  215482. ComSmartPtr <IAudioRenderClient> renderClient;
  215483. ScopedPointer <AudioData::Converter> converter;
  215484. private:
  215485. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  215486. };
  215487. class WASAPIAudioIODevice : public AudioIODevice,
  215488. public Thread
  215489. {
  215490. public:
  215491. WASAPIAudioIODevice (const String& deviceName,
  215492. const String& outputDeviceId_,
  215493. const String& inputDeviceId_,
  215494. const bool useExclusiveMode_)
  215495. : AudioIODevice (deviceName, "Windows Audio"),
  215496. Thread ("Juce WASAPI"),
  215497. isOpen_ (false),
  215498. isStarted (false),
  215499. outputDeviceId (outputDeviceId_),
  215500. inputDeviceId (inputDeviceId_),
  215501. useExclusiveMode (useExclusiveMode_),
  215502. currentBufferSizeSamples (0),
  215503. currentSampleRate (0),
  215504. callback (0)
  215505. {
  215506. }
  215507. ~WASAPIAudioIODevice()
  215508. {
  215509. close();
  215510. }
  215511. bool initialise()
  215512. {
  215513. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215514. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215515. latencyIn = latencyOut = 0;
  215516. Array <double> ratesIn, ratesOut;
  215517. if (createDevices())
  215518. {
  215519. jassert (inputDevice != 0 || outputDevice != 0);
  215520. if (inputDevice != 0 && outputDevice != 0)
  215521. {
  215522. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215523. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215524. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215525. sampleRates = inputDevice->rates;
  215526. sampleRates.removeValuesNotIn (outputDevice->rates);
  215527. }
  215528. else
  215529. {
  215530. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215531. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215532. defaultSampleRate = d->defaultSampleRate;
  215533. minBufferSize = d->minBufferSize;
  215534. defaultBufferSize = d->defaultBufferSize;
  215535. sampleRates = d->rates;
  215536. }
  215537. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215538. if (minBufferSize != defaultBufferSize)
  215539. bufferSizes.addUsingDefaultSort (minBufferSize);
  215540. int n = 64;
  215541. for (int i = 0; i < 40; ++i)
  215542. {
  215543. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  215544. bufferSizes.addUsingDefaultSort (n);
  215545. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  215546. }
  215547. return true;
  215548. }
  215549. return false;
  215550. }
  215551. const StringArray getOutputChannelNames()
  215552. {
  215553. StringArray outChannels;
  215554. if (outputDevice != 0)
  215555. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215556. outChannels.add ("Output channel " + String (i));
  215557. return outChannels;
  215558. }
  215559. const StringArray getInputChannelNames()
  215560. {
  215561. StringArray inChannels;
  215562. if (inputDevice != 0)
  215563. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215564. inChannels.add ("Input channel " + String (i));
  215565. return inChannels;
  215566. }
  215567. int getNumSampleRates() { return sampleRates.size(); }
  215568. double getSampleRate (int index) { return sampleRates [index]; }
  215569. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215570. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215571. int getDefaultBufferSize() { return defaultBufferSize; }
  215572. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215573. double getCurrentSampleRate() { return currentSampleRate; }
  215574. int getCurrentBitDepth() { return 32; }
  215575. int getOutputLatencyInSamples() { return latencyOut; }
  215576. int getInputLatencyInSamples() { return latencyIn; }
  215577. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215578. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215579. const String getLastError() { return lastError; }
  215580. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215581. double sampleRate, int bufferSizeSamples)
  215582. {
  215583. close();
  215584. lastError = String::empty;
  215585. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215586. {
  215587. lastError = "The input and output devices don't share a common sample rate!";
  215588. return lastError;
  215589. }
  215590. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215591. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215592. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215593. {
  215594. lastError = "Couldn't open the input device!";
  215595. return lastError;
  215596. }
  215597. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215598. {
  215599. close();
  215600. lastError = "Couldn't open the output device!";
  215601. return lastError;
  215602. }
  215603. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215604. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215605. startThread (8);
  215606. Thread::sleep (5);
  215607. if (inputDevice != 0 && inputDevice->client != 0)
  215608. {
  215609. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215610. HRESULT hr = inputDevice->client->Start();
  215611. logFailure (hr); //xxx handle this
  215612. }
  215613. if (outputDevice != 0 && outputDevice->client != 0)
  215614. {
  215615. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215616. HRESULT hr = outputDevice->client->Start();
  215617. logFailure (hr); //xxx handle this
  215618. }
  215619. isOpen_ = true;
  215620. return lastError;
  215621. }
  215622. void close()
  215623. {
  215624. stop();
  215625. signalThreadShouldExit();
  215626. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215627. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215628. stopThread (5000);
  215629. if (inputDevice != 0) inputDevice->close();
  215630. if (outputDevice != 0) outputDevice->close();
  215631. isOpen_ = false;
  215632. }
  215633. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215634. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215635. void start (AudioIODeviceCallback* call)
  215636. {
  215637. if (isOpen_ && call != 0 && ! isStarted)
  215638. {
  215639. if (! isThreadRunning())
  215640. {
  215641. // something's gone wrong and the thread's stopped..
  215642. isOpen_ = false;
  215643. return;
  215644. }
  215645. call->audioDeviceAboutToStart (this);
  215646. const ScopedLock sl (startStopLock);
  215647. callback = call;
  215648. isStarted = true;
  215649. }
  215650. }
  215651. void stop()
  215652. {
  215653. if (isStarted)
  215654. {
  215655. AudioIODeviceCallback* const callbackLocal = callback;
  215656. {
  215657. const ScopedLock sl (startStopLock);
  215658. isStarted = false;
  215659. }
  215660. if (callbackLocal != 0)
  215661. callbackLocal->audioDeviceStopped();
  215662. }
  215663. }
  215664. void setMMThreadPriority()
  215665. {
  215666. DynamicLibraryLoader dll ("avrt.dll");
  215667. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215668. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215669. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215670. {
  215671. DWORD dummy = 0;
  215672. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215673. if (h != 0)
  215674. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215675. }
  215676. }
  215677. void run()
  215678. {
  215679. setMMThreadPriority();
  215680. const int bufferSize = currentBufferSizeSamples;
  215681. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215682. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215683. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215684. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215685. float** const inputBuffers = ins.getArrayOfChannels();
  215686. float** const outputBuffers = outs.getArrayOfChannels();
  215687. ins.clear();
  215688. while (! threadShouldExit())
  215689. {
  215690. if (inputDevice != 0)
  215691. {
  215692. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215693. if (threadShouldExit())
  215694. break;
  215695. }
  215696. JUCE_TRY
  215697. {
  215698. const ScopedLock sl (startStopLock);
  215699. if (isStarted)
  215700. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215701. outputBuffers, numOutputBuffers, bufferSize);
  215702. else
  215703. outs.clear();
  215704. }
  215705. JUCE_CATCH_EXCEPTION
  215706. if (outputDevice != 0)
  215707. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215708. }
  215709. }
  215710. String outputDeviceId, inputDeviceId;
  215711. String lastError;
  215712. private:
  215713. // Device stats...
  215714. ScopedPointer<WASAPIInputDevice> inputDevice;
  215715. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215716. const bool useExclusiveMode;
  215717. double defaultSampleRate;
  215718. int minBufferSize, defaultBufferSize;
  215719. int latencyIn, latencyOut;
  215720. Array <double> sampleRates;
  215721. Array <int> bufferSizes;
  215722. // Active state...
  215723. bool isOpen_, isStarted;
  215724. int currentBufferSizeSamples;
  215725. double currentSampleRate;
  215726. AudioIODeviceCallback* callback;
  215727. CriticalSection startStopLock;
  215728. bool createDevices()
  215729. {
  215730. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215731. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215732. return false;
  215733. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215734. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215735. return false;
  215736. UINT32 numDevices = 0;
  215737. if (! check (deviceCollection->GetCount (&numDevices)))
  215738. return false;
  215739. for (UINT32 i = 0; i < numDevices; ++i)
  215740. {
  215741. ComSmartPtr <IMMDevice> device;
  215742. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215743. continue;
  215744. const String deviceId (getDeviceID (device));
  215745. if (deviceId.isEmpty())
  215746. continue;
  215747. const EDataFlow flow = getDataFlow (device);
  215748. if (deviceId == inputDeviceId && flow == eCapture)
  215749. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215750. else if (deviceId == outputDeviceId && flow == eRender)
  215751. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215752. }
  215753. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215754. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215755. }
  215756. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215757. };
  215758. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215759. {
  215760. public:
  215761. WASAPIAudioIODeviceType()
  215762. : AudioIODeviceType ("Windows Audio"),
  215763. hasScanned (false)
  215764. {
  215765. }
  215766. ~WASAPIAudioIODeviceType()
  215767. {
  215768. }
  215769. void scanForDevices()
  215770. {
  215771. hasScanned = true;
  215772. outputDeviceNames.clear();
  215773. inputDeviceNames.clear();
  215774. outputDeviceIds.clear();
  215775. inputDeviceIds.clear();
  215776. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215777. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215778. return;
  215779. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215780. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215781. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215782. UINT32 numDevices = 0;
  215783. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215784. && check (deviceCollection->GetCount (&numDevices))))
  215785. return;
  215786. for (UINT32 i = 0; i < numDevices; ++i)
  215787. {
  215788. ComSmartPtr <IMMDevice> device;
  215789. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215790. continue;
  215791. const String deviceId (getDeviceID (device));
  215792. DWORD state = 0;
  215793. if (! check (device->GetState (&state)))
  215794. continue;
  215795. if (state != DEVICE_STATE_ACTIVE)
  215796. continue;
  215797. String name;
  215798. {
  215799. ComSmartPtr <IPropertyStore> properties;
  215800. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215801. continue;
  215802. PROPVARIANT value;
  215803. PropVariantInit (&value);
  215804. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215805. name = value.pwszVal;
  215806. PropVariantClear (&value);
  215807. }
  215808. const EDataFlow flow = getDataFlow (device);
  215809. if (flow == eRender)
  215810. {
  215811. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215812. outputDeviceIds.insert (index, deviceId);
  215813. outputDeviceNames.insert (index, name);
  215814. }
  215815. else if (flow == eCapture)
  215816. {
  215817. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215818. inputDeviceIds.insert (index, deviceId);
  215819. inputDeviceNames.insert (index, name);
  215820. }
  215821. }
  215822. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215823. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215824. }
  215825. const StringArray getDeviceNames (bool wantInputNames) const
  215826. {
  215827. jassert (hasScanned); // need to call scanForDevices() before doing this
  215828. return wantInputNames ? inputDeviceNames
  215829. : outputDeviceNames;
  215830. }
  215831. int getDefaultDeviceIndex (bool /*forInput*/) const
  215832. {
  215833. jassert (hasScanned); // need to call scanForDevices() before doing this
  215834. return 0;
  215835. }
  215836. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215837. {
  215838. jassert (hasScanned); // need to call scanForDevices() before doing this
  215839. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215840. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215841. : outputDeviceIds.indexOf (d->outputDeviceId));
  215842. }
  215843. bool hasSeparateInputsAndOutputs() const { return true; }
  215844. AudioIODevice* createDevice (const String& outputDeviceName,
  215845. const String& inputDeviceName)
  215846. {
  215847. jassert (hasScanned); // need to call scanForDevices() before doing this
  215848. const bool useExclusiveMode = false;
  215849. ScopedPointer<WASAPIAudioIODevice> device;
  215850. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215851. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215852. if (outputIndex >= 0 || inputIndex >= 0)
  215853. {
  215854. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215855. : inputDeviceName,
  215856. outputDeviceIds [outputIndex],
  215857. inputDeviceIds [inputIndex],
  215858. useExclusiveMode);
  215859. if (! device->initialise())
  215860. device = 0;
  215861. }
  215862. return device.release();
  215863. }
  215864. StringArray outputDeviceNames, outputDeviceIds;
  215865. StringArray inputDeviceNames, inputDeviceIds;
  215866. private:
  215867. bool hasScanned;
  215868. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215869. {
  215870. String s;
  215871. IMMDevice* dev = 0;
  215872. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215873. eMultimedia, &dev)))
  215874. {
  215875. WCHAR* deviceId = 0;
  215876. if (check (dev->GetId (&deviceId)))
  215877. {
  215878. s = String (deviceId);
  215879. CoTaskMemFree (deviceId);
  215880. }
  215881. dev->Release();
  215882. }
  215883. return s;
  215884. }
  215885. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215886. };
  215887. }
  215888. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215889. {
  215890. return new WasapiClasses::WASAPIAudioIODeviceType();
  215891. }
  215892. #endif
  215893. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215894. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215895. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215896. // compiled on its own).
  215897. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215898. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215899. {
  215900. public:
  215901. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215902. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215903. const ComSmartPtr <IBaseFilter>& filter_,
  215904. int minWidth, int minHeight,
  215905. int maxWidth, int maxHeight)
  215906. : owner (owner_),
  215907. captureGraphBuilder (captureGraphBuilder_),
  215908. filter (filter_),
  215909. ok (false),
  215910. imageNeedsFlipping (false),
  215911. width (0),
  215912. height (0),
  215913. activeUsers (0),
  215914. recordNextFrameTime (false),
  215915. previewMaxFPS (60)
  215916. {
  215917. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215918. if (FAILED (hr))
  215919. return;
  215920. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215921. if (FAILED (hr))
  215922. return;
  215923. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215924. if (FAILED (hr))
  215925. return;
  215926. {
  215927. ComSmartPtr <IAMStreamConfig> streamConfig;
  215928. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215929. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215930. if (streamConfig != 0)
  215931. {
  215932. getVideoSizes (streamConfig);
  215933. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215934. return;
  215935. }
  215936. }
  215937. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215938. if (FAILED (hr))
  215939. return;
  215940. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215941. if (FAILED (hr))
  215942. return;
  215943. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215944. if (FAILED (hr))
  215945. return;
  215946. if (! connectFilters (filter, smartTee))
  215947. return;
  215948. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215949. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215950. if (FAILED (hr))
  215951. return;
  215952. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215953. if (FAILED (hr))
  215954. return;
  215955. AM_MEDIA_TYPE mt;
  215956. zerostruct (mt);
  215957. mt.majortype = MEDIATYPE_Video;
  215958. mt.subtype = MEDIASUBTYPE_RGB24;
  215959. mt.formattype = FORMAT_VideoInfo;
  215960. sampleGrabber->SetMediaType (&mt);
  215961. callback = new GrabberCallback (*this);
  215962. hr = sampleGrabber->SetCallback (callback, 1);
  215963. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215964. if (FAILED (hr))
  215965. return;
  215966. ComSmartPtr <IPin> grabberInputPin;
  215967. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215968. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215969. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215970. return;
  215971. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215972. if (FAILED (hr))
  215973. return;
  215974. zerostruct (mt);
  215975. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215976. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215977. width = pVih->bmiHeader.biWidth;
  215978. height = pVih->bmiHeader.biHeight;
  215979. ComSmartPtr <IBaseFilter> nullFilter;
  215980. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215981. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215982. if (connectFilters (sampleGrabberBase, nullFilter)
  215983. && addGraphToRot())
  215984. {
  215985. activeImage = Image (Image::RGB, width, height, true);
  215986. loadingImage = Image (Image::RGB, width, height, true);
  215987. ok = true;
  215988. }
  215989. }
  215990. ~DShowCameraDeviceInteral()
  215991. {
  215992. if (mediaControl != 0)
  215993. mediaControl->Stop();
  215994. removeGraphFromRot();
  215995. for (int i = viewerComps.size(); --i >= 0;)
  215996. viewerComps.getUnchecked(i)->ownerDeleted();
  215997. callback = 0;
  215998. graphBuilder = 0;
  215999. sampleGrabber = 0;
  216000. mediaControl = 0;
  216001. filter = 0;
  216002. captureGraphBuilder = 0;
  216003. smartTee = 0;
  216004. smartTeePreviewOutputPin = 0;
  216005. smartTeeCaptureOutputPin = 0;
  216006. asfWriter = 0;
  216007. }
  216008. void addUser()
  216009. {
  216010. if (ok && activeUsers++ == 0)
  216011. mediaControl->Run();
  216012. }
  216013. void removeUser()
  216014. {
  216015. if (ok && --activeUsers == 0)
  216016. mediaControl->Stop();
  216017. }
  216018. int getPreviewMaxFPS() const
  216019. {
  216020. return previewMaxFPS;
  216021. }
  216022. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216023. {
  216024. if (recordNextFrameTime)
  216025. {
  216026. const double defaultCameraLatency = 0.1;
  216027. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216028. recordNextFrameTime = false;
  216029. ComSmartPtr <IPin> pin;
  216030. if (getPin (filter, PINDIR_OUTPUT, pin))
  216031. {
  216032. ComSmartPtr <IAMPushSource> pushSource;
  216033. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216034. if (pushSource != 0)
  216035. {
  216036. REFERENCE_TIME latency = 0;
  216037. hr = pushSource->GetLatency (&latency);
  216038. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216039. }
  216040. }
  216041. }
  216042. {
  216043. const int lineStride = width * 3;
  216044. const ScopedLock sl (imageSwapLock);
  216045. {
  216046. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216047. for (int i = 0; i < height; ++i)
  216048. memcpy (destData.getLinePointer ((height - 1) - i),
  216049. buffer + lineStride * i,
  216050. lineStride);
  216051. }
  216052. imageNeedsFlipping = true;
  216053. }
  216054. if (listeners.size() > 0)
  216055. callListeners (loadingImage);
  216056. sendChangeMessage();
  216057. }
  216058. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216059. {
  216060. if (imageNeedsFlipping)
  216061. {
  216062. const ScopedLock sl (imageSwapLock);
  216063. swapVariables (loadingImage, activeImage);
  216064. imageNeedsFlipping = false;
  216065. }
  216066. RectanglePlacement rp (RectanglePlacement::centred);
  216067. double dx = 0, dy = 0, dw = width, dh = height;
  216068. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216069. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216070. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216071. {
  216072. Graphics::ScopedSaveState ss (g);
  216073. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216074. g.fillAll (Colours::black);
  216075. }
  216076. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216077. }
  216078. bool createFileCaptureFilter (const File& file, int quality)
  216079. {
  216080. removeFileCaptureFilter();
  216081. file.deleteFile();
  216082. mediaControl->Stop();
  216083. firstRecordedTime = Time();
  216084. recordNextFrameTime = true;
  216085. previewMaxFPS = 60;
  216086. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216087. if (SUCCEEDED (hr))
  216088. {
  216089. ComSmartPtr <IFileSinkFilter> fileSink;
  216090. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216091. if (SUCCEEDED (hr))
  216092. {
  216093. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216094. if (SUCCEEDED (hr))
  216095. {
  216096. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216097. if (SUCCEEDED (hr))
  216098. {
  216099. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216100. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216101. asfConfig->SetIndexMode (true);
  216102. ComSmartPtr <IWMProfileManager> profileManager;
  216103. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216104. // This gibberish is the DirectShow profile for a video-only wmv file.
  216105. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216106. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  216107. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216108. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216109. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216110. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  216111. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  216112. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216113. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216114. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216115. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216116. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  216117. "biclrused=\"0\" biclrimportant=\"0\"/>"
  216118. "</videoinfoheader>"
  216119. "</wmmediatype>"
  216120. "</streamconfig>"
  216121. "</profile>");
  216122. const int fps[] = { 10, 15, 30 };
  216123. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  216124. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216125. maxFramesPerSecond = (quality >> 24) & 0xff;
  216126. prof = prof.replace ("$WIDTH", String (width))
  216127. .replace ("$HEIGHT", String (height))
  216128. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216129. ComSmartPtr <IWMProfile> currentProfile;
  216130. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216131. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216132. if (SUCCEEDED (hr))
  216133. {
  216134. ComSmartPtr <IPin> asfWriterInputPin;
  216135. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216136. {
  216137. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216138. if (SUCCEEDED (hr) && ok && activeUsers > 0
  216139. && SUCCEEDED (mediaControl->Run()))
  216140. {
  216141. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216142. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  216143. previewMaxFPS = (quality >> 16) & 0xff;
  216144. return true;
  216145. }
  216146. }
  216147. }
  216148. }
  216149. }
  216150. }
  216151. }
  216152. removeFileCaptureFilter();
  216153. if (ok && activeUsers > 0)
  216154. mediaControl->Run();
  216155. return false;
  216156. }
  216157. void removeFileCaptureFilter()
  216158. {
  216159. mediaControl->Stop();
  216160. if (asfWriter != 0)
  216161. {
  216162. graphBuilder->RemoveFilter (asfWriter);
  216163. asfWriter = 0;
  216164. }
  216165. if (ok && activeUsers > 0)
  216166. mediaControl->Run();
  216167. previewMaxFPS = 60;
  216168. }
  216169. void addListener (CameraDevice::Listener* listenerToAdd)
  216170. {
  216171. const ScopedLock sl (listenerLock);
  216172. if (listeners.size() == 0)
  216173. addUser();
  216174. listeners.addIfNotAlreadyThere (listenerToAdd);
  216175. }
  216176. void removeListener (CameraDevice::Listener* listenerToRemove)
  216177. {
  216178. const ScopedLock sl (listenerLock);
  216179. listeners.removeValue (listenerToRemove);
  216180. if (listeners.size() == 0)
  216181. removeUser();
  216182. }
  216183. void callListeners (const Image& image)
  216184. {
  216185. const ScopedLock sl (listenerLock);
  216186. for (int i = listeners.size(); --i >= 0;)
  216187. {
  216188. CameraDevice::Listener* const l = listeners[i];
  216189. if (l != 0)
  216190. l->imageReceived (image);
  216191. }
  216192. }
  216193. class DShowCaptureViewerComp : public Component,
  216194. public ChangeListener
  216195. {
  216196. public:
  216197. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216198. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216199. {
  216200. setOpaque (true);
  216201. owner->addChangeListener (this);
  216202. owner->addUser();
  216203. owner->viewerComps.add (this);
  216204. setSize (owner->width, owner->height);
  216205. }
  216206. ~DShowCaptureViewerComp()
  216207. {
  216208. if (owner != 0)
  216209. {
  216210. owner->viewerComps.removeValue (this);
  216211. owner->removeUser();
  216212. owner->removeChangeListener (this);
  216213. }
  216214. }
  216215. void ownerDeleted()
  216216. {
  216217. owner = 0;
  216218. }
  216219. void paint (Graphics& g)
  216220. {
  216221. g.setColour (Colours::black);
  216222. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216223. if (owner != 0)
  216224. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216225. else
  216226. g.fillAll (Colours::black);
  216227. }
  216228. void changeListenerCallback (ChangeBroadcaster*)
  216229. {
  216230. const int64 now = Time::currentTimeMillis();
  216231. if (now >= lastRepaintTime + (1000 / maxFPS))
  216232. {
  216233. lastRepaintTime = now;
  216234. repaint();
  216235. if (owner != 0)
  216236. maxFPS = owner->getPreviewMaxFPS();
  216237. }
  216238. }
  216239. private:
  216240. DShowCameraDeviceInteral* owner;
  216241. int maxFPS;
  216242. int64 lastRepaintTime;
  216243. };
  216244. bool ok;
  216245. int width, height;
  216246. Time firstRecordedTime;
  216247. Array <DShowCaptureViewerComp*> viewerComps;
  216248. private:
  216249. CameraDevice* const owner;
  216250. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216251. ComSmartPtr <IBaseFilter> filter;
  216252. ComSmartPtr <IBaseFilter> smartTee;
  216253. ComSmartPtr <IGraphBuilder> graphBuilder;
  216254. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216255. ComSmartPtr <IMediaControl> mediaControl;
  216256. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216257. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216258. ComSmartPtr <IBaseFilter> asfWriter;
  216259. int activeUsers;
  216260. Array <int> widths, heights;
  216261. DWORD graphRegistrationID;
  216262. CriticalSection imageSwapLock;
  216263. bool imageNeedsFlipping;
  216264. Image loadingImage;
  216265. Image activeImage;
  216266. bool recordNextFrameTime;
  216267. int previewMaxFPS;
  216268. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216269. {
  216270. widths.clear();
  216271. heights.clear();
  216272. int count = 0, size = 0;
  216273. streamConfig->GetNumberOfCapabilities (&count, &size);
  216274. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216275. {
  216276. for (int i = 0; i < count; ++i)
  216277. {
  216278. VIDEO_STREAM_CONFIG_CAPS scc;
  216279. AM_MEDIA_TYPE* config;
  216280. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216281. if (SUCCEEDED (hr))
  216282. {
  216283. const int w = scc.InputSize.cx;
  216284. const int h = scc.InputSize.cy;
  216285. bool duplicate = false;
  216286. for (int j = widths.size(); --j >= 0;)
  216287. {
  216288. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216289. {
  216290. duplicate = true;
  216291. break;
  216292. }
  216293. }
  216294. if (! duplicate)
  216295. {
  216296. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216297. widths.add (w);
  216298. heights.add (h);
  216299. }
  216300. deleteMediaType (config);
  216301. }
  216302. }
  216303. }
  216304. }
  216305. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216306. const int minWidth, const int minHeight,
  216307. const int maxWidth, const int maxHeight)
  216308. {
  216309. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216310. streamConfig->GetNumberOfCapabilities (&count, &size);
  216311. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216312. {
  216313. AM_MEDIA_TYPE* config;
  216314. VIDEO_STREAM_CONFIG_CAPS scc;
  216315. for (int i = 0; i < count; ++i)
  216316. {
  216317. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216318. if (SUCCEEDED (hr))
  216319. {
  216320. if (scc.InputSize.cx >= minWidth
  216321. && scc.InputSize.cy >= minHeight
  216322. && scc.InputSize.cx <= maxWidth
  216323. && scc.InputSize.cy <= maxHeight)
  216324. {
  216325. int area = scc.InputSize.cx * scc.InputSize.cy;
  216326. if (area > bestArea)
  216327. {
  216328. bestIndex = i;
  216329. bestArea = area;
  216330. }
  216331. }
  216332. deleteMediaType (config);
  216333. }
  216334. }
  216335. if (bestIndex >= 0)
  216336. {
  216337. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216338. hr = streamConfig->SetFormat (config);
  216339. deleteMediaType (config);
  216340. return SUCCEEDED (hr);
  216341. }
  216342. }
  216343. return false;
  216344. }
  216345. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216346. {
  216347. ComSmartPtr <IEnumPins> enumerator;
  216348. ComSmartPtr <IPin> pin;
  216349. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216350. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216351. {
  216352. PIN_DIRECTION dir;
  216353. pin->QueryDirection (&dir);
  216354. if (wantedDirection == dir)
  216355. {
  216356. PIN_INFO info;
  216357. zerostruct (info);
  216358. pin->QueryPinInfo (&info);
  216359. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216360. {
  216361. result = pin;
  216362. return true;
  216363. }
  216364. }
  216365. }
  216366. return false;
  216367. }
  216368. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216369. {
  216370. ComSmartPtr <IPin> in, out;
  216371. return getPin (first, PINDIR_OUTPUT, out)
  216372. && getPin (second, PINDIR_INPUT, in)
  216373. && SUCCEEDED (graphBuilder->Connect (out, in));
  216374. }
  216375. bool addGraphToRot()
  216376. {
  216377. ComSmartPtr <IRunningObjectTable> rot;
  216378. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216379. return false;
  216380. ComSmartPtr <IMoniker> moniker;
  216381. WCHAR buffer[128];
  216382. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216383. if (FAILED (hr))
  216384. return false;
  216385. graphRegistrationID = 0;
  216386. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216387. }
  216388. void removeGraphFromRot()
  216389. {
  216390. ComSmartPtr <IRunningObjectTable> rot;
  216391. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216392. rot->Revoke (graphRegistrationID);
  216393. }
  216394. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216395. {
  216396. if (pmt->cbFormat != 0)
  216397. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216398. if (pmt->pUnk != 0)
  216399. pmt->pUnk->Release();
  216400. CoTaskMemFree (pmt);
  216401. }
  216402. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216403. {
  216404. public:
  216405. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216406. : owner (owner_)
  216407. {
  216408. }
  216409. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216410. {
  216411. return E_FAIL;
  216412. }
  216413. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216414. {
  216415. owner.handleFrame (time, buffer, bufferSize);
  216416. return S_OK;
  216417. }
  216418. private:
  216419. DShowCameraDeviceInteral& owner;
  216420. GrabberCallback (const GrabberCallback&);
  216421. GrabberCallback& operator= (const GrabberCallback&);
  216422. };
  216423. ComSmartPtr <GrabberCallback> callback;
  216424. Array <CameraDevice::Listener*> listeners;
  216425. CriticalSection listenerLock;
  216426. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  216427. };
  216428. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216429. : name (name_)
  216430. {
  216431. isRecording = false;
  216432. }
  216433. CameraDevice::~CameraDevice()
  216434. {
  216435. stopRecording();
  216436. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216437. internal = 0;
  216438. }
  216439. Component* CameraDevice::createViewerComponent()
  216440. {
  216441. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216442. }
  216443. const String CameraDevice::getFileExtension()
  216444. {
  216445. return ".wmv";
  216446. }
  216447. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216448. {
  216449. stopRecording();
  216450. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216451. d->addUser();
  216452. isRecording = d->createFileCaptureFilter (file, quality);
  216453. }
  216454. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216455. {
  216456. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216457. return d->firstRecordedTime;
  216458. }
  216459. void CameraDevice::stopRecording()
  216460. {
  216461. if (isRecording)
  216462. {
  216463. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216464. d->removeFileCaptureFilter();
  216465. d->removeUser();
  216466. isRecording = false;
  216467. }
  216468. }
  216469. void CameraDevice::addListener (Listener* listenerToAdd)
  216470. {
  216471. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216472. if (listenerToAdd != 0)
  216473. d->addListener (listenerToAdd);
  216474. }
  216475. void CameraDevice::removeListener (Listener* listenerToRemove)
  216476. {
  216477. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216478. if (listenerToRemove != 0)
  216479. d->removeListener (listenerToRemove);
  216480. }
  216481. namespace
  216482. {
  216483. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216484. const int deviceIndexToOpen,
  216485. String& name)
  216486. {
  216487. int index = 0;
  216488. ComSmartPtr <IBaseFilter> result;
  216489. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216490. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216491. if (SUCCEEDED (hr))
  216492. {
  216493. ComSmartPtr <IEnumMoniker> enumerator;
  216494. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216495. if (SUCCEEDED (hr) && enumerator != 0)
  216496. {
  216497. ComSmartPtr <IMoniker> moniker;
  216498. ULONG fetched;
  216499. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216500. {
  216501. ComSmartPtr <IBaseFilter> captureFilter;
  216502. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216503. if (SUCCEEDED (hr))
  216504. {
  216505. ComSmartPtr <IPropertyBag> propertyBag;
  216506. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216507. if (SUCCEEDED (hr))
  216508. {
  216509. VARIANT var;
  216510. var.vt = VT_BSTR;
  216511. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216512. propertyBag = 0;
  216513. if (SUCCEEDED (hr))
  216514. {
  216515. if (names != 0)
  216516. names->add (var.bstrVal);
  216517. if (index == deviceIndexToOpen)
  216518. {
  216519. name = var.bstrVal;
  216520. result = captureFilter;
  216521. break;
  216522. }
  216523. ++index;
  216524. }
  216525. }
  216526. }
  216527. }
  216528. }
  216529. }
  216530. return result;
  216531. }
  216532. }
  216533. const StringArray CameraDevice::getAvailableDevices()
  216534. {
  216535. StringArray devs;
  216536. String dummy;
  216537. enumerateCameras (&devs, -1, dummy);
  216538. return devs;
  216539. }
  216540. CameraDevice* CameraDevice::openDevice (int index,
  216541. int minWidth, int minHeight,
  216542. int maxWidth, int maxHeight)
  216543. {
  216544. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216545. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  216546. if (SUCCEEDED (hr))
  216547. {
  216548. String name;
  216549. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216550. if (filter != 0)
  216551. {
  216552. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216553. DShowCameraDeviceInteral* const intern
  216554. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216555. minWidth, minHeight, maxWidth, maxHeight);
  216556. cam->internal = intern;
  216557. if (intern->ok)
  216558. return cam.release();
  216559. }
  216560. }
  216561. return 0;
  216562. }
  216563. #endif
  216564. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216565. #endif
  216566. // Auto-link the other win32 libs that are needed by library calls..
  216567. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216568. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216569. // Auto-links to various win32 libs that are needed by library calls..
  216570. #pragma comment(lib, "kernel32.lib")
  216571. #pragma comment(lib, "user32.lib")
  216572. #pragma comment(lib, "shell32.lib")
  216573. #pragma comment(lib, "gdi32.lib")
  216574. #pragma comment(lib, "vfw32.lib")
  216575. #pragma comment(lib, "comdlg32.lib")
  216576. #pragma comment(lib, "winmm.lib")
  216577. #pragma comment(lib, "wininet.lib")
  216578. #pragma comment(lib, "ole32.lib")
  216579. #pragma comment(lib, "oleaut32.lib")
  216580. #pragma comment(lib, "advapi32.lib")
  216581. #pragma comment(lib, "ws2_32.lib")
  216582. #pragma comment(lib, "version.lib")
  216583. #ifdef _NATIVE_WCHAR_T_DEFINED
  216584. #ifdef _DEBUG
  216585. #pragma comment(lib, "comsuppwd.lib")
  216586. #else
  216587. #pragma comment(lib, "comsuppw.lib")
  216588. #endif
  216589. #else
  216590. #ifdef _DEBUG
  216591. #pragma comment(lib, "comsuppd.lib")
  216592. #else
  216593. #pragma comment(lib, "comsupp.lib")
  216594. #endif
  216595. #endif
  216596. #if JUCE_OPENGL
  216597. #pragma comment(lib, "OpenGL32.Lib")
  216598. #pragma comment(lib, "GlU32.Lib")
  216599. #endif
  216600. #if JUCE_QUICKTIME
  216601. #pragma comment (lib, "QTMLClient.lib")
  216602. #endif
  216603. #if JUCE_USE_CAMERA
  216604. #pragma comment (lib, "Strmiids.lib")
  216605. #pragma comment (lib, "wmvcore.lib")
  216606. #endif
  216607. #if JUCE_DIRECT2D
  216608. #pragma comment (lib, "Dwrite.lib")
  216609. #pragma comment (lib, "D2d1.lib")
  216610. #endif
  216611. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216612. #endif
  216613. END_JUCE_NAMESPACE
  216614. #endif
  216615. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216616. #endif
  216617. #if JUCE_LINUX
  216618. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216619. /*
  216620. This file wraps together all the mac-specific code, so that
  216621. we can include all the native headers just once, and compile all our
  216622. platform-specific stuff in one big lump, keeping it out of the way of
  216623. the rest of the codebase.
  216624. */
  216625. #if JUCE_LINUX
  216626. #undef JUCE_BUILD_NATIVE
  216627. #define JUCE_BUILD_NATIVE 1
  216628. BEGIN_JUCE_NAMESPACE
  216629. #define JUCE_INCLUDED_FILE 1
  216630. // Now include the actual code files..
  216631. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216632. /*
  216633. This file contains posix routines that are common to both the Linux and Mac builds.
  216634. It gets included directly in the cpp files for these platforms.
  216635. */
  216636. CriticalSection::CriticalSection() throw()
  216637. {
  216638. pthread_mutexattr_t atts;
  216639. pthread_mutexattr_init (&atts);
  216640. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216641. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216642. pthread_mutex_init (&internal, &atts);
  216643. }
  216644. CriticalSection::~CriticalSection() throw()
  216645. {
  216646. pthread_mutex_destroy (&internal);
  216647. }
  216648. void CriticalSection::enter() const throw()
  216649. {
  216650. pthread_mutex_lock (&internal);
  216651. }
  216652. bool CriticalSection::tryEnter() const throw()
  216653. {
  216654. return pthread_mutex_trylock (&internal) == 0;
  216655. }
  216656. void CriticalSection::exit() const throw()
  216657. {
  216658. pthread_mutex_unlock (&internal);
  216659. }
  216660. class WaitableEventImpl
  216661. {
  216662. public:
  216663. WaitableEventImpl (const bool manualReset_)
  216664. : triggered (false),
  216665. manualReset (manualReset_)
  216666. {
  216667. pthread_cond_init (&condition, 0);
  216668. pthread_mutexattr_t atts;
  216669. pthread_mutexattr_init (&atts);
  216670. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216671. pthread_mutex_init (&mutex, &atts);
  216672. }
  216673. ~WaitableEventImpl()
  216674. {
  216675. pthread_cond_destroy (&condition);
  216676. pthread_mutex_destroy (&mutex);
  216677. }
  216678. bool wait (const int timeOutMillisecs) throw()
  216679. {
  216680. pthread_mutex_lock (&mutex);
  216681. if (! triggered)
  216682. {
  216683. if (timeOutMillisecs < 0)
  216684. {
  216685. do
  216686. {
  216687. pthread_cond_wait (&condition, &mutex);
  216688. }
  216689. while (! triggered);
  216690. }
  216691. else
  216692. {
  216693. struct timeval now;
  216694. gettimeofday (&now, 0);
  216695. struct timespec time;
  216696. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216697. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216698. if (time.tv_nsec >= 1000000000)
  216699. {
  216700. time.tv_nsec -= 1000000000;
  216701. time.tv_sec++;
  216702. }
  216703. do
  216704. {
  216705. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216706. {
  216707. pthread_mutex_unlock (&mutex);
  216708. return false;
  216709. }
  216710. }
  216711. while (! triggered);
  216712. }
  216713. }
  216714. if (! manualReset)
  216715. triggered = false;
  216716. pthread_mutex_unlock (&mutex);
  216717. return true;
  216718. }
  216719. void signal() throw()
  216720. {
  216721. pthread_mutex_lock (&mutex);
  216722. triggered = true;
  216723. pthread_cond_broadcast (&condition);
  216724. pthread_mutex_unlock (&mutex);
  216725. }
  216726. void reset() throw()
  216727. {
  216728. pthread_mutex_lock (&mutex);
  216729. triggered = false;
  216730. pthread_mutex_unlock (&mutex);
  216731. }
  216732. private:
  216733. pthread_cond_t condition;
  216734. pthread_mutex_t mutex;
  216735. bool triggered;
  216736. const bool manualReset;
  216737. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216738. };
  216739. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216740. : internal (new WaitableEventImpl (manualReset))
  216741. {
  216742. }
  216743. WaitableEvent::~WaitableEvent() throw()
  216744. {
  216745. delete static_cast <WaitableEventImpl*> (internal);
  216746. }
  216747. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216748. {
  216749. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216750. }
  216751. void WaitableEvent::signal() const throw()
  216752. {
  216753. static_cast <WaitableEventImpl*> (internal)->signal();
  216754. }
  216755. void WaitableEvent::reset() const throw()
  216756. {
  216757. static_cast <WaitableEventImpl*> (internal)->reset();
  216758. }
  216759. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216760. {
  216761. struct timespec time;
  216762. time.tv_sec = millisecs / 1000;
  216763. time.tv_nsec = (millisecs % 1000) * 1000000;
  216764. nanosleep (&time, 0);
  216765. }
  216766. const juce_wchar File::separator = '/';
  216767. const String File::separatorString ("/");
  216768. const File File::getCurrentWorkingDirectory()
  216769. {
  216770. HeapBlock<char> heapBuffer;
  216771. char localBuffer [1024];
  216772. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216773. int bufferSize = 4096;
  216774. while (cwd == 0 && errno == ERANGE)
  216775. {
  216776. heapBuffer.malloc (bufferSize);
  216777. cwd = getcwd (heapBuffer, bufferSize - 1);
  216778. bufferSize += 1024;
  216779. }
  216780. return File (String::fromUTF8 (cwd));
  216781. }
  216782. bool File::setAsCurrentWorkingDirectory() const
  216783. {
  216784. return chdir (getFullPathName().toUTF8()) == 0;
  216785. }
  216786. namespace
  216787. {
  216788. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216789. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216790. #else
  216791. typedef struct stat juce_statStruct;
  216792. #endif
  216793. bool juce_stat (const String& fileName, juce_statStruct& info)
  216794. {
  216795. return fileName.isNotEmpty()
  216796. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216797. && (stat64 (fileName.toUTF8(), &info) == 0);
  216798. #else
  216799. && (stat (fileName.toUTF8(), &info) == 0);
  216800. #endif
  216801. }
  216802. // if this file doesn't exist, find a parent of it that does..
  216803. bool juce_doStatFS (File f, struct statfs& result)
  216804. {
  216805. for (int i = 5; --i >= 0;)
  216806. {
  216807. if (f.exists())
  216808. break;
  216809. f = f.getParentDirectory();
  216810. }
  216811. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216812. }
  216813. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216814. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216815. {
  216816. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216817. {
  216818. juce_statStruct info;
  216819. const bool statOk = juce_stat (path, info);
  216820. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216821. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216822. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216823. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216824. }
  216825. if (isReadOnly != 0)
  216826. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216827. }
  216828. }
  216829. bool File::isDirectory() const
  216830. {
  216831. juce_statStruct info;
  216832. return fullPath.isEmpty()
  216833. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216834. }
  216835. bool File::exists() const
  216836. {
  216837. juce_statStruct info;
  216838. return fullPath.isNotEmpty()
  216839. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216840. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216841. #else
  216842. && (lstat (fullPath.toUTF8(), &info) == 0);
  216843. #endif
  216844. }
  216845. bool File::existsAsFile() const
  216846. {
  216847. return exists() && ! isDirectory();
  216848. }
  216849. int64 File::getSize() const
  216850. {
  216851. juce_statStruct info;
  216852. return juce_stat (fullPath, info) ? info.st_size : 0;
  216853. }
  216854. bool File::hasWriteAccess() const
  216855. {
  216856. if (exists())
  216857. return access (fullPath.toUTF8(), W_OK) == 0;
  216858. if ((! isDirectory()) && fullPath.containsChar (separator))
  216859. return getParentDirectory().hasWriteAccess();
  216860. return false;
  216861. }
  216862. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216863. {
  216864. juce_statStruct info;
  216865. if (! juce_stat (fullPath, info))
  216866. return false;
  216867. info.st_mode &= 0777; // Just permissions
  216868. if (shouldBeReadOnly)
  216869. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216870. else
  216871. // Give everybody write permission?
  216872. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216873. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216874. }
  216875. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216876. {
  216877. modificationTime = 0;
  216878. accessTime = 0;
  216879. creationTime = 0;
  216880. juce_statStruct info;
  216881. if (juce_stat (fullPath, info))
  216882. {
  216883. modificationTime = (int64) info.st_mtime * 1000;
  216884. accessTime = (int64) info.st_atime * 1000;
  216885. creationTime = (int64) info.st_ctime * 1000;
  216886. }
  216887. }
  216888. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216889. {
  216890. struct utimbuf times;
  216891. times.actime = (time_t) (accessTime / 1000);
  216892. times.modtime = (time_t) (modificationTime / 1000);
  216893. return utime (fullPath.toUTF8(), &times) == 0;
  216894. }
  216895. bool File::deleteFile() const
  216896. {
  216897. if (! exists())
  216898. return true;
  216899. else if (isDirectory())
  216900. return rmdir (fullPath.toUTF8()) == 0;
  216901. else
  216902. return remove (fullPath.toUTF8()) == 0;
  216903. }
  216904. bool File::moveInternal (const File& dest) const
  216905. {
  216906. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216907. return true;
  216908. if (hasWriteAccess() && copyInternal (dest))
  216909. {
  216910. if (deleteFile())
  216911. return true;
  216912. dest.deleteFile();
  216913. }
  216914. return false;
  216915. }
  216916. void File::createDirectoryInternal (const String& fileName) const
  216917. {
  216918. mkdir (fileName.toUTF8(), 0777);
  216919. }
  216920. int64 juce_fileSetPosition (void* handle, int64 pos)
  216921. {
  216922. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216923. return pos;
  216924. return -1;
  216925. }
  216926. void FileInputStream::openHandle()
  216927. {
  216928. totalSize = file.getSize();
  216929. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216930. if (f != -1)
  216931. fileHandle = (void*) f;
  216932. }
  216933. void FileInputStream::closeHandle()
  216934. {
  216935. if (fileHandle != 0)
  216936. {
  216937. close ((int) (pointer_sized_int) fileHandle);
  216938. fileHandle = 0;
  216939. }
  216940. }
  216941. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216942. {
  216943. if (fileHandle != 0)
  216944. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216945. return 0;
  216946. }
  216947. void FileOutputStream::openHandle()
  216948. {
  216949. if (file.exists())
  216950. {
  216951. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216952. if (f != -1)
  216953. {
  216954. currentPosition = lseek (f, 0, SEEK_END);
  216955. if (currentPosition >= 0)
  216956. fileHandle = (void*) f;
  216957. else
  216958. close (f);
  216959. }
  216960. }
  216961. else
  216962. {
  216963. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216964. if (f != -1)
  216965. fileHandle = (void*) f;
  216966. }
  216967. }
  216968. void FileOutputStream::closeHandle()
  216969. {
  216970. if (fileHandle != 0)
  216971. {
  216972. close ((int) (pointer_sized_int) fileHandle);
  216973. fileHandle = 0;
  216974. }
  216975. }
  216976. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216977. {
  216978. if (fileHandle != 0)
  216979. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216980. return 0;
  216981. }
  216982. void FileOutputStream::flushInternal()
  216983. {
  216984. if (fileHandle != 0)
  216985. fsync ((int) (pointer_sized_int) fileHandle);
  216986. }
  216987. const File juce_getExecutableFile()
  216988. {
  216989. Dl_info exeInfo;
  216990. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  216991. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216992. }
  216993. int64 File::getBytesFreeOnVolume() const
  216994. {
  216995. struct statfs buf;
  216996. if (juce_doStatFS (*this, buf))
  216997. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216998. return 0;
  216999. }
  217000. int64 File::getVolumeTotalSize() const
  217001. {
  217002. struct statfs buf;
  217003. if (juce_doStatFS (*this, buf))
  217004. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217005. return 0;
  217006. }
  217007. const String File::getVolumeLabel() const
  217008. {
  217009. #if JUCE_MAC
  217010. struct VolAttrBuf
  217011. {
  217012. u_int32_t length;
  217013. attrreference_t mountPointRef;
  217014. char mountPointSpace [MAXPATHLEN];
  217015. } attrBuf;
  217016. struct attrlist attrList;
  217017. zerostruct (attrList);
  217018. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217019. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217020. File f (*this);
  217021. for (;;)
  217022. {
  217023. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217024. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217025. (int) attrBuf.mountPointRef.attr_length);
  217026. const File parent (f.getParentDirectory());
  217027. if (f == parent)
  217028. break;
  217029. f = parent;
  217030. }
  217031. #endif
  217032. return String::empty;
  217033. }
  217034. int File::getVolumeSerialNumber() const
  217035. {
  217036. return 0; // xxx
  217037. }
  217038. void juce_runSystemCommand (const String& command)
  217039. {
  217040. int result = system (command.toUTF8());
  217041. (void) result;
  217042. }
  217043. const String juce_getOutputFromCommand (const String& command)
  217044. {
  217045. // slight bodge here, as we just pipe the output into a temp file and read it...
  217046. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217047. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217048. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217049. String result (tempFile.loadFileAsString());
  217050. tempFile.deleteFile();
  217051. return result;
  217052. }
  217053. class InterProcessLock::Pimpl
  217054. {
  217055. public:
  217056. Pimpl (const String& name, const int timeOutMillisecs)
  217057. : handle (0), refCount (1)
  217058. {
  217059. #if JUCE_MAC
  217060. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217061. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217062. #else
  217063. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217064. #endif
  217065. temp.create();
  217066. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217067. if (handle != 0)
  217068. {
  217069. struct flock fl;
  217070. zerostruct (fl);
  217071. fl.l_whence = SEEK_SET;
  217072. fl.l_type = F_WRLCK;
  217073. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217074. for (;;)
  217075. {
  217076. const int result = fcntl (handle, F_SETLK, &fl);
  217077. if (result >= 0)
  217078. return;
  217079. if (errno != EINTR)
  217080. {
  217081. if (timeOutMillisecs == 0
  217082. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217083. break;
  217084. Thread::sleep (10);
  217085. }
  217086. }
  217087. }
  217088. closeFile();
  217089. }
  217090. ~Pimpl()
  217091. {
  217092. closeFile();
  217093. }
  217094. void closeFile()
  217095. {
  217096. if (handle != 0)
  217097. {
  217098. struct flock fl;
  217099. zerostruct (fl);
  217100. fl.l_whence = SEEK_SET;
  217101. fl.l_type = F_UNLCK;
  217102. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217103. {}
  217104. close (handle);
  217105. handle = 0;
  217106. }
  217107. }
  217108. int handle, refCount;
  217109. };
  217110. InterProcessLock::InterProcessLock (const String& name_)
  217111. : name (name_)
  217112. {
  217113. }
  217114. InterProcessLock::~InterProcessLock()
  217115. {
  217116. }
  217117. bool InterProcessLock::enter (const int timeOutMillisecs)
  217118. {
  217119. const ScopedLock sl (lock);
  217120. if (pimpl == 0)
  217121. {
  217122. pimpl = new Pimpl (name, timeOutMillisecs);
  217123. if (pimpl->handle == 0)
  217124. pimpl = 0;
  217125. }
  217126. else
  217127. {
  217128. pimpl->refCount++;
  217129. }
  217130. return pimpl != 0;
  217131. }
  217132. void InterProcessLock::exit()
  217133. {
  217134. const ScopedLock sl (lock);
  217135. // Trying to release the lock too many times!
  217136. jassert (pimpl != 0);
  217137. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217138. pimpl = 0;
  217139. }
  217140. void JUCE_API juce_threadEntryPoint (void*);
  217141. void* threadEntryProc (void* userData)
  217142. {
  217143. JUCE_AUTORELEASEPOOL
  217144. juce_threadEntryPoint (userData);
  217145. return 0;
  217146. }
  217147. void Thread::launchThread()
  217148. {
  217149. threadHandle_ = 0;
  217150. pthread_t handle = 0;
  217151. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  217152. {
  217153. pthread_detach (handle);
  217154. threadHandle_ = (void*) handle;
  217155. threadId_ = (ThreadID) threadHandle_;
  217156. }
  217157. }
  217158. void Thread::closeThreadHandle()
  217159. {
  217160. threadId_ = 0;
  217161. threadHandle_ = 0;
  217162. }
  217163. void Thread::killThread()
  217164. {
  217165. if (threadHandle_ != 0)
  217166. pthread_cancel ((pthread_t) threadHandle_);
  217167. }
  217168. void Thread::setCurrentThreadName (const String& /*name*/)
  217169. {
  217170. }
  217171. bool Thread::setThreadPriority (void* handle, int priority)
  217172. {
  217173. struct sched_param param;
  217174. int policy;
  217175. priority = jlimit (0, 10, priority);
  217176. if (handle == 0)
  217177. handle = (void*) pthread_self();
  217178. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217179. return false;
  217180. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217181. const int minPriority = sched_get_priority_min (policy);
  217182. const int maxPriority = sched_get_priority_max (policy);
  217183. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217184. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217185. }
  217186. Thread::ThreadID Thread::getCurrentThreadId()
  217187. {
  217188. return (ThreadID) pthread_self();
  217189. }
  217190. void Thread::yield()
  217191. {
  217192. sched_yield();
  217193. }
  217194. /* Remove this macro if you're having problems compiling the cpu affinity
  217195. calls (the API for these has changed about quite a bit in various Linux
  217196. versions, and a lot of distros seem to ship with obsolete versions)
  217197. */
  217198. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217199. #define SUPPORT_AFFINITIES 1
  217200. #endif
  217201. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217202. {
  217203. #if SUPPORT_AFFINITIES
  217204. cpu_set_t affinity;
  217205. CPU_ZERO (&affinity);
  217206. for (int i = 0; i < 32; ++i)
  217207. if ((affinityMask & (1 << i)) != 0)
  217208. CPU_SET (i, &affinity);
  217209. /*
  217210. N.B. If this line causes a compile error, then you've probably not got the latest
  217211. version of glibc installed.
  217212. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217213. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217214. */
  217215. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217216. sched_yield();
  217217. #else
  217218. /* affinities aren't supported because either the appropriate header files weren't found,
  217219. or the SUPPORT_AFFINITIES macro was turned off
  217220. */
  217221. jassertfalse;
  217222. (void) affinityMask;
  217223. #endif
  217224. }
  217225. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217226. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217227. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217228. // compiled on its own).
  217229. #if JUCE_INCLUDED_FILE
  217230. enum
  217231. {
  217232. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217233. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217234. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217235. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217236. };
  217237. bool File::copyInternal (const File& dest) const
  217238. {
  217239. FileInputStream in (*this);
  217240. if (dest.deleteFile())
  217241. {
  217242. {
  217243. FileOutputStream out (dest);
  217244. if (out.failedToOpen())
  217245. return false;
  217246. if (out.writeFromInputStream (in, -1) == getSize())
  217247. return true;
  217248. }
  217249. dest.deleteFile();
  217250. }
  217251. return false;
  217252. }
  217253. void File::findFileSystemRoots (Array<File>& destArray)
  217254. {
  217255. destArray.add (File ("/"));
  217256. }
  217257. bool File::isOnCDRomDrive() const
  217258. {
  217259. struct statfs buf;
  217260. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217261. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217262. }
  217263. bool File::isOnHardDisk() const
  217264. {
  217265. struct statfs buf;
  217266. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217267. {
  217268. switch (buf.f_type)
  217269. {
  217270. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217271. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217272. case U_NFS_SUPER_MAGIC: // Network NFS
  217273. case U_SMB_SUPER_MAGIC: // Network Samba
  217274. return false;
  217275. default:
  217276. // Assume anything else is a hard-disk (but note it could
  217277. // be a RAM disk. There isn't a good way of determining
  217278. // this for sure)
  217279. return true;
  217280. }
  217281. }
  217282. // Assume so if this fails for some reason
  217283. return true;
  217284. }
  217285. bool File::isOnRemovableDrive() const
  217286. {
  217287. jassertfalse; // xxx not implemented for linux!
  217288. return false;
  217289. }
  217290. bool File::isHidden() const
  217291. {
  217292. return getFileName().startsWithChar ('.');
  217293. }
  217294. namespace
  217295. {
  217296. const File juce_readlink (const String& file, const File& defaultFile)
  217297. {
  217298. const int size = 8192;
  217299. HeapBlock<char> buffer;
  217300. buffer.malloc (size + 4);
  217301. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217302. if (numBytes > 0 && numBytes <= size)
  217303. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217304. return defaultFile;
  217305. }
  217306. }
  217307. const File File::getLinkedTarget() const
  217308. {
  217309. return juce_readlink (getFullPathName().toUTF8(), *this);
  217310. }
  217311. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217312. const File File::getSpecialLocation (const SpecialLocationType type)
  217313. {
  217314. switch (type)
  217315. {
  217316. case userHomeDirectory:
  217317. {
  217318. const char* homeDir = getenv ("HOME");
  217319. if (homeDir == 0)
  217320. {
  217321. struct passwd* const pw = getpwuid (getuid());
  217322. if (pw != 0)
  217323. homeDir = pw->pw_dir;
  217324. }
  217325. return File (String::fromUTF8 (homeDir));
  217326. }
  217327. case userDocumentsDirectory:
  217328. case userMusicDirectory:
  217329. case userMoviesDirectory:
  217330. case userApplicationDataDirectory:
  217331. return File ("~");
  217332. case userDesktopDirectory:
  217333. return File ("~/Desktop");
  217334. case commonApplicationDataDirectory:
  217335. return File ("/var");
  217336. case globalApplicationsDirectory:
  217337. return File ("/usr");
  217338. case tempDirectory:
  217339. {
  217340. File tmp ("/var/tmp");
  217341. if (! tmp.isDirectory())
  217342. {
  217343. tmp = "/tmp";
  217344. if (! tmp.isDirectory())
  217345. tmp = File::getCurrentWorkingDirectory();
  217346. }
  217347. return tmp;
  217348. }
  217349. case invokedExecutableFile:
  217350. if (juce_Argv0 != 0)
  217351. return File (String::fromUTF8 (juce_Argv0));
  217352. // deliberate fall-through...
  217353. case currentExecutableFile:
  217354. case currentApplicationFile:
  217355. return juce_getExecutableFile();
  217356. case hostApplicationPath:
  217357. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217358. default:
  217359. jassertfalse; // unknown type?
  217360. break;
  217361. }
  217362. return File::nonexistent;
  217363. }
  217364. const String File::getVersion() const
  217365. {
  217366. return String::empty; // xxx not yet implemented
  217367. }
  217368. bool File::moveToTrash() const
  217369. {
  217370. if (! exists())
  217371. return true;
  217372. File trashCan ("~/.Trash");
  217373. if (! trashCan.isDirectory())
  217374. trashCan = "~/.local/share/Trash/files";
  217375. if (! trashCan.isDirectory())
  217376. return false;
  217377. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217378. getFileExtension()));
  217379. }
  217380. class DirectoryIterator::NativeIterator::Pimpl
  217381. {
  217382. public:
  217383. Pimpl (const File& directory, const String& wildCard_)
  217384. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217385. wildCard (wildCard_),
  217386. dir (opendir (directory.getFullPathName().toUTF8()))
  217387. {
  217388. wildcardUTF8 = wildCard.toUTF8();
  217389. }
  217390. ~Pimpl()
  217391. {
  217392. if (dir != 0)
  217393. closedir (dir);
  217394. }
  217395. bool next (String& filenameFound,
  217396. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217397. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217398. {
  217399. if (dir != 0)
  217400. {
  217401. for (;;)
  217402. {
  217403. struct dirent* const de = readdir (dir);
  217404. if (de == 0)
  217405. break;
  217406. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217407. {
  217408. filenameFound = String::fromUTF8 (de->d_name);
  217409. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  217410. if (isHidden != 0)
  217411. *isHidden = filenameFound.startsWithChar ('.');
  217412. return true;
  217413. }
  217414. }
  217415. }
  217416. return false;
  217417. }
  217418. private:
  217419. String parentDir, wildCard;
  217420. const char* wildcardUTF8;
  217421. DIR* dir;
  217422. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  217423. };
  217424. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217425. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217426. {
  217427. }
  217428. DirectoryIterator::NativeIterator::~NativeIterator()
  217429. {
  217430. }
  217431. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217432. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217433. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217434. {
  217435. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217436. }
  217437. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217438. {
  217439. String cmdString (fileName.replace (" ", "\\ ",false));
  217440. cmdString << " " << parameters;
  217441. if (URL::isProbablyAWebsiteURL (fileName)
  217442. || cmdString.startsWithIgnoreCase ("file:")
  217443. || URL::isProbablyAnEmailAddress (fileName))
  217444. {
  217445. // create a command that tries to launch a bunch of likely browsers
  217446. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217447. StringArray cmdLines;
  217448. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217449. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217450. cmdString = cmdLines.joinIntoString (" || ");
  217451. }
  217452. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217453. const int cpid = fork();
  217454. if (cpid == 0)
  217455. {
  217456. setsid();
  217457. // Child process
  217458. execve (argv[0], (char**) argv, environ);
  217459. exit (0);
  217460. }
  217461. return cpid >= 0;
  217462. }
  217463. void File::revealToUser() const
  217464. {
  217465. if (isDirectory())
  217466. startAsProcess();
  217467. else if (getParentDirectory().exists())
  217468. getParentDirectory().startAsProcess();
  217469. }
  217470. #endif
  217471. /*** End of inlined file: juce_linux_Files.cpp ***/
  217472. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217473. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217474. // compiled on its own).
  217475. #if JUCE_INCLUDED_FILE
  217476. struct NamedPipeInternal
  217477. {
  217478. String pipeInName, pipeOutName;
  217479. int pipeIn, pipeOut;
  217480. bool volatile createdPipe, blocked, stopReadOperation;
  217481. static void signalHandler (int) {}
  217482. };
  217483. void NamedPipe::cancelPendingReads()
  217484. {
  217485. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217486. {
  217487. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217488. intern->stopReadOperation = true;
  217489. char buffer [1] = { 0 };
  217490. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217491. (void) bytesWritten;
  217492. int timeout = 2000;
  217493. while (intern->blocked && --timeout >= 0)
  217494. Thread::sleep (2);
  217495. intern->stopReadOperation = false;
  217496. }
  217497. }
  217498. void NamedPipe::close()
  217499. {
  217500. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217501. if (intern != 0)
  217502. {
  217503. internal = 0;
  217504. if (intern->pipeIn != -1)
  217505. ::close (intern->pipeIn);
  217506. if (intern->pipeOut != -1)
  217507. ::close (intern->pipeOut);
  217508. if (intern->createdPipe)
  217509. {
  217510. unlink (intern->pipeInName.toUTF8());
  217511. unlink (intern->pipeOutName.toUTF8());
  217512. }
  217513. delete intern;
  217514. }
  217515. }
  217516. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217517. {
  217518. close();
  217519. NamedPipeInternal* const intern = new NamedPipeInternal();
  217520. internal = intern;
  217521. intern->createdPipe = createPipe;
  217522. intern->blocked = false;
  217523. intern->stopReadOperation = false;
  217524. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217525. siginterrupt (SIGPIPE, 1);
  217526. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217527. intern->pipeInName = pipePath + "_in";
  217528. intern->pipeOutName = pipePath + "_out";
  217529. intern->pipeIn = -1;
  217530. intern->pipeOut = -1;
  217531. if (createPipe)
  217532. {
  217533. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217534. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217535. {
  217536. delete intern;
  217537. internal = 0;
  217538. return false;
  217539. }
  217540. }
  217541. return true;
  217542. }
  217543. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217544. {
  217545. int bytesRead = -1;
  217546. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217547. if (intern != 0)
  217548. {
  217549. intern->blocked = true;
  217550. if (intern->pipeIn == -1)
  217551. {
  217552. if (intern->createdPipe)
  217553. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217554. else
  217555. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217556. if (intern->pipeIn == -1)
  217557. {
  217558. intern->blocked = false;
  217559. return -1;
  217560. }
  217561. }
  217562. bytesRead = 0;
  217563. char* p = static_cast<char*> (destBuffer);
  217564. while (bytesRead < maxBytesToRead)
  217565. {
  217566. const int bytesThisTime = maxBytesToRead - bytesRead;
  217567. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217568. if (numRead <= 0 || intern->stopReadOperation)
  217569. {
  217570. bytesRead = -1;
  217571. break;
  217572. }
  217573. bytesRead += numRead;
  217574. p += bytesRead;
  217575. }
  217576. intern->blocked = false;
  217577. }
  217578. return bytesRead;
  217579. }
  217580. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217581. {
  217582. int bytesWritten = -1;
  217583. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217584. if (intern != 0)
  217585. {
  217586. if (intern->pipeOut == -1)
  217587. {
  217588. if (intern->createdPipe)
  217589. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217590. else
  217591. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217592. if (intern->pipeOut == -1)
  217593. {
  217594. return -1;
  217595. }
  217596. }
  217597. const char* p = static_cast<const char*> (sourceBuffer);
  217598. bytesWritten = 0;
  217599. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217600. while (bytesWritten < numBytesToWrite
  217601. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217602. {
  217603. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217604. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217605. if (numWritten <= 0)
  217606. {
  217607. bytesWritten = -1;
  217608. break;
  217609. }
  217610. bytesWritten += numWritten;
  217611. p += bytesWritten;
  217612. }
  217613. }
  217614. return bytesWritten;
  217615. }
  217616. #endif
  217617. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217618. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217619. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217620. // compiled on its own).
  217621. #if JUCE_INCLUDED_FILE
  217622. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217623. {
  217624. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217625. if (s != -1)
  217626. {
  217627. char buf [1024];
  217628. struct ifconf ifc;
  217629. ifc.ifc_len = sizeof (buf);
  217630. ifc.ifc_buf = buf;
  217631. ioctl (s, SIOCGIFCONF, &ifc);
  217632. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217633. {
  217634. struct ifreq ifr;
  217635. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217636. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217637. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217638. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217639. {
  217640. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217641. }
  217642. }
  217643. close (s);
  217644. }
  217645. }
  217646. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217647. const String& emailSubject,
  217648. const String& bodyText,
  217649. const StringArray& filesToAttach)
  217650. {
  217651. jassertfalse; // xxx todo
  217652. return false;
  217653. }
  217654. class WebInputStream : public InputStream
  217655. {
  217656. public:
  217657. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217658. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217659. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217660. : socketHandle (-1), levelsOfRedirection (0),
  217661. address (address_), headers (headers_), postData (postData_), position (0),
  217662. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217663. {
  217664. createConnection (progressCallback, progressCallbackContext);
  217665. if (responseHeaders != 0 && ! isError())
  217666. {
  217667. for (int i = 0; i < headerLines.size(); ++i)
  217668. {
  217669. const String& headersEntry = headerLines[i];
  217670. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217671. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217672. const String previousValue ((*responseHeaders) [key]);
  217673. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217674. }
  217675. }
  217676. }
  217677. ~WebInputStream()
  217678. {
  217679. closeSocket();
  217680. }
  217681. bool isError() const { return socketHandle < 0; }
  217682. bool isExhausted() { return finished; }
  217683. int64 getPosition() { return position; }
  217684. int64 getTotalLength()
  217685. {
  217686. jassertfalse; //xxx to do
  217687. return -1;
  217688. }
  217689. int read (void* buffer, int bytesToRead)
  217690. {
  217691. if (finished || isError())
  217692. return 0;
  217693. fd_set readbits;
  217694. FD_ZERO (&readbits);
  217695. FD_SET (socketHandle, &readbits);
  217696. struct timeval tv;
  217697. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217698. tv.tv_usec = 0;
  217699. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217700. return 0; // (timeout)
  217701. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217702. if (bytesRead == 0)
  217703. finished = true;
  217704. position += bytesRead;
  217705. return bytesRead;
  217706. }
  217707. bool setPosition (int64 wantedPos)
  217708. {
  217709. if (isError())
  217710. return false;
  217711. if (wantedPos != position)
  217712. {
  217713. finished = false;
  217714. if (wantedPos < position)
  217715. {
  217716. closeSocket();
  217717. position = 0;
  217718. createConnection (0, 0);
  217719. }
  217720. skipNextBytes (wantedPos - position);
  217721. }
  217722. return true;
  217723. }
  217724. private:
  217725. int socketHandle, levelsOfRedirection;
  217726. StringArray headerLines;
  217727. String address, headers;
  217728. MemoryBlock postData;
  217729. int64 position;
  217730. bool finished;
  217731. const bool isPost;
  217732. const int timeOutMs;
  217733. void closeSocket()
  217734. {
  217735. if (socketHandle >= 0)
  217736. close (socketHandle);
  217737. socketHandle = -1;
  217738. levelsOfRedirection = 0;
  217739. }
  217740. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217741. {
  217742. closeSocket();
  217743. uint32 timeOutTime = Time::getMillisecondCounter();
  217744. if (timeOutMs == 0)
  217745. timeOutTime += 60000;
  217746. else if (timeOutMs < 0)
  217747. timeOutTime = 0xffffffff;
  217748. else
  217749. timeOutTime += timeOutMs;
  217750. String hostName, hostPath;
  217751. int hostPort;
  217752. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217753. return;
  217754. const struct hostent* host = 0;
  217755. int port = 0;
  217756. String proxyName, proxyPath;
  217757. int proxyPort = 0;
  217758. String proxyURL (getenv ("http_proxy"));
  217759. if (proxyURL.startsWithIgnoreCase ("http://"))
  217760. {
  217761. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217762. return;
  217763. host = gethostbyname (proxyName.toUTF8());
  217764. port = proxyPort;
  217765. }
  217766. else
  217767. {
  217768. host = gethostbyname (hostName.toUTF8());
  217769. port = hostPort;
  217770. }
  217771. if (host == 0)
  217772. return;
  217773. {
  217774. struct sockaddr_in socketAddress;
  217775. zerostruct (socketAddress);
  217776. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217777. socketAddress.sin_family = host->h_addrtype;
  217778. socketAddress.sin_port = htons (port);
  217779. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217780. if (socketHandle == -1)
  217781. return;
  217782. int receiveBufferSize = 16384;
  217783. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217784. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217785. #if JUCE_MAC
  217786. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217787. #endif
  217788. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217789. {
  217790. closeSocket();
  217791. return;
  217792. }
  217793. }
  217794. {
  217795. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217796. hostPath, address, headers, postData, isPost));
  217797. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217798. {
  217799. closeSocket();
  217800. return;
  217801. }
  217802. }
  217803. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217804. if (responseHeader.isNotEmpty())
  217805. {
  217806. headerLines.clear();
  217807. headerLines.addLines (responseHeader);
  217808. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217809. .substring (0, 3).getIntValue();
  217810. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217811. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217812. String location (findHeaderItem (headerLines, "Location:"));
  217813. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217814. {
  217815. if (! location.startsWithIgnoreCase ("http://"))
  217816. location = "http://" + location;
  217817. if (++levelsOfRedirection <= 3)
  217818. {
  217819. address = location;
  217820. createConnection (progressCallback, progressCallbackContext);
  217821. return;
  217822. }
  217823. }
  217824. else
  217825. {
  217826. levelsOfRedirection = 0;
  217827. return;
  217828. }
  217829. }
  217830. closeSocket();
  217831. }
  217832. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217833. {
  217834. int bytesRead = 0, numConsecutiveLFs = 0;
  217835. MemoryBlock buffer (1024, true);
  217836. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217837. && Time::getMillisecondCounter() <= timeOutTime)
  217838. {
  217839. fd_set readbits;
  217840. FD_ZERO (&readbits);
  217841. FD_SET (socketHandle, &readbits);
  217842. struct timeval tv;
  217843. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217844. tv.tv_usec = 0;
  217845. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217846. return String::empty; // (timeout)
  217847. buffer.ensureSize (bytesRead + 8, true);
  217848. char* const dest = (char*) buffer.getData() + bytesRead;
  217849. if (recv (socketHandle, dest, 1, 0) == -1)
  217850. return String::empty;
  217851. const char lastByte = *dest;
  217852. ++bytesRead;
  217853. if (lastByte == '\n')
  217854. ++numConsecutiveLFs;
  217855. else if (lastByte != '\r')
  217856. numConsecutiveLFs = 0;
  217857. }
  217858. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217859. if (header.startsWithIgnoreCase ("HTTP/"))
  217860. return header.trimEnd();
  217861. return String::empty;
  217862. }
  217863. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217864. const String& proxyName, const int proxyPort,
  217865. const String& hostPath, const String& originalURL,
  217866. const String& headers, const MemoryBlock& postData,
  217867. const bool isPost)
  217868. {
  217869. String header (isPost ? "POST " : "GET ");
  217870. if (proxyName.isEmpty())
  217871. {
  217872. header << hostPath << " HTTP/1.0\r\nHost: "
  217873. << hostName << ':' << hostPort;
  217874. }
  217875. else
  217876. {
  217877. header << originalURL << " HTTP/1.0\r\nHost: "
  217878. << proxyName << ':' << proxyPort;
  217879. }
  217880. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217881. << "\r\nConnection: Close\r\nContent-Length: "
  217882. << postData.getSize() << "\r\n"
  217883. << headers << "\r\n";
  217884. MemoryBlock mb;
  217885. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217886. mb.append (postData.getData(), postData.getSize());
  217887. return mb;
  217888. }
  217889. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217890. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217891. {
  217892. size_t totalHeaderSent = 0;
  217893. while (totalHeaderSent < requestHeader.getSize())
  217894. {
  217895. if (Time::getMillisecondCounter() > timeOutTime)
  217896. return false;
  217897. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217898. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217899. return false;
  217900. totalHeaderSent += numToSend;
  217901. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217902. return false;
  217903. }
  217904. return true;
  217905. }
  217906. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217907. {
  217908. if (! url.startsWithIgnoreCase ("http://"))
  217909. return false;
  217910. const int nextSlash = url.indexOfChar (7, '/');
  217911. int nextColon = url.indexOfChar (7, ':');
  217912. if (nextColon > nextSlash && nextSlash > 0)
  217913. nextColon = -1;
  217914. if (nextColon >= 0)
  217915. {
  217916. host = url.substring (7, nextColon);
  217917. if (nextSlash >= 0)
  217918. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217919. else
  217920. port = url.substring (nextColon + 1).getIntValue();
  217921. }
  217922. else
  217923. {
  217924. port = 80;
  217925. if (nextSlash >= 0)
  217926. host = url.substring (7, nextSlash);
  217927. else
  217928. host = url.substring (7);
  217929. }
  217930. if (nextSlash >= 0)
  217931. path = url.substring (nextSlash);
  217932. else
  217933. path = "/";
  217934. return true;
  217935. }
  217936. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217937. {
  217938. for (int i = 0; i < lines.size(); ++i)
  217939. if (lines[i].startsWithIgnoreCase (itemName))
  217940. return lines[i].substring (itemName.length()).trim();
  217941. return String::empty;
  217942. }
  217943. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217944. };
  217945. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217946. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217947. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217948. {
  217949. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217950. progressCallback, progressCallbackContext,
  217951. headers, timeOutMs, responseHeaders));
  217952. return wi->isError() ? 0 : wi.release();
  217953. }
  217954. #endif
  217955. /*** End of inlined file: juce_linux_Network.cpp ***/
  217956. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217957. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217958. // compiled on its own).
  217959. #if JUCE_INCLUDED_FILE
  217960. void Logger::outputDebugString (const String& text)
  217961. {
  217962. std::cerr << text << std::endl;
  217963. }
  217964. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217965. {
  217966. return Linux;
  217967. }
  217968. const String SystemStats::getOperatingSystemName()
  217969. {
  217970. return "Linux";
  217971. }
  217972. bool SystemStats::isOperatingSystem64Bit()
  217973. {
  217974. #if JUCE_64BIT
  217975. return true;
  217976. #else
  217977. //xxx not sure how to find this out?..
  217978. return false;
  217979. #endif
  217980. }
  217981. namespace LinuxStatsHelpers
  217982. {
  217983. const String getCpuInfo (const char* const key)
  217984. {
  217985. StringArray lines;
  217986. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217987. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217988. if (lines[i].startsWithIgnoreCase (key))
  217989. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217990. return String::empty;
  217991. }
  217992. }
  217993. const String SystemStats::getCpuVendor()
  217994. {
  217995. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217996. }
  217997. int SystemStats::getCpuSpeedInMegaherz()
  217998. {
  217999. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218000. }
  218001. int SystemStats::getMemorySizeInMegabytes()
  218002. {
  218003. struct sysinfo sysi;
  218004. if (sysinfo (&sysi) == 0)
  218005. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218006. return 0;
  218007. }
  218008. int SystemStats::getPageSize()
  218009. {
  218010. return sysconf (_SC_PAGESIZE);
  218011. }
  218012. const String SystemStats::getLogonName()
  218013. {
  218014. const char* user = getenv ("USER");
  218015. if (user == 0)
  218016. {
  218017. struct passwd* const pw = getpwuid (getuid());
  218018. if (pw != 0)
  218019. user = pw->pw_name;
  218020. }
  218021. return String::fromUTF8 (user);
  218022. }
  218023. const String SystemStats::getFullUserName()
  218024. {
  218025. return getLogonName();
  218026. }
  218027. void SystemStats::initialiseStats()
  218028. {
  218029. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218030. cpuFlags.hasMMX = flags.contains ("mmx");
  218031. cpuFlags.hasSSE = flags.contains ("sse");
  218032. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218033. cpuFlags.has3DNow = flags.contains ("3dnow");
  218034. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218035. }
  218036. void PlatformUtilities::fpuReset()
  218037. {
  218038. }
  218039. uint32 juce_millisecondsSinceStartup() throw()
  218040. {
  218041. timespec t;
  218042. clock_gettime (CLOCK_MONOTONIC, &t);
  218043. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  218044. }
  218045. int64 Time::getHighResolutionTicks() throw()
  218046. {
  218047. timespec t;
  218048. clock_gettime (CLOCK_MONOTONIC, &t);
  218049. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  218050. }
  218051. int64 Time::getHighResolutionTicksPerSecond() throw()
  218052. {
  218053. return 1000000; // (microseconds)
  218054. }
  218055. double Time::getMillisecondCounterHiRes() throw()
  218056. {
  218057. return getHighResolutionTicks() * 0.001;
  218058. }
  218059. bool Time::setSystemTimeToThisTime() const
  218060. {
  218061. timeval t;
  218062. t.tv_sec = millisSinceEpoch / 1000;
  218063. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  218064. return settimeofday (&t, 0) == 0;
  218065. }
  218066. #endif
  218067. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218068. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218069. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218070. // compiled on its own).
  218071. #if JUCE_INCLUDED_FILE
  218072. /*
  218073. Note that a lot of methods that you'd expect to find in this file actually
  218074. live in juce_posix_SharedCode.h!
  218075. */
  218076. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218077. void Process::setPriority (ProcessPriority prior)
  218078. {
  218079. struct sched_param param;
  218080. int policy, maxp, minp;
  218081. const int p = (int) prior;
  218082. if (p <= 1)
  218083. policy = SCHED_OTHER;
  218084. else
  218085. policy = SCHED_RR;
  218086. minp = sched_get_priority_min (policy);
  218087. maxp = sched_get_priority_max (policy);
  218088. if (p < 2)
  218089. param.sched_priority = 0;
  218090. else if (p == 2 )
  218091. // Set to middle of lower realtime priority range
  218092. param.sched_priority = minp + (maxp - minp) / 4;
  218093. else
  218094. // Set to middle of higher realtime priority range
  218095. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218096. pthread_setschedparam (pthread_self(), policy, &param);
  218097. }
  218098. void Process::terminate()
  218099. {
  218100. exit (0);
  218101. }
  218102. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218103. {
  218104. static char testResult = 0;
  218105. if (testResult == 0)
  218106. {
  218107. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218108. if (testResult >= 0)
  218109. {
  218110. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218111. testResult = 1;
  218112. }
  218113. }
  218114. return testResult < 0;
  218115. }
  218116. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218117. {
  218118. return juce_isRunningUnderDebugger();
  218119. }
  218120. void Process::raisePrivilege()
  218121. {
  218122. // If running suid root, change effective user
  218123. // to root
  218124. if (geteuid() != 0 && getuid() == 0)
  218125. {
  218126. setreuid (geteuid(), getuid());
  218127. setregid (getegid(), getgid());
  218128. }
  218129. }
  218130. void Process::lowerPrivilege()
  218131. {
  218132. // If runing suid root, change effective user
  218133. // back to real user
  218134. if (geteuid() == 0 && getuid() != 0)
  218135. {
  218136. setreuid (geteuid(), getuid());
  218137. setregid (getegid(), getgid());
  218138. }
  218139. }
  218140. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218141. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218142. {
  218143. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218144. }
  218145. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218146. {
  218147. dlclose(handle);
  218148. }
  218149. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218150. {
  218151. return dlsym (libraryHandle, procedureName.toCString());
  218152. }
  218153. #endif
  218154. #endif
  218155. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218156. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218157. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218158. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218159. // compiled on its own).
  218160. #if JUCE_INCLUDED_FILE
  218161. extern Display* display;
  218162. extern Window juce_messageWindowHandle;
  218163. namespace ClipboardHelpers
  218164. {
  218165. static String localClipboardContent;
  218166. static Atom atom_UTF8_STRING;
  218167. static Atom atom_CLIPBOARD;
  218168. static Atom atom_TARGETS;
  218169. static void initSelectionAtoms()
  218170. {
  218171. static bool isInitialised = false;
  218172. if (! isInitialised)
  218173. {
  218174. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218175. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218176. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218177. }
  218178. }
  218179. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218180. // works only for strings shorter than 1000000 bytes
  218181. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218182. {
  218183. String returnData;
  218184. char* clipData;
  218185. Atom actualType;
  218186. int actualFormat;
  218187. unsigned long numItems, bytesLeft;
  218188. if (XGetWindowProperty (display, window, prop,
  218189. 0L /* offset */, 1000000 /* length (max) */, False,
  218190. AnyPropertyType /* format */,
  218191. &actualType, &actualFormat, &numItems, &bytesLeft,
  218192. (unsigned char**) &clipData) == Success)
  218193. {
  218194. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218195. returnData = String::fromUTF8 (clipData, numItems);
  218196. else if (actualType == XA_STRING && actualFormat == 8)
  218197. returnData = String (clipData, numItems);
  218198. if (clipData != 0)
  218199. XFree (clipData);
  218200. jassert (bytesLeft == 0 || numItems == 1000000);
  218201. }
  218202. XDeleteProperty (display, window, prop);
  218203. return returnData;
  218204. }
  218205. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218206. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218207. {
  218208. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218209. // The selection owner will be asked to set the JUCE_SEL property on the
  218210. // juce_messageWindowHandle with the selection content
  218211. XConvertSelection (display, selection, requestedFormat, property_name,
  218212. juce_messageWindowHandle, CurrentTime);
  218213. int count = 50; // will wait at most for 200 ms
  218214. while (--count >= 0)
  218215. {
  218216. XEvent event;
  218217. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218218. {
  218219. if (event.xselection.property == property_name)
  218220. {
  218221. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218222. selectionContent = readWindowProperty (event.xselection.requestor,
  218223. event.xselection.property,
  218224. requestedFormat);
  218225. return true;
  218226. }
  218227. else
  218228. {
  218229. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218230. }
  218231. }
  218232. // not very elegant.. we could do a select() or something like that...
  218233. // however clipboard content requesting is inherently slow on x11, it
  218234. // often takes 50ms or more so...
  218235. Thread::sleep (4);
  218236. }
  218237. return false;
  218238. }
  218239. }
  218240. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218241. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218242. {
  218243. ClipboardHelpers::initSelectionAtoms();
  218244. // the selection content is sent to the target window as a window property
  218245. XSelectionEvent reply;
  218246. reply.type = SelectionNotify;
  218247. reply.display = evt.display;
  218248. reply.requestor = evt.requestor;
  218249. reply.selection = evt.selection;
  218250. reply.target = evt.target;
  218251. reply.property = None; // == "fail"
  218252. reply.time = evt.time;
  218253. HeapBlock <char> data;
  218254. int propertyFormat = 0, numDataItems = 0;
  218255. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218256. {
  218257. if (evt.target == XA_STRING)
  218258. {
  218259. // format data according to system locale
  218260. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218261. data.calloc (numDataItems + 1);
  218262. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218263. propertyFormat = 8; // bits/item
  218264. }
  218265. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218266. {
  218267. // translate to utf8
  218268. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218269. data.calloc (numDataItems + 1);
  218270. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218271. propertyFormat = 8; // bits/item
  218272. }
  218273. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218274. {
  218275. // another application wants to know what we are able to send
  218276. numDataItems = 2;
  218277. propertyFormat = 32; // atoms are 32-bit
  218278. data.calloc (numDataItems * 4);
  218279. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218280. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218281. atoms[1] = XA_STRING;
  218282. }
  218283. }
  218284. else
  218285. {
  218286. DBG ("requested unsupported clipboard");
  218287. }
  218288. if (data != 0)
  218289. {
  218290. const int maxReasonableSelectionSize = 1000000;
  218291. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218292. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218293. {
  218294. XChangeProperty (evt.display, evt.requestor,
  218295. evt.property, evt.target,
  218296. propertyFormat /* 8 or 32 */, PropModeReplace,
  218297. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218298. reply.property = evt.property; // " == success"
  218299. }
  218300. }
  218301. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218302. }
  218303. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218304. {
  218305. ClipboardHelpers::initSelectionAtoms();
  218306. ClipboardHelpers::localClipboardContent = clipText;
  218307. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218308. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218309. }
  218310. const String SystemClipboard::getTextFromClipboard()
  218311. {
  218312. ClipboardHelpers::initSelectionAtoms();
  218313. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218314. level" clipboard that is supposed to be filled by ctrl-C
  218315. etc). When a clipboard manager is running, the content of this
  218316. selection is preserved even when the original selection owner
  218317. exits.
  218318. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218319. filled by good old x11 apps such as xterm)
  218320. */
  218321. String content;
  218322. Atom selection = XA_PRIMARY;
  218323. Window selectionOwner = None;
  218324. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218325. {
  218326. selection = ClipboardHelpers::atom_CLIPBOARD;
  218327. selectionOwner = XGetSelectionOwner (display, selection);
  218328. }
  218329. if (selectionOwner != None)
  218330. {
  218331. if (selectionOwner == juce_messageWindowHandle)
  218332. {
  218333. content = ClipboardHelpers::localClipboardContent;
  218334. }
  218335. else
  218336. {
  218337. // first try: we want an utf8 string
  218338. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218339. if (! ok)
  218340. {
  218341. // second chance, ask for a good old locale-dependent string ..
  218342. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218343. }
  218344. }
  218345. }
  218346. return content;
  218347. }
  218348. #endif
  218349. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218350. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218351. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218352. // compiled on its own).
  218353. #if JUCE_INCLUDED_FILE
  218354. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218355. #define JUCE_DEBUG_XERRORS 1
  218356. #endif
  218357. Display* display = 0;
  218358. Window juce_messageWindowHandle = None;
  218359. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218360. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218361. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218362. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218363. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218364. class InternalMessageQueue
  218365. {
  218366. public:
  218367. InternalMessageQueue()
  218368. : bytesInSocket (0),
  218369. totalEventCount (0)
  218370. {
  218371. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218372. (void) ret; jassert (ret == 0);
  218373. //setNonBlocking (fd[0]);
  218374. //setNonBlocking (fd[1]);
  218375. }
  218376. ~InternalMessageQueue()
  218377. {
  218378. close (fd[0]);
  218379. close (fd[1]);
  218380. clearSingletonInstance();
  218381. }
  218382. void postMessage (Message* msg)
  218383. {
  218384. const int maxBytesInSocketQueue = 128;
  218385. ScopedLock sl (lock);
  218386. queue.add (msg);
  218387. if (bytesInSocket < maxBytesInSocketQueue)
  218388. {
  218389. ++bytesInSocket;
  218390. ScopedUnlock ul (lock);
  218391. const unsigned char x = 0xff;
  218392. size_t bytesWritten = write (fd[0], &x, 1);
  218393. (void) bytesWritten;
  218394. }
  218395. }
  218396. bool isEmpty() const
  218397. {
  218398. ScopedLock sl (lock);
  218399. return queue.size() == 0;
  218400. }
  218401. bool dispatchNextEvent()
  218402. {
  218403. // This alternates between giving priority to XEvents or internal messages,
  218404. // to keep everything running smoothly..
  218405. if ((++totalEventCount & 1) != 0)
  218406. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218407. else
  218408. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218409. }
  218410. // Wait for an event (either XEvent, or an internal Message)
  218411. bool sleepUntilEvent (const int timeoutMs)
  218412. {
  218413. if (! isEmpty())
  218414. return true;
  218415. if (display != 0)
  218416. {
  218417. ScopedXLock xlock;
  218418. if (XPending (display))
  218419. return true;
  218420. }
  218421. struct timeval tv;
  218422. tv.tv_sec = 0;
  218423. tv.tv_usec = timeoutMs * 1000;
  218424. int fd0 = getWaitHandle();
  218425. int fdmax = fd0;
  218426. fd_set readset;
  218427. FD_ZERO (&readset);
  218428. FD_SET (fd0, &readset);
  218429. if (display != 0)
  218430. {
  218431. ScopedXLock xlock;
  218432. int fd1 = XConnectionNumber (display);
  218433. FD_SET (fd1, &readset);
  218434. fdmax = jmax (fd0, fd1);
  218435. }
  218436. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218437. return (ret > 0); // ret <= 0 if error or timeout
  218438. }
  218439. struct MessageThreadFuncCall
  218440. {
  218441. enum { uniqueID = 0x73774623 };
  218442. MessageCallbackFunction* func;
  218443. void* parameter;
  218444. void* result;
  218445. CriticalSection lock;
  218446. WaitableEvent event;
  218447. };
  218448. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218449. private:
  218450. CriticalSection lock;
  218451. ReferenceCountedArray <Message> queue;
  218452. int fd[2];
  218453. int bytesInSocket;
  218454. int totalEventCount;
  218455. int getWaitHandle() const throw() { return fd[1]; }
  218456. static bool setNonBlocking (int handle)
  218457. {
  218458. int socketFlags = fcntl (handle, F_GETFL, 0);
  218459. if (socketFlags == -1)
  218460. return false;
  218461. socketFlags |= O_NONBLOCK;
  218462. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218463. }
  218464. static bool dispatchNextXEvent()
  218465. {
  218466. if (display == 0)
  218467. return false;
  218468. XEvent evt;
  218469. {
  218470. ScopedXLock xlock;
  218471. if (! XPending (display))
  218472. return false;
  218473. XNextEvent (display, &evt);
  218474. }
  218475. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218476. juce_handleSelectionRequest (evt.xselectionrequest);
  218477. else if (evt.xany.window != juce_messageWindowHandle)
  218478. juce_windowMessageReceive (&evt);
  218479. return true;
  218480. }
  218481. const Message::Ptr popNextMessage()
  218482. {
  218483. const ScopedLock sl (lock);
  218484. if (bytesInSocket > 0)
  218485. {
  218486. --bytesInSocket;
  218487. const ScopedUnlock ul (lock);
  218488. unsigned char x;
  218489. size_t numBytes = read (fd[1], &x, 1);
  218490. (void) numBytes;
  218491. }
  218492. return queue.removeAndReturn (0);
  218493. }
  218494. bool dispatchNextInternalMessage()
  218495. {
  218496. const Message::Ptr msg (popNextMessage());
  218497. if (msg == 0)
  218498. return false;
  218499. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218500. {
  218501. // Handle callback message
  218502. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218503. call->result = (*(call->func)) (call->parameter);
  218504. call->event.signal();
  218505. }
  218506. else
  218507. {
  218508. // Handle "normal" messages
  218509. MessageManager::getInstance()->deliverMessage (msg);
  218510. }
  218511. return true;
  218512. }
  218513. };
  218514. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218515. namespace LinuxErrorHandling
  218516. {
  218517. static bool errorOccurred = false;
  218518. static bool keyboardBreakOccurred = false;
  218519. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218520. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218521. // Usually happens when client-server connection is broken
  218522. static int ioErrorHandler (Display* display)
  218523. {
  218524. DBG ("ERROR: connection to X server broken.. terminating.");
  218525. if (JUCEApplication::isStandaloneApp())
  218526. MessageManager::getInstance()->stopDispatchLoop();
  218527. errorOccurred = true;
  218528. return 0;
  218529. }
  218530. // A protocol error has occurred
  218531. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218532. {
  218533. #if JUCE_DEBUG_XERRORS
  218534. char errorStr[64] = { 0 };
  218535. char requestStr[64] = { 0 };
  218536. XGetErrorText (display, event->error_code, errorStr, 64);
  218537. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218538. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218539. #endif
  218540. return 0;
  218541. }
  218542. static void installXErrorHandlers()
  218543. {
  218544. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218545. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218546. }
  218547. static void removeXErrorHandlers()
  218548. {
  218549. if (JUCEApplication::isStandaloneApp())
  218550. {
  218551. XSetIOErrorHandler (oldIOErrorHandler);
  218552. oldIOErrorHandler = 0;
  218553. XSetErrorHandler (oldErrorHandler);
  218554. oldErrorHandler = 0;
  218555. }
  218556. }
  218557. static void keyboardBreakSignalHandler (int sig)
  218558. {
  218559. if (sig == SIGINT)
  218560. keyboardBreakOccurred = true;
  218561. }
  218562. static void installKeyboardBreakHandler()
  218563. {
  218564. struct sigaction saction;
  218565. sigset_t maskSet;
  218566. sigemptyset (&maskSet);
  218567. saction.sa_handler = keyboardBreakSignalHandler;
  218568. saction.sa_mask = maskSet;
  218569. saction.sa_flags = 0;
  218570. sigaction (SIGINT, &saction, 0);
  218571. }
  218572. }
  218573. void MessageManager::doPlatformSpecificInitialisation()
  218574. {
  218575. if (JUCEApplication::isStandaloneApp())
  218576. {
  218577. // Initialise xlib for multiple thread support
  218578. static bool initThreadCalled = false;
  218579. if (! initThreadCalled)
  218580. {
  218581. if (! XInitThreads())
  218582. {
  218583. // This is fatal! Print error and closedown
  218584. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218585. Process::terminate();
  218586. return;
  218587. }
  218588. initThreadCalled = true;
  218589. }
  218590. LinuxErrorHandling::installXErrorHandlers();
  218591. LinuxErrorHandling::installKeyboardBreakHandler();
  218592. }
  218593. // Create the internal message queue
  218594. InternalMessageQueue::getInstance();
  218595. // Try to connect to a display
  218596. String displayName (getenv ("DISPLAY"));
  218597. if (displayName.isEmpty())
  218598. displayName = ":0.0";
  218599. display = XOpenDisplay (displayName.toCString());
  218600. if (display != 0) // This is not fatal! we can run headless.
  218601. {
  218602. // Create a context to store user data associated with Windows we create in WindowDriver
  218603. windowHandleXContext = XUniqueContext();
  218604. // We're only interested in client messages for this window, which are always sent
  218605. XSetWindowAttributes swa;
  218606. swa.event_mask = NoEventMask;
  218607. // Create our message window (this will never be mapped)
  218608. const int screen = DefaultScreen (display);
  218609. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218610. 0, 0, 1, 1, 0, 0, InputOnly,
  218611. DefaultVisual (display, screen),
  218612. CWEventMask, &swa);
  218613. }
  218614. }
  218615. void MessageManager::doPlatformSpecificShutdown()
  218616. {
  218617. InternalMessageQueue::deleteInstance();
  218618. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218619. {
  218620. XDestroyWindow (display, juce_messageWindowHandle);
  218621. XCloseDisplay (display);
  218622. juce_messageWindowHandle = 0;
  218623. display = 0;
  218624. LinuxErrorHandling::removeXErrorHandlers();
  218625. }
  218626. }
  218627. bool juce_postMessageToSystemQueue (Message* message)
  218628. {
  218629. if (LinuxErrorHandling::errorOccurred)
  218630. return false;
  218631. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218632. return true;
  218633. }
  218634. void MessageManager::broadcastMessage (const String& value)
  218635. {
  218636. /* TODO */
  218637. }
  218638. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218639. {
  218640. if (LinuxErrorHandling::errorOccurred)
  218641. return 0;
  218642. if (isThisTheMessageThread())
  218643. return func (parameter);
  218644. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  218645. messageCallContext.func = func;
  218646. messageCallContext.parameter = parameter;
  218647. InternalMessageQueue::getInstanceWithoutCreating()
  218648. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  218649. 0, 0, &messageCallContext));
  218650. // Wait for it to complete before continuing
  218651. messageCallContext.event.wait();
  218652. return messageCallContext.result;
  218653. }
  218654. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218655. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218656. {
  218657. while (! LinuxErrorHandling::errorOccurred)
  218658. {
  218659. if (LinuxErrorHandling::keyboardBreakOccurred)
  218660. {
  218661. LinuxErrorHandling::errorOccurred = true;
  218662. if (JUCEApplication::isStandaloneApp())
  218663. Process::terminate();
  218664. break;
  218665. }
  218666. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218667. return true;
  218668. if (returnIfNoPendingMessages)
  218669. break;
  218670. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218671. }
  218672. return false;
  218673. }
  218674. #endif
  218675. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218676. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218677. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218678. // compiled on its own).
  218679. #if JUCE_INCLUDED_FILE
  218680. class FreeTypeFontFace
  218681. {
  218682. public:
  218683. enum FontStyle
  218684. {
  218685. Plain = 0,
  218686. Bold = 1,
  218687. Italic = 2
  218688. };
  218689. FreeTypeFontFace (const String& familyName)
  218690. : hasSerif (false),
  218691. monospaced (false)
  218692. {
  218693. family = familyName;
  218694. }
  218695. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218696. {
  218697. if (names [(int) style].fileName.isEmpty())
  218698. {
  218699. names [(int) style].fileName = name;
  218700. names [(int) style].faceIndex = faceIndex;
  218701. }
  218702. }
  218703. const String& getFamilyName() const throw() { return family; }
  218704. const String& getFileName (const int style, int& faceIndex) const throw()
  218705. {
  218706. faceIndex = names[style].faceIndex;
  218707. return names[style].fileName;
  218708. }
  218709. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218710. bool getMonospaced() const throw() { return monospaced; }
  218711. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218712. bool getSerif() const throw() { return hasSerif; }
  218713. private:
  218714. String family;
  218715. struct FontNameIndex
  218716. {
  218717. String fileName;
  218718. int faceIndex;
  218719. };
  218720. FontNameIndex names[4];
  218721. bool hasSerif, monospaced;
  218722. };
  218723. class FreeTypeInterface : public DeletedAtShutdown
  218724. {
  218725. public:
  218726. FreeTypeInterface()
  218727. : ftLib (0),
  218728. lastFace (0),
  218729. lastBold (false),
  218730. lastItalic (false)
  218731. {
  218732. if (FT_Init_FreeType (&ftLib) != 0)
  218733. {
  218734. ftLib = 0;
  218735. DBG ("Failed to initialize FreeType");
  218736. }
  218737. StringArray fontDirs;
  218738. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218739. fontDirs.removeEmptyStrings (true);
  218740. if (fontDirs.size() == 0)
  218741. {
  218742. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218743. if (fontsInfo != 0)
  218744. {
  218745. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218746. {
  218747. fontDirs.add (e->getAllSubText().trim());
  218748. }
  218749. }
  218750. }
  218751. if (fontDirs.size() == 0)
  218752. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218753. for (int i = 0; i < fontDirs.size(); ++i)
  218754. enumerateFaces (fontDirs[i]);
  218755. }
  218756. ~FreeTypeInterface()
  218757. {
  218758. if (lastFace != 0)
  218759. FT_Done_Face (lastFace);
  218760. if (ftLib != 0)
  218761. FT_Done_FreeType (ftLib);
  218762. clearSingletonInstance();
  218763. }
  218764. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218765. {
  218766. for (int i = 0; i < faces.size(); i++)
  218767. if (faces[i]->getFamilyName() == familyName)
  218768. return faces[i];
  218769. if (! create)
  218770. return 0;
  218771. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218772. faces.add (newFace);
  218773. return newFace;
  218774. }
  218775. // Enumerate all font faces available in a given directory
  218776. void enumerateFaces (const String& path)
  218777. {
  218778. File dirPath (path);
  218779. if (path.isEmpty() || ! dirPath.isDirectory())
  218780. return;
  218781. DirectoryIterator di (dirPath, true);
  218782. while (di.next())
  218783. {
  218784. File possible (di.getFile());
  218785. if (possible.hasFileExtension ("ttf")
  218786. || possible.hasFileExtension ("pfb")
  218787. || possible.hasFileExtension ("pcf"))
  218788. {
  218789. FT_Face face;
  218790. int faceIndex = 0;
  218791. int numFaces = 0;
  218792. do
  218793. {
  218794. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218795. faceIndex, &face) == 0)
  218796. {
  218797. if (faceIndex == 0)
  218798. numFaces = face->num_faces;
  218799. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218800. {
  218801. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218802. int style = (int) FreeTypeFontFace::Plain;
  218803. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218804. style |= (int) FreeTypeFontFace::Bold;
  218805. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218806. style |= (int) FreeTypeFontFace::Italic;
  218807. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218808. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218809. // Surely there must be a better way to do this?
  218810. const String name (face->family_name);
  218811. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218812. || name.containsIgnoreCase ("Verdana")
  218813. || name.containsIgnoreCase ("Arial")));
  218814. }
  218815. FT_Done_Face (face);
  218816. }
  218817. ++faceIndex;
  218818. }
  218819. while (faceIndex < numFaces);
  218820. }
  218821. }
  218822. }
  218823. // Create a FreeType face object for a given font
  218824. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218825. {
  218826. FT_Face face = 0;
  218827. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218828. {
  218829. face = lastFace;
  218830. }
  218831. else
  218832. {
  218833. if (lastFace != 0)
  218834. {
  218835. FT_Done_Face (lastFace);
  218836. lastFace = 0;
  218837. }
  218838. lastFontName = fontName;
  218839. lastBold = bold;
  218840. lastItalic = italic;
  218841. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218842. if (ftFace != 0)
  218843. {
  218844. int style = (int) FreeTypeFontFace::Plain;
  218845. if (bold)
  218846. style |= (int) FreeTypeFontFace::Bold;
  218847. if (italic)
  218848. style |= (int) FreeTypeFontFace::Italic;
  218849. int faceIndex;
  218850. String fileName (ftFace->getFileName (style, faceIndex));
  218851. if (fileName.isEmpty())
  218852. {
  218853. style ^= (int) FreeTypeFontFace::Bold;
  218854. fileName = ftFace->getFileName (style, faceIndex);
  218855. if (fileName.isEmpty())
  218856. {
  218857. style ^= (int) FreeTypeFontFace::Bold;
  218858. style ^= (int) FreeTypeFontFace::Italic;
  218859. fileName = ftFace->getFileName (style, faceIndex);
  218860. if (! fileName.length())
  218861. {
  218862. style ^= (int) FreeTypeFontFace::Bold;
  218863. fileName = ftFace->getFileName (style, faceIndex);
  218864. }
  218865. }
  218866. }
  218867. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218868. {
  218869. face = lastFace;
  218870. // If there isn't a unicode charmap then select the first one.
  218871. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218872. FT_Set_Charmap (face, face->charmaps[0]);
  218873. }
  218874. }
  218875. }
  218876. return face;
  218877. }
  218878. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218879. {
  218880. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218881. const float height = (float) (face->ascender - face->descender);
  218882. const float scaleX = 1.0f / height;
  218883. const float scaleY = -1.0f / height;
  218884. Path destShape;
  218885. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218886. || face->glyph->format != ft_glyph_format_outline)
  218887. {
  218888. return false;
  218889. }
  218890. const FT_Outline* const outline = &face->glyph->outline;
  218891. const short* const contours = outline->contours;
  218892. const char* const tags = outline->tags;
  218893. FT_Vector* const points = outline->points;
  218894. for (int c = 0; c < outline->n_contours; c++)
  218895. {
  218896. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218897. const int endPoint = contours[c];
  218898. for (int p = startPoint; p <= endPoint; p++)
  218899. {
  218900. const float x = scaleX * points[p].x;
  218901. const float y = scaleY * points[p].y;
  218902. if (p == startPoint)
  218903. {
  218904. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218905. {
  218906. float x2 = scaleX * points [endPoint].x;
  218907. float y2 = scaleY * points [endPoint].y;
  218908. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218909. {
  218910. x2 = (x + x2) * 0.5f;
  218911. y2 = (y + y2) * 0.5f;
  218912. }
  218913. destShape.startNewSubPath (x2, y2);
  218914. }
  218915. else
  218916. {
  218917. destShape.startNewSubPath (x, y);
  218918. }
  218919. }
  218920. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218921. {
  218922. if (p != startPoint)
  218923. destShape.lineTo (x, y);
  218924. }
  218925. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218926. {
  218927. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218928. float x2 = scaleX * points [nextIndex].x;
  218929. float y2 = scaleY * points [nextIndex].y;
  218930. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218931. {
  218932. x2 = (x + x2) * 0.5f;
  218933. y2 = (y + y2) * 0.5f;
  218934. }
  218935. else
  218936. {
  218937. ++p;
  218938. }
  218939. destShape.quadraticTo (x, y, x2, y2);
  218940. }
  218941. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218942. {
  218943. if (p >= endPoint)
  218944. return false;
  218945. const int next1 = p + 1;
  218946. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218947. const float x2 = scaleX * points [next1].x;
  218948. const float y2 = scaleY * points [next1].y;
  218949. const float x3 = scaleX * points [next2].x;
  218950. const float y3 = scaleY * points [next2].y;
  218951. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218952. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218953. return false;
  218954. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218955. p += 2;
  218956. }
  218957. }
  218958. destShape.closeSubPath();
  218959. }
  218960. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218961. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218962. addKerning (face, dest, character, glyphIndex);
  218963. return true;
  218964. }
  218965. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218966. {
  218967. const float height = (float) (face->ascender - face->descender);
  218968. uint32 rightGlyphIndex;
  218969. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218970. while (rightGlyphIndex != 0)
  218971. {
  218972. FT_Vector kerning;
  218973. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218974. {
  218975. if (kerning.x != 0)
  218976. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218977. }
  218978. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218979. }
  218980. }
  218981. // Add a glyph to a font
  218982. bool addGlyphToFont (const uint32 character, const String& fontName,
  218983. bool bold, bool italic, CustomTypeface& dest)
  218984. {
  218985. FT_Face face = createFT_Face (fontName, bold, italic);
  218986. return face != 0 && addGlyph (face, dest, character);
  218987. }
  218988. void getFamilyNames (StringArray& familyNames) const
  218989. {
  218990. for (int i = 0; i < faces.size(); i++)
  218991. familyNames.add (faces[i]->getFamilyName());
  218992. }
  218993. void getMonospacedNames (StringArray& monoSpaced) const
  218994. {
  218995. for (int i = 0; i < faces.size(); i++)
  218996. if (faces[i]->getMonospaced())
  218997. monoSpaced.add (faces[i]->getFamilyName());
  218998. }
  218999. void getSerifNames (StringArray& serif) const
  219000. {
  219001. for (int i = 0; i < faces.size(); i++)
  219002. if (faces[i]->getSerif())
  219003. serif.add (faces[i]->getFamilyName());
  219004. }
  219005. void getSansSerifNames (StringArray& sansSerif) const
  219006. {
  219007. for (int i = 0; i < faces.size(); i++)
  219008. if (! faces[i]->getSerif())
  219009. sansSerif.add (faces[i]->getFamilyName());
  219010. }
  219011. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219012. private:
  219013. FT_Library ftLib;
  219014. FT_Face lastFace;
  219015. String lastFontName;
  219016. bool lastBold, lastItalic;
  219017. OwnedArray<FreeTypeFontFace> faces;
  219018. };
  219019. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219020. class FreetypeTypeface : public CustomTypeface
  219021. {
  219022. public:
  219023. FreetypeTypeface (const Font& font)
  219024. {
  219025. FT_Face face = FreeTypeInterface::getInstance()
  219026. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219027. if (face == 0)
  219028. {
  219029. #if JUCE_DEBUG
  219030. String msg ("Failed to create typeface: ");
  219031. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219032. DBG (msg);
  219033. #endif
  219034. }
  219035. else
  219036. {
  219037. setCharacteristics (font.getTypefaceName(),
  219038. face->ascender / (float) (face->ascender - face->descender),
  219039. font.isBold(), font.isItalic(),
  219040. L' ');
  219041. }
  219042. }
  219043. bool loadGlyphIfPossible (juce_wchar character)
  219044. {
  219045. return FreeTypeInterface::getInstance()
  219046. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219047. }
  219048. };
  219049. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219050. {
  219051. return new FreetypeTypeface (font);
  219052. }
  219053. const StringArray Font::findAllTypefaceNames()
  219054. {
  219055. StringArray s;
  219056. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219057. s.sort (true);
  219058. return s;
  219059. }
  219060. namespace
  219061. {
  219062. const String pickBestFont (const StringArray& names,
  219063. const char* const choicesString)
  219064. {
  219065. StringArray choices;
  219066. choices.addTokens (String (choicesString), ",", String::empty);
  219067. choices.trim();
  219068. choices.removeEmptyStrings();
  219069. int i, j;
  219070. for (j = 0; j < choices.size(); ++j)
  219071. if (names.contains (choices[j], true))
  219072. return choices[j];
  219073. for (j = 0; j < choices.size(); ++j)
  219074. for (i = 0; i < names.size(); i++)
  219075. if (names[i].startsWithIgnoreCase (choices[j]))
  219076. return names[i];
  219077. for (j = 0; j < choices.size(); ++j)
  219078. for (i = 0; i < names.size(); i++)
  219079. if (names[i].containsIgnoreCase (choices[j]))
  219080. return names[i];
  219081. return names[0];
  219082. }
  219083. const String linux_getDefaultSansSerifFontName()
  219084. {
  219085. StringArray allFonts;
  219086. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219087. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219088. }
  219089. const String linux_getDefaultSerifFontName()
  219090. {
  219091. StringArray allFonts;
  219092. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219093. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219094. }
  219095. const String linux_getDefaultMonospacedFontName()
  219096. {
  219097. StringArray allFonts;
  219098. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219099. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219100. }
  219101. }
  219102. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  219103. {
  219104. defaultSans = linux_getDefaultSansSerifFontName();
  219105. defaultSerif = linux_getDefaultSerifFontName();
  219106. defaultFixed = linux_getDefaultMonospacedFontName();
  219107. }
  219108. #endif
  219109. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219110. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219111. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219112. // compiled on its own).
  219113. #if JUCE_INCLUDED_FILE
  219114. // These are defined in juce_linux_Messaging.cpp
  219115. extern Display* display;
  219116. extern XContext windowHandleXContext;
  219117. namespace Atoms
  219118. {
  219119. enum ProtocolItems
  219120. {
  219121. TAKE_FOCUS = 0,
  219122. DELETE_WINDOW = 1,
  219123. PING = 2
  219124. };
  219125. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219126. ActiveWin, Pid, WindowType, WindowState,
  219127. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219128. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219129. XdndActionDescription, XdndActionCopy,
  219130. allowedActions[5],
  219131. allowedMimeTypes[2];
  219132. const unsigned long DndVersion = 3;
  219133. static void initialiseAtoms()
  219134. {
  219135. static bool atomsInitialised = false;
  219136. if (! atomsInitialised)
  219137. {
  219138. atomsInitialised = true;
  219139. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219140. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219141. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219142. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219143. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219144. State = XInternAtom (display, "WM_STATE", True);
  219145. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219146. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219147. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219148. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219149. XdndAware = XInternAtom (display, "XdndAware", False);
  219150. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219151. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219152. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219153. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219154. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219155. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219156. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219157. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219158. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219159. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219160. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219161. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219162. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219163. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219164. allowedActions[1] = XdndActionCopy;
  219165. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219166. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219167. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219168. }
  219169. }
  219170. }
  219171. namespace Keys
  219172. {
  219173. enum MouseButtons
  219174. {
  219175. NoButton = 0,
  219176. LeftButton = 1,
  219177. MiddleButton = 2,
  219178. RightButton = 3,
  219179. WheelUp = 4,
  219180. WheelDown = 5
  219181. };
  219182. static int AltMask = 0;
  219183. static int NumLockMask = 0;
  219184. static bool numLock = false;
  219185. static bool capsLock = false;
  219186. static char keyStates [32];
  219187. static const int extendedKeyModifier = 0x10000000;
  219188. }
  219189. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219190. {
  219191. int keysym;
  219192. if (keyCode & Keys::extendedKeyModifier)
  219193. {
  219194. keysym = 0xff00 | (keyCode & 0xff);
  219195. }
  219196. else
  219197. {
  219198. keysym = keyCode;
  219199. if (keysym == (XK_Tab & 0xff)
  219200. || keysym == (XK_Return & 0xff)
  219201. || keysym == (XK_Escape & 0xff)
  219202. || keysym == (XK_BackSpace & 0xff))
  219203. {
  219204. keysym |= 0xff00;
  219205. }
  219206. }
  219207. ScopedXLock xlock;
  219208. const int keycode = XKeysymToKeycode (display, keysym);
  219209. const int keybyte = keycode >> 3;
  219210. const int keybit = (1 << (keycode & 7));
  219211. return (Keys::keyStates [keybyte] & keybit) != 0;
  219212. }
  219213. #if JUCE_USE_XSHM
  219214. namespace XSHMHelpers
  219215. {
  219216. static int trappedErrorCode = 0;
  219217. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219218. {
  219219. trappedErrorCode = err->error_code;
  219220. return 0;
  219221. }
  219222. static bool isShmAvailable() throw()
  219223. {
  219224. static bool isChecked = false;
  219225. static bool isAvailable = false;
  219226. if (! isChecked)
  219227. {
  219228. isChecked = true;
  219229. int major, minor;
  219230. Bool pixmaps;
  219231. ScopedXLock xlock;
  219232. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219233. {
  219234. trappedErrorCode = 0;
  219235. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219236. XShmSegmentInfo segmentInfo;
  219237. zerostruct (segmentInfo);
  219238. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219239. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219240. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219241. xImage->bytes_per_line * xImage->height,
  219242. IPC_CREAT | 0777)) >= 0)
  219243. {
  219244. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219245. if (segmentInfo.shmaddr != (void*) -1)
  219246. {
  219247. segmentInfo.readOnly = False;
  219248. xImage->data = segmentInfo.shmaddr;
  219249. XSync (display, False);
  219250. if (XShmAttach (display, &segmentInfo) != 0)
  219251. {
  219252. XSync (display, False);
  219253. XShmDetach (display, &segmentInfo);
  219254. isAvailable = true;
  219255. }
  219256. }
  219257. XFlush (display);
  219258. XDestroyImage (xImage);
  219259. shmdt (segmentInfo.shmaddr);
  219260. }
  219261. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219262. XSetErrorHandler (oldHandler);
  219263. if (trappedErrorCode != 0)
  219264. isAvailable = false;
  219265. }
  219266. }
  219267. return isAvailable;
  219268. }
  219269. }
  219270. #endif
  219271. #if JUCE_USE_XRENDER
  219272. namespace XRender
  219273. {
  219274. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219275. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219276. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219277. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219278. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219279. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219280. static tXRenderFindFormat xRenderFindFormat = 0;
  219281. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219282. static bool isAvailable()
  219283. {
  219284. static bool hasLoaded = false;
  219285. if (! hasLoaded)
  219286. {
  219287. ScopedXLock xlock;
  219288. hasLoaded = true;
  219289. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219290. if (h != 0)
  219291. {
  219292. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219293. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219294. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219295. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219296. }
  219297. if (xRenderQueryVersion != 0
  219298. && xRenderFindStandardFormat != 0
  219299. && xRenderFindFormat != 0
  219300. && xRenderFindVisualFormat != 0)
  219301. {
  219302. int major, minor;
  219303. if (xRenderQueryVersion (display, &major, &minor))
  219304. return true;
  219305. }
  219306. xRenderQueryVersion = 0;
  219307. }
  219308. return xRenderQueryVersion != 0;
  219309. }
  219310. static XRenderPictFormat* findPictureFormat()
  219311. {
  219312. ScopedXLock xlock;
  219313. XRenderPictFormat* pictFormat = 0;
  219314. if (isAvailable())
  219315. {
  219316. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219317. if (pictFormat == 0)
  219318. {
  219319. XRenderPictFormat desiredFormat;
  219320. desiredFormat.type = PictTypeDirect;
  219321. desiredFormat.depth = 32;
  219322. desiredFormat.direct.alphaMask = 0xff;
  219323. desiredFormat.direct.redMask = 0xff;
  219324. desiredFormat.direct.greenMask = 0xff;
  219325. desiredFormat.direct.blueMask = 0xff;
  219326. desiredFormat.direct.alpha = 24;
  219327. desiredFormat.direct.red = 16;
  219328. desiredFormat.direct.green = 8;
  219329. desiredFormat.direct.blue = 0;
  219330. pictFormat = xRenderFindFormat (display,
  219331. PictFormatType | PictFormatDepth
  219332. | PictFormatRedMask | PictFormatRed
  219333. | PictFormatGreenMask | PictFormatGreen
  219334. | PictFormatBlueMask | PictFormatBlue
  219335. | PictFormatAlphaMask | PictFormatAlpha,
  219336. &desiredFormat,
  219337. 0);
  219338. }
  219339. }
  219340. return pictFormat;
  219341. }
  219342. }
  219343. #endif
  219344. namespace Visuals
  219345. {
  219346. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219347. {
  219348. ScopedXLock xlock;
  219349. Visual* visual = 0;
  219350. int numVisuals = 0;
  219351. long desiredMask = VisualNoMask;
  219352. XVisualInfo desiredVisual;
  219353. desiredVisual.screen = DefaultScreen (display);
  219354. desiredVisual.depth = desiredDepth;
  219355. desiredMask = VisualScreenMask | VisualDepthMask;
  219356. if (desiredDepth == 32)
  219357. {
  219358. desiredVisual.c_class = TrueColor;
  219359. desiredVisual.red_mask = 0x00FF0000;
  219360. desiredVisual.green_mask = 0x0000FF00;
  219361. desiredVisual.blue_mask = 0x000000FF;
  219362. desiredVisual.bits_per_rgb = 8;
  219363. desiredMask |= VisualClassMask;
  219364. desiredMask |= VisualRedMaskMask;
  219365. desiredMask |= VisualGreenMaskMask;
  219366. desiredMask |= VisualBlueMaskMask;
  219367. desiredMask |= VisualBitsPerRGBMask;
  219368. }
  219369. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219370. desiredMask,
  219371. &desiredVisual,
  219372. &numVisuals);
  219373. if (xvinfos != 0)
  219374. {
  219375. for (int i = 0; i < numVisuals; i++)
  219376. {
  219377. if (xvinfos[i].depth == desiredDepth)
  219378. {
  219379. visual = xvinfos[i].visual;
  219380. break;
  219381. }
  219382. }
  219383. XFree (xvinfos);
  219384. }
  219385. return visual;
  219386. }
  219387. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219388. {
  219389. Visual* visual = 0;
  219390. if (desiredDepth == 32)
  219391. {
  219392. #if JUCE_USE_XSHM
  219393. if (XSHMHelpers::isShmAvailable())
  219394. {
  219395. #if JUCE_USE_XRENDER
  219396. if (XRender::isAvailable())
  219397. {
  219398. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219399. if (pictFormat != 0)
  219400. {
  219401. int numVisuals = 0;
  219402. XVisualInfo desiredVisual;
  219403. desiredVisual.screen = DefaultScreen (display);
  219404. desiredVisual.depth = 32;
  219405. desiredVisual.bits_per_rgb = 8;
  219406. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219407. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219408. &desiredVisual, &numVisuals);
  219409. if (xvinfos != 0)
  219410. {
  219411. for (int i = 0; i < numVisuals; ++i)
  219412. {
  219413. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219414. if (pictVisualFormat != 0
  219415. && pictVisualFormat->type == PictTypeDirect
  219416. && pictVisualFormat->direct.alphaMask)
  219417. {
  219418. visual = xvinfos[i].visual;
  219419. matchedDepth = 32;
  219420. break;
  219421. }
  219422. }
  219423. XFree (xvinfos);
  219424. }
  219425. }
  219426. }
  219427. #endif
  219428. if (visual == 0)
  219429. {
  219430. visual = findVisualWithDepth (32);
  219431. if (visual != 0)
  219432. matchedDepth = 32;
  219433. }
  219434. }
  219435. #endif
  219436. }
  219437. if (visual == 0 && desiredDepth >= 24)
  219438. {
  219439. visual = findVisualWithDepth (24);
  219440. if (visual != 0)
  219441. matchedDepth = 24;
  219442. }
  219443. if (visual == 0 && desiredDepth >= 16)
  219444. {
  219445. visual = findVisualWithDepth (16);
  219446. if (visual != 0)
  219447. matchedDepth = 16;
  219448. }
  219449. return visual;
  219450. }
  219451. }
  219452. class XBitmapImage : public Image::SharedImage
  219453. {
  219454. public:
  219455. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219456. const bool clearImage, const int imageDepth_, Visual* visual)
  219457. : Image::SharedImage (format_, w, h),
  219458. imageDepth (imageDepth_),
  219459. gc (None)
  219460. {
  219461. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219462. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219463. lineStride = ((w * pixelStride + 3) & ~3);
  219464. ScopedXLock xlock;
  219465. #if JUCE_USE_XSHM
  219466. usingXShm = false;
  219467. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219468. {
  219469. zerostruct (segmentInfo);
  219470. segmentInfo.shmid = -1;
  219471. segmentInfo.shmaddr = (char *) -1;
  219472. segmentInfo.readOnly = False;
  219473. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219474. if (xImage != 0)
  219475. {
  219476. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219477. xImage->bytes_per_line * xImage->height,
  219478. IPC_CREAT | 0777)) >= 0)
  219479. {
  219480. if (segmentInfo.shmid != -1)
  219481. {
  219482. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219483. if (segmentInfo.shmaddr != (void*) -1)
  219484. {
  219485. segmentInfo.readOnly = False;
  219486. xImage->data = segmentInfo.shmaddr;
  219487. imageData = (uint8*) segmentInfo.shmaddr;
  219488. if (XShmAttach (display, &segmentInfo) != 0)
  219489. usingXShm = true;
  219490. else
  219491. jassertfalse;
  219492. }
  219493. else
  219494. {
  219495. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219496. }
  219497. }
  219498. }
  219499. }
  219500. }
  219501. if (! usingXShm)
  219502. #endif
  219503. {
  219504. imageDataAllocated.malloc (lineStride * h);
  219505. imageData = imageDataAllocated;
  219506. if (format_ == Image::ARGB && clearImage)
  219507. zeromem (imageData, h * lineStride);
  219508. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219509. xImage->width = w;
  219510. xImage->height = h;
  219511. xImage->xoffset = 0;
  219512. xImage->format = ZPixmap;
  219513. xImage->data = (char*) imageData;
  219514. xImage->byte_order = ImageByteOrder (display);
  219515. xImage->bitmap_unit = BitmapUnit (display);
  219516. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219517. xImage->bitmap_pad = 32;
  219518. xImage->depth = pixelStride * 8;
  219519. xImage->bytes_per_line = lineStride;
  219520. xImage->bits_per_pixel = pixelStride * 8;
  219521. xImage->red_mask = 0x00FF0000;
  219522. xImage->green_mask = 0x0000FF00;
  219523. xImage->blue_mask = 0x000000FF;
  219524. if (imageDepth == 16)
  219525. {
  219526. const int pixelStride = 2;
  219527. const int lineStride = ((w * pixelStride + 3) & ~3);
  219528. imageData16Bit.malloc (lineStride * h);
  219529. xImage->data = imageData16Bit;
  219530. xImage->bitmap_pad = 16;
  219531. xImage->depth = pixelStride * 8;
  219532. xImage->bytes_per_line = lineStride;
  219533. xImage->bits_per_pixel = pixelStride * 8;
  219534. xImage->red_mask = visual->red_mask;
  219535. xImage->green_mask = visual->green_mask;
  219536. xImage->blue_mask = visual->blue_mask;
  219537. }
  219538. if (! XInitImage (xImage))
  219539. jassertfalse;
  219540. }
  219541. }
  219542. ~XBitmapImage()
  219543. {
  219544. ScopedXLock xlock;
  219545. if (gc != None)
  219546. XFreeGC (display, gc);
  219547. #if JUCE_USE_XSHM
  219548. if (usingXShm)
  219549. {
  219550. XShmDetach (display, &segmentInfo);
  219551. XFlush (display);
  219552. XDestroyImage (xImage);
  219553. shmdt (segmentInfo.shmaddr);
  219554. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219555. }
  219556. else
  219557. #endif
  219558. {
  219559. xImage->data = 0;
  219560. XDestroyImage (xImage);
  219561. }
  219562. }
  219563. Image::ImageType getType() const { return Image::NativeImage; }
  219564. LowLevelGraphicsContext* createLowLevelContext()
  219565. {
  219566. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219567. }
  219568. SharedImage* clone()
  219569. {
  219570. jassertfalse;
  219571. return 0;
  219572. }
  219573. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219574. {
  219575. ScopedXLock xlock;
  219576. if (gc == None)
  219577. {
  219578. XGCValues gcvalues;
  219579. gcvalues.foreground = None;
  219580. gcvalues.background = None;
  219581. gcvalues.function = GXcopy;
  219582. gcvalues.plane_mask = AllPlanes;
  219583. gcvalues.clip_mask = None;
  219584. gcvalues.graphics_exposures = False;
  219585. gc = XCreateGC (display, window,
  219586. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219587. &gcvalues);
  219588. }
  219589. if (imageDepth == 16)
  219590. {
  219591. const uint32 rMask = xImage->red_mask;
  219592. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219593. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219594. const uint32 gMask = xImage->green_mask;
  219595. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219596. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219597. const uint32 bMask = xImage->blue_mask;
  219598. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219599. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219600. const Image::BitmapData srcData (Image (this), false);
  219601. for (int y = sy; y < sy + dh; ++y)
  219602. {
  219603. const uint8* p = srcData.getPixelPointer (sx, y);
  219604. for (int x = sx; x < sx + dw; ++x)
  219605. {
  219606. const PixelRGB* const pixel = (const PixelRGB*) p;
  219607. p += srcData.pixelStride;
  219608. XPutPixel (xImage, x, y,
  219609. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219610. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219611. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219612. }
  219613. }
  219614. }
  219615. // blit results to screen.
  219616. #if JUCE_USE_XSHM
  219617. if (usingXShm)
  219618. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219619. else
  219620. #endif
  219621. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219622. }
  219623. private:
  219624. XImage* xImage;
  219625. const int imageDepth;
  219626. HeapBlock <uint8> imageDataAllocated;
  219627. HeapBlock <char> imageData16Bit;
  219628. GC gc;
  219629. #if JUCE_USE_XSHM
  219630. XShmSegmentInfo segmentInfo;
  219631. bool usingXShm;
  219632. #endif
  219633. static int getShiftNeeded (const uint32 mask) throw()
  219634. {
  219635. for (int i = 32; --i >= 0;)
  219636. if (((mask >> i) & 1) != 0)
  219637. return i - 7;
  219638. jassertfalse;
  219639. return 0;
  219640. }
  219641. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219642. };
  219643. namespace PixmapHelpers
  219644. {
  219645. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219646. {
  219647. ScopedXLock xlock;
  219648. const int width = image.getWidth();
  219649. const int height = image.getHeight();
  219650. HeapBlock <uint32> colour (width * height);
  219651. int index = 0;
  219652. for (int y = 0; y < height; ++y)
  219653. for (int x = 0; x < width; ++x)
  219654. colour[index++] = image.getPixelAt (x, y).getARGB();
  219655. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219656. 0, reinterpret_cast<char*> (colour.getData()),
  219657. width, height, 32, 0);
  219658. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219659. width, height, 24);
  219660. GC gc = XCreateGC (display, pixmap, 0, 0);
  219661. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219662. XFreeGC (display, gc);
  219663. return pixmap;
  219664. }
  219665. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219666. {
  219667. ScopedXLock xlock;
  219668. const int width = image.getWidth();
  219669. const int height = image.getHeight();
  219670. const int stride = (width + 7) >> 3;
  219671. HeapBlock <char> mask;
  219672. mask.calloc (stride * height);
  219673. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219674. for (int y = 0; y < height; ++y)
  219675. {
  219676. for (int x = 0; x < width; ++x)
  219677. {
  219678. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219679. const int offset = y * stride + (x >> 3);
  219680. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219681. mask[offset] |= bit;
  219682. }
  219683. }
  219684. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219685. mask.getData(), width, height, 1, 0, 1);
  219686. }
  219687. }
  219688. class LinuxComponentPeer : public ComponentPeer
  219689. {
  219690. public:
  219691. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219692. : ComponentPeer (component, windowStyleFlags),
  219693. windowH (0),
  219694. parentWindow (0),
  219695. wx (0),
  219696. wy (0),
  219697. ww (0),
  219698. wh (0),
  219699. fullScreen (false),
  219700. mapped (false),
  219701. visual (0),
  219702. depth (0)
  219703. {
  219704. // it's dangerous to create a window on a thread other than the message thread..
  219705. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219706. repainter = new LinuxRepaintManager (this);
  219707. createWindow();
  219708. setTitle (component->getName());
  219709. }
  219710. ~LinuxComponentPeer()
  219711. {
  219712. // it's dangerous to delete a window on a thread other than the message thread..
  219713. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219714. deleteIconPixmaps();
  219715. destroyWindow();
  219716. windowH = 0;
  219717. }
  219718. void* getNativeHandle() const
  219719. {
  219720. return (void*) windowH;
  219721. }
  219722. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219723. {
  219724. XPointer peer = 0;
  219725. ScopedXLock xlock;
  219726. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219727. {
  219728. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219729. peer = 0;
  219730. }
  219731. return (LinuxComponentPeer*) peer;
  219732. }
  219733. void setVisible (bool shouldBeVisible)
  219734. {
  219735. ScopedXLock xlock;
  219736. if (shouldBeVisible)
  219737. XMapWindow (display, windowH);
  219738. else
  219739. XUnmapWindow (display, windowH);
  219740. }
  219741. void setTitle (const String& title)
  219742. {
  219743. XTextProperty nameProperty;
  219744. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  219745. ScopedXLock xlock;
  219746. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219747. {
  219748. XSetWMName (display, windowH, &nameProperty);
  219749. XSetWMIconName (display, windowH, &nameProperty);
  219750. XFree (nameProperty.value);
  219751. }
  219752. }
  219753. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219754. {
  219755. fullScreen = isNowFullScreen;
  219756. if (windowH != 0)
  219757. {
  219758. WeakReference<Component> deletionChecker (component);
  219759. wx = x;
  219760. wy = y;
  219761. ww = jmax (1, w);
  219762. wh = jmax (1, h);
  219763. ScopedXLock xlock;
  219764. // Make sure the Window manager does what we want
  219765. XSizeHints* hints = XAllocSizeHints();
  219766. hints->flags = USSize | USPosition;
  219767. hints->width = ww;
  219768. hints->height = wh;
  219769. hints->x = wx;
  219770. hints->y = wy;
  219771. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219772. {
  219773. hints->min_width = hints->max_width = hints->width;
  219774. hints->min_height = hints->max_height = hints->height;
  219775. hints->flags |= PMinSize | PMaxSize;
  219776. }
  219777. XSetWMNormalHints (display, windowH, hints);
  219778. XFree (hints);
  219779. XMoveResizeWindow (display, windowH,
  219780. wx - windowBorder.getLeft(),
  219781. wy - windowBorder.getTop(), ww, wh);
  219782. if (deletionChecker != 0)
  219783. {
  219784. updateBorderSize();
  219785. handleMovedOrResized();
  219786. }
  219787. }
  219788. }
  219789. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219790. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219791. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219792. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219793. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219794. {
  219795. return relativePosition + getScreenPosition();
  219796. }
  219797. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219798. {
  219799. return screenPosition - getScreenPosition();
  219800. }
  219801. void setAlpha (float newAlpha)
  219802. {
  219803. //xxx todo!
  219804. }
  219805. void setMinimised (bool shouldBeMinimised)
  219806. {
  219807. if (shouldBeMinimised)
  219808. {
  219809. Window root = RootWindow (display, DefaultScreen (display));
  219810. XClientMessageEvent clientMsg;
  219811. clientMsg.display = display;
  219812. clientMsg.window = windowH;
  219813. clientMsg.type = ClientMessage;
  219814. clientMsg.format = 32;
  219815. clientMsg.message_type = Atoms::ChangeState;
  219816. clientMsg.data.l[0] = IconicState;
  219817. ScopedXLock xlock;
  219818. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219819. }
  219820. else
  219821. {
  219822. setVisible (true);
  219823. }
  219824. }
  219825. bool isMinimised() const
  219826. {
  219827. bool minimised = false;
  219828. unsigned char* stateProp;
  219829. unsigned long nitems, bytesLeft;
  219830. Atom actualType;
  219831. int actualFormat;
  219832. ScopedXLock xlock;
  219833. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219834. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219835. &stateProp) == Success
  219836. && actualType == Atoms::State
  219837. && actualFormat == 32
  219838. && nitems > 0)
  219839. {
  219840. if (((unsigned long*) stateProp)[0] == IconicState)
  219841. minimised = true;
  219842. XFree (stateProp);
  219843. }
  219844. return minimised;
  219845. }
  219846. void setFullScreen (const bool shouldBeFullScreen)
  219847. {
  219848. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219849. setMinimised (false);
  219850. if (fullScreen != shouldBeFullScreen)
  219851. {
  219852. if (shouldBeFullScreen)
  219853. r = Desktop::getInstance().getMainMonitorArea();
  219854. if (! r.isEmpty())
  219855. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219856. getComponent()->repaint();
  219857. }
  219858. }
  219859. bool isFullScreen() const
  219860. {
  219861. return fullScreen;
  219862. }
  219863. bool isChildWindowOf (Window possibleParent) const
  219864. {
  219865. Window* windowList = 0;
  219866. uint32 windowListSize = 0;
  219867. Window parent, root;
  219868. ScopedXLock xlock;
  219869. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219870. {
  219871. if (windowList != 0)
  219872. XFree (windowList);
  219873. return parent == possibleParent;
  219874. }
  219875. return false;
  219876. }
  219877. bool isFrontWindow() const
  219878. {
  219879. Window* windowList = 0;
  219880. uint32 windowListSize = 0;
  219881. bool result = false;
  219882. ScopedXLock xlock;
  219883. Window parent, root = RootWindow (display, DefaultScreen (display));
  219884. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219885. {
  219886. for (int i = windowListSize; --i >= 0;)
  219887. {
  219888. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219889. if (peer != 0)
  219890. {
  219891. result = (peer == this);
  219892. break;
  219893. }
  219894. }
  219895. }
  219896. if (windowList != 0)
  219897. XFree (windowList);
  219898. return result;
  219899. }
  219900. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219901. {
  219902. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219903. return false;
  219904. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219905. {
  219906. Component* const c = Desktop::getInstance().getComponent (i);
  219907. if (c == getComponent())
  219908. break;
  219909. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219910. return false;
  219911. }
  219912. if (trueIfInAChildWindow)
  219913. return true;
  219914. ::Window root, child;
  219915. unsigned int bw, depth;
  219916. int wx, wy, w, h;
  219917. ScopedXLock xlock;
  219918. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219919. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219920. &bw, &depth))
  219921. {
  219922. return false;
  219923. }
  219924. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219925. return false;
  219926. return child == None;
  219927. }
  219928. const BorderSize getFrameSize() const
  219929. {
  219930. return BorderSize();
  219931. }
  219932. bool setAlwaysOnTop (bool alwaysOnTop)
  219933. {
  219934. return false;
  219935. }
  219936. void toFront (bool makeActive)
  219937. {
  219938. if (makeActive)
  219939. {
  219940. setVisible (true);
  219941. grabFocus();
  219942. }
  219943. XEvent ev;
  219944. ev.xclient.type = ClientMessage;
  219945. ev.xclient.serial = 0;
  219946. ev.xclient.send_event = True;
  219947. ev.xclient.message_type = Atoms::ActiveWin;
  219948. ev.xclient.window = windowH;
  219949. ev.xclient.format = 32;
  219950. ev.xclient.data.l[0] = 2;
  219951. ev.xclient.data.l[1] = CurrentTime;
  219952. ev.xclient.data.l[2] = 0;
  219953. ev.xclient.data.l[3] = 0;
  219954. ev.xclient.data.l[4] = 0;
  219955. {
  219956. ScopedXLock xlock;
  219957. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219958. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219959. XWindowAttributes attr;
  219960. XGetWindowAttributes (display, windowH, &attr);
  219961. if (component->isAlwaysOnTop())
  219962. XRaiseWindow (display, windowH);
  219963. XSync (display, False);
  219964. }
  219965. handleBroughtToFront();
  219966. }
  219967. void toBehind (ComponentPeer* other)
  219968. {
  219969. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219970. jassert (otherPeer != 0); // wrong type of window?
  219971. if (otherPeer != 0)
  219972. {
  219973. setMinimised (false);
  219974. Window newStack[] = { otherPeer->windowH, windowH };
  219975. ScopedXLock xlock;
  219976. XRestackWindows (display, newStack, 2);
  219977. }
  219978. }
  219979. bool isFocused() const
  219980. {
  219981. int revert = 0;
  219982. Window focusedWindow = 0;
  219983. ScopedXLock xlock;
  219984. XGetInputFocus (display, &focusedWindow, &revert);
  219985. return focusedWindow == windowH;
  219986. }
  219987. void grabFocus()
  219988. {
  219989. XWindowAttributes atts;
  219990. ScopedXLock xlock;
  219991. if (windowH != 0
  219992. && XGetWindowAttributes (display, windowH, &atts)
  219993. && atts.map_state == IsViewable
  219994. && ! isFocused())
  219995. {
  219996. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219997. isActiveApplication = true;
  219998. }
  219999. }
  220000. void textInputRequired (const Point<int>&)
  220001. {
  220002. }
  220003. void repaint (const Rectangle<int>& area)
  220004. {
  220005. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220006. }
  220007. void performAnyPendingRepaintsNow()
  220008. {
  220009. repainter->performAnyPendingRepaintsNow();
  220010. }
  220011. void setIcon (const Image& newIcon)
  220012. {
  220013. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220014. HeapBlock <unsigned long> data (dataSize);
  220015. int index = 0;
  220016. data[index++] = newIcon.getWidth();
  220017. data[index++] = newIcon.getHeight();
  220018. for (int y = 0; y < newIcon.getHeight(); ++y)
  220019. for (int x = 0; x < newIcon.getWidth(); ++x)
  220020. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220021. ScopedXLock xlock;
  220022. XChangeProperty (display, windowH,
  220023. XInternAtom (display, "_NET_WM_ICON", False),
  220024. XA_CARDINAL, 32, PropModeReplace,
  220025. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220026. deleteIconPixmaps();
  220027. XWMHints* wmHints = XGetWMHints (display, windowH);
  220028. if (wmHints == 0)
  220029. wmHints = XAllocWMHints();
  220030. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220031. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  220032. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  220033. XSetWMHints (display, windowH, wmHints);
  220034. XFree (wmHints);
  220035. XSync (display, False);
  220036. }
  220037. void deleteIconPixmaps()
  220038. {
  220039. ScopedXLock xlock;
  220040. XWMHints* wmHints = XGetWMHints (display, windowH);
  220041. if (wmHints != 0)
  220042. {
  220043. if ((wmHints->flags & IconPixmapHint) != 0)
  220044. {
  220045. wmHints->flags &= ~IconPixmapHint;
  220046. XFreePixmap (display, wmHints->icon_pixmap);
  220047. }
  220048. if ((wmHints->flags & IconMaskHint) != 0)
  220049. {
  220050. wmHints->flags &= ~IconMaskHint;
  220051. XFreePixmap (display, wmHints->icon_mask);
  220052. }
  220053. XSetWMHints (display, windowH, wmHints);
  220054. XFree (wmHints);
  220055. }
  220056. }
  220057. void handleWindowMessage (XEvent* event)
  220058. {
  220059. switch (event->xany.type)
  220060. {
  220061. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  220062. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  220063. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  220064. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  220065. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  220066. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  220067. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  220068. case FocusIn: handleFocusInEvent(); break;
  220069. case FocusOut: handleFocusOutEvent(); break;
  220070. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  220071. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  220072. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  220073. case SelectionNotify: handleDragAndDropSelection (event); break;
  220074. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  220075. case ReparentNotify: handleReparentNotifyEvent(); break;
  220076. case GravityNotify: handleGravityNotify(); break;
  220077. case CirculateNotify:
  220078. case CreateNotify:
  220079. case DestroyNotify:
  220080. // Think we can ignore these
  220081. break;
  220082. case MapNotify:
  220083. mapped = true;
  220084. handleBroughtToFront();
  220085. break;
  220086. case UnmapNotify:
  220087. mapped = false;
  220088. break;
  220089. case SelectionClear:
  220090. case SelectionRequest:
  220091. break;
  220092. default:
  220093. #if JUCE_USE_XSHM
  220094. {
  220095. ScopedXLock xlock;
  220096. if (event->xany.type == XShmGetEventBase (display))
  220097. repainter->notifyPaintCompleted();
  220098. }
  220099. #endif
  220100. break;
  220101. }
  220102. }
  220103. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  220104. {
  220105. char utf8 [64] = { 0 };
  220106. juce_wchar unicodeChar = 0;
  220107. int keyCode = 0;
  220108. bool keyDownChange = false;
  220109. KeySym sym;
  220110. {
  220111. ScopedXLock xlock;
  220112. updateKeyStates (keyEvent->keycode, true);
  220113. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220114. ::setlocale (LC_ALL, "");
  220115. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220116. ::setlocale (LC_ALL, oldLocale);
  220117. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220118. keyCode = (int) unicodeChar;
  220119. if (keyCode < 0x20)
  220120. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220121. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220122. }
  220123. const ModifierKeys oldMods (currentModifiers);
  220124. bool keyPressed = false;
  220125. if ((sym & 0xff00) == 0xff00)
  220126. {
  220127. switch (sym) // Translate keypad
  220128. {
  220129. case XK_KP_Divide: keyCode = XK_slash; break;
  220130. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  220131. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  220132. case XK_KP_Add: keyCode = XK_plus; break;
  220133. case XK_KP_Enter: keyCode = XK_Return; break;
  220134. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  220135. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  220136. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  220137. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  220138. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  220139. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  220140. case XK_KP_5: keyCode = XK_5; break;
  220141. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  220142. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  220143. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  220144. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  220145. default: break;
  220146. }
  220147. switch (sym)
  220148. {
  220149. case XK_Left:
  220150. case XK_Right:
  220151. case XK_Up:
  220152. case XK_Down:
  220153. case XK_Page_Up:
  220154. case XK_Page_Down:
  220155. case XK_End:
  220156. case XK_Home:
  220157. case XK_Delete:
  220158. case XK_Insert:
  220159. keyPressed = true;
  220160. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220161. break;
  220162. case XK_Tab:
  220163. case XK_Return:
  220164. case XK_Escape:
  220165. case XK_BackSpace:
  220166. keyPressed = true;
  220167. keyCode &= 0xff;
  220168. break;
  220169. default:
  220170. if (sym >= XK_F1 && sym <= XK_F16)
  220171. {
  220172. keyPressed = true;
  220173. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220174. }
  220175. break;
  220176. }
  220177. }
  220178. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220179. keyPressed = true;
  220180. if (oldMods != currentModifiers)
  220181. handleModifierKeysChange();
  220182. if (keyDownChange)
  220183. handleKeyUpOrDown (true);
  220184. if (keyPressed)
  220185. handleKeyPress (keyCode, unicodeChar);
  220186. }
  220187. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  220188. {
  220189. updateKeyStates (keyEvent->keycode, false);
  220190. KeySym sym;
  220191. {
  220192. ScopedXLock xlock;
  220193. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220194. }
  220195. const ModifierKeys oldMods (currentModifiers);
  220196. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220197. if (oldMods != currentModifiers)
  220198. handleModifierKeysChange();
  220199. if (keyDownChange)
  220200. handleKeyUpOrDown (false);
  220201. }
  220202. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  220203. {
  220204. updateKeyModifiers (buttonPressEvent->state);
  220205. bool buttonMsg = false;
  220206. const int map = pointerMap [buttonPressEvent->button - Button1];
  220207. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220208. {
  220209. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220210. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220211. }
  220212. if (map == Keys::LeftButton)
  220213. {
  220214. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220215. buttonMsg = true;
  220216. }
  220217. else if (map == Keys::RightButton)
  220218. {
  220219. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220220. buttonMsg = true;
  220221. }
  220222. else if (map == Keys::MiddleButton)
  220223. {
  220224. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220225. buttonMsg = true;
  220226. }
  220227. if (buttonMsg)
  220228. {
  220229. toFront (true);
  220230. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220231. getEventTime (buttonPressEvent->time));
  220232. }
  220233. clearLastMousePos();
  220234. }
  220235. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  220236. {
  220237. updateKeyModifiers (buttonRelEvent->state);
  220238. const int map = pointerMap [buttonRelEvent->button - Button1];
  220239. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220240. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220241. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220242. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220243. getEventTime (buttonRelEvent->time));
  220244. clearLastMousePos();
  220245. }
  220246. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  220247. {
  220248. updateKeyModifiers (movedEvent->state);
  220249. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  220250. if (lastMousePos != mousePos)
  220251. {
  220252. lastMousePos = mousePos;
  220253. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220254. {
  220255. Window wRoot = 0, wParent = 0;
  220256. {
  220257. ScopedXLock xlock;
  220258. unsigned int numChildren;
  220259. Window* wChild = 0;
  220260. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220261. }
  220262. if (wParent != 0
  220263. && wParent != windowH
  220264. && wParent != wRoot)
  220265. {
  220266. parentWindow = wParent;
  220267. updateBounds();
  220268. }
  220269. else
  220270. {
  220271. parentWindow = 0;
  220272. }
  220273. }
  220274. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220275. }
  220276. }
  220277. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  220278. {
  220279. clearLastMousePos();
  220280. if (! currentModifiers.isAnyMouseButtonDown())
  220281. {
  220282. updateKeyModifiers (enterEvent->state);
  220283. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220284. }
  220285. }
  220286. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  220287. {
  220288. // Suppress the normal leave if we've got a pointer grab, or if
  220289. // it's a bogus one caused by clicking a mouse button when running
  220290. // in a Window manager
  220291. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220292. || leaveEvent->mode == NotifyUngrab)
  220293. {
  220294. updateKeyModifiers (leaveEvent->state);
  220295. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220296. }
  220297. }
  220298. void handleFocusInEvent()
  220299. {
  220300. isActiveApplication = true;
  220301. if (isFocused())
  220302. handleFocusGain();
  220303. }
  220304. void handleFocusOutEvent()
  220305. {
  220306. isActiveApplication = false;
  220307. if (! isFocused())
  220308. handleFocusLoss();
  220309. }
  220310. void handleExposeEvent (XExposeEvent* exposeEvent)
  220311. {
  220312. // Batch together all pending expose events
  220313. XEvent nextEvent;
  220314. ScopedXLock xlock;
  220315. if (exposeEvent->window != windowH)
  220316. {
  220317. Window child;
  220318. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220319. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220320. &child);
  220321. }
  220322. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220323. exposeEvent->width, exposeEvent->height));
  220324. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220325. {
  220326. XPeekEvent (display, (XEvent*) &nextEvent);
  220327. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  220328. break;
  220329. XNextEvent (display, (XEvent*) &nextEvent);
  220330. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220331. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220332. nextExposeEvent->width, nextExposeEvent->height));
  220333. }
  220334. }
  220335. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  220336. {
  220337. updateBounds();
  220338. updateBorderSize();
  220339. handleMovedOrResized();
  220340. // if the native title bar is dragged, need to tell any active menus, etc.
  220341. if ((styleFlags & windowHasTitleBar) != 0
  220342. && component->isCurrentlyBlockedByAnotherModalComponent())
  220343. {
  220344. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220345. if (currentModalComp != 0)
  220346. currentModalComp->inputAttemptWhenModal();
  220347. }
  220348. if (confEvent->window == windowH
  220349. && confEvent->above != 0
  220350. && isFrontWindow())
  220351. {
  220352. handleBroughtToFront();
  220353. }
  220354. }
  220355. void handleReparentNotifyEvent()
  220356. {
  220357. parentWindow = 0;
  220358. Window wRoot = 0;
  220359. Window* wChild = 0;
  220360. unsigned int numChildren;
  220361. {
  220362. ScopedXLock xlock;
  220363. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220364. }
  220365. if (parentWindow == windowH || parentWindow == wRoot)
  220366. parentWindow = 0;
  220367. handleGravityNotify();
  220368. }
  220369. void handleGravityNotify()
  220370. {
  220371. updateBounds();
  220372. updateBorderSize();
  220373. handleMovedOrResized();
  220374. }
  220375. void handleMappingNotify (XMappingEvent* const mappingEvent)
  220376. {
  220377. if (mappingEvent->request != MappingPointer)
  220378. {
  220379. // Deal with modifier/keyboard mapping
  220380. ScopedXLock xlock;
  220381. XRefreshKeyboardMapping (mappingEvent);
  220382. updateModifierMappings();
  220383. }
  220384. }
  220385. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  220386. {
  220387. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220388. {
  220389. const Atom atom = (Atom) clientMsg->data.l[0];
  220390. if (atom == Atoms::ProtocolList [Atoms::PING])
  220391. {
  220392. Window root = RootWindow (display, DefaultScreen (display));
  220393. clientMsg->window = root;
  220394. XSendEvent (display, root, False, NoEventMask, event);
  220395. XFlush (display);
  220396. }
  220397. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220398. {
  220399. XWindowAttributes atts;
  220400. ScopedXLock xlock;
  220401. if (clientMsg->window != 0
  220402. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220403. {
  220404. if (atts.map_state == IsViewable)
  220405. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220406. }
  220407. }
  220408. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220409. {
  220410. handleUserClosingWindow();
  220411. }
  220412. }
  220413. else if (clientMsg->message_type == Atoms::XdndEnter)
  220414. {
  220415. handleDragAndDropEnter (clientMsg);
  220416. }
  220417. else if (clientMsg->message_type == Atoms::XdndLeave)
  220418. {
  220419. resetDragAndDrop();
  220420. }
  220421. else if (clientMsg->message_type == Atoms::XdndPosition)
  220422. {
  220423. handleDragAndDropPosition (clientMsg);
  220424. }
  220425. else if (clientMsg->message_type == Atoms::XdndDrop)
  220426. {
  220427. handleDragAndDropDrop (clientMsg);
  220428. }
  220429. else if (clientMsg->message_type == Atoms::XdndStatus)
  220430. {
  220431. handleDragAndDropStatus (clientMsg);
  220432. }
  220433. else if (clientMsg->message_type == Atoms::XdndFinished)
  220434. {
  220435. resetDragAndDrop();
  220436. }
  220437. }
  220438. void showMouseCursor (Cursor cursor) throw()
  220439. {
  220440. ScopedXLock xlock;
  220441. XDefineCursor (display, windowH, cursor);
  220442. }
  220443. void setTaskBarIcon (const Image& image)
  220444. {
  220445. ScopedXLock xlock;
  220446. taskbarImage = image;
  220447. Screen* const screen = XDefaultScreenOfDisplay (display);
  220448. const int screenNumber = XScreenNumberOfScreen (screen);
  220449. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220450. screenAtom << screenNumber;
  220451. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220452. XGrabServer (display);
  220453. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220454. if (managerWin != None)
  220455. XSelectInput (display, managerWin, StructureNotifyMask);
  220456. XUngrabServer (display);
  220457. XFlush (display);
  220458. if (managerWin != None)
  220459. {
  220460. XEvent ev;
  220461. zerostruct (ev);
  220462. ev.xclient.type = ClientMessage;
  220463. ev.xclient.window = managerWin;
  220464. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220465. ev.xclient.format = 32;
  220466. ev.xclient.data.l[0] = CurrentTime;
  220467. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220468. ev.xclient.data.l[2] = windowH;
  220469. ev.xclient.data.l[3] = 0;
  220470. ev.xclient.data.l[4] = 0;
  220471. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220472. XSync (display, False);
  220473. }
  220474. // For older KDE's ...
  220475. long atomData = 1;
  220476. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220477. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220478. // For more recent KDE's...
  220479. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220480. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220481. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220482. XSizeHints* hints = XAllocSizeHints();
  220483. hints->flags = PMinSize;
  220484. hints->min_width = 22;
  220485. hints->min_height = 22;
  220486. XSetWMNormalHints (display, windowH, hints);
  220487. XFree (hints);
  220488. }
  220489. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220490. bool dontRepaint;
  220491. static ModifierKeys currentModifiers;
  220492. static bool isActiveApplication;
  220493. private:
  220494. class LinuxRepaintManager : public Timer
  220495. {
  220496. public:
  220497. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220498. : peer (peer_),
  220499. lastTimeImageUsed (0)
  220500. {
  220501. #if JUCE_USE_XSHM
  220502. shmCompletedDrawing = true;
  220503. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220504. if (useARGBImagesForRendering)
  220505. {
  220506. ScopedXLock xlock;
  220507. XShmSegmentInfo segmentinfo;
  220508. XImage* const testImage
  220509. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220510. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220511. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220512. XDestroyImage (testImage);
  220513. }
  220514. #endif
  220515. }
  220516. void timerCallback()
  220517. {
  220518. #if JUCE_USE_XSHM
  220519. if (! shmCompletedDrawing)
  220520. return;
  220521. #endif
  220522. if (! regionsNeedingRepaint.isEmpty())
  220523. {
  220524. stopTimer();
  220525. performAnyPendingRepaintsNow();
  220526. }
  220527. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220528. {
  220529. stopTimer();
  220530. image = Image::null;
  220531. }
  220532. }
  220533. void repaint (const Rectangle<int>& area)
  220534. {
  220535. if (! isTimerRunning())
  220536. startTimer (repaintTimerPeriod);
  220537. regionsNeedingRepaint.add (area);
  220538. }
  220539. void performAnyPendingRepaintsNow()
  220540. {
  220541. #if JUCE_USE_XSHM
  220542. if (! shmCompletedDrawing)
  220543. {
  220544. startTimer (repaintTimerPeriod);
  220545. return;
  220546. }
  220547. #endif
  220548. peer->clearMaskedRegion();
  220549. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220550. regionsNeedingRepaint.clear();
  220551. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220552. if (! totalArea.isEmpty())
  220553. {
  220554. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220555. || image.getHeight() < totalArea.getHeight())
  220556. {
  220557. #if JUCE_USE_XSHM
  220558. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220559. : Image::RGB,
  220560. #else
  220561. image = Image (new XBitmapImage (Image::RGB,
  220562. #endif
  220563. (totalArea.getWidth() + 31) & ~31,
  220564. (totalArea.getHeight() + 31) & ~31,
  220565. false, peer->depth, peer->visual));
  220566. }
  220567. startTimer (repaintTimerPeriod);
  220568. RectangleList adjustedList (originalRepaintRegion);
  220569. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220570. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220571. if (peer->depth == 32)
  220572. {
  220573. RectangleList::Iterator i (originalRepaintRegion);
  220574. while (i.next())
  220575. image.clear (*i.getRectangle() - totalArea.getPosition());
  220576. }
  220577. peer->handlePaint (context);
  220578. if (! peer->maskedRegion.isEmpty())
  220579. originalRepaintRegion.subtract (peer->maskedRegion);
  220580. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220581. {
  220582. #if JUCE_USE_XSHM
  220583. shmCompletedDrawing = false;
  220584. #endif
  220585. const Rectangle<int>& r = *i.getRectangle();
  220586. static_cast<XBitmapImage*> (image.getSharedImage())
  220587. ->blitToWindow (peer->windowH,
  220588. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220589. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220590. }
  220591. }
  220592. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220593. startTimer (repaintTimerPeriod);
  220594. }
  220595. #if JUCE_USE_XSHM
  220596. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220597. #endif
  220598. private:
  220599. enum { repaintTimerPeriod = 1000 / 100 };
  220600. LinuxComponentPeer* const peer;
  220601. Image image;
  220602. uint32 lastTimeImageUsed;
  220603. RectangleList regionsNeedingRepaint;
  220604. #if JUCE_USE_XSHM
  220605. bool useARGBImagesForRendering, shmCompletedDrawing;
  220606. #endif
  220607. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220608. };
  220609. ScopedPointer <LinuxRepaintManager> repainter;
  220610. friend class LinuxRepaintManager;
  220611. Window windowH, parentWindow;
  220612. int wx, wy, ww, wh;
  220613. Image taskbarImage;
  220614. bool fullScreen, mapped;
  220615. Visual* visual;
  220616. int depth;
  220617. BorderSize windowBorder;
  220618. struct MotifWmHints
  220619. {
  220620. unsigned long flags;
  220621. unsigned long functions;
  220622. unsigned long decorations;
  220623. long input_mode;
  220624. unsigned long status;
  220625. };
  220626. static void updateKeyStates (const int keycode, const bool press) throw()
  220627. {
  220628. const int keybyte = keycode >> 3;
  220629. const int keybit = (1 << (keycode & 7));
  220630. if (press)
  220631. Keys::keyStates [keybyte] |= keybit;
  220632. else
  220633. Keys::keyStates [keybyte] &= ~keybit;
  220634. }
  220635. static void updateKeyModifiers (const int status) throw()
  220636. {
  220637. int keyMods = 0;
  220638. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220639. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220640. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220641. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220642. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220643. Keys::capsLock = ((status & LockMask) != 0);
  220644. }
  220645. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220646. {
  220647. int modifier = 0;
  220648. bool isModifier = true;
  220649. switch (sym)
  220650. {
  220651. case XK_Shift_L:
  220652. case XK_Shift_R:
  220653. modifier = ModifierKeys::shiftModifier;
  220654. break;
  220655. case XK_Control_L:
  220656. case XK_Control_R:
  220657. modifier = ModifierKeys::ctrlModifier;
  220658. break;
  220659. case XK_Alt_L:
  220660. case XK_Alt_R:
  220661. modifier = ModifierKeys::altModifier;
  220662. break;
  220663. case XK_Num_Lock:
  220664. if (press)
  220665. Keys::numLock = ! Keys::numLock;
  220666. break;
  220667. case XK_Caps_Lock:
  220668. if (press)
  220669. Keys::capsLock = ! Keys::capsLock;
  220670. break;
  220671. case XK_Scroll_Lock:
  220672. break;
  220673. default:
  220674. isModifier = false;
  220675. break;
  220676. }
  220677. if (modifier != 0)
  220678. {
  220679. if (press)
  220680. currentModifiers = currentModifiers.withFlags (modifier);
  220681. else
  220682. currentModifiers = currentModifiers.withoutFlags (modifier);
  220683. }
  220684. return isModifier;
  220685. }
  220686. // Alt and Num lock are not defined by standard X
  220687. // modifier constants: check what they're mapped to
  220688. static void updateModifierMappings() throw()
  220689. {
  220690. ScopedXLock xlock;
  220691. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220692. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220693. Keys::AltMask = 0;
  220694. Keys::NumLockMask = 0;
  220695. XModifierKeymap* mapping = XGetModifierMapping (display);
  220696. if (mapping)
  220697. {
  220698. for (int i = 0; i < 8; i++)
  220699. {
  220700. if (mapping->modifiermap [i << 1] == altLeftCode)
  220701. Keys::AltMask = 1 << i;
  220702. else if (mapping->modifiermap [i << 1] == numLockCode)
  220703. Keys::NumLockMask = 1 << i;
  220704. }
  220705. XFreeModifiermap (mapping);
  220706. }
  220707. }
  220708. void removeWindowDecorations (Window wndH)
  220709. {
  220710. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220711. if (hints != None)
  220712. {
  220713. MotifWmHints motifHints;
  220714. zerostruct (motifHints);
  220715. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220716. motifHints.decorations = 0;
  220717. ScopedXLock xlock;
  220718. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220719. (unsigned char*) &motifHints, 4);
  220720. }
  220721. hints = XInternAtom (display, "_WIN_HINTS", True);
  220722. if (hints != None)
  220723. {
  220724. long gnomeHints = 0;
  220725. ScopedXLock xlock;
  220726. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220727. (unsigned char*) &gnomeHints, 1);
  220728. }
  220729. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220730. if (hints != None)
  220731. {
  220732. long kwmHints = 2; /*KDE_tinyDecoration*/
  220733. ScopedXLock xlock;
  220734. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220735. (unsigned char*) &kwmHints, 1);
  220736. }
  220737. }
  220738. void addWindowButtons (Window wndH)
  220739. {
  220740. ScopedXLock xlock;
  220741. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220742. if (hints != None)
  220743. {
  220744. MotifWmHints motifHints;
  220745. zerostruct (motifHints);
  220746. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220747. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220748. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220749. if ((styleFlags & windowHasCloseButton) != 0)
  220750. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220751. if ((styleFlags & windowHasMinimiseButton) != 0)
  220752. {
  220753. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220754. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220755. }
  220756. if ((styleFlags & windowHasMaximiseButton) != 0)
  220757. {
  220758. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220759. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220760. }
  220761. if ((styleFlags & windowIsResizable) != 0)
  220762. {
  220763. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220764. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220765. }
  220766. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220767. }
  220768. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220769. if (hints != None)
  220770. {
  220771. int netHints [6];
  220772. int num = 0;
  220773. if ((styleFlags & windowIsResizable) != 0)
  220774. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220775. if ((styleFlags & windowHasMaximiseButton) != 0)
  220776. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220777. if ((styleFlags & windowHasMinimiseButton) != 0)
  220778. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220779. if ((styleFlags & windowHasCloseButton) != 0)
  220780. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220781. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220782. }
  220783. }
  220784. void setWindowType()
  220785. {
  220786. int netHints [2];
  220787. int numHints = 0;
  220788. if ((styleFlags & windowIsTemporary) != 0
  220789. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220790. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220791. else
  220792. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220793. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220794. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220795. (unsigned char*) &netHints, numHints);
  220796. numHints = 0;
  220797. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220798. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220799. if (component->isAlwaysOnTop())
  220800. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220801. if (numHints > 0)
  220802. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220803. (unsigned char*) &netHints, numHints);
  220804. }
  220805. void createWindow()
  220806. {
  220807. ScopedXLock xlock;
  220808. Atoms::initialiseAtoms();
  220809. resetDragAndDrop();
  220810. // Get defaults for various properties
  220811. const int screen = DefaultScreen (display);
  220812. Window root = RootWindow (display, screen);
  220813. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220814. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220815. if (visual == 0)
  220816. {
  220817. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220818. Process::terminate();
  220819. }
  220820. // Create and install a colormap suitable fr our visual
  220821. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220822. XInstallColormap (display, colormap);
  220823. // Set up the window attributes
  220824. XSetWindowAttributes swa;
  220825. swa.border_pixel = 0;
  220826. swa.background_pixmap = None;
  220827. swa.colormap = colormap;
  220828. swa.event_mask = getAllEventsMask();
  220829. windowH = XCreateWindow (display, root,
  220830. 0, 0, 1, 1,
  220831. 0, depth, InputOutput, visual,
  220832. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220833. &swa);
  220834. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220835. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220836. GrabModeAsync, GrabModeAsync, None, None);
  220837. // Set the window context to identify the window handle object
  220838. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220839. {
  220840. // Failed
  220841. jassertfalse;
  220842. Logger::outputDebugString ("Failed to create context information for window.\n");
  220843. XDestroyWindow (display, windowH);
  220844. windowH = 0;
  220845. return;
  220846. }
  220847. // Set window manager hints
  220848. XWMHints* wmHints = XAllocWMHints();
  220849. wmHints->flags = InputHint | StateHint;
  220850. wmHints->input = True; // Locally active input model
  220851. wmHints->initial_state = NormalState;
  220852. XSetWMHints (display, windowH, wmHints);
  220853. XFree (wmHints);
  220854. // Set the window type
  220855. setWindowType();
  220856. // Define decoration
  220857. if ((styleFlags & windowHasTitleBar) == 0)
  220858. removeWindowDecorations (windowH);
  220859. else
  220860. addWindowButtons (windowH);
  220861. setTitle (getComponent()->getName());
  220862. // Associate the PID, allowing to be shut down when something goes wrong
  220863. unsigned long pid = getpid();
  220864. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220865. (unsigned char*) &pid, 1);
  220866. // Set window manager protocols
  220867. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220868. (unsigned char*) Atoms::ProtocolList, 2);
  220869. // Set drag and drop flags
  220870. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220871. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220872. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220873. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220874. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220875. (const unsigned char*) "", 0);
  220876. unsigned long dndVersion = Atoms::DndVersion;
  220877. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220878. (const unsigned char*) &dndVersion, 1);
  220879. // Initialise the pointer and keyboard mapping
  220880. // This is not the same as the logical pointer mapping the X server uses:
  220881. // we don't mess with this.
  220882. static bool mappingInitialised = false;
  220883. if (! mappingInitialised)
  220884. {
  220885. mappingInitialised = true;
  220886. const int numButtons = XGetPointerMapping (display, 0, 0);
  220887. if (numButtons == 2)
  220888. {
  220889. pointerMap[0] = Keys::LeftButton;
  220890. pointerMap[1] = Keys::RightButton;
  220891. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220892. }
  220893. else if (numButtons >= 3)
  220894. {
  220895. pointerMap[0] = Keys::LeftButton;
  220896. pointerMap[1] = Keys::MiddleButton;
  220897. pointerMap[2] = Keys::RightButton;
  220898. if (numButtons >= 5)
  220899. {
  220900. pointerMap[3] = Keys::WheelUp;
  220901. pointerMap[4] = Keys::WheelDown;
  220902. }
  220903. }
  220904. updateModifierMappings();
  220905. }
  220906. }
  220907. void destroyWindow()
  220908. {
  220909. ScopedXLock xlock;
  220910. XPointer handlePointer;
  220911. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220912. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220913. XDestroyWindow (display, windowH);
  220914. // Wait for it to complete and then remove any events for this
  220915. // window from the event queue.
  220916. XSync (display, false);
  220917. XEvent event;
  220918. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220919. {}
  220920. }
  220921. static int getAllEventsMask() throw()
  220922. {
  220923. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220924. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220925. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220926. }
  220927. static int64 getEventTime (::Time t)
  220928. {
  220929. static int64 eventTimeOffset = 0x12345678;
  220930. const int64 thisMessageTime = t;
  220931. if (eventTimeOffset == 0x12345678)
  220932. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220933. return eventTimeOffset + thisMessageTime;
  220934. }
  220935. void updateBorderSize()
  220936. {
  220937. if ((styleFlags & windowHasTitleBar) == 0)
  220938. {
  220939. windowBorder = BorderSize (0);
  220940. }
  220941. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220942. {
  220943. ScopedXLock xlock;
  220944. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220945. if (hints != None)
  220946. {
  220947. unsigned char* data = 0;
  220948. unsigned long nitems, bytesLeft;
  220949. Atom actualType;
  220950. int actualFormat;
  220951. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220952. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220953. &data) == Success)
  220954. {
  220955. const unsigned long* const sizes = (const unsigned long*) data;
  220956. if (actualFormat == 32)
  220957. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  220958. (int) sizes[3], (int) sizes[1]);
  220959. XFree (data);
  220960. }
  220961. }
  220962. }
  220963. }
  220964. void updateBounds()
  220965. {
  220966. jassert (windowH != 0);
  220967. if (windowH != 0)
  220968. {
  220969. Window root, child;
  220970. unsigned int bw, depth;
  220971. ScopedXLock xlock;
  220972. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220973. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220974. &bw, &depth))
  220975. {
  220976. wx = wy = ww = wh = 0;
  220977. }
  220978. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220979. {
  220980. wx = wy = 0;
  220981. }
  220982. }
  220983. }
  220984. void resetDragAndDrop()
  220985. {
  220986. dragAndDropFiles.clear();
  220987. lastDropPos = Point<int> (-1, -1);
  220988. dragAndDropCurrentMimeType = 0;
  220989. dragAndDropSourceWindow = 0;
  220990. srcMimeTypeAtomList.clear();
  220991. }
  220992. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220993. {
  220994. msg.type = ClientMessage;
  220995. msg.display = display;
  220996. msg.window = dragAndDropSourceWindow;
  220997. msg.format = 32;
  220998. msg.data.l[0] = windowH;
  220999. ScopedXLock xlock;
  221000. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221001. }
  221002. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221003. {
  221004. XClientMessageEvent msg;
  221005. zerostruct (msg);
  221006. msg.message_type = Atoms::XdndStatus;
  221007. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221008. msg.data.l[4] = dropAction;
  221009. sendDragAndDropMessage (msg);
  221010. }
  221011. void sendDragAndDropLeave()
  221012. {
  221013. XClientMessageEvent msg;
  221014. zerostruct (msg);
  221015. msg.message_type = Atoms::XdndLeave;
  221016. sendDragAndDropMessage (msg);
  221017. }
  221018. void sendDragAndDropFinish()
  221019. {
  221020. XClientMessageEvent msg;
  221021. zerostruct (msg);
  221022. msg.message_type = Atoms::XdndFinished;
  221023. sendDragAndDropMessage (msg);
  221024. }
  221025. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221026. {
  221027. if ((clientMsg->data.l[1] & 1) == 0)
  221028. {
  221029. sendDragAndDropLeave();
  221030. if (dragAndDropFiles.size() > 0)
  221031. handleFileDragExit (dragAndDropFiles);
  221032. dragAndDropFiles.clear();
  221033. }
  221034. }
  221035. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221036. {
  221037. if (dragAndDropSourceWindow == 0)
  221038. return;
  221039. dragAndDropSourceWindow = clientMsg->data.l[0];
  221040. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221041. (int) clientMsg->data.l[2] & 0xffff);
  221042. dropPos -= getScreenPosition();
  221043. if (lastDropPos != dropPos)
  221044. {
  221045. lastDropPos = dropPos;
  221046. dragAndDropTimestamp = clientMsg->data.l[3];
  221047. Atom targetAction = Atoms::XdndActionCopy;
  221048. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221049. {
  221050. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221051. {
  221052. targetAction = Atoms::allowedActions[i];
  221053. break;
  221054. }
  221055. }
  221056. sendDragAndDropStatus (true, targetAction);
  221057. if (dragAndDropFiles.size() == 0)
  221058. updateDraggedFileList (clientMsg);
  221059. if (dragAndDropFiles.size() > 0)
  221060. handleFileDragMove (dragAndDropFiles, dropPos);
  221061. }
  221062. }
  221063. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221064. {
  221065. if (dragAndDropFiles.size() == 0)
  221066. updateDraggedFileList (clientMsg);
  221067. const StringArray files (dragAndDropFiles);
  221068. const Point<int> lastPos (lastDropPos);
  221069. sendDragAndDropFinish();
  221070. resetDragAndDrop();
  221071. if (files.size() > 0)
  221072. handleFileDragDrop (files, lastPos);
  221073. }
  221074. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221075. {
  221076. dragAndDropFiles.clear();
  221077. srcMimeTypeAtomList.clear();
  221078. dragAndDropCurrentMimeType = 0;
  221079. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221080. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221081. {
  221082. dragAndDropSourceWindow = 0;
  221083. return;
  221084. }
  221085. dragAndDropSourceWindow = clientMsg->data.l[0];
  221086. if ((clientMsg->data.l[1] & 1) != 0)
  221087. {
  221088. Atom actual;
  221089. int format;
  221090. unsigned long count = 0, remaining = 0;
  221091. unsigned char* data = 0;
  221092. ScopedXLock xlock;
  221093. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221094. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221095. &count, &remaining, &data);
  221096. if (data != 0)
  221097. {
  221098. if (actual == XA_ATOM && format == 32 && count != 0)
  221099. {
  221100. const unsigned long* const types = (const unsigned long*) data;
  221101. for (unsigned int i = 0; i < count; ++i)
  221102. if (types[i] != None)
  221103. srcMimeTypeAtomList.add (types[i]);
  221104. }
  221105. XFree (data);
  221106. }
  221107. }
  221108. if (srcMimeTypeAtomList.size() == 0)
  221109. {
  221110. for (int i = 2; i < 5; ++i)
  221111. if (clientMsg->data.l[i] != None)
  221112. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221113. if (srcMimeTypeAtomList.size() == 0)
  221114. {
  221115. dragAndDropSourceWindow = 0;
  221116. return;
  221117. }
  221118. }
  221119. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221120. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221121. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221122. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221123. handleDragAndDropPosition (clientMsg);
  221124. }
  221125. void handleDragAndDropSelection (const XEvent* const evt)
  221126. {
  221127. dragAndDropFiles.clear();
  221128. if (evt->xselection.property != 0)
  221129. {
  221130. StringArray lines;
  221131. {
  221132. MemoryBlock dropData;
  221133. for (;;)
  221134. {
  221135. Atom actual;
  221136. uint8* data = 0;
  221137. unsigned long count = 0, remaining = 0;
  221138. int format = 0;
  221139. ScopedXLock xlock;
  221140. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221141. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221142. &format, &count, &remaining, &data) == Success)
  221143. {
  221144. dropData.append (data, count * format / 8);
  221145. XFree (data);
  221146. if (remaining == 0)
  221147. break;
  221148. }
  221149. else
  221150. {
  221151. XFree (data);
  221152. break;
  221153. }
  221154. }
  221155. lines.addLines (dropData.toString());
  221156. }
  221157. for (int i = 0; i < lines.size(); ++i)
  221158. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221159. dragAndDropFiles.trim();
  221160. dragAndDropFiles.removeEmptyStrings();
  221161. }
  221162. }
  221163. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221164. {
  221165. dragAndDropFiles.clear();
  221166. if (dragAndDropSourceWindow != None
  221167. && dragAndDropCurrentMimeType != 0)
  221168. {
  221169. dragAndDropTimestamp = clientMsg->data.l[2];
  221170. ScopedXLock xlock;
  221171. XConvertSelection (display,
  221172. Atoms::XdndSelection,
  221173. dragAndDropCurrentMimeType,
  221174. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221175. windowH,
  221176. dragAndDropTimestamp);
  221177. }
  221178. }
  221179. StringArray dragAndDropFiles;
  221180. int dragAndDropTimestamp;
  221181. Point<int> lastDropPos;
  221182. Atom dragAndDropCurrentMimeType;
  221183. Window dragAndDropSourceWindow;
  221184. Array <Atom> srcMimeTypeAtomList;
  221185. static int pointerMap[5];
  221186. static Point<int> lastMousePos;
  221187. static void clearLastMousePos() throw()
  221188. {
  221189. lastMousePos = Point<int> (0x100000, 0x100000);
  221190. }
  221191. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  221192. };
  221193. ModifierKeys LinuxComponentPeer::currentModifiers;
  221194. bool LinuxComponentPeer::isActiveApplication = false;
  221195. int LinuxComponentPeer::pointerMap[5];
  221196. Point<int> LinuxComponentPeer::lastMousePos;
  221197. bool Process::isForegroundProcess()
  221198. {
  221199. return LinuxComponentPeer::isActiveApplication;
  221200. }
  221201. void ModifierKeys::updateCurrentModifiers() throw()
  221202. {
  221203. currentModifiers = LinuxComponentPeer::currentModifiers;
  221204. }
  221205. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221206. {
  221207. Window root, child;
  221208. int x, y, winx, winy;
  221209. unsigned int mask;
  221210. int mouseMods = 0;
  221211. ScopedXLock xlock;
  221212. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221213. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221214. {
  221215. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221216. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221217. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221218. }
  221219. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221220. return LinuxComponentPeer::currentModifiers;
  221221. }
  221222. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221223. {
  221224. if (enableOrDisable)
  221225. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221226. }
  221227. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221228. {
  221229. return new LinuxComponentPeer (this, styleFlags);
  221230. }
  221231. // (this callback is hooked up in the messaging code)
  221232. void juce_windowMessageReceive (XEvent* event)
  221233. {
  221234. if (event->xany.window != None)
  221235. {
  221236. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221237. if (ComponentPeer::isValidPeer (peer))
  221238. peer->handleWindowMessage (event);
  221239. }
  221240. else
  221241. {
  221242. switch (event->xany.type)
  221243. {
  221244. case KeymapNotify:
  221245. {
  221246. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221247. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221248. break;
  221249. }
  221250. default:
  221251. break;
  221252. }
  221253. }
  221254. }
  221255. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221256. {
  221257. if (display == 0)
  221258. return;
  221259. #if JUCE_USE_XINERAMA
  221260. int major_opcode, first_event, first_error;
  221261. ScopedXLock xlock;
  221262. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221263. {
  221264. typedef Bool (*tXineramaIsActive) (Display*);
  221265. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221266. static tXineramaIsActive xXineramaIsActive = 0;
  221267. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221268. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221269. {
  221270. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221271. if (h == 0)
  221272. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221273. if (h != 0)
  221274. {
  221275. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221276. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221277. }
  221278. }
  221279. if (xXineramaIsActive != 0
  221280. && xXineramaQueryScreens != 0
  221281. && xXineramaIsActive (display))
  221282. {
  221283. int numMonitors = 0;
  221284. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221285. if (screens != 0)
  221286. {
  221287. for (int i = numMonitors; --i >= 0;)
  221288. {
  221289. int index = screens[i].screen_number;
  221290. if (index >= 0)
  221291. {
  221292. while (monitorCoords.size() < index)
  221293. monitorCoords.add (Rectangle<int>());
  221294. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221295. screens[i].y_org,
  221296. screens[i].width,
  221297. screens[i].height));
  221298. }
  221299. }
  221300. XFree (screens);
  221301. }
  221302. }
  221303. }
  221304. if (monitorCoords.size() == 0)
  221305. #endif
  221306. {
  221307. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221308. if (hints != None)
  221309. {
  221310. const int numMonitors = ScreenCount (display);
  221311. for (int i = 0; i < numMonitors; ++i)
  221312. {
  221313. Window root = RootWindow (display, i);
  221314. unsigned long nitems, bytesLeft;
  221315. Atom actualType;
  221316. int actualFormat;
  221317. unsigned char* data = 0;
  221318. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221319. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221320. &data) == Success)
  221321. {
  221322. const long* const position = (const long*) data;
  221323. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221324. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221325. position[2], position[3]));
  221326. XFree (data);
  221327. }
  221328. }
  221329. }
  221330. if (monitorCoords.size() == 0)
  221331. {
  221332. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221333. DisplayHeight (display, DefaultScreen (display))));
  221334. }
  221335. }
  221336. }
  221337. void Desktop::createMouseInputSources()
  221338. {
  221339. mouseSources.add (new MouseInputSource (0, true));
  221340. }
  221341. bool Desktop::canUseSemiTransparentWindows() throw()
  221342. {
  221343. int matchedDepth = 0;
  221344. const int desiredDepth = 32;
  221345. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221346. && (matchedDepth == desiredDepth);
  221347. }
  221348. const Point<int> MouseInputSource::getCurrentMousePosition()
  221349. {
  221350. Window root, child;
  221351. int x, y, winx, winy;
  221352. unsigned int mask;
  221353. ScopedXLock xlock;
  221354. if (XQueryPointer (display,
  221355. RootWindow (display, DefaultScreen (display)),
  221356. &root, &child,
  221357. &x, &y, &winx, &winy, &mask) == False)
  221358. {
  221359. // Pointer not on the default screen
  221360. x = y = -1;
  221361. }
  221362. return Point<int> (x, y);
  221363. }
  221364. void Desktop::setMousePosition (const Point<int>& newPosition)
  221365. {
  221366. ScopedXLock xlock;
  221367. Window root = RootWindow (display, DefaultScreen (display));
  221368. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221369. }
  221370. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  221371. {
  221372. return upright;
  221373. }
  221374. static bool screenSaverAllowed = true;
  221375. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221376. {
  221377. if (screenSaverAllowed != isEnabled)
  221378. {
  221379. screenSaverAllowed = isEnabled;
  221380. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221381. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221382. if (xScreenSaverSuspend == 0)
  221383. {
  221384. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221385. if (h != 0)
  221386. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221387. }
  221388. ScopedXLock xlock;
  221389. if (xScreenSaverSuspend != 0)
  221390. xScreenSaverSuspend (display, ! isEnabled);
  221391. }
  221392. }
  221393. bool Desktop::isScreenSaverEnabled()
  221394. {
  221395. return screenSaverAllowed;
  221396. }
  221397. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221398. {
  221399. ScopedXLock xlock;
  221400. const unsigned int imageW = image.getWidth();
  221401. const unsigned int imageH = image.getHeight();
  221402. #if JUCE_USE_XCURSOR
  221403. {
  221404. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221405. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221406. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221407. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221408. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221409. static tXcursorImageCreate xXcursorImageCreate = 0;
  221410. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221411. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221412. static bool hasBeenLoaded = false;
  221413. if (! hasBeenLoaded)
  221414. {
  221415. hasBeenLoaded = true;
  221416. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221417. if (h != 0)
  221418. {
  221419. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221420. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221421. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221422. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221423. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221424. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221425. || ! xXcursorSupportsARGB (display))
  221426. xXcursorSupportsARGB = 0;
  221427. }
  221428. }
  221429. if (xXcursorSupportsARGB != 0)
  221430. {
  221431. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221432. if (xcImage != 0)
  221433. {
  221434. xcImage->xhot = hotspotX;
  221435. xcImage->yhot = hotspotY;
  221436. XcursorPixel* dest = xcImage->pixels;
  221437. for (int y = 0; y < (int) imageH; ++y)
  221438. for (int x = 0; x < (int) imageW; ++x)
  221439. *dest++ = image.getPixelAt (x, y).getARGB();
  221440. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221441. xXcursorImageDestroy (xcImage);
  221442. if (result != 0)
  221443. return result;
  221444. }
  221445. }
  221446. }
  221447. #endif
  221448. Window root = RootWindow (display, DefaultScreen (display));
  221449. unsigned int cursorW, cursorH;
  221450. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221451. return 0;
  221452. Image im (Image::ARGB, cursorW, cursorH, true);
  221453. {
  221454. Graphics g (im);
  221455. if (imageW > cursorW || imageH > cursorH)
  221456. {
  221457. hotspotX = (hotspotX * cursorW) / imageW;
  221458. hotspotY = (hotspotY * cursorH) / imageH;
  221459. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221460. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221461. false);
  221462. }
  221463. else
  221464. {
  221465. g.drawImageAt (image, 0, 0);
  221466. }
  221467. }
  221468. const int stride = (cursorW + 7) >> 3;
  221469. HeapBlock <char> maskPlane, sourcePlane;
  221470. maskPlane.calloc (stride * cursorH);
  221471. sourcePlane.calloc (stride * cursorH);
  221472. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221473. for (int y = cursorH; --y >= 0;)
  221474. {
  221475. for (int x = cursorW; --x >= 0;)
  221476. {
  221477. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221478. const int offset = y * stride + (x >> 3);
  221479. const Colour c (im.getPixelAt (x, y));
  221480. if (c.getAlpha() >= 128)
  221481. maskPlane[offset] |= mask;
  221482. if (c.getBrightness() >= 0.5f)
  221483. sourcePlane[offset] |= mask;
  221484. }
  221485. }
  221486. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221487. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221488. XColor white, black;
  221489. black.red = black.green = black.blue = 0;
  221490. white.red = white.green = white.blue = 0xffff;
  221491. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221492. XFreePixmap (display, sourcePixmap);
  221493. XFreePixmap (display, maskPixmap);
  221494. return result;
  221495. }
  221496. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  221497. {
  221498. ScopedXLock xlock;
  221499. if (cursorHandle != 0)
  221500. XFreeCursor (display, (Cursor) cursorHandle);
  221501. }
  221502. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221503. {
  221504. unsigned int shape;
  221505. switch (type)
  221506. {
  221507. case NormalCursor: return None; // Use parent cursor
  221508. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221509. case WaitCursor: shape = XC_watch; break;
  221510. case IBeamCursor: shape = XC_xterm; break;
  221511. case PointingHandCursor: shape = XC_hand2; break;
  221512. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221513. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221514. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221515. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221516. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221517. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221518. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221519. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221520. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221521. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221522. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221523. case CrosshairCursor: shape = XC_crosshair; break;
  221524. case DraggingHandCursor:
  221525. {
  221526. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221527. 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,
  221528. 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 };
  221529. const int dragHandDataSize = 99;
  221530. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221531. }
  221532. case CopyingCursor:
  221533. {
  221534. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221535. 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,
  221536. 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,
  221537. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221538. const int copyCursorSize = 119;
  221539. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221540. }
  221541. default:
  221542. jassertfalse;
  221543. return None;
  221544. }
  221545. ScopedXLock xlock;
  221546. return (void*) XCreateFontCursor (display, shape);
  221547. }
  221548. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221549. {
  221550. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221551. if (lp != 0)
  221552. lp->showMouseCursor ((Cursor) getHandle());
  221553. }
  221554. void MouseCursor::showInAllWindows() const
  221555. {
  221556. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221557. showInWindow (ComponentPeer::getPeer (i));
  221558. }
  221559. const Image juce_createIconForFile (const File& file)
  221560. {
  221561. return Image::null;
  221562. }
  221563. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221564. {
  221565. return createSoftwareImage (format, width, height, clearImage);
  221566. }
  221567. #if JUCE_OPENGL
  221568. class WindowedGLContext : public OpenGLContext
  221569. {
  221570. public:
  221571. WindowedGLContext (Component* const component,
  221572. const OpenGLPixelFormat& pixelFormat_,
  221573. GLXContext sharedContext)
  221574. : renderContext (0),
  221575. embeddedWindow (0),
  221576. pixelFormat (pixelFormat_),
  221577. swapInterval (0)
  221578. {
  221579. jassert (component != 0);
  221580. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221581. if (peer == 0)
  221582. return;
  221583. ScopedXLock xlock;
  221584. XSync (display, False);
  221585. GLint attribs [64];
  221586. int n = 0;
  221587. attribs[n++] = GLX_RGBA;
  221588. attribs[n++] = GLX_DOUBLEBUFFER;
  221589. attribs[n++] = GLX_RED_SIZE;
  221590. attribs[n++] = pixelFormat.redBits;
  221591. attribs[n++] = GLX_GREEN_SIZE;
  221592. attribs[n++] = pixelFormat.greenBits;
  221593. attribs[n++] = GLX_BLUE_SIZE;
  221594. attribs[n++] = pixelFormat.blueBits;
  221595. attribs[n++] = GLX_ALPHA_SIZE;
  221596. attribs[n++] = pixelFormat.alphaBits;
  221597. attribs[n++] = GLX_DEPTH_SIZE;
  221598. attribs[n++] = pixelFormat.depthBufferBits;
  221599. attribs[n++] = GLX_STENCIL_SIZE;
  221600. attribs[n++] = pixelFormat.stencilBufferBits;
  221601. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221602. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221603. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221604. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221605. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221606. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221607. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221608. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221609. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221610. attribs[n++] = None;
  221611. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221612. if (bestVisual == 0)
  221613. return;
  221614. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221615. Window windowH = (Window) peer->getNativeHandle();
  221616. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221617. XSetWindowAttributes swa;
  221618. swa.colormap = colourMap;
  221619. swa.border_pixel = 0;
  221620. swa.event_mask = ExposureMask | StructureNotifyMask;
  221621. embeddedWindow = XCreateWindow (display, windowH,
  221622. 0, 0, 1, 1, 0,
  221623. bestVisual->depth,
  221624. InputOutput,
  221625. bestVisual->visual,
  221626. CWBorderPixel | CWColormap | CWEventMask,
  221627. &swa);
  221628. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221629. XMapWindow (display, embeddedWindow);
  221630. XFreeColormap (display, colourMap);
  221631. XFree (bestVisual);
  221632. XSync (display, False);
  221633. }
  221634. ~WindowedGLContext()
  221635. {
  221636. ScopedXLock xlock;
  221637. deleteContext();
  221638. XUnmapWindow (display, embeddedWindow);
  221639. XDestroyWindow (display, embeddedWindow);
  221640. }
  221641. void deleteContext()
  221642. {
  221643. makeInactive();
  221644. if (renderContext != 0)
  221645. {
  221646. ScopedXLock xlock;
  221647. glXDestroyContext (display, renderContext);
  221648. renderContext = 0;
  221649. }
  221650. }
  221651. bool makeActive() const throw()
  221652. {
  221653. jassert (renderContext != 0);
  221654. ScopedXLock xlock;
  221655. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221656. && XSync (display, False);
  221657. }
  221658. bool makeInactive() const throw()
  221659. {
  221660. ScopedXLock xlock;
  221661. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221662. }
  221663. bool isActive() const throw()
  221664. {
  221665. ScopedXLock xlock;
  221666. return glXGetCurrentContext() == renderContext;
  221667. }
  221668. const OpenGLPixelFormat getPixelFormat() const
  221669. {
  221670. return pixelFormat;
  221671. }
  221672. void* getRawContext() const throw()
  221673. {
  221674. return renderContext;
  221675. }
  221676. void updateWindowPosition (int x, int y, int w, int h, int)
  221677. {
  221678. ScopedXLock xlock;
  221679. XMoveResizeWindow (display, embeddedWindow,
  221680. x, y, jmax (1, w), jmax (1, h));
  221681. }
  221682. void swapBuffers()
  221683. {
  221684. ScopedXLock xlock;
  221685. glXSwapBuffers (display, embeddedWindow);
  221686. }
  221687. bool setSwapInterval (const int numFramesPerSwap)
  221688. {
  221689. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221690. if (GLXSwapIntervalSGI != 0)
  221691. {
  221692. swapInterval = numFramesPerSwap;
  221693. GLXSwapIntervalSGI (numFramesPerSwap);
  221694. return true;
  221695. }
  221696. return false;
  221697. }
  221698. int getSwapInterval() const
  221699. {
  221700. return swapInterval;
  221701. }
  221702. void repaint()
  221703. {
  221704. }
  221705. GLXContext renderContext;
  221706. private:
  221707. Window embeddedWindow;
  221708. OpenGLPixelFormat pixelFormat;
  221709. int swapInterval;
  221710. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221711. };
  221712. OpenGLContext* OpenGLComponent::createContext()
  221713. {
  221714. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221715. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221716. return (c->renderContext != 0) ? c.release() : 0;
  221717. }
  221718. void juce_glViewport (const int w, const int h)
  221719. {
  221720. glViewport (0, 0, w, h);
  221721. }
  221722. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221723. OwnedArray <OpenGLPixelFormat>& results)
  221724. {
  221725. results.add (new OpenGLPixelFormat()); // xxx
  221726. }
  221727. #endif
  221728. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221729. {
  221730. jassertfalse; // not implemented!
  221731. return false;
  221732. }
  221733. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221734. {
  221735. jassertfalse; // not implemented!
  221736. return false;
  221737. }
  221738. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221739. {
  221740. if (! isOnDesktop ())
  221741. addToDesktop (0);
  221742. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221743. if (wp != 0)
  221744. {
  221745. wp->setTaskBarIcon (newImage);
  221746. setVisible (true);
  221747. toFront (false);
  221748. repaint();
  221749. }
  221750. }
  221751. void SystemTrayIconComponent::paint (Graphics& g)
  221752. {
  221753. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221754. if (wp != 0)
  221755. {
  221756. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221757. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221758. false);
  221759. }
  221760. }
  221761. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221762. {
  221763. // xxx not yet implemented!
  221764. }
  221765. void PlatformUtilities::beep()
  221766. {
  221767. std::cout << "\a" << std::flush;
  221768. }
  221769. bool AlertWindow::showNativeDialogBox (const String& title,
  221770. const String& bodyText,
  221771. bool isOkCancel)
  221772. {
  221773. // use a non-native one for the time being..
  221774. if (isOkCancel)
  221775. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221776. else
  221777. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221778. return true;
  221779. }
  221780. const int KeyPress::spaceKey = XK_space & 0xff;
  221781. const int KeyPress::returnKey = XK_Return & 0xff;
  221782. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221783. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221784. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221785. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221786. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221787. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221788. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221789. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221790. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221791. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221792. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221793. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221794. const int KeyPress::tabKey = XK_Tab & 0xff;
  221795. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221796. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221797. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221798. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221799. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221800. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221801. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221802. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221803. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221804. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221805. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221806. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221807. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221808. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221809. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221810. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221811. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221812. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221813. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221814. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221815. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221816. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221817. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221818. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221819. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221820. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221821. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221822. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221823. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221824. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221825. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221826. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221827. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221828. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221829. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221830. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221831. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221832. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221833. #endif
  221834. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221835. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221836. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221837. // compiled on its own).
  221838. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221839. namespace
  221840. {
  221841. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221842. {
  221843. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221844. snd_pcm_hw_params_t* hwParams;
  221845. snd_pcm_hw_params_alloca (&hwParams);
  221846. for (int i = 0; ratesToTry[i] != 0; ++i)
  221847. {
  221848. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221849. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221850. {
  221851. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221852. }
  221853. }
  221854. }
  221855. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221856. {
  221857. snd_pcm_hw_params_t *params;
  221858. snd_pcm_hw_params_alloca (&params);
  221859. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221860. {
  221861. snd_pcm_hw_params_get_channels_min (params, minChans);
  221862. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221863. }
  221864. }
  221865. void getDeviceProperties (const String& deviceID,
  221866. unsigned int& minChansOut,
  221867. unsigned int& maxChansOut,
  221868. unsigned int& minChansIn,
  221869. unsigned int& maxChansIn,
  221870. Array <int>& rates)
  221871. {
  221872. if (deviceID.isEmpty())
  221873. return;
  221874. snd_ctl_t* handle;
  221875. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221876. {
  221877. snd_pcm_info_t* info;
  221878. snd_pcm_info_alloca (&info);
  221879. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221880. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221881. snd_pcm_info_set_subdevice (info, 0);
  221882. if (snd_ctl_pcm_info (handle, info) >= 0)
  221883. {
  221884. snd_pcm_t* pcmHandle;
  221885. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221886. {
  221887. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221888. getDeviceSampleRates (pcmHandle, rates);
  221889. snd_pcm_close (pcmHandle);
  221890. }
  221891. }
  221892. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221893. if (snd_ctl_pcm_info (handle, info) >= 0)
  221894. {
  221895. snd_pcm_t* pcmHandle;
  221896. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221897. {
  221898. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221899. if (rates.size() == 0)
  221900. getDeviceSampleRates (pcmHandle, rates);
  221901. snd_pcm_close (pcmHandle);
  221902. }
  221903. }
  221904. snd_ctl_close (handle);
  221905. }
  221906. }
  221907. }
  221908. class ALSADevice
  221909. {
  221910. public:
  221911. ALSADevice (const String& deviceID, bool forInput)
  221912. : handle (0),
  221913. bitDepth (16),
  221914. numChannelsRunning (0),
  221915. latency (0),
  221916. isInput (forInput),
  221917. isInterleaved (true)
  221918. {
  221919. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221920. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221921. SND_PCM_ASYNC));
  221922. }
  221923. ~ALSADevice()
  221924. {
  221925. if (handle != 0)
  221926. snd_pcm_close (handle);
  221927. }
  221928. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221929. {
  221930. if (handle == 0)
  221931. return false;
  221932. snd_pcm_hw_params_t* hwParams;
  221933. snd_pcm_hw_params_alloca (&hwParams);
  221934. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221935. return false;
  221936. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221937. isInterleaved = false;
  221938. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221939. isInterleaved = true;
  221940. else
  221941. {
  221942. jassertfalse;
  221943. return false;
  221944. }
  221945. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221946. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221947. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221948. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221949. SND_PCM_FORMAT_S32_BE, 32,
  221950. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221951. SND_PCM_FORMAT_S24_3BE, 24,
  221952. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221953. SND_PCM_FORMAT_S16_BE, 16 };
  221954. bitDepth = 0;
  221955. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221956. {
  221957. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221958. {
  221959. bitDepth = formatsToTry [i + 1] & 255;
  221960. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221961. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221962. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221963. break;
  221964. }
  221965. }
  221966. if (bitDepth == 0)
  221967. {
  221968. error = "device doesn't support a compatible PCM format";
  221969. DBG ("ALSA error: " + error + "\n");
  221970. return false;
  221971. }
  221972. int dir = 0;
  221973. unsigned int periods = 4;
  221974. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221975. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221976. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221977. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221978. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221979. || failed (snd_pcm_hw_params (handle, hwParams)))
  221980. {
  221981. return false;
  221982. }
  221983. snd_pcm_uframes_t frames = 0;
  221984. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221985. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221986. latency = 0;
  221987. else
  221988. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221989. snd_pcm_sw_params_t* swParams;
  221990. snd_pcm_sw_params_alloca (&swParams);
  221991. snd_pcm_uframes_t boundary;
  221992. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221993. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221994. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221995. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221996. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221997. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221998. || failed (snd_pcm_sw_params (handle, swParams)))
  221999. {
  222000. return false;
  222001. }
  222002. #if 0
  222003. // enable this to dump the config of the devices that get opened
  222004. snd_output_t* out;
  222005. snd_output_stdio_attach (&out, stderr, 0);
  222006. snd_pcm_hw_params_dump (hwParams, out);
  222007. snd_pcm_sw_params_dump (swParams, out);
  222008. #endif
  222009. numChannelsRunning = numChannels;
  222010. return true;
  222011. }
  222012. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222013. {
  222014. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222015. float** const data = outputChannelBuffer.getArrayOfChannels();
  222016. snd_pcm_sframes_t numDone = 0;
  222017. if (isInterleaved)
  222018. {
  222019. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222020. for (int i = 0; i < numChannelsRunning; ++i)
  222021. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222022. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222023. }
  222024. else
  222025. {
  222026. for (int i = 0; i < numChannelsRunning; ++i)
  222027. converter->convertSamples (data[i], data[i], numSamples);
  222028. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222029. }
  222030. if (failed (numDone))
  222031. {
  222032. if (numDone == -EPIPE)
  222033. {
  222034. if (failed (snd_pcm_prepare (handle)))
  222035. return false;
  222036. }
  222037. else if (numDone != -ESTRPIPE)
  222038. return false;
  222039. }
  222040. return true;
  222041. }
  222042. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222043. {
  222044. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222045. float** const data = inputChannelBuffer.getArrayOfChannels();
  222046. if (isInterleaved)
  222047. {
  222048. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222049. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  222050. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222051. if (failed (num))
  222052. {
  222053. if (num == -EPIPE)
  222054. {
  222055. if (failed (snd_pcm_prepare (handle)))
  222056. return false;
  222057. }
  222058. else if (num != -ESTRPIPE)
  222059. return false;
  222060. }
  222061. for (int i = 0; i < numChannelsRunning; ++i)
  222062. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222063. }
  222064. else
  222065. {
  222066. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222067. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222068. return false;
  222069. for (int i = 0; i < numChannelsRunning; ++i)
  222070. converter->convertSamples (data[i], data[i], numSamples);
  222071. }
  222072. return true;
  222073. }
  222074. snd_pcm_t* handle;
  222075. String error;
  222076. int bitDepth, numChannelsRunning, latency;
  222077. private:
  222078. const bool isInput;
  222079. bool isInterleaved;
  222080. MemoryBlock scratch;
  222081. ScopedPointer<AudioData::Converter> converter;
  222082. template <class SampleType>
  222083. struct ConverterHelper
  222084. {
  222085. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222086. {
  222087. if (forInput)
  222088. {
  222089. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222090. if (isLittleEndian)
  222091. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222092. else
  222093. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222094. }
  222095. else
  222096. {
  222097. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222098. if (isLittleEndian)
  222099. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222100. else
  222101. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222102. }
  222103. }
  222104. };
  222105. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222106. {
  222107. switch (bitDepth)
  222108. {
  222109. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222110. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222111. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222112. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222113. default: jassertfalse; break; // unsupported format!
  222114. }
  222115. return 0;
  222116. }
  222117. bool failed (const int errorNum)
  222118. {
  222119. if (errorNum >= 0)
  222120. return false;
  222121. error = snd_strerror (errorNum);
  222122. DBG ("ALSA error: " + error + "\n");
  222123. return true;
  222124. }
  222125. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  222126. };
  222127. class ALSAThread : public Thread
  222128. {
  222129. public:
  222130. ALSAThread (const String& inputId_,
  222131. const String& outputId_)
  222132. : Thread ("Juce ALSA"),
  222133. sampleRate (0),
  222134. bufferSize (0),
  222135. outputLatency (0),
  222136. inputLatency (0),
  222137. callback (0),
  222138. inputId (inputId_),
  222139. outputId (outputId_),
  222140. numCallbacks (0),
  222141. inputChannelBuffer (1, 1),
  222142. outputChannelBuffer (1, 1)
  222143. {
  222144. initialiseRatesAndChannels();
  222145. }
  222146. ~ALSAThread()
  222147. {
  222148. close();
  222149. }
  222150. void open (BigInteger inputChannels,
  222151. BigInteger outputChannels,
  222152. const double sampleRate_,
  222153. const int bufferSize_)
  222154. {
  222155. close();
  222156. error = String::empty;
  222157. sampleRate = sampleRate_;
  222158. bufferSize = bufferSize_;
  222159. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222160. inputChannelBuffer.clear();
  222161. inputChannelDataForCallback.clear();
  222162. currentInputChans.clear();
  222163. if (inputChannels.getHighestBit() >= 0)
  222164. {
  222165. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222166. {
  222167. if (inputChannels[i])
  222168. {
  222169. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222170. currentInputChans.setBit (i);
  222171. }
  222172. }
  222173. }
  222174. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222175. outputChannelBuffer.clear();
  222176. outputChannelDataForCallback.clear();
  222177. currentOutputChans.clear();
  222178. if (outputChannels.getHighestBit() >= 0)
  222179. {
  222180. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222181. {
  222182. if (outputChannels[i])
  222183. {
  222184. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222185. currentOutputChans.setBit (i);
  222186. }
  222187. }
  222188. }
  222189. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222190. {
  222191. outputDevice = new ALSADevice (outputId, false);
  222192. if (outputDevice->error.isNotEmpty())
  222193. {
  222194. error = outputDevice->error;
  222195. outputDevice = 0;
  222196. return;
  222197. }
  222198. currentOutputChans.setRange (0, minChansOut, true);
  222199. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222200. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222201. bufferSize))
  222202. {
  222203. error = outputDevice->error;
  222204. outputDevice = 0;
  222205. return;
  222206. }
  222207. outputLatency = outputDevice->latency;
  222208. }
  222209. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222210. {
  222211. inputDevice = new ALSADevice (inputId, true);
  222212. if (inputDevice->error.isNotEmpty())
  222213. {
  222214. error = inputDevice->error;
  222215. inputDevice = 0;
  222216. return;
  222217. }
  222218. currentInputChans.setRange (0, minChansIn, true);
  222219. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222220. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222221. bufferSize))
  222222. {
  222223. error = inputDevice->error;
  222224. inputDevice = 0;
  222225. return;
  222226. }
  222227. inputLatency = inputDevice->latency;
  222228. }
  222229. if (outputDevice == 0 && inputDevice == 0)
  222230. {
  222231. error = "no channels";
  222232. return;
  222233. }
  222234. if (outputDevice != 0 && inputDevice != 0)
  222235. {
  222236. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222237. }
  222238. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222239. return;
  222240. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222241. return;
  222242. startThread (9);
  222243. int count = 1000;
  222244. while (numCallbacks == 0)
  222245. {
  222246. sleep (5);
  222247. if (--count < 0 || ! isThreadRunning())
  222248. {
  222249. error = "device didn't start";
  222250. break;
  222251. }
  222252. }
  222253. }
  222254. void close()
  222255. {
  222256. stopThread (6000);
  222257. inputDevice = 0;
  222258. outputDevice = 0;
  222259. inputChannelBuffer.setSize (1, 1);
  222260. outputChannelBuffer.setSize (1, 1);
  222261. numCallbacks = 0;
  222262. }
  222263. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222264. {
  222265. const ScopedLock sl (callbackLock);
  222266. callback = newCallback;
  222267. }
  222268. void run()
  222269. {
  222270. while (! threadShouldExit())
  222271. {
  222272. if (inputDevice != 0)
  222273. {
  222274. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222275. {
  222276. DBG ("ALSA: read failure");
  222277. break;
  222278. }
  222279. }
  222280. if (threadShouldExit())
  222281. break;
  222282. {
  222283. const ScopedLock sl (callbackLock);
  222284. ++numCallbacks;
  222285. if (callback != 0)
  222286. {
  222287. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222288. inputChannelDataForCallback.size(),
  222289. outputChannelDataForCallback.getRawDataPointer(),
  222290. outputChannelDataForCallback.size(),
  222291. bufferSize);
  222292. }
  222293. else
  222294. {
  222295. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222296. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222297. }
  222298. }
  222299. if (outputDevice != 0)
  222300. {
  222301. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222302. if (threadShouldExit())
  222303. break;
  222304. failed (snd_pcm_avail_update (outputDevice->handle));
  222305. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222306. {
  222307. DBG ("ALSA: write failure");
  222308. break;
  222309. }
  222310. }
  222311. }
  222312. }
  222313. int getBitDepth() const throw()
  222314. {
  222315. if (outputDevice != 0)
  222316. return outputDevice->bitDepth;
  222317. if (inputDevice != 0)
  222318. return inputDevice->bitDepth;
  222319. return 16;
  222320. }
  222321. String error;
  222322. double sampleRate;
  222323. int bufferSize, outputLatency, inputLatency;
  222324. BigInteger currentInputChans, currentOutputChans;
  222325. Array <int> sampleRates;
  222326. StringArray channelNamesOut, channelNamesIn;
  222327. AudioIODeviceCallback* callback;
  222328. private:
  222329. const String inputId, outputId;
  222330. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222331. int numCallbacks;
  222332. CriticalSection callbackLock;
  222333. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222334. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222335. unsigned int minChansOut, maxChansOut;
  222336. unsigned int minChansIn, maxChansIn;
  222337. bool failed (const int errorNum)
  222338. {
  222339. if (errorNum >= 0)
  222340. return false;
  222341. error = snd_strerror (errorNum);
  222342. DBG ("ALSA error: " + error + "\n");
  222343. return true;
  222344. }
  222345. void initialiseRatesAndChannels()
  222346. {
  222347. sampleRates.clear();
  222348. channelNamesOut.clear();
  222349. channelNamesIn.clear();
  222350. minChansOut = 0;
  222351. maxChansOut = 0;
  222352. minChansIn = 0;
  222353. maxChansIn = 0;
  222354. unsigned int dummy = 0;
  222355. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222356. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222357. unsigned int i;
  222358. for (i = 0; i < maxChansOut; ++i)
  222359. channelNamesOut.add ("channel " + String ((int) i + 1));
  222360. for (i = 0; i < maxChansIn; ++i)
  222361. channelNamesIn.add ("channel " + String ((int) i + 1));
  222362. }
  222363. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  222364. };
  222365. class ALSAAudioIODevice : public AudioIODevice
  222366. {
  222367. public:
  222368. ALSAAudioIODevice (const String& deviceName,
  222369. const String& inputId_,
  222370. const String& outputId_)
  222371. : AudioIODevice (deviceName, "ALSA"),
  222372. inputId (inputId_),
  222373. outputId (outputId_),
  222374. isOpen_ (false),
  222375. isStarted (false),
  222376. internal (inputId_, outputId_)
  222377. {
  222378. }
  222379. ~ALSAAudioIODevice()
  222380. {
  222381. }
  222382. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222383. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222384. int getNumSampleRates() { return internal.sampleRates.size(); }
  222385. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222386. int getDefaultBufferSize() { return 512; }
  222387. int getNumBufferSizesAvailable() { return 50; }
  222388. int getBufferSizeSamples (int index)
  222389. {
  222390. int n = 16;
  222391. for (int i = 0; i < index; ++i)
  222392. n += n < 64 ? 16
  222393. : (n < 512 ? 32
  222394. : (n < 1024 ? 64
  222395. : (n < 2048 ? 128 : 256)));
  222396. return n;
  222397. }
  222398. const String open (const BigInteger& inputChannels,
  222399. const BigInteger& outputChannels,
  222400. double sampleRate,
  222401. int bufferSizeSamples)
  222402. {
  222403. close();
  222404. if (bufferSizeSamples <= 0)
  222405. bufferSizeSamples = getDefaultBufferSize();
  222406. if (sampleRate <= 0)
  222407. {
  222408. for (int i = 0; i < getNumSampleRates(); ++i)
  222409. {
  222410. if (getSampleRate (i) >= 44100)
  222411. {
  222412. sampleRate = getSampleRate (i);
  222413. break;
  222414. }
  222415. }
  222416. }
  222417. internal.open (inputChannels, outputChannels,
  222418. sampleRate, bufferSizeSamples);
  222419. isOpen_ = internal.error.isEmpty();
  222420. return internal.error;
  222421. }
  222422. void close()
  222423. {
  222424. stop();
  222425. internal.close();
  222426. isOpen_ = false;
  222427. }
  222428. bool isOpen() { return isOpen_; }
  222429. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222430. const String getLastError() { return internal.error; }
  222431. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222432. double getCurrentSampleRate() { return internal.sampleRate; }
  222433. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222434. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222435. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222436. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222437. int getInputLatencyInSamples() { return internal.inputLatency; }
  222438. void start (AudioIODeviceCallback* callback)
  222439. {
  222440. if (! isOpen_)
  222441. callback = 0;
  222442. if (callback != 0)
  222443. callback->audioDeviceAboutToStart (this);
  222444. internal.setCallback (callback);
  222445. isStarted = (callback != 0);
  222446. }
  222447. void stop()
  222448. {
  222449. AudioIODeviceCallback* const oldCallback = internal.callback;
  222450. start (0);
  222451. if (oldCallback != 0)
  222452. oldCallback->audioDeviceStopped();
  222453. }
  222454. String inputId, outputId;
  222455. private:
  222456. bool isOpen_, isStarted;
  222457. ALSAThread internal;
  222458. };
  222459. class ALSAAudioIODeviceType : public AudioIODeviceType
  222460. {
  222461. public:
  222462. ALSAAudioIODeviceType()
  222463. : AudioIODeviceType ("ALSA"),
  222464. hasScanned (false)
  222465. {
  222466. }
  222467. ~ALSAAudioIODeviceType()
  222468. {
  222469. }
  222470. void scanForDevices()
  222471. {
  222472. if (hasScanned)
  222473. return;
  222474. hasScanned = true;
  222475. inputNames.clear();
  222476. inputIds.clear();
  222477. outputNames.clear();
  222478. outputIds.clear();
  222479. /* void** hints = 0;
  222480. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222481. {
  222482. for (void** hint = hints; *hint != 0; ++hint)
  222483. {
  222484. const String name (getHint (*hint, "NAME"));
  222485. if (name.isNotEmpty())
  222486. {
  222487. const String ioid (getHint (*hint, "IOID"));
  222488. String desc (getHint (*hint, "DESC"));
  222489. if (desc.isEmpty())
  222490. desc = name;
  222491. desc = desc.replaceCharacters ("\n\r", " ");
  222492. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222493. if (ioid.isEmpty() || ioid == "Input")
  222494. {
  222495. inputNames.add (desc);
  222496. inputIds.add (name);
  222497. }
  222498. if (ioid.isEmpty() || ioid == "Output")
  222499. {
  222500. outputNames.add (desc);
  222501. outputIds.add (name);
  222502. }
  222503. }
  222504. }
  222505. snd_device_name_free_hint (hints);
  222506. }
  222507. */
  222508. snd_ctl_t* handle = 0;
  222509. snd_ctl_card_info_t* info = 0;
  222510. snd_ctl_card_info_alloca (&info);
  222511. int cardNum = -1;
  222512. while (outputIds.size() + inputIds.size() <= 32)
  222513. {
  222514. snd_card_next (&cardNum);
  222515. if (cardNum < 0)
  222516. break;
  222517. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222518. {
  222519. if (snd_ctl_card_info (handle, info) >= 0)
  222520. {
  222521. String cardId (snd_ctl_card_info_get_id (info));
  222522. if (cardId.removeCharacters ("0123456789").isEmpty())
  222523. cardId = String (cardNum);
  222524. int device = -1;
  222525. for (;;)
  222526. {
  222527. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222528. break;
  222529. String id, name;
  222530. id << "hw:" << cardId << ',' << device;
  222531. bool isInput, isOutput;
  222532. if (testDevice (id, isInput, isOutput))
  222533. {
  222534. name << snd_ctl_card_info_get_name (info);
  222535. if (name.isEmpty())
  222536. name = id;
  222537. if (isInput)
  222538. {
  222539. inputNames.add (name);
  222540. inputIds.add (id);
  222541. }
  222542. if (isOutput)
  222543. {
  222544. outputNames.add (name);
  222545. outputIds.add (id);
  222546. }
  222547. }
  222548. }
  222549. }
  222550. snd_ctl_close (handle);
  222551. }
  222552. }
  222553. inputNames.appendNumbersToDuplicates (false, true);
  222554. outputNames.appendNumbersToDuplicates (false, true);
  222555. }
  222556. const StringArray getDeviceNames (bool wantInputNames) const
  222557. {
  222558. jassert (hasScanned); // need to call scanForDevices() before doing this
  222559. return wantInputNames ? inputNames : outputNames;
  222560. }
  222561. int getDefaultDeviceIndex (bool forInput) const
  222562. {
  222563. jassert (hasScanned); // need to call scanForDevices() before doing this
  222564. return 0;
  222565. }
  222566. bool hasSeparateInputsAndOutputs() const { return true; }
  222567. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222568. {
  222569. jassert (hasScanned); // need to call scanForDevices() before doing this
  222570. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222571. if (d == 0)
  222572. return -1;
  222573. return asInput ? inputIds.indexOf (d->inputId)
  222574. : outputIds.indexOf (d->outputId);
  222575. }
  222576. AudioIODevice* createDevice (const String& outputDeviceName,
  222577. const String& inputDeviceName)
  222578. {
  222579. jassert (hasScanned); // need to call scanForDevices() before doing this
  222580. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222581. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222582. String deviceName (outputIndex >= 0 ? outputDeviceName
  222583. : inputDeviceName);
  222584. if (inputIndex >= 0 || outputIndex >= 0)
  222585. return new ALSAAudioIODevice (deviceName,
  222586. inputIds [inputIndex],
  222587. outputIds [outputIndex]);
  222588. return 0;
  222589. }
  222590. private:
  222591. StringArray inputNames, outputNames, inputIds, outputIds;
  222592. bool hasScanned;
  222593. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222594. {
  222595. unsigned int minChansOut = 0, maxChansOut = 0;
  222596. unsigned int minChansIn = 0, maxChansIn = 0;
  222597. Array <int> rates;
  222598. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222599. DBG ("ALSA device: " + id
  222600. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222601. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222602. + " rates=" + String (rates.size()));
  222603. isInput = maxChansIn > 0;
  222604. isOutput = maxChansOut > 0;
  222605. return (isInput || isOutput) && rates.size() > 0;
  222606. }
  222607. /*static const String getHint (void* hint, const char* type)
  222608. {
  222609. char* const n = snd_device_name_get_hint (hint, type);
  222610. const String s ((const char*) n);
  222611. free (n);
  222612. return s;
  222613. }*/
  222614. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222615. };
  222616. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222617. {
  222618. return new ALSAAudioIODeviceType();
  222619. }
  222620. #endif
  222621. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222622. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222623. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222624. // compiled on its own).
  222625. #ifdef JUCE_INCLUDED_FILE
  222626. #if JUCE_JACK
  222627. static void* juce_libjack_handle = 0;
  222628. void* juce_load_jack_function (const char* const name)
  222629. {
  222630. if (juce_libjack_handle == 0)
  222631. return 0;
  222632. return dlsym (juce_libjack_handle, name);
  222633. }
  222634. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222635. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222636. return_type fn_name argument_types { \
  222637. static fn_name##_ptr_t fn = 0; \
  222638. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222639. if (fn) return (*fn)arguments; \
  222640. else return 0; \
  222641. }
  222642. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222643. typedef void (*fn_name##_ptr_t)argument_types; \
  222644. void fn_name argument_types { \
  222645. static fn_name##_ptr_t fn = 0; \
  222646. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222647. if (fn) (*fn)arguments; \
  222648. }
  222649. 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));
  222650. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222651. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222652. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222653. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222654. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222655. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222656. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222657. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222658. 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));
  222659. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222660. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222661. 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));
  222662. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222663. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222664. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222665. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222666. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222667. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222668. #if JUCE_DEBUG
  222669. #define JACK_LOGGING_ENABLED 1
  222670. #endif
  222671. #if JACK_LOGGING_ENABLED
  222672. namespace
  222673. {
  222674. void jack_Log (const String& s)
  222675. {
  222676. std::cerr << s << std::endl;
  222677. }
  222678. void dumpJackErrorMessage (const jack_status_t status)
  222679. {
  222680. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222681. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222682. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222683. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222684. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222685. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222686. }
  222687. }
  222688. #else
  222689. #define dumpJackErrorMessage(a) {}
  222690. #define jack_Log(...) {}
  222691. #endif
  222692. #ifndef JUCE_JACK_CLIENT_NAME
  222693. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222694. #endif
  222695. class JackAudioIODevice : public AudioIODevice
  222696. {
  222697. public:
  222698. JackAudioIODevice (const String& deviceName,
  222699. const String& inputId_,
  222700. const String& outputId_)
  222701. : AudioIODevice (deviceName, "JACK"),
  222702. inputId (inputId_),
  222703. outputId (outputId_),
  222704. isOpen_ (false),
  222705. callback (0),
  222706. totalNumberOfInputChannels (0),
  222707. totalNumberOfOutputChannels (0)
  222708. {
  222709. jassert (deviceName.isNotEmpty());
  222710. jack_status_t status;
  222711. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222712. if (client == 0)
  222713. {
  222714. dumpJackErrorMessage (status);
  222715. }
  222716. else
  222717. {
  222718. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222719. // open input ports
  222720. const StringArray inputChannels (getInputChannelNames());
  222721. for (int i = 0; i < inputChannels.size(); i++)
  222722. {
  222723. String inputName;
  222724. inputName << "in_" << ++totalNumberOfInputChannels;
  222725. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222726. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222727. }
  222728. // open output ports
  222729. const StringArray outputChannels (getOutputChannelNames());
  222730. for (int i = 0; i < outputChannels.size (); i++)
  222731. {
  222732. String outputName;
  222733. outputName << "out_" << ++totalNumberOfOutputChannels;
  222734. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222735. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222736. }
  222737. inChans.calloc (totalNumberOfInputChannels + 2);
  222738. outChans.calloc (totalNumberOfOutputChannels + 2);
  222739. }
  222740. }
  222741. ~JackAudioIODevice()
  222742. {
  222743. close();
  222744. if (client != 0)
  222745. {
  222746. JUCE_NAMESPACE::jack_client_close (client);
  222747. client = 0;
  222748. }
  222749. }
  222750. const StringArray getChannelNames (bool forInput) const
  222751. {
  222752. StringArray names;
  222753. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222754. forInput ? JackPortIsInput : JackPortIsOutput);
  222755. if (ports != 0)
  222756. {
  222757. int j = 0;
  222758. while (ports[j] != 0)
  222759. {
  222760. const String portName (ports [j++]);
  222761. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222762. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222763. }
  222764. free (ports);
  222765. }
  222766. return names;
  222767. }
  222768. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222769. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222770. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222771. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222772. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222773. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222774. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222775. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222776. double sampleRate, int bufferSizeSamples)
  222777. {
  222778. if (client == 0)
  222779. {
  222780. lastError = "No JACK client running";
  222781. return lastError;
  222782. }
  222783. lastError = String::empty;
  222784. close();
  222785. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222786. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222787. JUCE_NAMESPACE::jack_activate (client);
  222788. isOpen_ = true;
  222789. if (! inputChannels.isZero())
  222790. {
  222791. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222792. if (ports != 0)
  222793. {
  222794. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222795. for (int i = 0; i < numInputChannels; ++i)
  222796. {
  222797. const String portName (ports[i]);
  222798. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222799. {
  222800. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222801. if (error != 0)
  222802. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222803. }
  222804. }
  222805. free (ports);
  222806. }
  222807. }
  222808. if (! outputChannels.isZero())
  222809. {
  222810. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222811. if (ports != 0)
  222812. {
  222813. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222814. for (int i = 0; i < numOutputChannels; ++i)
  222815. {
  222816. const String portName (ports[i]);
  222817. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222818. {
  222819. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222820. if (error != 0)
  222821. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222822. }
  222823. }
  222824. free (ports);
  222825. }
  222826. }
  222827. return lastError;
  222828. }
  222829. void close()
  222830. {
  222831. stop();
  222832. if (client != 0)
  222833. {
  222834. JUCE_NAMESPACE::jack_deactivate (client);
  222835. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222836. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222837. }
  222838. isOpen_ = false;
  222839. }
  222840. void start (AudioIODeviceCallback* newCallback)
  222841. {
  222842. if (isOpen_ && newCallback != callback)
  222843. {
  222844. if (newCallback != 0)
  222845. newCallback->audioDeviceAboutToStart (this);
  222846. AudioIODeviceCallback* const oldCallback = callback;
  222847. {
  222848. const ScopedLock sl (callbackLock);
  222849. callback = newCallback;
  222850. }
  222851. if (oldCallback != 0)
  222852. oldCallback->audioDeviceStopped();
  222853. }
  222854. }
  222855. void stop()
  222856. {
  222857. start (0);
  222858. }
  222859. bool isOpen() { return isOpen_; }
  222860. bool isPlaying() { return callback != 0; }
  222861. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222862. double getCurrentSampleRate() { return getSampleRate (0); }
  222863. int getCurrentBitDepth() { return 32; }
  222864. const String getLastError() { return lastError; }
  222865. const BigInteger getActiveOutputChannels() const
  222866. {
  222867. BigInteger outputBits;
  222868. for (int i = 0; i < outputPorts.size(); i++)
  222869. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222870. outputBits.setBit (i);
  222871. return outputBits;
  222872. }
  222873. const BigInteger getActiveInputChannels() const
  222874. {
  222875. BigInteger inputBits;
  222876. for (int i = 0; i < inputPorts.size(); i++)
  222877. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222878. inputBits.setBit (i);
  222879. return inputBits;
  222880. }
  222881. int getOutputLatencyInSamples()
  222882. {
  222883. int latency = 0;
  222884. for (int i = 0; i < outputPorts.size(); i++)
  222885. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222886. return latency;
  222887. }
  222888. int getInputLatencyInSamples()
  222889. {
  222890. int latency = 0;
  222891. for (int i = 0; i < inputPorts.size(); i++)
  222892. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222893. return latency;
  222894. }
  222895. String inputId, outputId;
  222896. private:
  222897. void process (const int numSamples)
  222898. {
  222899. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222900. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222901. {
  222902. jack_default_audio_sample_t* in
  222903. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222904. if (in != 0)
  222905. inChans [numActiveInChans++] = (float*) in;
  222906. }
  222907. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222908. {
  222909. jack_default_audio_sample_t* out
  222910. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222911. if (out != 0)
  222912. outChans [numActiveOutChans++] = (float*) out;
  222913. }
  222914. const ScopedLock sl (callbackLock);
  222915. if (callback != 0)
  222916. {
  222917. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222918. outChans, numActiveOutChans, numSamples);
  222919. }
  222920. else
  222921. {
  222922. for (i = 0; i < numActiveOutChans; ++i)
  222923. zeromem (outChans[i], sizeof (float) * numSamples);
  222924. }
  222925. }
  222926. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222927. {
  222928. if (callbackArgument != 0)
  222929. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222930. return 0;
  222931. }
  222932. static void threadInitCallback (void* callbackArgument)
  222933. {
  222934. jack_Log ("JackAudioIODevice::initialise");
  222935. }
  222936. static void shutdownCallback (void* callbackArgument)
  222937. {
  222938. jack_Log ("JackAudioIODevice::shutdown");
  222939. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222940. if (device != 0)
  222941. {
  222942. device->client = 0;
  222943. device->close();
  222944. }
  222945. }
  222946. static void errorCallback (const char* msg)
  222947. {
  222948. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222949. }
  222950. bool isOpen_;
  222951. jack_client_t* client;
  222952. String lastError;
  222953. AudioIODeviceCallback* callback;
  222954. CriticalSection callbackLock;
  222955. HeapBlock <float*> inChans, outChans;
  222956. int totalNumberOfInputChannels;
  222957. int totalNumberOfOutputChannels;
  222958. Array<void*> inputPorts, outputPorts;
  222959. };
  222960. class JackAudioIODeviceType : public AudioIODeviceType
  222961. {
  222962. public:
  222963. JackAudioIODeviceType()
  222964. : AudioIODeviceType ("JACK"),
  222965. hasScanned (false)
  222966. {
  222967. }
  222968. ~JackAudioIODeviceType()
  222969. {
  222970. }
  222971. void scanForDevices()
  222972. {
  222973. hasScanned = true;
  222974. inputNames.clear();
  222975. inputIds.clear();
  222976. outputNames.clear();
  222977. outputIds.clear();
  222978. if (juce_libjack_handle == 0)
  222979. {
  222980. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222981. if (juce_libjack_handle == 0)
  222982. return;
  222983. }
  222984. // open a dummy client
  222985. jack_status_t status;
  222986. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222987. if (client == 0)
  222988. {
  222989. dumpJackErrorMessage (status);
  222990. }
  222991. else
  222992. {
  222993. // scan for output devices
  222994. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222995. if (ports != 0)
  222996. {
  222997. int j = 0;
  222998. while (ports[j] != 0)
  222999. {
  223000. String clientName (ports[j]);
  223001. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223002. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223003. && ! inputNames.contains (clientName))
  223004. {
  223005. inputNames.add (clientName);
  223006. inputIds.add (ports [j]);
  223007. }
  223008. ++j;
  223009. }
  223010. free (ports);
  223011. }
  223012. // scan for input devices
  223013. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223014. if (ports != 0)
  223015. {
  223016. int j = 0;
  223017. while (ports[j] != 0)
  223018. {
  223019. String clientName (ports[j]);
  223020. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223021. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223022. && ! outputNames.contains (clientName))
  223023. {
  223024. outputNames.add (clientName);
  223025. outputIds.add (ports [j]);
  223026. }
  223027. ++j;
  223028. }
  223029. free (ports);
  223030. }
  223031. JUCE_NAMESPACE::jack_client_close (client);
  223032. }
  223033. }
  223034. const StringArray getDeviceNames (bool wantInputNames) const
  223035. {
  223036. jassert (hasScanned); // need to call scanForDevices() before doing this
  223037. return wantInputNames ? inputNames : outputNames;
  223038. }
  223039. int getDefaultDeviceIndex (bool forInput) const
  223040. {
  223041. jassert (hasScanned); // need to call scanForDevices() before doing this
  223042. return 0;
  223043. }
  223044. bool hasSeparateInputsAndOutputs() const { return true; }
  223045. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223046. {
  223047. jassert (hasScanned); // need to call scanForDevices() before doing this
  223048. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223049. if (d == 0)
  223050. return -1;
  223051. return asInput ? inputIds.indexOf (d->inputId)
  223052. : outputIds.indexOf (d->outputId);
  223053. }
  223054. AudioIODevice* createDevice (const String& outputDeviceName,
  223055. const String& inputDeviceName)
  223056. {
  223057. jassert (hasScanned); // need to call scanForDevices() before doing this
  223058. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223059. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223060. if (inputIndex >= 0 || outputIndex >= 0)
  223061. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223062. : inputDeviceName,
  223063. inputIds [inputIndex],
  223064. outputIds [outputIndex]);
  223065. return 0;
  223066. }
  223067. private:
  223068. StringArray inputNames, outputNames, inputIds, outputIds;
  223069. bool hasScanned;
  223070. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  223071. };
  223072. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223073. {
  223074. return new JackAudioIODeviceType();
  223075. }
  223076. #else // if JACK is turned off..
  223077. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223078. #endif
  223079. #endif
  223080. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223081. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223082. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223083. // compiled on its own).
  223084. #if JUCE_INCLUDED_FILE
  223085. #if JUCE_ALSA
  223086. namespace
  223087. {
  223088. snd_seq_t* iterateMidiDevices (const bool forInput,
  223089. StringArray& deviceNamesFound,
  223090. const int deviceIndexToOpen)
  223091. {
  223092. snd_seq_t* returnedHandle = 0;
  223093. snd_seq_t* seqHandle;
  223094. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223095. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223096. {
  223097. snd_seq_system_info_t* systemInfo;
  223098. snd_seq_client_info_t* clientInfo;
  223099. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223100. {
  223101. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223102. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223103. {
  223104. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223105. while (--numClients >= 0 && returnedHandle == 0)
  223106. {
  223107. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223108. {
  223109. snd_seq_port_info_t* portInfo;
  223110. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223111. {
  223112. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223113. const int client = snd_seq_client_info_get_client (clientInfo);
  223114. snd_seq_port_info_set_client (portInfo, client);
  223115. snd_seq_port_info_set_port (portInfo, -1);
  223116. while (--numPorts >= 0)
  223117. {
  223118. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223119. && (snd_seq_port_info_get_capability (portInfo)
  223120. & (forInput ? SND_SEQ_PORT_CAP_READ
  223121. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223122. {
  223123. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223124. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223125. {
  223126. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223127. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223128. if (sourcePort != -1)
  223129. {
  223130. snd_seq_set_client_name (seqHandle,
  223131. forInput ? "Juce Midi Input"
  223132. : "Juce Midi Output");
  223133. const int portId
  223134. = snd_seq_create_simple_port (seqHandle,
  223135. forInput ? "Juce Midi In Port"
  223136. : "Juce Midi Out Port",
  223137. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223138. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223139. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223140. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223141. returnedHandle = seqHandle;
  223142. }
  223143. }
  223144. }
  223145. }
  223146. snd_seq_port_info_free (portInfo);
  223147. }
  223148. }
  223149. }
  223150. snd_seq_client_info_free (clientInfo);
  223151. }
  223152. snd_seq_system_info_free (systemInfo);
  223153. }
  223154. if (returnedHandle == 0)
  223155. snd_seq_close (seqHandle);
  223156. }
  223157. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223158. return returnedHandle;
  223159. }
  223160. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223161. {
  223162. snd_seq_t* seqHandle = 0;
  223163. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223164. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223165. {
  223166. snd_seq_set_client_name (seqHandle,
  223167. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223168. const int portId
  223169. = snd_seq_create_simple_port (seqHandle,
  223170. forInput ? "in"
  223171. : "out",
  223172. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223173. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223174. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223175. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223176. if (portId < 0)
  223177. {
  223178. snd_seq_close (seqHandle);
  223179. seqHandle = 0;
  223180. }
  223181. }
  223182. return seqHandle;
  223183. }
  223184. }
  223185. class MidiOutputDevice
  223186. {
  223187. public:
  223188. MidiOutputDevice (MidiOutput* const midiOutput_,
  223189. snd_seq_t* const seqHandle_)
  223190. :
  223191. midiOutput (midiOutput_),
  223192. seqHandle (seqHandle_),
  223193. maxEventSize (16 * 1024)
  223194. {
  223195. jassert (seqHandle != 0 && midiOutput != 0);
  223196. snd_midi_event_new (maxEventSize, &midiParser);
  223197. }
  223198. ~MidiOutputDevice()
  223199. {
  223200. snd_midi_event_free (midiParser);
  223201. snd_seq_close (seqHandle);
  223202. }
  223203. void sendMessageNow (const MidiMessage& message)
  223204. {
  223205. if (message.getRawDataSize() > maxEventSize)
  223206. {
  223207. maxEventSize = message.getRawDataSize();
  223208. snd_midi_event_free (midiParser);
  223209. snd_midi_event_new (maxEventSize, &midiParser);
  223210. }
  223211. snd_seq_event_t event;
  223212. snd_seq_ev_clear (&event);
  223213. snd_midi_event_encode (midiParser,
  223214. message.getRawData(),
  223215. message.getRawDataSize(),
  223216. &event);
  223217. snd_midi_event_reset_encode (midiParser);
  223218. snd_seq_ev_set_source (&event, 0);
  223219. snd_seq_ev_set_subs (&event);
  223220. snd_seq_ev_set_direct (&event);
  223221. snd_seq_event_output (seqHandle, &event);
  223222. snd_seq_drain_output (seqHandle);
  223223. }
  223224. private:
  223225. MidiOutput* const midiOutput;
  223226. snd_seq_t* const seqHandle;
  223227. snd_midi_event_t* midiParser;
  223228. int maxEventSize;
  223229. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  223230. };
  223231. const StringArray MidiOutput::getDevices()
  223232. {
  223233. StringArray devices;
  223234. iterateMidiDevices (false, devices, -1);
  223235. return devices;
  223236. }
  223237. int MidiOutput::getDefaultDeviceIndex()
  223238. {
  223239. return 0;
  223240. }
  223241. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223242. {
  223243. MidiOutput* newDevice = 0;
  223244. StringArray devices;
  223245. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223246. if (handle != 0)
  223247. {
  223248. newDevice = new MidiOutput();
  223249. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223250. }
  223251. return newDevice;
  223252. }
  223253. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223254. {
  223255. MidiOutput* newDevice = 0;
  223256. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223257. if (handle != 0)
  223258. {
  223259. newDevice = new MidiOutput();
  223260. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223261. }
  223262. return newDevice;
  223263. }
  223264. MidiOutput::~MidiOutput()
  223265. {
  223266. delete static_cast <MidiOutputDevice*> (internal);
  223267. }
  223268. void MidiOutput::reset()
  223269. {
  223270. }
  223271. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223272. {
  223273. return false;
  223274. }
  223275. void MidiOutput::setVolume (float leftVol, float rightVol)
  223276. {
  223277. }
  223278. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223279. {
  223280. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223281. }
  223282. class MidiInputThread : public Thread
  223283. {
  223284. public:
  223285. MidiInputThread (MidiInput* const midiInput_,
  223286. snd_seq_t* const seqHandle_,
  223287. MidiInputCallback* const callback_)
  223288. : Thread ("Juce MIDI Input"),
  223289. midiInput (midiInput_),
  223290. seqHandle (seqHandle_),
  223291. callback (callback_)
  223292. {
  223293. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223294. }
  223295. ~MidiInputThread()
  223296. {
  223297. snd_seq_close (seqHandle);
  223298. }
  223299. void run()
  223300. {
  223301. const int maxEventSize = 16 * 1024;
  223302. snd_midi_event_t* midiParser;
  223303. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223304. {
  223305. HeapBlock <uint8> buffer (maxEventSize);
  223306. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223307. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223308. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223309. while (! threadShouldExit())
  223310. {
  223311. if (poll (pfd, numPfds, 500) > 0)
  223312. {
  223313. snd_seq_event_t* inputEvent = 0;
  223314. snd_seq_nonblock (seqHandle, 1);
  223315. do
  223316. {
  223317. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223318. {
  223319. // xxx what about SYSEXes that are too big for the buffer?
  223320. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223321. snd_midi_event_reset_decode (midiParser);
  223322. if (numBytes > 0)
  223323. {
  223324. const MidiMessage message ((const uint8*) buffer,
  223325. numBytes,
  223326. Time::getMillisecondCounter() * 0.001);
  223327. callback->handleIncomingMidiMessage (midiInput, message);
  223328. }
  223329. snd_seq_free_event (inputEvent);
  223330. }
  223331. }
  223332. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223333. snd_seq_free_event (inputEvent);
  223334. }
  223335. }
  223336. snd_midi_event_free (midiParser);
  223337. }
  223338. };
  223339. private:
  223340. MidiInput* const midiInput;
  223341. snd_seq_t* const seqHandle;
  223342. MidiInputCallback* const callback;
  223343. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  223344. };
  223345. MidiInput::MidiInput (const String& name_)
  223346. : name (name_),
  223347. internal (0)
  223348. {
  223349. }
  223350. MidiInput::~MidiInput()
  223351. {
  223352. stop();
  223353. delete static_cast <MidiInputThread*> (internal);
  223354. }
  223355. void MidiInput::start()
  223356. {
  223357. static_cast <MidiInputThread*> (internal)->startThread();
  223358. }
  223359. void MidiInput::stop()
  223360. {
  223361. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223362. }
  223363. int MidiInput::getDefaultDeviceIndex()
  223364. {
  223365. return 0;
  223366. }
  223367. const StringArray MidiInput::getDevices()
  223368. {
  223369. StringArray devices;
  223370. iterateMidiDevices (true, devices, -1);
  223371. return devices;
  223372. }
  223373. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223374. {
  223375. MidiInput* newDevice = 0;
  223376. StringArray devices;
  223377. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223378. if (handle != 0)
  223379. {
  223380. newDevice = new MidiInput (devices [deviceIndex]);
  223381. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223382. }
  223383. return newDevice;
  223384. }
  223385. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223386. {
  223387. MidiInput* newDevice = 0;
  223388. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223389. if (handle != 0)
  223390. {
  223391. newDevice = new MidiInput (deviceName);
  223392. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223393. }
  223394. return newDevice;
  223395. }
  223396. #else
  223397. // (These are just stub functions if ALSA is unavailable...)
  223398. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223399. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223400. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223401. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223402. MidiOutput::~MidiOutput() {}
  223403. void MidiOutput::reset() {}
  223404. bool MidiOutput::getVolume (float&, float&) { return false; }
  223405. void MidiOutput::setVolume (float, float) {}
  223406. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223407. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223408. MidiInput::~MidiInput() {}
  223409. void MidiInput::start() {}
  223410. void MidiInput::stop() {}
  223411. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223412. const StringArray MidiInput::getDevices() { return StringArray(); }
  223413. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223414. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223415. #endif
  223416. #endif
  223417. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223418. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223419. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223420. // compiled on its own).
  223421. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223422. AudioCDReader::AudioCDReader()
  223423. : AudioFormatReader (0, "CD Audio")
  223424. {
  223425. }
  223426. const StringArray AudioCDReader::getAvailableCDNames()
  223427. {
  223428. StringArray names;
  223429. return names;
  223430. }
  223431. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223432. {
  223433. return 0;
  223434. }
  223435. AudioCDReader::~AudioCDReader()
  223436. {
  223437. }
  223438. void AudioCDReader::refreshTrackLengths()
  223439. {
  223440. }
  223441. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223442. int64 startSampleInFile, int numSamples)
  223443. {
  223444. return false;
  223445. }
  223446. bool AudioCDReader::isCDStillPresent() const
  223447. {
  223448. return false;
  223449. }
  223450. bool AudioCDReader::isTrackAudio (int trackNum) const
  223451. {
  223452. return false;
  223453. }
  223454. void AudioCDReader::enableIndexScanning (bool b)
  223455. {
  223456. }
  223457. int AudioCDReader::getLastIndex() const
  223458. {
  223459. return 0;
  223460. }
  223461. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223462. {
  223463. return Array<int>();
  223464. }
  223465. #endif
  223466. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223467. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223468. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223469. // compiled on its own).
  223470. #if JUCE_INCLUDED_FILE
  223471. void FileChooser::showPlatformDialog (Array<File>& results,
  223472. const String& title,
  223473. const File& file,
  223474. const String& filters,
  223475. bool isDirectory,
  223476. bool selectsFiles,
  223477. bool isSave,
  223478. bool warnAboutOverwritingExistingFiles,
  223479. bool selectMultipleFiles,
  223480. FilePreviewComponent* previewComponent)
  223481. {
  223482. const String separator (":");
  223483. String command ("zenity --file-selection");
  223484. if (title.isNotEmpty())
  223485. command << " --title=\"" << title << "\"";
  223486. if (file != File::nonexistent)
  223487. command << " --filename=\"" << file.getFullPathName () << "\"";
  223488. if (isDirectory)
  223489. command << " --directory";
  223490. if (isSave)
  223491. command << " --save";
  223492. if (selectMultipleFiles)
  223493. command << " --multiple --separator=\"" << separator << "\"";
  223494. command << " 2>&1";
  223495. MemoryOutputStream result;
  223496. int status = -1;
  223497. FILE* stream = popen (command.toUTF8(), "r");
  223498. if (stream != 0)
  223499. {
  223500. for (;;)
  223501. {
  223502. char buffer [1024];
  223503. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223504. if (bytesRead <= 0)
  223505. break;
  223506. result.write (buffer, bytesRead);
  223507. }
  223508. status = pclose (stream);
  223509. }
  223510. if (status == 0)
  223511. {
  223512. StringArray tokens;
  223513. if (selectMultipleFiles)
  223514. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223515. else
  223516. tokens.add (result.toUTF8());
  223517. for (int i = 0; i < tokens.size(); i++)
  223518. results.add (File (tokens[i]));
  223519. return;
  223520. }
  223521. //xxx ain't got one!
  223522. jassertfalse;
  223523. }
  223524. #endif
  223525. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223526. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223527. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223528. // compiled on its own).
  223529. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223530. /*
  223531. Sorry.. This class isn't implemented on Linux!
  223532. */
  223533. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223534. : browser (0),
  223535. blankPageShown (false),
  223536. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223537. {
  223538. setOpaque (true);
  223539. }
  223540. WebBrowserComponent::~WebBrowserComponent()
  223541. {
  223542. }
  223543. void WebBrowserComponent::goToURL (const String& url,
  223544. const StringArray* headers,
  223545. const MemoryBlock* postData)
  223546. {
  223547. lastURL = url;
  223548. lastHeaders.clear();
  223549. if (headers != 0)
  223550. lastHeaders = *headers;
  223551. lastPostData.setSize (0);
  223552. if (postData != 0)
  223553. lastPostData = *postData;
  223554. blankPageShown = false;
  223555. }
  223556. void WebBrowserComponent::stop()
  223557. {
  223558. }
  223559. void WebBrowserComponent::goBack()
  223560. {
  223561. lastURL = String::empty;
  223562. blankPageShown = false;
  223563. }
  223564. void WebBrowserComponent::goForward()
  223565. {
  223566. lastURL = String::empty;
  223567. }
  223568. void WebBrowserComponent::refresh()
  223569. {
  223570. }
  223571. void WebBrowserComponent::paint (Graphics& g)
  223572. {
  223573. g.fillAll (Colours::white);
  223574. }
  223575. void WebBrowserComponent::checkWindowAssociation()
  223576. {
  223577. }
  223578. void WebBrowserComponent::reloadLastURL()
  223579. {
  223580. if (lastURL.isNotEmpty())
  223581. {
  223582. goToURL (lastURL, &lastHeaders, &lastPostData);
  223583. lastURL = String::empty;
  223584. }
  223585. }
  223586. void WebBrowserComponent::parentHierarchyChanged()
  223587. {
  223588. checkWindowAssociation();
  223589. }
  223590. void WebBrowserComponent::resized()
  223591. {
  223592. }
  223593. void WebBrowserComponent::visibilityChanged()
  223594. {
  223595. checkWindowAssociation();
  223596. }
  223597. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223598. {
  223599. return true;
  223600. }
  223601. #endif
  223602. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223603. #endif
  223604. END_JUCE_NAMESPACE
  223605. #endif
  223606. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223607. #endif
  223608. #if JUCE_MAC || JUCE_IPHONE
  223609. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223610. /*
  223611. This file wraps together all the mac-specific code, so that
  223612. we can include all the native headers just once, and compile all our
  223613. platform-specific stuff in one big lump, keeping it out of the way of
  223614. the rest of the codebase.
  223615. */
  223616. #if JUCE_MAC || JUCE_IOS
  223617. #undef JUCE_BUILD_NATIVE
  223618. #define JUCE_BUILD_NATIVE 1
  223619. BEGIN_JUCE_NAMESPACE
  223620. #undef Point
  223621. namespace
  223622. {
  223623. template <class RectType>
  223624. const Rectangle<int> convertToRectInt (const RectType& r)
  223625. {
  223626. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223627. }
  223628. template <class RectType>
  223629. const Rectangle<float> convertToRectFloat (const RectType& r)
  223630. {
  223631. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223632. }
  223633. template <class RectType>
  223634. CGRect convertToCGRect (const RectType& r)
  223635. {
  223636. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223637. }
  223638. }
  223639. class MessageQueue
  223640. {
  223641. public:
  223642. MessageQueue()
  223643. {
  223644. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223645. runLoop = CFRunLoopGetMain();
  223646. #else
  223647. runLoop = CFRunLoopGetCurrent();
  223648. #endif
  223649. CFRunLoopSourceContext sourceContext;
  223650. zerostruct (sourceContext);
  223651. sourceContext.info = this;
  223652. sourceContext.perform = runLoopSourceCallback;
  223653. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223654. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223655. }
  223656. ~MessageQueue()
  223657. {
  223658. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223659. CFRunLoopSourceInvalidate (runLoopSource);
  223660. CFRelease (runLoopSource);
  223661. }
  223662. void post (Message* const message)
  223663. {
  223664. messages.add (message);
  223665. CFRunLoopSourceSignal (runLoopSource);
  223666. CFRunLoopWakeUp (runLoop);
  223667. }
  223668. private:
  223669. ReferenceCountedArray <Message, CriticalSection> messages;
  223670. CriticalSection lock;
  223671. CFRunLoopRef runLoop;
  223672. CFRunLoopSourceRef runLoopSource;
  223673. bool deliverNextMessage()
  223674. {
  223675. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223676. if (nextMessage == 0)
  223677. return false;
  223678. const ScopedAutoReleasePool pool;
  223679. MessageManager::getInstance()->deliverMessage (nextMessage);
  223680. return true;
  223681. }
  223682. void runLoopCallback()
  223683. {
  223684. for (int i = 4; --i >= 0;)
  223685. if (! deliverNextMessage())
  223686. return;
  223687. CFRunLoopSourceSignal (runLoopSource);
  223688. CFRunLoopWakeUp (runLoop);
  223689. }
  223690. static void runLoopSourceCallback (void* info)
  223691. {
  223692. static_cast <MessageQueue*> (info)->runLoopCallback();
  223693. }
  223694. };
  223695. #define JUCE_INCLUDED_FILE 1
  223696. // Now include the actual code files..
  223697. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223698. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223699. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223700. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223701. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223702. actually calling into a similarly named class in the other module's address space.
  223703. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223704. have unique names, and should avoid this problem.
  223705. If you're using the amalgamated version, you can just set this macro to something unique before
  223706. you include juce_amalgamated.cpp.
  223707. */
  223708. #ifndef JUCE_ObjCExtraSuffix
  223709. #define JUCE_ObjCExtraSuffix 3
  223710. #endif
  223711. #ifndef DOXYGEN
  223712. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223713. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223714. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223715. #endif
  223716. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223717. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223718. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223719. // compiled on its own).
  223720. #if JUCE_INCLUDED_FILE
  223721. namespace
  223722. {
  223723. const String nsStringToJuce (NSString* s)
  223724. {
  223725. return String::fromUTF8 ([s UTF8String]);
  223726. }
  223727. NSString* juceStringToNS (const String& s)
  223728. {
  223729. return [NSString stringWithUTF8String: s.toUTF8()];
  223730. }
  223731. const String convertUTF16ToString (const UniChar* utf16)
  223732. {
  223733. String s;
  223734. while (*utf16 != 0)
  223735. s += (juce_wchar) *utf16++;
  223736. return s;
  223737. }
  223738. }
  223739. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223740. {
  223741. String result;
  223742. if (cfString != 0)
  223743. {
  223744. CFRange range = { 0, CFStringGetLength (cfString) };
  223745. HeapBlock <UniChar> u (range.length + 1);
  223746. CFStringGetCharacters (cfString, range, u);
  223747. u[range.length] = 0;
  223748. result = convertUTF16ToString (u);
  223749. }
  223750. return result;
  223751. }
  223752. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223753. {
  223754. const int len = s.length();
  223755. HeapBlock <UniChar> temp (len + 2);
  223756. for (int i = 0; i <= len; ++i)
  223757. temp[i] = s[i];
  223758. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223759. }
  223760. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223761. {
  223762. #if JUCE_IOS
  223763. const ScopedAutoReleasePool pool;
  223764. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223765. #else
  223766. UnicodeMapping map;
  223767. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223768. kUnicodeNoSubset,
  223769. kTextEncodingDefaultFormat);
  223770. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223771. kUnicodeCanonicalCompVariant,
  223772. kTextEncodingDefaultFormat);
  223773. map.mappingVersion = kUnicodeUseLatestMapping;
  223774. UnicodeToTextInfo conversionInfo = 0;
  223775. String result;
  223776. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223777. {
  223778. const int len = s.length();
  223779. HeapBlock <UniChar> tempIn, tempOut;
  223780. tempIn.calloc (len + 2);
  223781. tempOut.calloc (len + 2);
  223782. for (int i = 0; i <= len; ++i)
  223783. tempIn[i] = s[i];
  223784. ByteCount bytesRead = 0;
  223785. ByteCount outputBufferSize = 0;
  223786. if (ConvertFromUnicodeToText (conversionInfo,
  223787. len * sizeof (UniChar), tempIn,
  223788. kUnicodeDefaultDirectionMask,
  223789. 0, 0, 0, 0,
  223790. len * sizeof (UniChar), &bytesRead,
  223791. &outputBufferSize, tempOut) == noErr)
  223792. {
  223793. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223794. juce_wchar* t = result;
  223795. unsigned int i;
  223796. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  223797. t[i] = (juce_wchar) tempOut[i];
  223798. t[i] = 0;
  223799. }
  223800. DisposeUnicodeToTextInfo (&conversionInfo);
  223801. }
  223802. return result;
  223803. #endif
  223804. }
  223805. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223806. void SystemClipboard::copyTextToClipboard (const String& text)
  223807. {
  223808. #if JUCE_IOS
  223809. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223810. forPasteboardType: @"public.text"];
  223811. #else
  223812. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223813. owner: nil];
  223814. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223815. forType: NSStringPboardType];
  223816. #endif
  223817. }
  223818. const String SystemClipboard::getTextFromClipboard()
  223819. {
  223820. #if JUCE_IOS
  223821. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223822. #else
  223823. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223824. #endif
  223825. return text == 0 ? String::empty
  223826. : nsStringToJuce (text);
  223827. }
  223828. #endif
  223829. #endif
  223830. /*** End of inlined file: juce_mac_Strings.mm ***/
  223831. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223832. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223833. // compiled on its own).
  223834. #if JUCE_INCLUDED_FILE
  223835. namespace SystemStatsHelpers
  223836. {
  223837. static int64 highResTimerFrequency = 0;
  223838. static double highResTimerToMillisecRatio = 0;
  223839. #if JUCE_INTEL
  223840. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223841. {
  223842. uint32 la = a, lb = b, lc = c, ld = d;
  223843. asm ("mov %%ebx, %%esi \n\t"
  223844. "cpuid \n\t"
  223845. "xchg %%esi, %%ebx"
  223846. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223847. #if JUCE_64BIT
  223848. , "b" (lb), "c" (lc), "d" (ld)
  223849. #endif
  223850. );
  223851. a = la; b = lb; c = lc; d = ld;
  223852. }
  223853. #endif
  223854. }
  223855. void SystemStats::initialiseStats()
  223856. {
  223857. using namespace SystemStatsHelpers;
  223858. static bool initialised = false;
  223859. if (! initialised)
  223860. {
  223861. initialised = true;
  223862. #if JUCE_MAC
  223863. [NSApplication sharedApplication];
  223864. #endif
  223865. #if JUCE_INTEL
  223866. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223867. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223868. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223869. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223870. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223871. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223872. #else
  223873. cpuFlags.hasMMX = false;
  223874. cpuFlags.hasSSE = false;
  223875. cpuFlags.hasSSE2 = false;
  223876. cpuFlags.has3DNow = false;
  223877. #endif
  223878. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223879. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223880. #else
  223881. cpuFlags.numCpus = (int) MPProcessors();
  223882. #endif
  223883. mach_timebase_info_data_t timebase;
  223884. (void) mach_timebase_info (&timebase);
  223885. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223886. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223887. String s (SystemStats::getJUCEVersion());
  223888. rlimit lim;
  223889. getrlimit (RLIMIT_NOFILE, &lim);
  223890. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223891. setrlimit (RLIMIT_NOFILE, &lim);
  223892. }
  223893. }
  223894. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223895. {
  223896. return MacOSX;
  223897. }
  223898. const String SystemStats::getOperatingSystemName()
  223899. {
  223900. return "Mac OS X";
  223901. }
  223902. #if ! JUCE_IOS
  223903. int PlatformUtilities::getOSXMinorVersionNumber()
  223904. {
  223905. SInt32 versionMinor = 0;
  223906. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223907. (void) err;
  223908. jassert (err == noErr);
  223909. return (int) versionMinor;
  223910. }
  223911. #endif
  223912. bool SystemStats::isOperatingSystem64Bit()
  223913. {
  223914. #if JUCE_IOS
  223915. return false;
  223916. #elif JUCE_64BIT
  223917. return true;
  223918. #else
  223919. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223920. #endif
  223921. }
  223922. int SystemStats::getMemorySizeInMegabytes()
  223923. {
  223924. uint64 mem = 0;
  223925. size_t memSize = sizeof (mem);
  223926. int mib[] = { CTL_HW, HW_MEMSIZE };
  223927. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223928. return (int) (mem / (1024 * 1024));
  223929. }
  223930. const String SystemStats::getCpuVendor()
  223931. {
  223932. #if JUCE_INTEL
  223933. uint32 dummy = 0;
  223934. uint32 vendor[4];
  223935. zerostruct (vendor);
  223936. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223937. return String (reinterpret_cast <const char*> (vendor), 12);
  223938. #else
  223939. return String::empty;
  223940. #endif
  223941. }
  223942. int SystemStats::getCpuSpeedInMegaherz()
  223943. {
  223944. uint64 speedHz = 0;
  223945. size_t speedSize = sizeof (speedHz);
  223946. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223947. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223948. #if JUCE_BIG_ENDIAN
  223949. if (speedSize == 4)
  223950. speedHz >>= 32;
  223951. #endif
  223952. return (int) (speedHz / 1000000);
  223953. }
  223954. const String SystemStats::getLogonName()
  223955. {
  223956. return nsStringToJuce (NSUserName());
  223957. }
  223958. const String SystemStats::getFullUserName()
  223959. {
  223960. return nsStringToJuce (NSFullUserName());
  223961. }
  223962. uint32 juce_millisecondsSinceStartup() throw()
  223963. {
  223964. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223965. }
  223966. double Time::getMillisecondCounterHiRes() throw()
  223967. {
  223968. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223969. }
  223970. int64 Time::getHighResolutionTicks() throw()
  223971. {
  223972. return (int64) mach_absolute_time();
  223973. }
  223974. int64 Time::getHighResolutionTicksPerSecond() throw()
  223975. {
  223976. return SystemStatsHelpers::highResTimerFrequency;
  223977. }
  223978. bool Time::setSystemTimeToThisTime() const
  223979. {
  223980. jassertfalse;
  223981. return false;
  223982. }
  223983. int SystemStats::getPageSize()
  223984. {
  223985. return (int) NSPageSize();
  223986. }
  223987. void PlatformUtilities::fpuReset()
  223988. {
  223989. }
  223990. #endif
  223991. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223992. /*** Start of inlined file: juce_mac_Network.mm ***/
  223993. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223994. // compiled on its own).
  223995. #if JUCE_INCLUDED_FILE
  223996. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223997. {
  223998. ifaddrs* addrs = 0;
  223999. if (getifaddrs (&addrs) == 0)
  224000. {
  224001. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  224002. {
  224003. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224004. if (sto->ss_family == AF_LINK)
  224005. {
  224006. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224007. #ifndef IFT_ETHER
  224008. #define IFT_ETHER 6
  224009. #endif
  224010. if (sadd->sdl_type == IFT_ETHER)
  224011. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  224012. }
  224013. }
  224014. freeifaddrs (addrs);
  224015. }
  224016. }
  224017. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224018. const String& emailSubject,
  224019. const String& bodyText,
  224020. const StringArray& filesToAttach)
  224021. {
  224022. #if JUCE_IOS
  224023. //xxx probably need to use MFMailComposeViewController
  224024. jassertfalse;
  224025. return false;
  224026. #else
  224027. const ScopedAutoReleasePool pool;
  224028. String script;
  224029. script << "tell application \"Mail\"\r\n"
  224030. "set newMessage to make new outgoing message with properties {subject:\""
  224031. << emailSubject.replace ("\"", "\\\"")
  224032. << "\", content:\""
  224033. << bodyText.replace ("\"", "\\\"")
  224034. << "\" & return & return}\r\n"
  224035. "tell newMessage\r\n"
  224036. "set visible to true\r\n"
  224037. "set sender to \"sdfsdfsdfewf\"\r\n"
  224038. "make new to recipient at end of to recipients with properties {address:\""
  224039. << targetEmailAddress
  224040. << "\"}\r\n";
  224041. for (int i = 0; i < filesToAttach.size(); ++i)
  224042. {
  224043. script << "tell content\r\n"
  224044. "make new attachment with properties {file name:\""
  224045. << filesToAttach[i].replace ("\"", "\\\"")
  224046. << "\"} at after the last paragraph\r\n"
  224047. "end tell\r\n";
  224048. }
  224049. script << "end tell\r\n"
  224050. "end tell\r\n";
  224051. NSAppleScript* s = [[NSAppleScript alloc]
  224052. initWithSource: juceStringToNS (script)];
  224053. NSDictionary* error = 0;
  224054. const bool ok = [s executeAndReturnError: &error] != nil;
  224055. [s release];
  224056. return ok;
  224057. #endif
  224058. }
  224059. END_JUCE_NAMESPACE
  224060. using namespace JUCE_NAMESPACE;
  224061. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224062. @interface JuceURLConnection : NSObject
  224063. {
  224064. @public
  224065. NSURLRequest* request;
  224066. NSURLConnection* connection;
  224067. NSMutableData* data;
  224068. Thread* runLoopThread;
  224069. bool initialised, hasFailed, hasFinished;
  224070. int position;
  224071. int64 contentLength;
  224072. NSDictionary* headers;
  224073. NSLock* dataLock;
  224074. }
  224075. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224076. - (void) dealloc;
  224077. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224078. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224079. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224080. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224081. - (BOOL) isOpen;
  224082. - (int) read: (char*) dest numBytes: (int) num;
  224083. - (int) readPosition;
  224084. - (void) stop;
  224085. - (void) createConnection;
  224086. @end
  224087. class JuceURLConnectionMessageThread : public Thread
  224088. {
  224089. public:
  224090. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224091. : Thread ("http connection"),
  224092. owner (owner_)
  224093. {
  224094. }
  224095. ~JuceURLConnectionMessageThread()
  224096. {
  224097. stopThread (10000);
  224098. }
  224099. void run()
  224100. {
  224101. [owner createConnection];
  224102. while (! threadShouldExit())
  224103. {
  224104. const ScopedAutoReleasePool pool;
  224105. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224106. }
  224107. }
  224108. private:
  224109. JuceURLConnection* owner;
  224110. };
  224111. @implementation JuceURLConnection
  224112. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224113. withCallback: (URL::OpenStreamProgressCallback*) callback
  224114. withContext: (void*) context;
  224115. {
  224116. [super init];
  224117. request = req;
  224118. [request retain];
  224119. data = [[NSMutableData data] retain];
  224120. dataLock = [[NSLock alloc] init];
  224121. connection = 0;
  224122. initialised = false;
  224123. hasFailed = false;
  224124. hasFinished = false;
  224125. contentLength = -1;
  224126. headers = 0;
  224127. runLoopThread = new JuceURLConnectionMessageThread (self);
  224128. runLoopThread->startThread();
  224129. while (runLoopThread->isThreadRunning() && ! initialised)
  224130. {
  224131. if (callback != 0)
  224132. callback (context, -1, (int) [[request HTTPBody] length]);
  224133. Thread::sleep (1);
  224134. }
  224135. return self;
  224136. }
  224137. - (void) dealloc
  224138. {
  224139. [self stop];
  224140. deleteAndZero (runLoopThread);
  224141. [connection release];
  224142. [data release];
  224143. [dataLock release];
  224144. [request release];
  224145. [headers release];
  224146. [super dealloc];
  224147. }
  224148. - (void) createConnection
  224149. {
  224150. NSUInteger oldRetainCount = [self retainCount];
  224151. connection = [[NSURLConnection alloc] initWithRequest: request
  224152. delegate: self];
  224153. if (oldRetainCount == [self retainCount])
  224154. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224155. if (connection == nil)
  224156. runLoopThread->signalThreadShouldExit();
  224157. }
  224158. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224159. {
  224160. (void) conn;
  224161. [dataLock lock];
  224162. [data setLength: 0];
  224163. [dataLock unlock];
  224164. initialised = true;
  224165. contentLength = [response expectedContentLength];
  224166. [headers release];
  224167. headers = 0;
  224168. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224169. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224170. }
  224171. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224172. {
  224173. (void) conn;
  224174. DBG (nsStringToJuce ([error description]));
  224175. hasFailed = true;
  224176. initialised = true;
  224177. if (runLoopThread != 0)
  224178. runLoopThread->signalThreadShouldExit();
  224179. }
  224180. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224181. {
  224182. (void) conn;
  224183. [dataLock lock];
  224184. [data appendData: newData];
  224185. [dataLock unlock];
  224186. initialised = true;
  224187. }
  224188. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224189. {
  224190. (void) conn;
  224191. hasFinished = true;
  224192. initialised = true;
  224193. if (runLoopThread != 0)
  224194. runLoopThread->signalThreadShouldExit();
  224195. }
  224196. - (BOOL) isOpen
  224197. {
  224198. return connection != 0 && ! hasFailed;
  224199. }
  224200. - (int) readPosition
  224201. {
  224202. return position;
  224203. }
  224204. - (int) read: (char*) dest numBytes: (int) numNeeded
  224205. {
  224206. int numDone = 0;
  224207. while (numNeeded > 0)
  224208. {
  224209. int available = jmin (numNeeded, (int) [data length]);
  224210. if (available > 0)
  224211. {
  224212. [dataLock lock];
  224213. [data getBytes: dest length: available];
  224214. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224215. [dataLock unlock];
  224216. numDone += available;
  224217. numNeeded -= available;
  224218. dest += available;
  224219. }
  224220. else
  224221. {
  224222. if (hasFailed || hasFinished)
  224223. break;
  224224. Thread::sleep (1);
  224225. }
  224226. }
  224227. position += numDone;
  224228. return numDone;
  224229. }
  224230. - (void) stop
  224231. {
  224232. [connection cancel];
  224233. if (runLoopThread != 0)
  224234. runLoopThread->stopThread (10000);
  224235. }
  224236. @end
  224237. BEGIN_JUCE_NAMESPACE
  224238. class WebInputStream : public InputStream
  224239. {
  224240. public:
  224241. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  224242. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224243. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  224244. : connection (nil),
  224245. address (address_), headers (headers_), postData (postData_), position (0),
  224246. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  224247. {
  224248. JUCE_AUTORELEASEPOOL
  224249. connection = createConnection (progressCallback, progressCallbackContext);
  224250. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  224251. {
  224252. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  224253. NSString* key;
  224254. while ((key = [enumerator nextObject]) != nil)
  224255. responseHeaders->set (nsStringToJuce (key),
  224256. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  224257. }
  224258. }
  224259. ~WebInputStream()
  224260. {
  224261. close();
  224262. }
  224263. bool isError() const { return connection == nil; }
  224264. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  224265. bool isExhausted() { return finished; }
  224266. int64 getPosition() { return position; }
  224267. int read (void* buffer, int bytesToRead)
  224268. {
  224269. if (finished || isError())
  224270. {
  224271. return 0;
  224272. }
  224273. else
  224274. {
  224275. JUCE_AUTORELEASEPOOL
  224276. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  224277. position += bytesRead;
  224278. if (bytesRead == 0)
  224279. finished = true;
  224280. return bytesRead;
  224281. }
  224282. }
  224283. bool setPosition (int64 wantedPos)
  224284. {
  224285. if (wantedPos != position)
  224286. {
  224287. finished = false;
  224288. if (wantedPos < position)
  224289. {
  224290. close();
  224291. position = 0;
  224292. connection = createConnection (0, 0);
  224293. }
  224294. skipNextBytes (wantedPos - position);
  224295. }
  224296. return true;
  224297. }
  224298. private:
  224299. JuceURLConnection* connection;
  224300. String address, headers;
  224301. MemoryBlock postData;
  224302. int64 position;
  224303. bool finished;
  224304. const bool isPost;
  224305. const int timeOutMs;
  224306. void close()
  224307. {
  224308. [connection stop];
  224309. [connection release];
  224310. connection = nil;
  224311. }
  224312. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  224313. void* progressCallbackContext)
  224314. {
  224315. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  224316. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224317. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224318. if (req == nil)
  224319. return 0;
  224320. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224321. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224322. StringArray headerLines;
  224323. headerLines.addLines (headers);
  224324. headerLines.removeEmptyStrings (true);
  224325. for (int i = 0; i < headerLines.size(); ++i)
  224326. {
  224327. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224328. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224329. if (key.isNotEmpty() && value.isNotEmpty())
  224330. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224331. }
  224332. if (isPost && postData.getSize() > 0)
  224333. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224334. length: postData.getSize()]];
  224335. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224336. withCallback: progressCallback
  224337. withContext: progressCallbackContext];
  224338. if ([s isOpen])
  224339. return s;
  224340. [s release];
  224341. return 0;
  224342. }
  224343. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  224344. };
  224345. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  224346. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  224347. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  224348. {
  224349. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  224350. progressCallback, progressCallbackContext,
  224351. headers, timeOutMs, responseHeaders));
  224352. return wi->isError() ? 0 : wi.release();
  224353. }
  224354. #endif
  224355. /*** End of inlined file: juce_mac_Network.mm ***/
  224356. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224357. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224358. // compiled on its own).
  224359. #if JUCE_INCLUDED_FILE
  224360. struct NamedPipeInternal
  224361. {
  224362. String pipeInName, pipeOutName;
  224363. int pipeIn, pipeOut;
  224364. bool volatile createdPipe, blocked, stopReadOperation;
  224365. static void signalHandler (int) {}
  224366. };
  224367. void NamedPipe::cancelPendingReads()
  224368. {
  224369. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224370. {
  224371. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224372. intern->stopReadOperation = true;
  224373. char buffer [1] = { 0 };
  224374. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224375. (void) bytesWritten;
  224376. int timeout = 2000;
  224377. while (intern->blocked && --timeout >= 0)
  224378. Thread::sleep (2);
  224379. intern->stopReadOperation = false;
  224380. }
  224381. }
  224382. void NamedPipe::close()
  224383. {
  224384. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224385. if (intern != 0)
  224386. {
  224387. internal = 0;
  224388. if (intern->pipeIn != -1)
  224389. ::close (intern->pipeIn);
  224390. if (intern->pipeOut != -1)
  224391. ::close (intern->pipeOut);
  224392. if (intern->createdPipe)
  224393. {
  224394. unlink (intern->pipeInName.toUTF8());
  224395. unlink (intern->pipeOutName.toUTF8());
  224396. }
  224397. delete intern;
  224398. }
  224399. }
  224400. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224401. {
  224402. close();
  224403. NamedPipeInternal* const intern = new NamedPipeInternal();
  224404. internal = intern;
  224405. intern->createdPipe = createPipe;
  224406. intern->blocked = false;
  224407. intern->stopReadOperation = false;
  224408. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224409. siginterrupt (SIGPIPE, 1);
  224410. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224411. intern->pipeInName = pipePath + "_in";
  224412. intern->pipeOutName = pipePath + "_out";
  224413. intern->pipeIn = -1;
  224414. intern->pipeOut = -1;
  224415. if (createPipe)
  224416. {
  224417. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224418. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224419. {
  224420. delete intern;
  224421. internal = 0;
  224422. return false;
  224423. }
  224424. }
  224425. return true;
  224426. }
  224427. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224428. {
  224429. int bytesRead = -1;
  224430. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224431. if (intern != 0)
  224432. {
  224433. intern->blocked = true;
  224434. if (intern->pipeIn == -1)
  224435. {
  224436. if (intern->createdPipe)
  224437. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224438. else
  224439. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224440. if (intern->pipeIn == -1)
  224441. {
  224442. intern->blocked = false;
  224443. return -1;
  224444. }
  224445. }
  224446. bytesRead = 0;
  224447. char* p = static_cast<char*> (destBuffer);
  224448. while (bytesRead < maxBytesToRead)
  224449. {
  224450. const int bytesThisTime = maxBytesToRead - bytesRead;
  224451. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224452. if (numRead <= 0 || intern->stopReadOperation)
  224453. {
  224454. bytesRead = -1;
  224455. break;
  224456. }
  224457. bytesRead += numRead;
  224458. p += bytesRead;
  224459. }
  224460. intern->blocked = false;
  224461. }
  224462. return bytesRead;
  224463. }
  224464. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224465. {
  224466. int bytesWritten = -1;
  224467. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224468. if (intern != 0)
  224469. {
  224470. if (intern->pipeOut == -1)
  224471. {
  224472. if (intern->createdPipe)
  224473. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224474. else
  224475. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224476. if (intern->pipeOut == -1)
  224477. {
  224478. return -1;
  224479. }
  224480. }
  224481. const char* p = static_cast<const char*> (sourceBuffer);
  224482. bytesWritten = 0;
  224483. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224484. while (bytesWritten < numBytesToWrite
  224485. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224486. {
  224487. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224488. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224489. if (numWritten <= 0)
  224490. {
  224491. bytesWritten = -1;
  224492. break;
  224493. }
  224494. bytesWritten += numWritten;
  224495. p += bytesWritten;
  224496. }
  224497. }
  224498. return bytesWritten;
  224499. }
  224500. #endif
  224501. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224502. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224503. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224504. // compiled on its own).
  224505. #if JUCE_INCLUDED_FILE
  224506. /*
  224507. Note that a lot of methods that you'd expect to find in this file actually
  224508. live in juce_posix_SharedCode.h!
  224509. */
  224510. bool Process::isForegroundProcess()
  224511. {
  224512. #if JUCE_MAC
  224513. return [NSApp isActive];
  224514. #else
  224515. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224516. #endif
  224517. }
  224518. void Process::raisePrivilege()
  224519. {
  224520. jassertfalse;
  224521. }
  224522. void Process::lowerPrivilege()
  224523. {
  224524. jassertfalse;
  224525. }
  224526. void Process::terminate()
  224527. {
  224528. exit (0);
  224529. }
  224530. void Process::setPriority (ProcessPriority)
  224531. {
  224532. // xxx
  224533. }
  224534. #endif
  224535. /*** End of inlined file: juce_mac_Threads.mm ***/
  224536. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224537. /*
  224538. This file contains posix routines that are common to both the Linux and Mac builds.
  224539. It gets included directly in the cpp files for these platforms.
  224540. */
  224541. CriticalSection::CriticalSection() throw()
  224542. {
  224543. pthread_mutexattr_t atts;
  224544. pthread_mutexattr_init (&atts);
  224545. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224546. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224547. pthread_mutex_init (&internal, &atts);
  224548. }
  224549. CriticalSection::~CriticalSection() throw()
  224550. {
  224551. pthread_mutex_destroy (&internal);
  224552. }
  224553. void CriticalSection::enter() const throw()
  224554. {
  224555. pthread_mutex_lock (&internal);
  224556. }
  224557. bool CriticalSection::tryEnter() const throw()
  224558. {
  224559. return pthread_mutex_trylock (&internal) == 0;
  224560. }
  224561. void CriticalSection::exit() const throw()
  224562. {
  224563. pthread_mutex_unlock (&internal);
  224564. }
  224565. class WaitableEventImpl
  224566. {
  224567. public:
  224568. WaitableEventImpl (const bool manualReset_)
  224569. : triggered (false),
  224570. manualReset (manualReset_)
  224571. {
  224572. pthread_cond_init (&condition, 0);
  224573. pthread_mutexattr_t atts;
  224574. pthread_mutexattr_init (&atts);
  224575. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224576. pthread_mutex_init (&mutex, &atts);
  224577. }
  224578. ~WaitableEventImpl()
  224579. {
  224580. pthread_cond_destroy (&condition);
  224581. pthread_mutex_destroy (&mutex);
  224582. }
  224583. bool wait (const int timeOutMillisecs) throw()
  224584. {
  224585. pthread_mutex_lock (&mutex);
  224586. if (! triggered)
  224587. {
  224588. if (timeOutMillisecs < 0)
  224589. {
  224590. do
  224591. {
  224592. pthread_cond_wait (&condition, &mutex);
  224593. }
  224594. while (! triggered);
  224595. }
  224596. else
  224597. {
  224598. struct timeval now;
  224599. gettimeofday (&now, 0);
  224600. struct timespec time;
  224601. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224602. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224603. if (time.tv_nsec >= 1000000000)
  224604. {
  224605. time.tv_nsec -= 1000000000;
  224606. time.tv_sec++;
  224607. }
  224608. do
  224609. {
  224610. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224611. {
  224612. pthread_mutex_unlock (&mutex);
  224613. return false;
  224614. }
  224615. }
  224616. while (! triggered);
  224617. }
  224618. }
  224619. if (! manualReset)
  224620. triggered = false;
  224621. pthread_mutex_unlock (&mutex);
  224622. return true;
  224623. }
  224624. void signal() throw()
  224625. {
  224626. pthread_mutex_lock (&mutex);
  224627. triggered = true;
  224628. pthread_cond_broadcast (&condition);
  224629. pthread_mutex_unlock (&mutex);
  224630. }
  224631. void reset() throw()
  224632. {
  224633. pthread_mutex_lock (&mutex);
  224634. triggered = false;
  224635. pthread_mutex_unlock (&mutex);
  224636. }
  224637. private:
  224638. pthread_cond_t condition;
  224639. pthread_mutex_t mutex;
  224640. bool triggered;
  224641. const bool manualReset;
  224642. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224643. };
  224644. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224645. : internal (new WaitableEventImpl (manualReset))
  224646. {
  224647. }
  224648. WaitableEvent::~WaitableEvent() throw()
  224649. {
  224650. delete static_cast <WaitableEventImpl*> (internal);
  224651. }
  224652. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224653. {
  224654. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224655. }
  224656. void WaitableEvent::signal() const throw()
  224657. {
  224658. static_cast <WaitableEventImpl*> (internal)->signal();
  224659. }
  224660. void WaitableEvent::reset() const throw()
  224661. {
  224662. static_cast <WaitableEventImpl*> (internal)->reset();
  224663. }
  224664. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224665. {
  224666. struct timespec time;
  224667. time.tv_sec = millisecs / 1000;
  224668. time.tv_nsec = (millisecs % 1000) * 1000000;
  224669. nanosleep (&time, 0);
  224670. }
  224671. const juce_wchar File::separator = '/';
  224672. const String File::separatorString ("/");
  224673. const File File::getCurrentWorkingDirectory()
  224674. {
  224675. HeapBlock<char> heapBuffer;
  224676. char localBuffer [1024];
  224677. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224678. int bufferSize = 4096;
  224679. while (cwd == 0 && errno == ERANGE)
  224680. {
  224681. heapBuffer.malloc (bufferSize);
  224682. cwd = getcwd (heapBuffer, bufferSize - 1);
  224683. bufferSize += 1024;
  224684. }
  224685. return File (String::fromUTF8 (cwd));
  224686. }
  224687. bool File::setAsCurrentWorkingDirectory() const
  224688. {
  224689. return chdir (getFullPathName().toUTF8()) == 0;
  224690. }
  224691. namespace
  224692. {
  224693. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224694. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224695. #else
  224696. typedef struct stat juce_statStruct;
  224697. #endif
  224698. bool juce_stat (const String& fileName, juce_statStruct& info)
  224699. {
  224700. return fileName.isNotEmpty()
  224701. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224702. && (stat64 (fileName.toUTF8(), &info) == 0);
  224703. #else
  224704. && (stat (fileName.toUTF8(), &info) == 0);
  224705. #endif
  224706. }
  224707. // if this file doesn't exist, find a parent of it that does..
  224708. bool juce_doStatFS (File f, struct statfs& result)
  224709. {
  224710. for (int i = 5; --i >= 0;)
  224711. {
  224712. if (f.exists())
  224713. break;
  224714. f = f.getParentDirectory();
  224715. }
  224716. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224717. }
  224718. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224719. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224720. {
  224721. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224722. {
  224723. juce_statStruct info;
  224724. const bool statOk = juce_stat (path, info);
  224725. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224726. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224727. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224728. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224729. }
  224730. if (isReadOnly != 0)
  224731. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224732. }
  224733. }
  224734. bool File::isDirectory() const
  224735. {
  224736. juce_statStruct info;
  224737. return fullPath.isEmpty()
  224738. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224739. }
  224740. bool File::exists() const
  224741. {
  224742. juce_statStruct info;
  224743. return fullPath.isNotEmpty()
  224744. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224745. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224746. #else
  224747. && (lstat (fullPath.toUTF8(), &info) == 0);
  224748. #endif
  224749. }
  224750. bool File::existsAsFile() const
  224751. {
  224752. return exists() && ! isDirectory();
  224753. }
  224754. int64 File::getSize() const
  224755. {
  224756. juce_statStruct info;
  224757. return juce_stat (fullPath, info) ? info.st_size : 0;
  224758. }
  224759. bool File::hasWriteAccess() const
  224760. {
  224761. if (exists())
  224762. return access (fullPath.toUTF8(), W_OK) == 0;
  224763. if ((! isDirectory()) && fullPath.containsChar (separator))
  224764. return getParentDirectory().hasWriteAccess();
  224765. return false;
  224766. }
  224767. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224768. {
  224769. juce_statStruct info;
  224770. if (! juce_stat (fullPath, info))
  224771. return false;
  224772. info.st_mode &= 0777; // Just permissions
  224773. if (shouldBeReadOnly)
  224774. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224775. else
  224776. // Give everybody write permission?
  224777. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224778. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224779. }
  224780. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224781. {
  224782. modificationTime = 0;
  224783. accessTime = 0;
  224784. creationTime = 0;
  224785. juce_statStruct info;
  224786. if (juce_stat (fullPath, info))
  224787. {
  224788. modificationTime = (int64) info.st_mtime * 1000;
  224789. accessTime = (int64) info.st_atime * 1000;
  224790. creationTime = (int64) info.st_ctime * 1000;
  224791. }
  224792. }
  224793. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224794. {
  224795. struct utimbuf times;
  224796. times.actime = (time_t) (accessTime / 1000);
  224797. times.modtime = (time_t) (modificationTime / 1000);
  224798. return utime (fullPath.toUTF8(), &times) == 0;
  224799. }
  224800. bool File::deleteFile() const
  224801. {
  224802. if (! exists())
  224803. return true;
  224804. else if (isDirectory())
  224805. return rmdir (fullPath.toUTF8()) == 0;
  224806. else
  224807. return remove (fullPath.toUTF8()) == 0;
  224808. }
  224809. bool File::moveInternal (const File& dest) const
  224810. {
  224811. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224812. return true;
  224813. if (hasWriteAccess() && copyInternal (dest))
  224814. {
  224815. if (deleteFile())
  224816. return true;
  224817. dest.deleteFile();
  224818. }
  224819. return false;
  224820. }
  224821. void File::createDirectoryInternal (const String& fileName) const
  224822. {
  224823. mkdir (fileName.toUTF8(), 0777);
  224824. }
  224825. int64 juce_fileSetPosition (void* handle, int64 pos)
  224826. {
  224827. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224828. return pos;
  224829. return -1;
  224830. }
  224831. void FileInputStream::openHandle()
  224832. {
  224833. totalSize = file.getSize();
  224834. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224835. if (f != -1)
  224836. fileHandle = (void*) f;
  224837. }
  224838. void FileInputStream::closeHandle()
  224839. {
  224840. if (fileHandle != 0)
  224841. {
  224842. close ((int) (pointer_sized_int) fileHandle);
  224843. fileHandle = 0;
  224844. }
  224845. }
  224846. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224847. {
  224848. if (fileHandle != 0)
  224849. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224850. return 0;
  224851. }
  224852. void FileOutputStream::openHandle()
  224853. {
  224854. if (file.exists())
  224855. {
  224856. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224857. if (f != -1)
  224858. {
  224859. currentPosition = lseek (f, 0, SEEK_END);
  224860. if (currentPosition >= 0)
  224861. fileHandle = (void*) f;
  224862. else
  224863. close (f);
  224864. }
  224865. }
  224866. else
  224867. {
  224868. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224869. if (f != -1)
  224870. fileHandle = (void*) f;
  224871. }
  224872. }
  224873. void FileOutputStream::closeHandle()
  224874. {
  224875. if (fileHandle != 0)
  224876. {
  224877. close ((int) (pointer_sized_int) fileHandle);
  224878. fileHandle = 0;
  224879. }
  224880. }
  224881. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224882. {
  224883. if (fileHandle != 0)
  224884. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224885. return 0;
  224886. }
  224887. void FileOutputStream::flushInternal()
  224888. {
  224889. if (fileHandle != 0)
  224890. fsync ((int) (pointer_sized_int) fileHandle);
  224891. }
  224892. const File juce_getExecutableFile()
  224893. {
  224894. Dl_info exeInfo;
  224895. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  224896. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224897. }
  224898. int64 File::getBytesFreeOnVolume() const
  224899. {
  224900. struct statfs buf;
  224901. if (juce_doStatFS (*this, buf))
  224902. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224903. return 0;
  224904. }
  224905. int64 File::getVolumeTotalSize() const
  224906. {
  224907. struct statfs buf;
  224908. if (juce_doStatFS (*this, buf))
  224909. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224910. return 0;
  224911. }
  224912. const String File::getVolumeLabel() const
  224913. {
  224914. #if JUCE_MAC
  224915. struct VolAttrBuf
  224916. {
  224917. u_int32_t length;
  224918. attrreference_t mountPointRef;
  224919. char mountPointSpace [MAXPATHLEN];
  224920. } attrBuf;
  224921. struct attrlist attrList;
  224922. zerostruct (attrList);
  224923. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224924. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224925. File f (*this);
  224926. for (;;)
  224927. {
  224928. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224929. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224930. (int) attrBuf.mountPointRef.attr_length);
  224931. const File parent (f.getParentDirectory());
  224932. if (f == parent)
  224933. break;
  224934. f = parent;
  224935. }
  224936. #endif
  224937. return String::empty;
  224938. }
  224939. int File::getVolumeSerialNumber() const
  224940. {
  224941. return 0; // xxx
  224942. }
  224943. void juce_runSystemCommand (const String& command)
  224944. {
  224945. int result = system (command.toUTF8());
  224946. (void) result;
  224947. }
  224948. const String juce_getOutputFromCommand (const String& command)
  224949. {
  224950. // slight bodge here, as we just pipe the output into a temp file and read it...
  224951. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224952. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224953. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224954. String result (tempFile.loadFileAsString());
  224955. tempFile.deleteFile();
  224956. return result;
  224957. }
  224958. class InterProcessLock::Pimpl
  224959. {
  224960. public:
  224961. Pimpl (const String& name, const int timeOutMillisecs)
  224962. : handle (0), refCount (1)
  224963. {
  224964. #if JUCE_MAC
  224965. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224966. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224967. #else
  224968. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224969. #endif
  224970. temp.create();
  224971. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224972. if (handle != 0)
  224973. {
  224974. struct flock fl;
  224975. zerostruct (fl);
  224976. fl.l_whence = SEEK_SET;
  224977. fl.l_type = F_WRLCK;
  224978. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224979. for (;;)
  224980. {
  224981. const int result = fcntl (handle, F_SETLK, &fl);
  224982. if (result >= 0)
  224983. return;
  224984. if (errno != EINTR)
  224985. {
  224986. if (timeOutMillisecs == 0
  224987. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224988. break;
  224989. Thread::sleep (10);
  224990. }
  224991. }
  224992. }
  224993. closeFile();
  224994. }
  224995. ~Pimpl()
  224996. {
  224997. closeFile();
  224998. }
  224999. void closeFile()
  225000. {
  225001. if (handle != 0)
  225002. {
  225003. struct flock fl;
  225004. zerostruct (fl);
  225005. fl.l_whence = SEEK_SET;
  225006. fl.l_type = F_UNLCK;
  225007. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225008. {}
  225009. close (handle);
  225010. handle = 0;
  225011. }
  225012. }
  225013. int handle, refCount;
  225014. };
  225015. InterProcessLock::InterProcessLock (const String& name_)
  225016. : name (name_)
  225017. {
  225018. }
  225019. InterProcessLock::~InterProcessLock()
  225020. {
  225021. }
  225022. bool InterProcessLock::enter (const int timeOutMillisecs)
  225023. {
  225024. const ScopedLock sl (lock);
  225025. if (pimpl == 0)
  225026. {
  225027. pimpl = new Pimpl (name, timeOutMillisecs);
  225028. if (pimpl->handle == 0)
  225029. pimpl = 0;
  225030. }
  225031. else
  225032. {
  225033. pimpl->refCount++;
  225034. }
  225035. return pimpl != 0;
  225036. }
  225037. void InterProcessLock::exit()
  225038. {
  225039. const ScopedLock sl (lock);
  225040. // Trying to release the lock too many times!
  225041. jassert (pimpl != 0);
  225042. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225043. pimpl = 0;
  225044. }
  225045. void JUCE_API juce_threadEntryPoint (void*);
  225046. void* threadEntryProc (void* userData)
  225047. {
  225048. JUCE_AUTORELEASEPOOL
  225049. juce_threadEntryPoint (userData);
  225050. return 0;
  225051. }
  225052. void Thread::launchThread()
  225053. {
  225054. threadHandle_ = 0;
  225055. pthread_t handle = 0;
  225056. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  225057. {
  225058. pthread_detach (handle);
  225059. threadHandle_ = (void*) handle;
  225060. threadId_ = (ThreadID) threadHandle_;
  225061. }
  225062. }
  225063. void Thread::closeThreadHandle()
  225064. {
  225065. threadId_ = 0;
  225066. threadHandle_ = 0;
  225067. }
  225068. void Thread::killThread()
  225069. {
  225070. if (threadHandle_ != 0)
  225071. pthread_cancel ((pthread_t) threadHandle_);
  225072. }
  225073. void Thread::setCurrentThreadName (const String& /*name*/)
  225074. {
  225075. }
  225076. bool Thread::setThreadPriority (void* handle, int priority)
  225077. {
  225078. struct sched_param param;
  225079. int policy;
  225080. priority = jlimit (0, 10, priority);
  225081. if (handle == 0)
  225082. handle = (void*) pthread_self();
  225083. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225084. return false;
  225085. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225086. const int minPriority = sched_get_priority_min (policy);
  225087. const int maxPriority = sched_get_priority_max (policy);
  225088. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225089. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225090. }
  225091. Thread::ThreadID Thread::getCurrentThreadId()
  225092. {
  225093. return (ThreadID) pthread_self();
  225094. }
  225095. void Thread::yield()
  225096. {
  225097. sched_yield();
  225098. }
  225099. /* Remove this macro if you're having problems compiling the cpu affinity
  225100. calls (the API for these has changed about quite a bit in various Linux
  225101. versions, and a lot of distros seem to ship with obsolete versions)
  225102. */
  225103. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225104. #define SUPPORT_AFFINITIES 1
  225105. #endif
  225106. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225107. {
  225108. #if SUPPORT_AFFINITIES
  225109. cpu_set_t affinity;
  225110. CPU_ZERO (&affinity);
  225111. for (int i = 0; i < 32; ++i)
  225112. if ((affinityMask & (1 << i)) != 0)
  225113. CPU_SET (i, &affinity);
  225114. /*
  225115. N.B. If this line causes a compile error, then you've probably not got the latest
  225116. version of glibc installed.
  225117. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225118. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225119. */
  225120. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225121. sched_yield();
  225122. #else
  225123. /* affinities aren't supported because either the appropriate header files weren't found,
  225124. or the SUPPORT_AFFINITIES macro was turned off
  225125. */
  225126. jassertfalse;
  225127. (void) affinityMask;
  225128. #endif
  225129. }
  225130. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225131. /*** Start of inlined file: juce_mac_Files.mm ***/
  225132. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225133. // compiled on its own).
  225134. #if JUCE_INCLUDED_FILE
  225135. /*
  225136. Note that a lot of methods that you'd expect to find in this file actually
  225137. live in juce_posix_SharedCode.h!
  225138. */
  225139. bool File::copyInternal (const File& dest) const
  225140. {
  225141. const ScopedAutoReleasePool pool;
  225142. NSFileManager* fm = [NSFileManager defaultManager];
  225143. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225144. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225145. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225146. toPath: juceStringToNS (dest.getFullPathName())
  225147. error: nil];
  225148. #else
  225149. && [fm copyPath: juceStringToNS (fullPath)
  225150. toPath: juceStringToNS (dest.getFullPathName())
  225151. handler: nil];
  225152. #endif
  225153. }
  225154. void File::findFileSystemRoots (Array<File>& destArray)
  225155. {
  225156. destArray.add (File ("/"));
  225157. }
  225158. namespace FileHelpers
  225159. {
  225160. bool isFileOnDriveType (const File& f, const char* const* types)
  225161. {
  225162. struct statfs buf;
  225163. if (juce_doStatFS (f, buf))
  225164. {
  225165. const String type (buf.f_fstypename);
  225166. while (*types != 0)
  225167. if (type.equalsIgnoreCase (*types++))
  225168. return true;
  225169. }
  225170. return false;
  225171. }
  225172. bool isHiddenFile (const String& path)
  225173. {
  225174. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225175. const ScopedAutoReleasePool pool;
  225176. NSNumber* hidden = nil;
  225177. NSError* err = nil;
  225178. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225179. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225180. && [hidden boolValue];
  225181. #else
  225182. #if JUCE_IOS
  225183. return File (path).getFileName().startsWithChar ('.');
  225184. #else
  225185. FSRef ref;
  225186. LSItemInfoRecord info;
  225187. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225188. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225189. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225190. #endif
  225191. #endif
  225192. }
  225193. #if JUCE_IOS
  225194. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225195. {
  225196. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225197. objectAtIndex: 0]);
  225198. }
  225199. #endif
  225200. bool launchExecutable (const String& pathAndArguments)
  225201. {
  225202. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225203. const int cpid = fork();
  225204. if (cpid == 0)
  225205. {
  225206. // Child process
  225207. if (execve (argv[0], (char**) argv, 0) < 0)
  225208. exit (0);
  225209. }
  225210. else
  225211. {
  225212. if (cpid < 0)
  225213. return false;
  225214. }
  225215. return true;
  225216. }
  225217. }
  225218. bool File::isOnCDRomDrive() const
  225219. {
  225220. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225221. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  225222. }
  225223. bool File::isOnHardDisk() const
  225224. {
  225225. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225226. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  225227. }
  225228. bool File::isOnRemovableDrive() const
  225229. {
  225230. #if JUCE_IOS
  225231. return false; // xxx is this possible?
  225232. #else
  225233. const ScopedAutoReleasePool pool;
  225234. BOOL removable = false;
  225235. [[NSWorkspace sharedWorkspace]
  225236. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225237. isRemovable: &removable
  225238. isWritable: nil
  225239. isUnmountable: nil
  225240. description: nil
  225241. type: nil];
  225242. return removable;
  225243. #endif
  225244. }
  225245. bool File::isHidden() const
  225246. {
  225247. return FileHelpers::isHiddenFile (getFullPathName());
  225248. }
  225249. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225250. const File File::getSpecialLocation (const SpecialLocationType type)
  225251. {
  225252. const ScopedAutoReleasePool pool;
  225253. String resultPath;
  225254. switch (type)
  225255. {
  225256. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225257. #if JUCE_IOS
  225258. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  225259. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  225260. case tempDirectory:
  225261. {
  225262. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  225263. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225264. tmp.createDirectory();
  225265. return tmp.getFullPathName();
  225266. }
  225267. #else
  225268. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225269. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225270. case tempDirectory:
  225271. {
  225272. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225273. tmp.createDirectory();
  225274. return tmp.getFullPathName();
  225275. }
  225276. #endif
  225277. case userMusicDirectory: resultPath = "~/Music"; break;
  225278. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225279. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225280. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225281. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225282. case invokedExecutableFile:
  225283. if (juce_Argv0 != 0)
  225284. return File (String::fromUTF8 (juce_Argv0));
  225285. // deliberate fall-through...
  225286. case currentExecutableFile:
  225287. return juce_getExecutableFile();
  225288. case currentApplicationFile:
  225289. {
  225290. const File exe (juce_getExecutableFile());
  225291. const File parent (exe.getParentDirectory());
  225292. #if JUCE_IOS
  225293. return parent;
  225294. #else
  225295. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225296. ? parent.getParentDirectory().getParentDirectory()
  225297. : exe;
  225298. #endif
  225299. }
  225300. case hostApplicationPath:
  225301. {
  225302. unsigned int size = 8192;
  225303. HeapBlock<char> buffer;
  225304. buffer.calloc (size + 8);
  225305. _NSGetExecutablePath (buffer.getData(), &size);
  225306. return String::fromUTF8 (buffer, size);
  225307. }
  225308. default:
  225309. jassertfalse; // unknown type?
  225310. break;
  225311. }
  225312. if (resultPath.isNotEmpty())
  225313. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225314. return File::nonexistent;
  225315. }
  225316. const String File::getVersion() const
  225317. {
  225318. const ScopedAutoReleasePool pool;
  225319. String result;
  225320. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225321. if (bundle != 0)
  225322. {
  225323. NSDictionary* info = [bundle infoDictionary];
  225324. if (info != 0)
  225325. {
  225326. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225327. if (name != nil)
  225328. result = nsStringToJuce (name);
  225329. }
  225330. }
  225331. return result;
  225332. }
  225333. const File File::getLinkedTarget() const
  225334. {
  225335. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225336. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225337. #else
  225338. // (the cast here avoids a deprecation warning)
  225339. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225340. #endif
  225341. if (dest != nil)
  225342. return File (nsStringToJuce (dest));
  225343. return *this;
  225344. }
  225345. bool File::moveToTrash() const
  225346. {
  225347. if (! exists())
  225348. return true;
  225349. #if JUCE_IOS
  225350. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225351. #else
  225352. const ScopedAutoReleasePool pool;
  225353. NSString* p = juceStringToNS (getFullPathName());
  225354. return [[NSWorkspace sharedWorkspace]
  225355. performFileOperation: NSWorkspaceRecycleOperation
  225356. source: [p stringByDeletingLastPathComponent]
  225357. destination: @""
  225358. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225359. tag: nil ];
  225360. #endif
  225361. }
  225362. class DirectoryIterator::NativeIterator::Pimpl
  225363. {
  225364. public:
  225365. Pimpl (const File& directory, const String& wildCard_)
  225366. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225367. wildCard (wildCard_),
  225368. enumerator (0)
  225369. {
  225370. const ScopedAutoReleasePool pool;
  225371. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225372. wildcardUTF8 = wildCard.toUTF8();
  225373. }
  225374. ~Pimpl()
  225375. {
  225376. [enumerator release];
  225377. }
  225378. bool next (String& filenameFound,
  225379. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225380. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225381. {
  225382. const ScopedAutoReleasePool pool;
  225383. for (;;)
  225384. {
  225385. NSString* file;
  225386. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225387. return false;
  225388. [enumerator skipDescendents];
  225389. filenameFound = nsStringToJuce (file);
  225390. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225391. continue;
  225392. const String path (parentDir + filenameFound);
  225393. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  225394. if (isHidden != 0)
  225395. *isHidden = FileHelpers::isHiddenFile (path);
  225396. return true;
  225397. }
  225398. }
  225399. private:
  225400. String parentDir, wildCard;
  225401. const char* wildcardUTF8;
  225402. NSDirectoryEnumerator* enumerator;
  225403. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  225404. };
  225405. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225406. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225407. {
  225408. }
  225409. DirectoryIterator::NativeIterator::~NativeIterator()
  225410. {
  225411. }
  225412. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225413. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225414. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225415. {
  225416. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225417. }
  225418. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225419. {
  225420. #if JUCE_IOS
  225421. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225422. #else
  225423. const ScopedAutoReleasePool pool;
  225424. if (parameters.isEmpty())
  225425. {
  225426. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225427. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225428. }
  225429. bool ok = false;
  225430. if (PlatformUtilities::isBundle (fileName))
  225431. {
  225432. NSMutableArray* urls = [NSMutableArray array];
  225433. StringArray docs;
  225434. docs.addTokens (parameters, true);
  225435. for (int i = 0; i < docs.size(); ++i)
  225436. [urls addObject: juceStringToNS (docs[i])];
  225437. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225438. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225439. options: 0
  225440. additionalEventParamDescriptor: nil
  225441. launchIdentifiers: nil];
  225442. }
  225443. else if (File (fileName).exists())
  225444. {
  225445. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  225446. }
  225447. return ok;
  225448. #endif
  225449. }
  225450. void File::revealToUser() const
  225451. {
  225452. #if ! JUCE_IOS
  225453. if (exists())
  225454. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225455. else if (getParentDirectory().exists())
  225456. getParentDirectory().revealToUser();
  225457. #endif
  225458. }
  225459. #if ! JUCE_IOS
  225460. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225461. {
  225462. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225463. }
  225464. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225465. {
  225466. char path [2048];
  225467. zerostruct (path);
  225468. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225469. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225470. return String::empty;
  225471. }
  225472. #endif
  225473. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225474. {
  225475. const ScopedAutoReleasePool pool;
  225476. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225477. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225478. #else
  225479. // (the cast here avoids a deprecation warning)
  225480. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225481. #endif
  225482. return [fileDict fileHFSTypeCode];
  225483. }
  225484. bool PlatformUtilities::isBundle (const String& filename)
  225485. {
  225486. #if JUCE_IOS
  225487. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225488. #else
  225489. const ScopedAutoReleasePool pool;
  225490. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225491. #endif
  225492. }
  225493. #endif
  225494. /*** End of inlined file: juce_mac_Files.mm ***/
  225495. #if JUCE_IOS
  225496. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225497. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225498. // compiled on its own).
  225499. #if JUCE_INCLUDED_FILE
  225500. END_JUCE_NAMESPACE
  225501. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225502. {
  225503. }
  225504. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225505. - (void) applicationWillTerminate: (UIApplication*) application;
  225506. @end
  225507. @implementation JuceAppStartupDelegate
  225508. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225509. {
  225510. initialiseJuce_GUI();
  225511. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225512. exit (0);
  225513. }
  225514. - (void) applicationWillTerminate: (UIApplication*) application
  225515. {
  225516. JUCEApplication::appWillTerminateByForce();
  225517. }
  225518. @end
  225519. BEGIN_JUCE_NAMESPACE
  225520. int juce_iOSMain (int argc, const char* argv[])
  225521. {
  225522. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225523. }
  225524. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225525. {
  225526. pool = [[NSAutoreleasePool alloc] init];
  225527. }
  225528. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225529. {
  225530. [((NSAutoreleasePool*) pool) release];
  225531. }
  225532. void PlatformUtilities::beep()
  225533. {
  225534. //xxx
  225535. //AudioServicesPlaySystemSound ();
  225536. }
  225537. void PlatformUtilities::addItemToDock (const File& file)
  225538. {
  225539. }
  225540. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225541. END_JUCE_NAMESPACE
  225542. @interface JuceAlertBoxDelegate : NSObject
  225543. {
  225544. @public
  225545. bool clickedOk;
  225546. }
  225547. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225548. @end
  225549. @implementation JuceAlertBoxDelegate
  225550. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225551. {
  225552. clickedOk = (buttonIndex == 0);
  225553. alertView.hidden = true;
  225554. }
  225555. @end
  225556. BEGIN_JUCE_NAMESPACE
  225557. // (This function is used directly by other bits of code)
  225558. bool juce_iPhoneShowModalAlert (const String& title,
  225559. const String& bodyText,
  225560. NSString* okButtonText,
  225561. NSString* cancelButtonText)
  225562. {
  225563. const ScopedAutoReleasePool pool;
  225564. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225565. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225566. message: juceStringToNS (bodyText)
  225567. delegate: callback
  225568. cancelButtonTitle: okButtonText
  225569. otherButtonTitles: cancelButtonText, nil];
  225570. [alert retain];
  225571. [alert show];
  225572. while (! alert.hidden && alert.superview != nil)
  225573. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225574. const bool result = callback->clickedOk;
  225575. [alert release];
  225576. [callback release];
  225577. return result;
  225578. }
  225579. bool AlertWindow::showNativeDialogBox (const String& title,
  225580. const String& bodyText,
  225581. bool isOkCancel)
  225582. {
  225583. return juce_iPhoneShowModalAlert (title, bodyText,
  225584. @"OK",
  225585. isOkCancel ? @"Cancel" : nil);
  225586. }
  225587. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225588. {
  225589. jassertfalse; // no such thing on the iphone!
  225590. return false;
  225591. }
  225592. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225593. {
  225594. jassertfalse; // no such thing on the iphone!
  225595. return false;
  225596. }
  225597. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225598. {
  225599. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225600. }
  225601. bool Desktop::isScreenSaverEnabled()
  225602. {
  225603. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225604. }
  225605. #endif
  225606. #endif
  225607. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225608. #else
  225609. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225610. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225611. // compiled on its own).
  225612. #if JUCE_INCLUDED_FILE
  225613. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225614. {
  225615. pool = [[NSAutoreleasePool alloc] init];
  225616. }
  225617. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225618. {
  225619. [((NSAutoreleasePool*) pool) release];
  225620. }
  225621. void PlatformUtilities::beep()
  225622. {
  225623. NSBeep();
  225624. }
  225625. void PlatformUtilities::addItemToDock (const File& file)
  225626. {
  225627. // check that it's not already there...
  225628. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225629. .containsIgnoreCase (file.getFullPathName()))
  225630. {
  225631. 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>"
  225632. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225633. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225634. }
  225635. }
  225636. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225637. bool AlertWindow::showNativeDialogBox (const String& title,
  225638. const String& bodyText,
  225639. bool isOkCancel)
  225640. {
  225641. const ScopedAutoReleasePool pool;
  225642. return NSRunAlertPanel (juceStringToNS (title),
  225643. juceStringToNS (bodyText),
  225644. @"Ok",
  225645. isOkCancel ? @"Cancel" : nil,
  225646. nil) == NSAlertDefaultReturn;
  225647. }
  225648. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225649. {
  225650. if (files.size() == 0)
  225651. return false;
  225652. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225653. if (draggingSource == 0)
  225654. {
  225655. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225656. return false;
  225657. }
  225658. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225659. if (sourceComp == 0)
  225660. {
  225661. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225662. return false;
  225663. }
  225664. const ScopedAutoReleasePool pool;
  225665. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225666. if (view == 0)
  225667. return false;
  225668. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225669. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225670. owner: nil];
  225671. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225672. for (int i = 0; i < files.size(); ++i)
  225673. [filesArray addObject: juceStringToNS (files[i])];
  225674. [pboard setPropertyList: filesArray
  225675. forType: NSFilenamesPboardType];
  225676. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225677. fromView: nil];
  225678. dragPosition.x -= 16;
  225679. dragPosition.y -= 16;
  225680. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225681. at: dragPosition
  225682. offset: NSMakeSize (0, 0)
  225683. event: [[view window] currentEvent]
  225684. pasteboard: pboard
  225685. source: view
  225686. slideBack: YES];
  225687. return true;
  225688. }
  225689. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225690. {
  225691. jassertfalse; // not implemented!
  225692. return false;
  225693. }
  225694. bool Desktop::canUseSemiTransparentWindows() throw()
  225695. {
  225696. return true;
  225697. }
  225698. const Point<int> MouseInputSource::getCurrentMousePosition()
  225699. {
  225700. const ScopedAutoReleasePool pool;
  225701. const NSPoint p ([NSEvent mouseLocation]);
  225702. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225703. }
  225704. void Desktop::setMousePosition (const Point<int>& newPosition)
  225705. {
  225706. // this rubbish needs to be done around the warp call, to avoid causing a
  225707. // bizarre glitch..
  225708. CGAssociateMouseAndMouseCursorPosition (false);
  225709. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225710. CGAssociateMouseAndMouseCursorPosition (true);
  225711. }
  225712. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225713. {
  225714. return upright;
  225715. }
  225716. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225717. class ScreenSaverDefeater : public Timer,
  225718. public DeletedAtShutdown
  225719. {
  225720. public:
  225721. ScreenSaverDefeater()
  225722. {
  225723. startTimer (10000);
  225724. timerCallback();
  225725. }
  225726. ~ScreenSaverDefeater() {}
  225727. void timerCallback()
  225728. {
  225729. if (Process::isForegroundProcess())
  225730. UpdateSystemActivity (UsrActivity);
  225731. }
  225732. };
  225733. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225734. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225735. {
  225736. if (isEnabled)
  225737. deleteAndZero (screenSaverDefeater);
  225738. else if (screenSaverDefeater == 0)
  225739. screenSaverDefeater = new ScreenSaverDefeater();
  225740. }
  225741. bool Desktop::isScreenSaverEnabled()
  225742. {
  225743. return screenSaverDefeater == 0;
  225744. }
  225745. #else
  225746. static IOPMAssertionID screenSaverDisablerID = 0;
  225747. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225748. {
  225749. if (isEnabled)
  225750. {
  225751. if (screenSaverDisablerID != 0)
  225752. {
  225753. IOPMAssertionRelease (screenSaverDisablerID);
  225754. screenSaverDisablerID = 0;
  225755. }
  225756. }
  225757. else
  225758. {
  225759. if (screenSaverDisablerID == 0)
  225760. {
  225761. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225762. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225763. CFSTR ("Juce"), &screenSaverDisablerID);
  225764. #else
  225765. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225766. &screenSaverDisablerID);
  225767. #endif
  225768. }
  225769. }
  225770. }
  225771. bool Desktop::isScreenSaverEnabled()
  225772. {
  225773. return screenSaverDisablerID == 0;
  225774. }
  225775. #endif
  225776. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225777. {
  225778. const ScopedAutoReleasePool pool;
  225779. monitorCoords.clear();
  225780. NSArray* screens = [NSScreen screens];
  225781. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225782. for (unsigned int i = 0; i < [screens count]; ++i)
  225783. {
  225784. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225785. NSRect r = clipToWorkArea ? [s visibleFrame]
  225786. : [s frame];
  225787. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225788. monitorCoords.add (convertToRectInt (r));
  225789. }
  225790. jassert (monitorCoords.size() > 0);
  225791. }
  225792. #endif
  225793. #endif
  225794. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225795. #endif
  225796. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225797. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225798. // compiled on its own).
  225799. #if JUCE_INCLUDED_FILE
  225800. void Logger::outputDebugString (const String& text)
  225801. {
  225802. std::cerr << text << std::endl;
  225803. }
  225804. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225805. {
  225806. static char testResult = 0;
  225807. if (testResult == 0)
  225808. {
  225809. struct kinfo_proc info;
  225810. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225811. size_t sz = sizeof (info);
  225812. sysctl (m, 4, &info, &sz, 0, 0);
  225813. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225814. }
  225815. return testResult > 0;
  225816. }
  225817. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225818. {
  225819. return juce_isRunningUnderDebugger();
  225820. }
  225821. #endif
  225822. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225823. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225824. #if JUCE_IOS
  225825. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225826. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225827. // compiled on its own).
  225828. #if JUCE_INCLUDED_FILE
  225829. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225830. #define SUPPORT_10_4_FONTS 1
  225831. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225832. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225833. #define SUPPORT_ONLY_10_4_FONTS 1
  225834. #endif
  225835. END_JUCE_NAMESPACE
  225836. @interface NSFont (PrivateHack)
  225837. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225838. @end
  225839. BEGIN_JUCE_NAMESPACE
  225840. #endif
  225841. class MacTypeface : public Typeface
  225842. {
  225843. public:
  225844. MacTypeface (const Font& font)
  225845. : Typeface (font.getTypefaceName())
  225846. {
  225847. const ScopedAutoReleasePool pool;
  225848. renderingTransform = CGAffineTransformIdentity;
  225849. bool needsItalicTransform = false;
  225850. #if JUCE_IOS
  225851. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225852. if (font.isItalic() || font.isBold())
  225853. {
  225854. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225855. for (NSString* i in familyFonts)
  225856. {
  225857. const String fn (nsStringToJuce (i));
  225858. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225859. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225860. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225861. || afterDash.containsIgnoreCase ("italic")
  225862. || fn.endsWithIgnoreCase ("oblique")
  225863. || fn.endsWithIgnoreCase ("italic");
  225864. if (probablyBold == font.isBold()
  225865. && probablyItalic == font.isItalic())
  225866. {
  225867. fontName = i;
  225868. needsItalicTransform = false;
  225869. break;
  225870. }
  225871. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225872. {
  225873. fontName = i;
  225874. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225875. }
  225876. }
  225877. if (needsItalicTransform)
  225878. renderingTransform.c = 0.15f;
  225879. }
  225880. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225881. const int ascender = abs (CGFontGetAscent (fontRef));
  225882. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225883. ascent = ascender / totalHeight;
  225884. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225885. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225886. #else
  225887. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225888. if (font.isItalic())
  225889. {
  225890. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225891. toHaveTrait: NSItalicFontMask];
  225892. if (newFont == nsFont)
  225893. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225894. nsFont = newFont;
  225895. }
  225896. if (font.isBold())
  225897. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225898. [nsFont retain];
  225899. ascent = std::abs ((float) [nsFont ascender]);
  225900. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225901. ascent /= totalSize;
  225902. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225903. if (needsItalicTransform)
  225904. {
  225905. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225906. renderingTransform.c = 0.15f;
  225907. }
  225908. #if SUPPORT_ONLY_10_4_FONTS
  225909. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225910. if (atsFont == 0)
  225911. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225912. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225913. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225914. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225915. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225916. #else
  225917. #if SUPPORT_10_4_FONTS
  225918. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225919. {
  225920. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225921. if (atsFont == 0)
  225922. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225923. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225924. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225925. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225926. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225927. }
  225928. else
  225929. #endif
  225930. {
  225931. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225932. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225933. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225934. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225935. }
  225936. #endif
  225937. #endif
  225938. }
  225939. ~MacTypeface()
  225940. {
  225941. #if ! JUCE_IOS
  225942. [nsFont release];
  225943. #endif
  225944. if (fontRef != 0)
  225945. CGFontRelease (fontRef);
  225946. }
  225947. float getAscent() const
  225948. {
  225949. return ascent;
  225950. }
  225951. float getDescent() const
  225952. {
  225953. return 1.0f - ascent;
  225954. }
  225955. float getStringWidth (const String& text)
  225956. {
  225957. if (fontRef == 0 || text.isEmpty())
  225958. return 0;
  225959. const int length = text.length();
  225960. HeapBlock <CGGlyph> glyphs;
  225961. createGlyphsForString (text, length, glyphs);
  225962. float x = 0;
  225963. #if SUPPORT_ONLY_10_4_FONTS
  225964. HeapBlock <NSSize> advances (length);
  225965. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225966. for (int i = 0; i < length; ++i)
  225967. x += advances[i].width;
  225968. #else
  225969. #if SUPPORT_10_4_FONTS
  225970. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225971. {
  225972. HeapBlock <NSSize> advances (length);
  225973. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225974. for (int i = 0; i < length; ++i)
  225975. x += advances[i].width;
  225976. }
  225977. else
  225978. #endif
  225979. {
  225980. HeapBlock <int> advances (length);
  225981. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225982. for (int i = 0; i < length; ++i)
  225983. x += advances[i];
  225984. }
  225985. #endif
  225986. return x * unitsToHeightScaleFactor;
  225987. }
  225988. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225989. {
  225990. xOffsets.add (0);
  225991. if (fontRef == 0 || text.isEmpty())
  225992. return;
  225993. const int length = text.length();
  225994. HeapBlock <CGGlyph> glyphs;
  225995. createGlyphsForString (text, length, glyphs);
  225996. #if SUPPORT_ONLY_10_4_FONTS
  225997. HeapBlock <NSSize> advances (length);
  225998. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225999. int x = 0;
  226000. for (int i = 0; i < length; ++i)
  226001. {
  226002. x += advances[i].width;
  226003. xOffsets.add (x * unitsToHeightScaleFactor);
  226004. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226005. }
  226006. #else
  226007. #if SUPPORT_10_4_FONTS
  226008. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226009. {
  226010. HeapBlock <NSSize> advances (length);
  226011. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226012. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226013. float x = 0;
  226014. for (int i = 0; i < length; ++i)
  226015. {
  226016. x += advances[i].width;
  226017. xOffsets.add (x * unitsToHeightScaleFactor);
  226018. resultGlyphs.add (nsGlyphs[i]);
  226019. }
  226020. }
  226021. else
  226022. #endif
  226023. {
  226024. HeapBlock <int> advances (length);
  226025. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226026. {
  226027. int x = 0;
  226028. for (int i = 0; i < length; ++i)
  226029. {
  226030. x += advances [i];
  226031. xOffsets.add (x * unitsToHeightScaleFactor);
  226032. resultGlyphs.add (glyphs[i]);
  226033. }
  226034. }
  226035. }
  226036. #endif
  226037. }
  226038. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226039. {
  226040. #if JUCE_IOS
  226041. return false;
  226042. #else
  226043. if (nsFont == 0)
  226044. return false;
  226045. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226046. jassert (path.isEmpty());
  226047. const ScopedAutoReleasePool pool;
  226048. NSBezierPath* bez = [NSBezierPath bezierPath];
  226049. [bez moveToPoint: NSMakePoint (0, 0)];
  226050. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226051. inFont: nsFont];
  226052. for (int i = 0; i < [bez elementCount]; ++i)
  226053. {
  226054. NSPoint p[3];
  226055. switch ([bez elementAtIndex: i associatedPoints: p])
  226056. {
  226057. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  226058. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  226059. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  226060. (float) p[1].x, (float) -p[1].y,
  226061. (float) p[2].x, (float) -p[2].y); break;
  226062. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  226063. default: jassertfalse; break;
  226064. }
  226065. }
  226066. path.applyTransform (pathTransform);
  226067. return true;
  226068. #endif
  226069. }
  226070. CGFontRef fontRef;
  226071. float fontHeightToCGSizeFactor;
  226072. CGAffineTransform renderingTransform;
  226073. private:
  226074. float ascent, unitsToHeightScaleFactor;
  226075. #if JUCE_IOS
  226076. #else
  226077. NSFont* nsFont;
  226078. AffineTransform pathTransform;
  226079. #endif
  226080. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226081. {
  226082. #if SUPPORT_10_4_FONTS
  226083. #if ! SUPPORT_ONLY_10_4_FONTS
  226084. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226085. #endif
  226086. {
  226087. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226088. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226089. for (int i = 0; i < length; ++i)
  226090. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226091. return;
  226092. }
  226093. #endif
  226094. #if ! SUPPORT_ONLY_10_4_FONTS
  226095. if (charToGlyphMapper == 0)
  226096. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226097. glyphs.malloc (length);
  226098. for (int i = 0; i < length; ++i)
  226099. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226100. #endif
  226101. }
  226102. #if ! SUPPORT_ONLY_10_4_FONTS
  226103. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226104. class CharToGlyphMapper
  226105. {
  226106. public:
  226107. CharToGlyphMapper (CGFontRef fontRef)
  226108. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226109. idRangeOffset (0), glyphIndexes (0)
  226110. {
  226111. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226112. if (cmapTable != 0)
  226113. {
  226114. const int numSubtables = getValue16 (cmapTable, 2);
  226115. for (int i = 0; i < numSubtables; ++i)
  226116. {
  226117. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226118. {
  226119. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226120. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226121. {
  226122. const int length = getValue16 (cmapTable, offset + 2);
  226123. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226124. segCount = segCountX2 / 2;
  226125. const int endCodeOffset = offset + 14;
  226126. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226127. const int idDeltaOffset = startCodeOffset + segCountX2;
  226128. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226129. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226130. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226131. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226132. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226133. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226134. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226135. }
  226136. break;
  226137. }
  226138. }
  226139. CFRelease (cmapTable);
  226140. }
  226141. }
  226142. ~CharToGlyphMapper()
  226143. {
  226144. if (endCode != 0)
  226145. {
  226146. CFRelease (endCode);
  226147. CFRelease (startCode);
  226148. CFRelease (idDelta);
  226149. CFRelease (idRangeOffset);
  226150. CFRelease (glyphIndexes);
  226151. }
  226152. }
  226153. int getGlyphForCharacter (const juce_wchar c) const
  226154. {
  226155. for (int i = 0; i < segCount; ++i)
  226156. {
  226157. if (getValue16 (endCode, i * 2) >= c)
  226158. {
  226159. const int start = getValue16 (startCode, i * 2);
  226160. if (start > c)
  226161. break;
  226162. const int delta = getValue16 (idDelta, i * 2);
  226163. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226164. if (rangeOffset == 0)
  226165. return delta + c;
  226166. else
  226167. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226168. }
  226169. }
  226170. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226171. return jmax (-1, (int) c - 29);
  226172. }
  226173. private:
  226174. int segCount;
  226175. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226176. static uint16 getValue16 (CFDataRef data, const int index)
  226177. {
  226178. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226179. }
  226180. static uint32 getValue32 (CFDataRef data, const int index)
  226181. {
  226182. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226183. }
  226184. };
  226185. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226186. #endif
  226187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  226188. };
  226189. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226190. {
  226191. return new MacTypeface (font);
  226192. }
  226193. const StringArray Font::findAllTypefaceNames()
  226194. {
  226195. StringArray names;
  226196. const ScopedAutoReleasePool pool;
  226197. #if JUCE_IOS
  226198. NSArray* fonts = [UIFont familyNames];
  226199. #else
  226200. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226201. #endif
  226202. for (unsigned int i = 0; i < [fonts count]; ++i)
  226203. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226204. names.sort (true);
  226205. return names;
  226206. }
  226207. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  226208. {
  226209. #if JUCE_IOS
  226210. defaultSans = "Helvetica";
  226211. defaultSerif = "Times New Roman";
  226212. defaultFixed = "Courier New";
  226213. #else
  226214. defaultSans = "Lucida Grande";
  226215. defaultSerif = "Times New Roman";
  226216. defaultFixed = "Monaco";
  226217. #endif
  226218. defaultFallback = "Arial Unicode MS";
  226219. }
  226220. #endif
  226221. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226222. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226223. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226224. // compiled on its own).
  226225. #if JUCE_INCLUDED_FILE
  226226. class CoreGraphicsImage : public Image::SharedImage
  226227. {
  226228. public:
  226229. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226230. : Image::SharedImage (format_, width_, height_)
  226231. {
  226232. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226233. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226234. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226235. imageData = imageDataAllocated;
  226236. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226237. : CGColorSpaceCreateDeviceRGB();
  226238. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226239. colourSpace, getCGImageFlags (format_));
  226240. CGColorSpaceRelease (colourSpace);
  226241. }
  226242. ~CoreGraphicsImage()
  226243. {
  226244. CGContextRelease (context);
  226245. }
  226246. Image::ImageType getType() const { return Image::NativeImage; }
  226247. LowLevelGraphicsContext* createLowLevelContext();
  226248. SharedImage* clone()
  226249. {
  226250. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226251. memcpy (im->imageData, imageData, lineStride * height);
  226252. return im;
  226253. }
  226254. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226255. {
  226256. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226257. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226258. {
  226259. return CGBitmapContextCreateImage (nativeImage->context);
  226260. }
  226261. else
  226262. {
  226263. const Image::BitmapData srcData (juceImage, false);
  226264. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226265. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226266. 8, srcData.pixelStride * 8, srcData.lineStride,
  226267. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226268. 0, true, kCGRenderingIntentDefault);
  226269. CGDataProviderRelease (provider);
  226270. return imageRef;
  226271. }
  226272. }
  226273. #if JUCE_MAC
  226274. static NSImage* createNSImage (const Image& image)
  226275. {
  226276. const ScopedAutoReleasePool pool;
  226277. NSImage* im = [[NSImage alloc] init];
  226278. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226279. [im lockFocus];
  226280. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226281. CGImageRef imageRef = createImage (image, false, colourSpace);
  226282. CGColorSpaceRelease (colourSpace);
  226283. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226284. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226285. CGImageRelease (imageRef);
  226286. [im unlockFocus];
  226287. return im;
  226288. }
  226289. #endif
  226290. CGContextRef context;
  226291. HeapBlock<uint8> imageDataAllocated;
  226292. private:
  226293. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226294. {
  226295. #if JUCE_BIG_ENDIAN
  226296. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226297. #else
  226298. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226299. #endif
  226300. }
  226301. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  226302. };
  226303. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226304. {
  226305. #if USE_COREGRAPHICS_RENDERING
  226306. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226307. #else
  226308. return createSoftwareImage (format, width, height, clearImage);
  226309. #endif
  226310. }
  226311. class CoreGraphicsContext : public LowLevelGraphicsContext
  226312. {
  226313. public:
  226314. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226315. : context (context_),
  226316. flipHeight (flipHeight_),
  226317. lastClipRectIsValid (false),
  226318. state (new SavedState()),
  226319. numGradientLookupEntries (0)
  226320. {
  226321. CGContextRetain (context);
  226322. CGContextSaveGState(context);
  226323. CGContextSetShouldSmoothFonts (context, true);
  226324. CGContextSetShouldAntialias (context, true);
  226325. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226326. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226327. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226328. gradientCallbacks.version = 0;
  226329. gradientCallbacks.evaluate = gradientCallback;
  226330. gradientCallbacks.releaseInfo = 0;
  226331. setFont (Font());
  226332. }
  226333. ~CoreGraphicsContext()
  226334. {
  226335. CGContextRestoreGState (context);
  226336. CGContextRelease (context);
  226337. CGColorSpaceRelease (rgbColourSpace);
  226338. CGColorSpaceRelease (greyColourSpace);
  226339. }
  226340. bool isVectorDevice() const { return false; }
  226341. void setOrigin (int x, int y)
  226342. {
  226343. CGContextTranslateCTM (context, x, -y);
  226344. if (lastClipRectIsValid)
  226345. lastClipRect.translate (-x, -y);
  226346. }
  226347. void addTransform (const AffineTransform& transform)
  226348. {
  226349. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  226350. .translated (0, flipHeight)
  226351. .followedBy (transform)
  226352. .translated (0, -flipHeight)
  226353. .scaled (1.0f, -1.0f));
  226354. lastClipRectIsValid = false;
  226355. }
  226356. float getScaleFactor()
  226357. {
  226358. CGAffineTransform t = CGContextGetCTM (context);
  226359. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  226360. }
  226361. bool clipToRectangle (const Rectangle<int>& r)
  226362. {
  226363. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226364. if (lastClipRectIsValid)
  226365. {
  226366. // This is actually incorrect, because the actual clip region may be complex, and
  226367. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226368. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226369. // when calculating the resultant clip bounds, and makes the same mistake!
  226370. lastClipRect = lastClipRect.getIntersection (r);
  226371. return ! lastClipRect.isEmpty();
  226372. }
  226373. return ! isClipEmpty();
  226374. }
  226375. bool clipToRectangleList (const RectangleList& clipRegion)
  226376. {
  226377. if (clipRegion.isEmpty())
  226378. {
  226379. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226380. lastClipRectIsValid = true;
  226381. lastClipRect = Rectangle<int>();
  226382. return false;
  226383. }
  226384. else
  226385. {
  226386. const int numRects = clipRegion.getNumRectangles();
  226387. HeapBlock <CGRect> rects (numRects);
  226388. for (int i = 0; i < numRects; ++i)
  226389. {
  226390. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226391. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226392. }
  226393. CGContextClipToRects (context, rects, numRects);
  226394. lastClipRectIsValid = false;
  226395. return ! isClipEmpty();
  226396. }
  226397. }
  226398. void excludeClipRectangle (const Rectangle<int>& r)
  226399. {
  226400. RectangleList remaining (getClipBounds());
  226401. remaining.subtract (r);
  226402. clipToRectangleList (remaining);
  226403. lastClipRectIsValid = false;
  226404. }
  226405. void clipToPath (const Path& path, const AffineTransform& transform)
  226406. {
  226407. createPath (path, transform);
  226408. CGContextClip (context);
  226409. lastClipRectIsValid = false;
  226410. }
  226411. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226412. {
  226413. if (! transform.isSingularity())
  226414. {
  226415. Image singleChannelImage (sourceImage);
  226416. if (sourceImage.getFormat() != Image::SingleChannel)
  226417. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226418. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226419. flip();
  226420. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226421. applyTransform (t);
  226422. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226423. CGContextClipToMask (context, r, image);
  226424. applyTransform (t.inverted());
  226425. flip();
  226426. CGImageRelease (image);
  226427. lastClipRectIsValid = false;
  226428. }
  226429. }
  226430. bool clipRegionIntersects (const Rectangle<int>& r)
  226431. {
  226432. return getClipBounds().intersects (r);
  226433. }
  226434. const Rectangle<int> getClipBounds() const
  226435. {
  226436. if (! lastClipRectIsValid)
  226437. {
  226438. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226439. lastClipRectIsValid = true;
  226440. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226441. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226442. roundToInt (bounds.size.width),
  226443. roundToInt (bounds.size.height));
  226444. }
  226445. return lastClipRect;
  226446. }
  226447. bool isClipEmpty() const
  226448. {
  226449. return getClipBounds().isEmpty();
  226450. }
  226451. void saveState()
  226452. {
  226453. CGContextSaveGState (context);
  226454. stateStack.add (new SavedState (*state));
  226455. }
  226456. void restoreState()
  226457. {
  226458. CGContextRestoreGState (context);
  226459. SavedState* const top = stateStack.getLast();
  226460. if (top != 0)
  226461. {
  226462. state = top;
  226463. stateStack.removeLast (1, false);
  226464. lastClipRectIsValid = false;
  226465. }
  226466. else
  226467. {
  226468. jassertfalse; // trying to pop with an empty stack!
  226469. }
  226470. }
  226471. void beginTransparencyLayer (float opacity)
  226472. {
  226473. saveState();
  226474. CGContextSetAlpha (context, opacity);
  226475. CGContextBeginTransparencyLayer (context, 0);
  226476. }
  226477. void endTransparencyLayer()
  226478. {
  226479. CGContextEndTransparencyLayer (context);
  226480. restoreState();
  226481. }
  226482. void setFill (const FillType& fillType)
  226483. {
  226484. state->fillType = fillType;
  226485. if (fillType.isColour())
  226486. {
  226487. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226488. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226489. CGContextSetAlpha (context, 1.0f);
  226490. }
  226491. }
  226492. void setOpacity (float newOpacity)
  226493. {
  226494. state->fillType.setOpacity (newOpacity);
  226495. setFill (state->fillType);
  226496. }
  226497. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226498. {
  226499. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226500. ? kCGInterpolationLow
  226501. : kCGInterpolationHigh);
  226502. }
  226503. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226504. {
  226505. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226506. }
  226507. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226508. {
  226509. if (replaceExistingContents)
  226510. {
  226511. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226512. CGContextClearRect (context, cgRect);
  226513. #else
  226514. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226515. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226516. CGContextClearRect (context, cgRect);
  226517. else
  226518. #endif
  226519. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226520. #endif
  226521. fillCGRect (cgRect, false);
  226522. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226523. }
  226524. else
  226525. {
  226526. if (state->fillType.isColour())
  226527. {
  226528. CGContextFillRect (context, cgRect);
  226529. }
  226530. else if (state->fillType.isGradient())
  226531. {
  226532. CGContextSaveGState (context);
  226533. CGContextClipToRect (context, cgRect);
  226534. drawGradient();
  226535. CGContextRestoreGState (context);
  226536. }
  226537. else
  226538. {
  226539. CGContextSaveGState (context);
  226540. CGContextClipToRect (context, cgRect);
  226541. drawImage (state->fillType.image, state->fillType.transform, true);
  226542. CGContextRestoreGState (context);
  226543. }
  226544. }
  226545. }
  226546. void fillPath (const Path& path, const AffineTransform& transform)
  226547. {
  226548. CGContextSaveGState (context);
  226549. if (state->fillType.isColour())
  226550. {
  226551. flip();
  226552. applyTransform (transform);
  226553. createPath (path);
  226554. if (path.isUsingNonZeroWinding())
  226555. CGContextFillPath (context);
  226556. else
  226557. CGContextEOFillPath (context);
  226558. }
  226559. else
  226560. {
  226561. createPath (path, transform);
  226562. if (path.isUsingNonZeroWinding())
  226563. CGContextClip (context);
  226564. else
  226565. CGContextEOClip (context);
  226566. if (state->fillType.isGradient())
  226567. drawGradient();
  226568. else
  226569. drawImage (state->fillType.image, state->fillType.transform, true);
  226570. }
  226571. CGContextRestoreGState (context);
  226572. }
  226573. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226574. {
  226575. const int iw = sourceImage.getWidth();
  226576. const int ih = sourceImage.getHeight();
  226577. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226578. CGContextSaveGState (context);
  226579. CGContextSetAlpha (context, state->fillType.getOpacity());
  226580. flip();
  226581. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226582. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226583. if (fillEntireClipAsTiles)
  226584. {
  226585. #if JUCE_IOS
  226586. CGContextDrawTiledImage (context, imageRect, image);
  226587. #else
  226588. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226589. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226590. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226591. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226592. CGContextDrawTiledImage (context, imageRect, image);
  226593. else
  226594. #endif
  226595. {
  226596. // Fallback to manually doing a tiled fill on 10.4
  226597. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226598. int x = 0, y = 0;
  226599. while (x > clip.origin.x) x -= iw;
  226600. while (y > clip.origin.y) y -= ih;
  226601. const int right = (int) (clip.origin.x + clip.size.width);
  226602. const int bottom = (int) (clip.origin.y + clip.size.height);
  226603. while (y < bottom)
  226604. {
  226605. for (int x2 = x; x2 < right; x2 += iw)
  226606. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226607. y += ih;
  226608. }
  226609. }
  226610. #endif
  226611. }
  226612. else
  226613. {
  226614. CGContextDrawImage (context, imageRect, image);
  226615. }
  226616. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226617. CGContextRestoreGState (context);
  226618. }
  226619. void drawLine (const Line<float>& line)
  226620. {
  226621. if (state->fillType.isColour())
  226622. {
  226623. CGContextSetLineCap (context, kCGLineCapSquare);
  226624. CGContextSetLineWidth (context, 1.0f);
  226625. CGContextSetRGBStrokeColor (context,
  226626. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226627. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226628. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226629. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226630. CGContextStrokeLineSegments (context, cgLine, 1);
  226631. }
  226632. else
  226633. {
  226634. Path p;
  226635. p.addLineSegment (line, 1.0f);
  226636. fillPath (p, AffineTransform::identity);
  226637. }
  226638. }
  226639. void drawVerticalLine (const int x, float top, float bottom)
  226640. {
  226641. if (state->fillType.isColour())
  226642. {
  226643. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226644. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226645. #else
  226646. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226647. // the x co-ord slightly to trick it..
  226648. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226649. #endif
  226650. }
  226651. else
  226652. {
  226653. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226654. }
  226655. }
  226656. void drawHorizontalLine (const int y, float left, float right)
  226657. {
  226658. if (state->fillType.isColour())
  226659. {
  226660. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226661. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226662. #else
  226663. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226664. // the x co-ord slightly to trick it..
  226665. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226666. #endif
  226667. }
  226668. else
  226669. {
  226670. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226671. }
  226672. }
  226673. void setFont (const Font& newFont)
  226674. {
  226675. if (state->font != newFont)
  226676. {
  226677. state->fontRef = 0;
  226678. state->font = newFont;
  226679. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226680. if (mf != 0)
  226681. {
  226682. state->fontRef = mf->fontRef;
  226683. CGContextSetFont (context, state->fontRef);
  226684. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226685. state->fontTransform = mf->renderingTransform;
  226686. state->fontTransform.a *= state->font.getHorizontalScale();
  226687. CGContextSetTextMatrix (context, state->fontTransform);
  226688. }
  226689. }
  226690. }
  226691. const Font getFont()
  226692. {
  226693. return state->font;
  226694. }
  226695. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226696. {
  226697. if (state->fontRef != 0 && state->fillType.isColour())
  226698. {
  226699. if (transform.isOnlyTranslation())
  226700. {
  226701. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226702. CGGlyph g = glyphNumber;
  226703. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226704. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226705. }
  226706. else
  226707. {
  226708. CGContextSaveGState (context);
  226709. flip();
  226710. applyTransform (transform);
  226711. CGAffineTransform t = state->fontTransform;
  226712. t.d = -t.d;
  226713. CGContextSetTextMatrix (context, t);
  226714. CGGlyph g = glyphNumber;
  226715. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226716. CGContextRestoreGState (context);
  226717. }
  226718. }
  226719. else
  226720. {
  226721. Path p;
  226722. Font& f = state->font;
  226723. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226724. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226725. .followedBy (transform));
  226726. }
  226727. }
  226728. private:
  226729. CGContextRef context;
  226730. const CGFloat flipHeight;
  226731. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226732. CGFunctionCallbacks gradientCallbacks;
  226733. mutable Rectangle<int> lastClipRect;
  226734. mutable bool lastClipRectIsValid;
  226735. struct SavedState
  226736. {
  226737. SavedState()
  226738. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226739. {
  226740. }
  226741. SavedState (const SavedState& other)
  226742. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226743. fontTransform (other.fontTransform)
  226744. {
  226745. }
  226746. FillType fillType;
  226747. Font font;
  226748. CGFontRef fontRef;
  226749. CGAffineTransform fontTransform;
  226750. };
  226751. ScopedPointer <SavedState> state;
  226752. OwnedArray <SavedState> stateStack;
  226753. HeapBlock <PixelARGB> gradientLookupTable;
  226754. int numGradientLookupEntries;
  226755. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226756. {
  226757. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226758. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226759. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226760. colour.unpremultiply();
  226761. outData[0] = colour.getRed() / 255.0f;
  226762. outData[1] = colour.getGreen() / 255.0f;
  226763. outData[2] = colour.getBlue() / 255.0f;
  226764. outData[3] = colour.getAlpha() / 255.0f;
  226765. }
  226766. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226767. {
  226768. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226769. CGShadingRef result = 0;
  226770. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226771. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226772. if (gradient.isRadial)
  226773. {
  226774. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226775. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226776. function, true, true);
  226777. }
  226778. else
  226779. {
  226780. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226781. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226782. function, true, true);
  226783. }
  226784. CGFunctionRelease (function);
  226785. return result;
  226786. }
  226787. void drawGradient()
  226788. {
  226789. flip();
  226790. applyTransform (state->fillType.transform);
  226791. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226792. // you draw a gradient with high quality interp enabled).
  226793. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226794. CGContextSetAlpha (context, state->fillType.getOpacity());
  226795. CGContextDrawShading (context, shading);
  226796. CGShadingRelease (shading);
  226797. }
  226798. void createPath (const Path& path) const
  226799. {
  226800. CGContextBeginPath (context);
  226801. Path::Iterator i (path);
  226802. while (i.next())
  226803. {
  226804. switch (i.elementType)
  226805. {
  226806. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226807. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226808. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226809. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226810. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226811. default: jassertfalse; break;
  226812. }
  226813. }
  226814. }
  226815. void createPath (const Path& path, const AffineTransform& transform) const
  226816. {
  226817. CGContextBeginPath (context);
  226818. Path::Iterator i (path);
  226819. while (i.next())
  226820. {
  226821. switch (i.elementType)
  226822. {
  226823. case Path::Iterator::startNewSubPath:
  226824. transform.transformPoint (i.x1, i.y1);
  226825. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226826. break;
  226827. case Path::Iterator::lineTo:
  226828. transform.transformPoint (i.x1, i.y1);
  226829. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226830. break;
  226831. case Path::Iterator::quadraticTo:
  226832. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226833. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226834. break;
  226835. case Path::Iterator::cubicTo:
  226836. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226837. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226838. break;
  226839. case Path::Iterator::closePath:
  226840. CGContextClosePath (context); break;
  226841. default:
  226842. jassertfalse;
  226843. break;
  226844. }
  226845. }
  226846. }
  226847. void flip() const
  226848. {
  226849. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226850. }
  226851. void applyTransform (const AffineTransform& transform) const
  226852. {
  226853. CGAffineTransform t;
  226854. t.a = transform.mat00;
  226855. t.b = transform.mat10;
  226856. t.c = transform.mat01;
  226857. t.d = transform.mat11;
  226858. t.tx = transform.mat02;
  226859. t.ty = transform.mat12;
  226860. CGContextConcatCTM (context, t);
  226861. }
  226862. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226863. };
  226864. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226865. {
  226866. return new CoreGraphicsContext (context, height);
  226867. }
  226868. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226869. const Image juce_loadWithCoreImage (InputStream& input)
  226870. {
  226871. MemoryBlock data;
  226872. input.readIntoMemoryBlock (data, -1);
  226873. #if JUCE_IOS
  226874. JUCE_AUTORELEASEPOOL
  226875. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226876. length: data.getSize()
  226877. freeWhenDone: NO]];
  226878. if (image != nil)
  226879. {
  226880. CGImageRef loadedImage = image.CGImage;
  226881. #else
  226882. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226883. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226884. CGDataProviderRelease (provider);
  226885. if (imageSource != 0)
  226886. {
  226887. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226888. CFRelease (imageSource);
  226889. #endif
  226890. if (loadedImage != 0)
  226891. {
  226892. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226893. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226894. && alphaInfo != kCGImageAlphaNoneSkipLast
  226895. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226896. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226897. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226898. hasAlphaChan, Image::NativeImage);
  226899. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226900. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226901. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226902. CGContextFlush (cgImage->context);
  226903. #if ! JUCE_IOS
  226904. CFRelease (loadedImage);
  226905. #endif
  226906. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226907. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226908. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226909. return image;
  226910. }
  226911. }
  226912. return Image::null;
  226913. }
  226914. #endif
  226915. #endif
  226916. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226917. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  226918. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226919. // compiled on its own).
  226920. #if JUCE_INCLUDED_FILE
  226921. class UIViewComponentPeer;
  226922. END_JUCE_NAMESPACE
  226923. #define JuceUIView MakeObjCClassName(JuceUIView)
  226924. @interface JuceUIView : UIView <UITextViewDelegate>
  226925. {
  226926. @public
  226927. UIViewComponentPeer* owner;
  226928. UITextView* hiddenTextView;
  226929. }
  226930. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226931. - (void) dealloc;
  226932. - (void) drawRect: (CGRect) r;
  226933. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226934. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226935. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226936. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226937. - (BOOL) becomeFirstResponder;
  226938. - (BOOL) resignFirstResponder;
  226939. - (BOOL) canBecomeFirstResponder;
  226940. - (void) asyncRepaint: (id) rect;
  226941. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226942. @end
  226943. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226944. @interface JuceUIViewController : UIViewController
  226945. {
  226946. }
  226947. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226948. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226949. @end
  226950. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226951. @interface JuceUIWindow : UIWindow
  226952. {
  226953. @private
  226954. UIViewComponentPeer* owner;
  226955. bool isZooming;
  226956. }
  226957. - (void) setOwner: (UIViewComponentPeer*) owner;
  226958. - (void) becomeKeyWindow;
  226959. @end
  226960. BEGIN_JUCE_NAMESPACE
  226961. class UIViewComponentPeer : public ComponentPeer,
  226962. public FocusChangeListener
  226963. {
  226964. public:
  226965. UIViewComponentPeer (Component* const component,
  226966. const int windowStyleFlags,
  226967. UIView* viewToAttachTo);
  226968. ~UIViewComponentPeer();
  226969. void* getNativeHandle() const;
  226970. void setVisible (bool shouldBeVisible);
  226971. void setTitle (const String& title);
  226972. void setPosition (int x, int y);
  226973. void setSize (int w, int h);
  226974. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226975. const Rectangle<int> getBounds() const;
  226976. const Rectangle<int> getBounds (const bool global) const;
  226977. const Point<int> getScreenPosition() const;
  226978. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226979. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226980. void setAlpha (float newAlpha);
  226981. void setMinimised (bool shouldBeMinimised);
  226982. bool isMinimised() const;
  226983. void setFullScreen (bool shouldBeFullScreen);
  226984. bool isFullScreen() const;
  226985. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226986. const BorderSize getFrameSize() const;
  226987. bool setAlwaysOnTop (bool alwaysOnTop);
  226988. void toFront (bool makeActiveWindow);
  226989. void toBehind (ComponentPeer* other);
  226990. void setIcon (const Image& newIcon);
  226991. virtual void drawRect (CGRect r);
  226992. virtual bool canBecomeKeyWindow();
  226993. virtual bool windowShouldClose();
  226994. virtual void redirectMovedOrResized();
  226995. virtual CGRect constrainRect (CGRect r);
  226996. virtual void viewFocusGain();
  226997. virtual void viewFocusLoss();
  226998. bool isFocused() const;
  226999. void grabFocus();
  227000. void textInputRequired (const Point<int>& position);
  227001. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227002. void updateHiddenTextContent (TextInputTarget* target);
  227003. void globalFocusChanged (Component*);
  227004. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227005. virtual void displayRotated();
  227006. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227007. void repaint (const Rectangle<int>& area);
  227008. void performAnyPendingRepaintsNow();
  227009. UIWindow* window;
  227010. JuceUIView* view;
  227011. JuceUIViewController* controller;
  227012. bool isSharedWindow, fullScreen, insideDrawRect;
  227013. static ModifierKeys currentModifiers;
  227014. static int64 getMouseTime (UIEvent* e)
  227015. {
  227016. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227017. + (int64) ([e timestamp] * 1000.0);
  227018. }
  227019. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227020. {
  227021. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227022. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227023. {
  227024. case UIInterfaceOrientationPortrait:
  227025. return r;
  227026. case UIInterfaceOrientationPortraitUpsideDown:
  227027. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227028. r.getWidth(), r.getHeight());
  227029. case UIInterfaceOrientationLandscapeLeft:
  227030. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227031. r.getHeight(), r.getWidth());
  227032. case UIInterfaceOrientationLandscapeRight:
  227033. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227034. r.getHeight(), r.getWidth());
  227035. default: jassertfalse; // unknown orientation!
  227036. }
  227037. return r;
  227038. }
  227039. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227040. {
  227041. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227042. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227043. {
  227044. case UIInterfaceOrientationPortrait:
  227045. return r;
  227046. case UIInterfaceOrientationPortraitUpsideDown:
  227047. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227048. r.getWidth(), r.getHeight());
  227049. case UIInterfaceOrientationLandscapeLeft:
  227050. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227051. r.getHeight(), r.getWidth());
  227052. case UIInterfaceOrientationLandscapeRight:
  227053. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227054. r.getHeight(), r.getWidth());
  227055. default: jassertfalse; // unknown orientation!
  227056. }
  227057. return r;
  227058. }
  227059. Array <UITouch*> currentTouches;
  227060. private:
  227061. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  227062. };
  227063. END_JUCE_NAMESPACE
  227064. @implementation JuceUIViewController
  227065. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227066. {
  227067. JuceUIView* juceView = (JuceUIView*) [self view];
  227068. jassert (juceView != 0 && juceView->owner != 0);
  227069. return juceView->owner->shouldRotate (interfaceOrientation);
  227070. }
  227071. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227072. {
  227073. JuceUIView* juceView = (JuceUIView*) [self view];
  227074. jassert (juceView != 0 && juceView->owner != 0);
  227075. juceView->owner->displayRotated();
  227076. }
  227077. @end
  227078. @implementation JuceUIView
  227079. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227080. withFrame: (CGRect) frame
  227081. {
  227082. [super initWithFrame: frame];
  227083. owner = owner_;
  227084. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227085. [self addSubview: hiddenTextView];
  227086. hiddenTextView.delegate = self;
  227087. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227088. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227089. return self;
  227090. }
  227091. - (void) dealloc
  227092. {
  227093. [hiddenTextView removeFromSuperview];
  227094. [hiddenTextView release];
  227095. [super dealloc];
  227096. }
  227097. - (void) drawRect: (CGRect) r
  227098. {
  227099. if (owner != 0)
  227100. owner->drawRect (r);
  227101. }
  227102. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227103. {
  227104. return false;
  227105. }
  227106. ModifierKeys UIViewComponentPeer::currentModifiers;
  227107. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227108. {
  227109. return UIViewComponentPeer::currentModifiers;
  227110. }
  227111. void ModifierKeys::updateCurrentModifiers() throw()
  227112. {
  227113. currentModifiers = UIViewComponentPeer::currentModifiers;
  227114. }
  227115. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227116. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227117. {
  227118. if (owner != 0)
  227119. owner->handleTouches (event, true, false, false);
  227120. }
  227121. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227122. {
  227123. if (owner != 0)
  227124. owner->handleTouches (event, false, false, false);
  227125. }
  227126. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227127. {
  227128. if (owner != 0)
  227129. owner->handleTouches (event, false, true, false);
  227130. }
  227131. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227132. {
  227133. if (owner != 0)
  227134. owner->handleTouches (event, false, true, true);
  227135. [self touchesEnded: touches withEvent: event];
  227136. }
  227137. - (BOOL) becomeFirstResponder
  227138. {
  227139. if (owner != 0)
  227140. owner->viewFocusGain();
  227141. return true;
  227142. }
  227143. - (BOOL) resignFirstResponder
  227144. {
  227145. if (owner != 0)
  227146. owner->viewFocusLoss();
  227147. return true;
  227148. }
  227149. - (BOOL) canBecomeFirstResponder
  227150. {
  227151. return owner != 0 && owner->canBecomeKeyWindow();
  227152. }
  227153. - (void) asyncRepaint: (id) rect
  227154. {
  227155. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227156. [self setNeedsDisplayInRect: *r];
  227157. }
  227158. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227159. {
  227160. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227161. nsStringToJuce (text));
  227162. }
  227163. @end
  227164. @implementation JuceUIWindow
  227165. - (void) setOwner: (UIViewComponentPeer*) owner_
  227166. {
  227167. owner = owner_;
  227168. isZooming = false;
  227169. }
  227170. - (void) becomeKeyWindow
  227171. {
  227172. [super becomeKeyWindow];
  227173. if (owner != 0)
  227174. owner->grabFocus();
  227175. }
  227176. @end
  227177. BEGIN_JUCE_NAMESPACE
  227178. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227179. const int windowStyleFlags,
  227180. UIView* viewToAttachTo)
  227181. : ComponentPeer (component, windowStyleFlags),
  227182. window (0),
  227183. view (0), controller (0),
  227184. isSharedWindow (viewToAttachTo != 0),
  227185. fullScreen (false),
  227186. insideDrawRect (false)
  227187. {
  227188. CGRect r = convertToCGRect (component->getLocalBounds());
  227189. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227190. if (isSharedWindow)
  227191. {
  227192. window = [viewToAttachTo window];
  227193. [viewToAttachTo addSubview: view];
  227194. setVisible (component->isVisible());
  227195. }
  227196. else
  227197. {
  227198. controller = [[JuceUIViewController alloc] init];
  227199. controller.view = view;
  227200. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227201. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227202. window = [[JuceUIWindow alloc] init];
  227203. window.frame = r;
  227204. window.opaque = component->isOpaque();
  227205. view.opaque = component->isOpaque();
  227206. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227207. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227208. [((JuceUIWindow*) window) setOwner: this];
  227209. if (component->isAlwaysOnTop())
  227210. window.windowLevel = UIWindowLevelAlert;
  227211. [window addSubview: view];
  227212. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227213. view.hidden = ! component->isVisible();
  227214. window.hidden = ! component->isVisible();
  227215. view.multipleTouchEnabled = YES;
  227216. }
  227217. setTitle (component->getName());
  227218. Desktop::getInstance().addFocusChangeListener (this);
  227219. }
  227220. UIViewComponentPeer::~UIViewComponentPeer()
  227221. {
  227222. Desktop::getInstance().removeFocusChangeListener (this);
  227223. view->owner = 0;
  227224. [view removeFromSuperview];
  227225. [view release];
  227226. [controller release];
  227227. if (! isSharedWindow)
  227228. {
  227229. [((JuceUIWindow*) window) setOwner: 0];
  227230. [window release];
  227231. }
  227232. }
  227233. void* UIViewComponentPeer::getNativeHandle() const
  227234. {
  227235. return view;
  227236. }
  227237. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227238. {
  227239. view.hidden = ! shouldBeVisible;
  227240. if (! isSharedWindow)
  227241. window.hidden = ! shouldBeVisible;
  227242. }
  227243. void UIViewComponentPeer::setTitle (const String& title)
  227244. {
  227245. // xxx is this possible?
  227246. }
  227247. void UIViewComponentPeer::setPosition (int x, int y)
  227248. {
  227249. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227250. }
  227251. void UIViewComponentPeer::setSize (int w, int h)
  227252. {
  227253. setBounds (component->getX(), component->getY(), w, h, false);
  227254. }
  227255. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227256. {
  227257. fullScreen = isNowFullScreen;
  227258. w = jmax (0, w);
  227259. h = jmax (0, h);
  227260. if (isSharedWindow)
  227261. {
  227262. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227263. if ([view frame].size.width != r.size.width
  227264. || [view frame].size.height != r.size.height)
  227265. [view setNeedsDisplay];
  227266. view.frame = r;
  227267. }
  227268. else
  227269. {
  227270. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227271. window.frame = convertToCGRect (bounds);
  227272. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  227273. handleMovedOrResized();
  227274. }
  227275. }
  227276. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227277. {
  227278. CGRect r = [view frame];
  227279. if (global && [view window] != 0)
  227280. {
  227281. r = [view convertRect: r toView: nil];
  227282. CGRect wr = [[view window] frame];
  227283. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  227284. r.origin.x = windowBounds.getX();
  227285. r.origin.y = windowBounds.getY();
  227286. }
  227287. return convertToRectInt (r);
  227288. }
  227289. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227290. {
  227291. return getBounds (! isSharedWindow);
  227292. }
  227293. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227294. {
  227295. return getBounds (true).getPosition();
  227296. }
  227297. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  227298. {
  227299. return relativePosition + getScreenPosition();
  227300. }
  227301. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  227302. {
  227303. return screenPosition - getScreenPosition();
  227304. }
  227305. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227306. {
  227307. if (constrainer != 0)
  227308. {
  227309. CGRect current = [window frame];
  227310. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227311. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227312. Rectangle<int> pos (convertToRectInt (r));
  227313. Rectangle<int> original (convertToRectInt (current));
  227314. constrainer->checkBounds (pos, original,
  227315. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227316. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227317. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227318. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227319. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227320. r.origin.x = pos.getX();
  227321. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227322. r.size.width = pos.getWidth();
  227323. r.size.height = pos.getHeight();
  227324. }
  227325. return r;
  227326. }
  227327. void UIViewComponentPeer::setAlpha (float newAlpha)
  227328. {
  227329. [[view window] setAlpha: (CGFloat) newAlpha];
  227330. }
  227331. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227332. {
  227333. }
  227334. bool UIViewComponentPeer::isMinimised() const
  227335. {
  227336. return false;
  227337. }
  227338. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227339. {
  227340. if (! isSharedWindow)
  227341. {
  227342. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  227343. : lastNonFullscreenBounds);
  227344. if ((! shouldBeFullScreen) && r.isEmpty())
  227345. r = getBounds();
  227346. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227347. if (! r.isEmpty())
  227348. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227349. component->repaint();
  227350. }
  227351. }
  227352. bool UIViewComponentPeer::isFullScreen() const
  227353. {
  227354. return fullScreen;
  227355. }
  227356. namespace
  227357. {
  227358. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  227359. {
  227360. switch (interfaceOrientation)
  227361. {
  227362. case UIInterfaceOrientationPortrait: return Desktop::upright;
  227363. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  227364. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  227365. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  227366. default: jassertfalse; // unknown orientation!
  227367. }
  227368. return Desktop::upright;
  227369. }
  227370. }
  227371. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  227372. {
  227373. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  227374. }
  227375. void UIViewComponentPeer::displayRotated()
  227376. {
  227377. const Rectangle<int> oldArea (component->getBounds());
  227378. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  227379. Desktop::getInstance().refreshMonitorSizes();
  227380. if (fullScreen)
  227381. {
  227382. fullScreen = false;
  227383. setFullScreen (true);
  227384. }
  227385. else
  227386. {
  227387. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  227388. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  227389. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  227390. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  227391. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  227392. setBounds ((int) (l * newDesktop.getWidth()),
  227393. (int) (t * newDesktop.getHeight()),
  227394. (int) ((r - l) * newDesktop.getWidth()),
  227395. (int) ((b - t) * newDesktop.getHeight()),
  227396. false);
  227397. }
  227398. }
  227399. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227400. {
  227401. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  227402. && isPositiveAndBelow (position.getY(), component->getHeight())))
  227403. return false;
  227404. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  227405. withEvent: nil];
  227406. if (trueIfInAChildWindow)
  227407. return v != nil;
  227408. return v == view;
  227409. }
  227410. const BorderSize UIViewComponentPeer::getFrameSize() const
  227411. {
  227412. return BorderSize();
  227413. }
  227414. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227415. {
  227416. if (! isSharedWindow)
  227417. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227418. return true;
  227419. }
  227420. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227421. {
  227422. if (isSharedWindow)
  227423. [[view superview] bringSubviewToFront: view];
  227424. if (window != 0 && component->isVisible())
  227425. [window makeKeyAndVisible];
  227426. }
  227427. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227428. {
  227429. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227430. jassert (otherPeer != 0); // wrong type of window?
  227431. if (otherPeer != 0)
  227432. {
  227433. if (isSharedWindow)
  227434. {
  227435. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227436. }
  227437. else
  227438. {
  227439. jassertfalse; // don't know how to do this
  227440. }
  227441. }
  227442. }
  227443. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227444. {
  227445. // to do..
  227446. }
  227447. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227448. {
  227449. NSArray* touches = [[event touchesForView: view] allObjects];
  227450. for (unsigned int i = 0; i < [touches count]; ++i)
  227451. {
  227452. UITouch* touch = [touches objectAtIndex: i];
  227453. CGPoint p = [touch locationInView: view];
  227454. const Point<int> pos ((int) p.x, (int) p.y);
  227455. juce_lastMousePos = pos + getScreenPosition();
  227456. const int64 time = getMouseTime (event);
  227457. int touchIndex = currentTouches.indexOf (touch);
  227458. if (touchIndex < 0)
  227459. {
  227460. touchIndex = currentTouches.size();
  227461. currentTouches.add (touch);
  227462. }
  227463. if (isDown)
  227464. {
  227465. currentModifiers = currentModifiers.withoutMouseButtons();
  227466. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227467. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227468. }
  227469. else if (isUp)
  227470. {
  227471. currentModifiers = currentModifiers.withoutMouseButtons();
  227472. currentTouches.remove (touchIndex);
  227473. }
  227474. if (isCancel)
  227475. currentTouches.clear();
  227476. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227477. }
  227478. }
  227479. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227480. void UIViewComponentPeer::viewFocusGain()
  227481. {
  227482. if (currentlyFocusedPeer != this)
  227483. {
  227484. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227485. currentlyFocusedPeer->handleFocusLoss();
  227486. currentlyFocusedPeer = this;
  227487. handleFocusGain();
  227488. }
  227489. }
  227490. void UIViewComponentPeer::viewFocusLoss()
  227491. {
  227492. if (currentlyFocusedPeer == this)
  227493. {
  227494. currentlyFocusedPeer = 0;
  227495. handleFocusLoss();
  227496. }
  227497. }
  227498. void juce_HandleProcessFocusChange()
  227499. {
  227500. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227501. {
  227502. if (Process::isForegroundProcess())
  227503. {
  227504. currentlyFocusedPeer->handleFocusGain();
  227505. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227506. }
  227507. else
  227508. {
  227509. currentlyFocusedPeer->handleFocusLoss();
  227510. // turn kiosk mode off if we lose focus..
  227511. Desktop::getInstance().setKioskModeComponent (0);
  227512. }
  227513. }
  227514. }
  227515. bool UIViewComponentPeer::isFocused() const
  227516. {
  227517. return isSharedWindow ? this == currentlyFocusedPeer
  227518. : (window != 0 && [window isKeyWindow]);
  227519. }
  227520. void UIViewComponentPeer::grabFocus()
  227521. {
  227522. if (window != 0)
  227523. {
  227524. [window makeKeyWindow];
  227525. viewFocusGain();
  227526. }
  227527. }
  227528. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227529. {
  227530. }
  227531. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227532. {
  227533. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227534. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227535. }
  227536. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227537. {
  227538. TextInputTarget* const target = findCurrentTextInputTarget();
  227539. if (target != 0)
  227540. {
  227541. const Range<int> currentSelection (target->getHighlightedRegion());
  227542. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227543. if (currentSelection.isEmpty())
  227544. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227545. target->insertTextAtCaret (text);
  227546. updateHiddenTextContent (target);
  227547. }
  227548. return NO;
  227549. }
  227550. void UIViewComponentPeer::globalFocusChanged (Component*)
  227551. {
  227552. TextInputTarget* const target = findCurrentTextInputTarget();
  227553. if (target != 0)
  227554. {
  227555. Component* comp = dynamic_cast<Component*> (target);
  227556. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227557. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227558. updateHiddenTextContent (target);
  227559. [view->hiddenTextView becomeFirstResponder];
  227560. }
  227561. else
  227562. {
  227563. [view->hiddenTextView resignFirstResponder];
  227564. }
  227565. }
  227566. void UIViewComponentPeer::drawRect (CGRect r)
  227567. {
  227568. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227569. return;
  227570. CGContextRef cg = UIGraphicsGetCurrentContext();
  227571. if (! component->isOpaque())
  227572. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227573. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227574. CoreGraphicsContext g (cg, view.bounds.size.height);
  227575. insideDrawRect = true;
  227576. handlePaint (g);
  227577. insideDrawRect = false;
  227578. }
  227579. bool UIViewComponentPeer::canBecomeKeyWindow()
  227580. {
  227581. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227582. }
  227583. bool UIViewComponentPeer::windowShouldClose()
  227584. {
  227585. if (! isValidPeer (this))
  227586. return YES;
  227587. handleUserClosingWindow();
  227588. return NO;
  227589. }
  227590. void UIViewComponentPeer::redirectMovedOrResized()
  227591. {
  227592. handleMovedOrResized();
  227593. }
  227594. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227595. {
  227596. }
  227597. class AsyncRepaintMessage : public CallbackMessage
  227598. {
  227599. public:
  227600. UIViewComponentPeer* const peer;
  227601. const Rectangle<int> rect;
  227602. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227603. : peer (peer_), rect (rect_)
  227604. {
  227605. }
  227606. void messageCallback()
  227607. {
  227608. if (ComponentPeer::isValidPeer (peer))
  227609. peer->repaint (rect);
  227610. }
  227611. };
  227612. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227613. {
  227614. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227615. {
  227616. (new AsyncRepaintMessage (this, area))->post();
  227617. }
  227618. else
  227619. {
  227620. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227621. }
  227622. }
  227623. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227624. {
  227625. }
  227626. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227627. {
  227628. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227629. }
  227630. const Image juce_createIconForFile (const File& file)
  227631. {
  227632. return Image::null;
  227633. }
  227634. void Desktop::createMouseInputSources()
  227635. {
  227636. for (int i = 0; i < 10; ++i)
  227637. mouseSources.add (new MouseInputSource (i, false));
  227638. }
  227639. bool Desktop::canUseSemiTransparentWindows() throw()
  227640. {
  227641. return true;
  227642. }
  227643. const Point<int> MouseInputSource::getCurrentMousePosition()
  227644. {
  227645. return juce_lastMousePos;
  227646. }
  227647. void Desktop::setMousePosition (const Point<int>&)
  227648. {
  227649. }
  227650. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227651. {
  227652. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227653. }
  227654. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227655. {
  227656. const ScopedAutoReleasePool pool;
  227657. monitorCoords.clear();
  227658. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227659. : [[UIScreen mainScreen] bounds];
  227660. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227661. }
  227662. const int KeyPress::spaceKey = ' ';
  227663. const int KeyPress::returnKey = 0x0d;
  227664. const int KeyPress::escapeKey = 0x1b;
  227665. const int KeyPress::backspaceKey = 0x7f;
  227666. const int KeyPress::leftKey = 0x1000;
  227667. const int KeyPress::rightKey = 0x1001;
  227668. const int KeyPress::upKey = 0x1002;
  227669. const int KeyPress::downKey = 0x1003;
  227670. const int KeyPress::pageUpKey = 0x1004;
  227671. const int KeyPress::pageDownKey = 0x1005;
  227672. const int KeyPress::endKey = 0x1006;
  227673. const int KeyPress::homeKey = 0x1007;
  227674. const int KeyPress::deleteKey = 0x1008;
  227675. const int KeyPress::insertKey = -1;
  227676. const int KeyPress::tabKey = 9;
  227677. const int KeyPress::F1Key = 0x2001;
  227678. const int KeyPress::F2Key = 0x2002;
  227679. const int KeyPress::F3Key = 0x2003;
  227680. const int KeyPress::F4Key = 0x2004;
  227681. const int KeyPress::F5Key = 0x2005;
  227682. const int KeyPress::F6Key = 0x2006;
  227683. const int KeyPress::F7Key = 0x2007;
  227684. const int KeyPress::F8Key = 0x2008;
  227685. const int KeyPress::F9Key = 0x2009;
  227686. const int KeyPress::F10Key = 0x200a;
  227687. const int KeyPress::F11Key = 0x200b;
  227688. const int KeyPress::F12Key = 0x200c;
  227689. const int KeyPress::F13Key = 0x200d;
  227690. const int KeyPress::F14Key = 0x200e;
  227691. const int KeyPress::F15Key = 0x200f;
  227692. const int KeyPress::F16Key = 0x2010;
  227693. const int KeyPress::numberPad0 = 0x30020;
  227694. const int KeyPress::numberPad1 = 0x30021;
  227695. const int KeyPress::numberPad2 = 0x30022;
  227696. const int KeyPress::numberPad3 = 0x30023;
  227697. const int KeyPress::numberPad4 = 0x30024;
  227698. const int KeyPress::numberPad5 = 0x30025;
  227699. const int KeyPress::numberPad6 = 0x30026;
  227700. const int KeyPress::numberPad7 = 0x30027;
  227701. const int KeyPress::numberPad8 = 0x30028;
  227702. const int KeyPress::numberPad9 = 0x30029;
  227703. const int KeyPress::numberPadAdd = 0x3002a;
  227704. const int KeyPress::numberPadSubtract = 0x3002b;
  227705. const int KeyPress::numberPadMultiply = 0x3002c;
  227706. const int KeyPress::numberPadDivide = 0x3002d;
  227707. const int KeyPress::numberPadSeparator = 0x3002e;
  227708. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227709. const int KeyPress::numberPadEquals = 0x30030;
  227710. const int KeyPress::numberPadDelete = 0x30031;
  227711. const int KeyPress::playKey = 0x30000;
  227712. const int KeyPress::stopKey = 0x30001;
  227713. const int KeyPress::fastForwardKey = 0x30002;
  227714. const int KeyPress::rewindKey = 0x30003;
  227715. #endif
  227716. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227717. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227718. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227719. // compiled on its own).
  227720. #if JUCE_INCLUDED_FILE
  227721. struct CallbackMessagePayload
  227722. {
  227723. MessageCallbackFunction* function;
  227724. void* parameter;
  227725. void* volatile result;
  227726. bool volatile hasBeenExecuted;
  227727. };
  227728. END_JUCE_NAMESPACE
  227729. @interface JuceCustomMessageHandler : NSObject
  227730. {
  227731. }
  227732. - (void) performCallback: (id) info;
  227733. @end
  227734. @implementation JuceCustomMessageHandler
  227735. - (void) performCallback: (id) info
  227736. {
  227737. if ([info isKindOfClass: [NSData class]])
  227738. {
  227739. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227740. if (pl != 0)
  227741. {
  227742. pl->result = (*pl->function) (pl->parameter);
  227743. pl->hasBeenExecuted = true;
  227744. }
  227745. }
  227746. else
  227747. {
  227748. jassertfalse; // should never get here!
  227749. }
  227750. }
  227751. @end
  227752. BEGIN_JUCE_NAMESPACE
  227753. void MessageManager::runDispatchLoop()
  227754. {
  227755. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227756. runDispatchLoopUntil (-1);
  227757. }
  227758. void MessageManager::stopDispatchLoop()
  227759. {
  227760. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227761. exit (0); // iPhone apps get no mercy..
  227762. }
  227763. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227764. {
  227765. const ScopedAutoReleasePool pool;
  227766. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227767. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227768. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227769. while (! quitMessagePosted)
  227770. {
  227771. const ScopedAutoReleasePool pool;
  227772. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227773. beforeDate: endDate];
  227774. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227775. break;
  227776. }
  227777. return ! quitMessagePosted;
  227778. }
  227779. struct MessageDispatchSystem
  227780. {
  227781. MessageDispatchSystem()
  227782. : juceCustomMessageHandler (0)
  227783. {
  227784. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227785. }
  227786. ~MessageDispatchSystem()
  227787. {
  227788. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227789. [juceCustomMessageHandler release];
  227790. }
  227791. JuceCustomMessageHandler* juceCustomMessageHandler;
  227792. MessageQueue messageQueue;
  227793. };
  227794. static MessageDispatchSystem* dispatcher = 0;
  227795. void MessageManager::doPlatformSpecificInitialisation()
  227796. {
  227797. if (dispatcher == 0)
  227798. dispatcher = new MessageDispatchSystem();
  227799. }
  227800. void MessageManager::doPlatformSpecificShutdown()
  227801. {
  227802. deleteAndZero (dispatcher);
  227803. }
  227804. bool juce_postMessageToSystemQueue (Message* message)
  227805. {
  227806. if (dispatcher != 0)
  227807. dispatcher->messageQueue.post (message);
  227808. return true;
  227809. }
  227810. void MessageManager::broadcastMessage (const String& value)
  227811. {
  227812. }
  227813. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227814. {
  227815. if (isThisTheMessageThread())
  227816. {
  227817. return (*callback) (data);
  227818. }
  227819. else
  227820. {
  227821. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227822. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227823. // deadlock because the message manager is blocked from running, so can never
  227824. // call your function..
  227825. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227826. const ScopedAutoReleasePool pool;
  227827. CallbackMessagePayload cmp;
  227828. cmp.function = callback;
  227829. cmp.parameter = data;
  227830. cmp.result = 0;
  227831. cmp.hasBeenExecuted = false;
  227832. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227833. withObject: [NSData dataWithBytesNoCopy: &cmp
  227834. length: sizeof (cmp)
  227835. freeWhenDone: NO]
  227836. waitUntilDone: YES];
  227837. return cmp.result;
  227838. }
  227839. }
  227840. #endif
  227841. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  227842. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227843. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227844. // compiled on its own).
  227845. #if JUCE_INCLUDED_FILE
  227846. #if JUCE_MAC
  227847. END_JUCE_NAMESPACE
  227848. using namespace JUCE_NAMESPACE;
  227849. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227850. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227851. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227852. #else
  227853. @interface JuceFileChooserDelegate : NSObject
  227854. #endif
  227855. {
  227856. StringArray* filters;
  227857. }
  227858. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227859. - (void) dealloc;
  227860. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227861. @end
  227862. @implementation JuceFileChooserDelegate
  227863. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227864. {
  227865. [super init];
  227866. filters = filters_;
  227867. return self;
  227868. }
  227869. - (void) dealloc
  227870. {
  227871. delete filters;
  227872. [super dealloc];
  227873. }
  227874. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227875. {
  227876. (void) sender;
  227877. const File f (nsStringToJuce (filename));
  227878. for (int i = filters->size(); --i >= 0;)
  227879. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227880. return true;
  227881. return f.isDirectory();
  227882. }
  227883. @end
  227884. BEGIN_JUCE_NAMESPACE
  227885. void FileChooser::showPlatformDialog (Array<File>& results,
  227886. const String& title,
  227887. const File& currentFileOrDirectory,
  227888. const String& filter,
  227889. bool selectsDirectory,
  227890. bool selectsFiles,
  227891. bool isSaveDialogue,
  227892. bool /*warnAboutOverwritingExistingFiles*/,
  227893. bool selectMultipleFiles,
  227894. FilePreviewComponent* /*extraInfoComponent*/)
  227895. {
  227896. const ScopedAutoReleasePool pool;
  227897. StringArray* filters = new StringArray();
  227898. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227899. filters->trim();
  227900. filters->removeEmptyStrings();
  227901. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227902. [delegate autorelease];
  227903. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227904. : [NSOpenPanel openPanel];
  227905. [panel setTitle: juceStringToNS (title)];
  227906. if (! isSaveDialogue)
  227907. {
  227908. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227909. [openPanel setCanChooseDirectories: selectsDirectory];
  227910. [openPanel setCanChooseFiles: selectsFiles];
  227911. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227912. }
  227913. [panel setDelegate: delegate];
  227914. if (isSaveDialogue || selectsDirectory)
  227915. [panel setCanCreateDirectories: YES];
  227916. String directory, filename;
  227917. if (currentFileOrDirectory.isDirectory())
  227918. {
  227919. directory = currentFileOrDirectory.getFullPathName();
  227920. }
  227921. else
  227922. {
  227923. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227924. filename = currentFileOrDirectory.getFileName();
  227925. }
  227926. if ([panel runModalForDirectory: juceStringToNS (directory)
  227927. file: juceStringToNS (filename)]
  227928. == NSOKButton)
  227929. {
  227930. if (isSaveDialogue)
  227931. {
  227932. results.add (File (nsStringToJuce ([panel filename])));
  227933. }
  227934. else
  227935. {
  227936. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227937. NSArray* urls = [openPanel filenames];
  227938. for (unsigned int i = 0; i < [urls count]; ++i)
  227939. {
  227940. NSString* f = [urls objectAtIndex: i];
  227941. results.add (File (nsStringToJuce (f)));
  227942. }
  227943. }
  227944. }
  227945. [panel setDelegate: nil];
  227946. }
  227947. #else
  227948. void FileChooser::showPlatformDialog (Array<File>& results,
  227949. const String& title,
  227950. const File& currentFileOrDirectory,
  227951. const String& filter,
  227952. bool selectsDirectory,
  227953. bool selectsFiles,
  227954. bool isSaveDialogue,
  227955. bool warnAboutOverwritingExistingFiles,
  227956. bool selectMultipleFiles,
  227957. FilePreviewComponent* extraInfoComponent)
  227958. {
  227959. const ScopedAutoReleasePool pool;
  227960. jassertfalse; //xxx to do
  227961. }
  227962. #endif
  227963. #endif
  227964. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227965. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227966. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227967. // compiled on its own).
  227968. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227969. #if JUCE_MAC
  227970. END_JUCE_NAMESPACE
  227971. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227972. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227973. {
  227974. CriticalSection* contextLock;
  227975. bool needsUpdate;
  227976. }
  227977. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227978. - (bool) makeActive;
  227979. - (void) makeInactive;
  227980. - (void) reshape;
  227981. @end
  227982. @implementation ThreadSafeNSOpenGLView
  227983. - (id) initWithFrame: (NSRect) frameRect
  227984. pixelFormat: (NSOpenGLPixelFormat*) format
  227985. {
  227986. contextLock = new CriticalSection();
  227987. self = [super initWithFrame: frameRect pixelFormat: format];
  227988. if (self != nil)
  227989. [[NSNotificationCenter defaultCenter] addObserver: self
  227990. selector: @selector (_surfaceNeedsUpdate:)
  227991. name: NSViewGlobalFrameDidChangeNotification
  227992. object: self];
  227993. return self;
  227994. }
  227995. - (void) dealloc
  227996. {
  227997. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227998. delete contextLock;
  227999. [super dealloc];
  228000. }
  228001. - (bool) makeActive
  228002. {
  228003. const ScopedLock sl (*contextLock);
  228004. if ([self openGLContext] == 0)
  228005. return false;
  228006. [[self openGLContext] makeCurrentContext];
  228007. if (needsUpdate)
  228008. {
  228009. [super update];
  228010. needsUpdate = false;
  228011. }
  228012. return true;
  228013. }
  228014. - (void) makeInactive
  228015. {
  228016. const ScopedLock sl (*contextLock);
  228017. [NSOpenGLContext clearCurrentContext];
  228018. }
  228019. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228020. {
  228021. (void) notification;
  228022. const ScopedLock sl (*contextLock);
  228023. needsUpdate = true;
  228024. }
  228025. - (void) update
  228026. {
  228027. const ScopedLock sl (*contextLock);
  228028. needsUpdate = true;
  228029. }
  228030. - (void) reshape
  228031. {
  228032. const ScopedLock sl (*contextLock);
  228033. needsUpdate = true;
  228034. }
  228035. @end
  228036. BEGIN_JUCE_NAMESPACE
  228037. class WindowedGLContext : public OpenGLContext
  228038. {
  228039. public:
  228040. WindowedGLContext (Component* const component,
  228041. const OpenGLPixelFormat& pixelFormat_,
  228042. NSOpenGLContext* sharedContext)
  228043. : renderContext (0),
  228044. pixelFormat (pixelFormat_)
  228045. {
  228046. jassert (component != 0);
  228047. NSOpenGLPixelFormatAttribute attribs [64];
  228048. int n = 0;
  228049. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228050. attribs[n++] = NSOpenGLPFAAccelerated;
  228051. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228052. attribs[n++] = NSOpenGLPFAColorSize;
  228053. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228054. pixelFormat.greenBits,
  228055. pixelFormat.blueBits);
  228056. attribs[n++] = NSOpenGLPFAAlphaSize;
  228057. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228058. attribs[n++] = NSOpenGLPFADepthSize;
  228059. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228060. attribs[n++] = NSOpenGLPFAStencilSize;
  228061. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228062. attribs[n++] = NSOpenGLPFAAccumSize;
  228063. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228064. pixelFormat.accumulationBufferGreenBits,
  228065. pixelFormat.accumulationBufferBlueBits,
  228066. pixelFormat.accumulationBufferAlphaBits);
  228067. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228068. attribs[n++] = NSOpenGLPFASampleBuffers;
  228069. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228070. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228071. attribs[n++] = NSOpenGLPFANoRecovery;
  228072. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228073. NSOpenGLPixelFormat* format
  228074. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228075. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228076. pixelFormat: format];
  228077. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228078. shareContext: sharedContext] autorelease];
  228079. const GLint swapInterval = 1;
  228080. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228081. [view setOpenGLContext: renderContext];
  228082. [format release];
  228083. viewHolder = new NSViewComponentInternal (view, component);
  228084. }
  228085. ~WindowedGLContext()
  228086. {
  228087. deleteContext();
  228088. viewHolder = 0;
  228089. }
  228090. void deleteContext()
  228091. {
  228092. makeInactive();
  228093. [renderContext clearDrawable];
  228094. [renderContext setView: nil];
  228095. [view setOpenGLContext: nil];
  228096. renderContext = nil;
  228097. }
  228098. bool makeActive() const throw()
  228099. {
  228100. jassert (renderContext != 0);
  228101. if ([renderContext view] != view)
  228102. [renderContext setView: view];
  228103. [view makeActive];
  228104. return isActive();
  228105. }
  228106. bool makeInactive() const throw()
  228107. {
  228108. [view makeInactive];
  228109. return true;
  228110. }
  228111. bool isActive() const throw()
  228112. {
  228113. return [NSOpenGLContext currentContext] == renderContext;
  228114. }
  228115. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228116. void* getRawContext() const throw() { return renderContext; }
  228117. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  228118. {
  228119. }
  228120. void swapBuffers()
  228121. {
  228122. [renderContext flushBuffer];
  228123. }
  228124. bool setSwapInterval (const int numFramesPerSwap)
  228125. {
  228126. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228127. forParameter: NSOpenGLCPSwapInterval];
  228128. return true;
  228129. }
  228130. int getSwapInterval() const
  228131. {
  228132. GLint numFrames = 0;
  228133. [renderContext getValues: &numFrames
  228134. forParameter: NSOpenGLCPSwapInterval];
  228135. return numFrames;
  228136. }
  228137. void repaint()
  228138. {
  228139. // we need to invalidate the juce view that holds this gl view, to make it
  228140. // cause a repaint callback
  228141. NSView* v = (NSView*) viewHolder->view;
  228142. NSRect r = [v frame];
  228143. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228144. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228145. // repaint message, thus never causing our paint() callback, and never repainting
  228146. // the comp. So invalidating just a little bit around the edge helps..
  228147. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228148. }
  228149. void* getNativeWindowHandle() const { return viewHolder->view; }
  228150. NSOpenGLContext* renderContext;
  228151. ThreadSafeNSOpenGLView* view;
  228152. private:
  228153. OpenGLPixelFormat pixelFormat;
  228154. ScopedPointer <NSViewComponentInternal> viewHolder;
  228155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  228156. };
  228157. OpenGLContext* OpenGLComponent::createContext()
  228158. {
  228159. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228160. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228161. return (c->renderContext != 0) ? c.release() : 0;
  228162. }
  228163. void* OpenGLComponent::getNativeWindowHandle() const
  228164. {
  228165. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228166. : 0;
  228167. }
  228168. void juce_glViewport (const int w, const int h)
  228169. {
  228170. glViewport (0, 0, w, h);
  228171. }
  228172. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228173. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228174. {
  228175. /* GLint attribs [64];
  228176. int n = 0;
  228177. attribs[n++] = AGL_RGBA;
  228178. attribs[n++] = AGL_DOUBLEBUFFER;
  228179. attribs[n++] = AGL_ACCELERATED;
  228180. attribs[n++] = AGL_NO_RECOVERY;
  228181. attribs[n++] = AGL_NONE;
  228182. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228183. while (p != 0)
  228184. {
  228185. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228186. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228187. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228188. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228189. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228190. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228191. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228192. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228193. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228194. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228195. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228196. results.add (pf);
  228197. p = aglNextPixelFormat (p);
  228198. }*/
  228199. //jassertfalse // can't see how you do this in cocoa!
  228200. }
  228201. #else
  228202. END_JUCE_NAMESPACE
  228203. @interface JuceGLView : UIView
  228204. {
  228205. }
  228206. + (Class) layerClass;
  228207. @end
  228208. @implementation JuceGLView
  228209. + (Class) layerClass
  228210. {
  228211. return [CAEAGLLayer class];
  228212. }
  228213. @end
  228214. BEGIN_JUCE_NAMESPACE
  228215. class GLESContext : public OpenGLContext
  228216. {
  228217. public:
  228218. GLESContext (UIViewComponentPeer* peer,
  228219. Component* const component_,
  228220. const OpenGLPixelFormat& pixelFormat_,
  228221. const GLESContext* const sharedContext,
  228222. NSUInteger apiType)
  228223. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228224. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228225. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228226. {
  228227. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228228. view.opaque = YES;
  228229. view.hidden = NO;
  228230. view.backgroundColor = [UIColor blackColor];
  228231. view.userInteractionEnabled = NO;
  228232. glLayer = (CAEAGLLayer*) [view layer];
  228233. [peer->view addSubview: view];
  228234. if (sharedContext != 0)
  228235. context = [[EAGLContext alloc] initWithAPI: apiType
  228236. sharegroup: [sharedContext->context sharegroup]];
  228237. else
  228238. context = [[EAGLContext alloc] initWithAPI: apiType];
  228239. createGLBuffers();
  228240. }
  228241. ~GLESContext()
  228242. {
  228243. deleteContext();
  228244. [view removeFromSuperview];
  228245. [view release];
  228246. freeGLBuffers();
  228247. }
  228248. void deleteContext()
  228249. {
  228250. makeInactive();
  228251. [context release];
  228252. context = nil;
  228253. }
  228254. bool makeActive() const throw()
  228255. {
  228256. jassert (context != 0);
  228257. [EAGLContext setCurrentContext: context];
  228258. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228259. return true;
  228260. }
  228261. void swapBuffers()
  228262. {
  228263. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228264. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228265. }
  228266. bool makeInactive() const throw()
  228267. {
  228268. return [EAGLContext setCurrentContext: nil];
  228269. }
  228270. bool isActive() const throw()
  228271. {
  228272. return [EAGLContext currentContext] == context;
  228273. }
  228274. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228275. void* getRawContext() const throw() { return glLayer; }
  228276. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228277. {
  228278. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228279. if (lastWidth != w || lastHeight != h)
  228280. {
  228281. lastWidth = w;
  228282. lastHeight = h;
  228283. freeGLBuffers();
  228284. createGLBuffers();
  228285. }
  228286. }
  228287. bool setSwapInterval (const int numFramesPerSwap)
  228288. {
  228289. numFrames = numFramesPerSwap;
  228290. return true;
  228291. }
  228292. int getSwapInterval() const
  228293. {
  228294. return numFrames;
  228295. }
  228296. void repaint()
  228297. {
  228298. }
  228299. void createGLBuffers()
  228300. {
  228301. makeActive();
  228302. glGenFramebuffersOES (1, &frameBufferHandle);
  228303. glGenRenderbuffersOES (1, &colorBufferHandle);
  228304. glGenRenderbuffersOES (1, &depthBufferHandle);
  228305. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228306. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228307. GLint width, height;
  228308. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228309. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228310. if (useDepthBuffer)
  228311. {
  228312. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228313. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228314. }
  228315. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228316. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228317. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228318. if (useDepthBuffer)
  228319. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228320. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228321. }
  228322. void freeGLBuffers()
  228323. {
  228324. if (frameBufferHandle != 0)
  228325. {
  228326. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228327. frameBufferHandle = 0;
  228328. }
  228329. if (colorBufferHandle != 0)
  228330. {
  228331. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228332. colorBufferHandle = 0;
  228333. }
  228334. if (depthBufferHandle != 0)
  228335. {
  228336. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228337. depthBufferHandle = 0;
  228338. }
  228339. }
  228340. private:
  228341. WeakReference<Component> component;
  228342. OpenGLPixelFormat pixelFormat;
  228343. JuceGLView* view;
  228344. CAEAGLLayer* glLayer;
  228345. EAGLContext* context;
  228346. bool useDepthBuffer;
  228347. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228348. int numFrames;
  228349. int lastWidth, lastHeight;
  228350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  228351. };
  228352. OpenGLContext* OpenGLComponent::createContext()
  228353. {
  228354. ScopedAutoReleasePool pool;
  228355. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228356. if (peer != 0)
  228357. return new GLESContext (peer, this, preferredPixelFormat,
  228358. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228359. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228360. return 0;
  228361. }
  228362. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228363. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228364. {
  228365. }
  228366. void juce_glViewport (const int w, const int h)
  228367. {
  228368. glViewport (0, 0, w, h);
  228369. }
  228370. #endif
  228371. #endif
  228372. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228373. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228374. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228375. // compiled on its own).
  228376. #if JUCE_INCLUDED_FILE
  228377. #if JUCE_MAC
  228378. namespace MouseCursorHelpers
  228379. {
  228380. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228381. {
  228382. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228383. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228384. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228385. [im release];
  228386. return c;
  228387. }
  228388. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228389. {
  228390. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228391. BufferedInputStream buf (fileStream, 4096);
  228392. PNGImageFormat pngFormat;
  228393. Image im (pngFormat.decodeImage (buf));
  228394. if (im.isValid())
  228395. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228396. jassertfalse;
  228397. return 0;
  228398. }
  228399. }
  228400. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228401. {
  228402. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228403. }
  228404. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228405. {
  228406. const ScopedAutoReleasePool pool;
  228407. NSCursor* c = 0;
  228408. switch (type)
  228409. {
  228410. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228411. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228412. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228413. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228414. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228415. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228416. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228417. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228418. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228419. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228420. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228421. case UpDownResizeCursor:
  228422. case TopEdgeResizeCursor:
  228423. case BottomEdgeResizeCursor:
  228424. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228425. case TopLeftCornerResizeCursor:
  228426. case BottomRightCornerResizeCursor:
  228427. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228428. case TopRightCornerResizeCursor:
  228429. case BottomLeftCornerResizeCursor:
  228430. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228431. case UpDownLeftRightResizeCursor:
  228432. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228433. default:
  228434. jassertfalse;
  228435. break;
  228436. }
  228437. [c retain];
  228438. return c;
  228439. }
  228440. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228441. {
  228442. [((NSCursor*) cursorHandle) release];
  228443. }
  228444. void MouseCursor::showInAllWindows() const
  228445. {
  228446. showInWindow (0);
  228447. }
  228448. void MouseCursor::showInWindow (ComponentPeer*) const
  228449. {
  228450. NSCursor* c = (NSCursor*) getHandle();
  228451. if (c == 0)
  228452. c = [NSCursor arrowCursor];
  228453. [c set];
  228454. }
  228455. #else
  228456. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228457. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228458. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228459. void MouseCursor::showInAllWindows() const {}
  228460. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228461. #endif
  228462. #endif
  228463. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228464. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228465. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228466. // compiled on its own).
  228467. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228468. #if JUCE_MAC
  228469. END_JUCE_NAMESPACE
  228470. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228471. @interface DownloadClickDetector : NSObject
  228472. {
  228473. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228474. }
  228475. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228476. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228477. request: (NSURLRequest*) request
  228478. frame: (WebFrame*) frame
  228479. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228480. @end
  228481. @implementation DownloadClickDetector
  228482. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228483. {
  228484. [super init];
  228485. ownerComponent = ownerComponent_;
  228486. return self;
  228487. }
  228488. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228489. request: (NSURLRequest*) request
  228490. frame: (WebFrame*) frame
  228491. decisionListener: (id <WebPolicyDecisionListener>) listener
  228492. {
  228493. (void) sender;
  228494. (void) request;
  228495. (void) frame;
  228496. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228497. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228498. [listener use];
  228499. else
  228500. [listener ignore];
  228501. }
  228502. @end
  228503. BEGIN_JUCE_NAMESPACE
  228504. class WebBrowserComponentInternal : public NSViewComponent
  228505. {
  228506. public:
  228507. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228508. {
  228509. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228510. frameName: @""
  228511. groupName: @""];
  228512. setView (webView);
  228513. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228514. [webView setPolicyDelegate: clickListener];
  228515. }
  228516. ~WebBrowserComponentInternal()
  228517. {
  228518. [webView setPolicyDelegate: nil];
  228519. [clickListener release];
  228520. setView (0);
  228521. }
  228522. void goToURL (const String& url,
  228523. const StringArray* headers,
  228524. const MemoryBlock* postData)
  228525. {
  228526. NSMutableURLRequest* r
  228527. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228528. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228529. timeoutInterval: 30.0];
  228530. if (postData != 0 && postData->getSize() > 0)
  228531. {
  228532. [r setHTTPMethod: @"POST"];
  228533. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228534. length: postData->getSize()]];
  228535. }
  228536. if (headers != 0)
  228537. {
  228538. for (int i = 0; i < headers->size(); ++i)
  228539. {
  228540. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228541. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228542. [r setValue: juceStringToNS (headerValue)
  228543. forHTTPHeaderField: juceStringToNS (headerName)];
  228544. }
  228545. }
  228546. stop();
  228547. [[webView mainFrame] loadRequest: r];
  228548. }
  228549. void goBack()
  228550. {
  228551. [webView goBack];
  228552. }
  228553. void goForward()
  228554. {
  228555. [webView goForward];
  228556. }
  228557. void stop()
  228558. {
  228559. [webView stopLoading: nil];
  228560. }
  228561. void refresh()
  228562. {
  228563. [webView reload: nil];
  228564. }
  228565. void mouseMove (const MouseEvent&)
  228566. {
  228567. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228568. // them work is to push them via this non-public method..
  228569. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228570. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228571. }
  228572. private:
  228573. WebView* webView;
  228574. DownloadClickDetector* clickListener;
  228575. };
  228576. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228577. : browser (0),
  228578. blankPageShown (false),
  228579. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228580. {
  228581. setOpaque (true);
  228582. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228583. }
  228584. WebBrowserComponent::~WebBrowserComponent()
  228585. {
  228586. deleteAndZero (browser);
  228587. }
  228588. void WebBrowserComponent::goToURL (const String& url,
  228589. const StringArray* headers,
  228590. const MemoryBlock* postData)
  228591. {
  228592. lastURL = url;
  228593. lastHeaders.clear();
  228594. if (headers != 0)
  228595. lastHeaders = *headers;
  228596. lastPostData.setSize (0);
  228597. if (postData != 0)
  228598. lastPostData = *postData;
  228599. blankPageShown = false;
  228600. browser->goToURL (url, headers, postData);
  228601. }
  228602. void WebBrowserComponent::stop()
  228603. {
  228604. browser->stop();
  228605. }
  228606. void WebBrowserComponent::goBack()
  228607. {
  228608. lastURL = String::empty;
  228609. blankPageShown = false;
  228610. browser->goBack();
  228611. }
  228612. void WebBrowserComponent::goForward()
  228613. {
  228614. lastURL = String::empty;
  228615. browser->goForward();
  228616. }
  228617. void WebBrowserComponent::refresh()
  228618. {
  228619. browser->refresh();
  228620. }
  228621. void WebBrowserComponent::paint (Graphics&)
  228622. {
  228623. }
  228624. void WebBrowserComponent::checkWindowAssociation()
  228625. {
  228626. if (isShowing())
  228627. {
  228628. if (blankPageShown)
  228629. goBack();
  228630. }
  228631. else
  228632. {
  228633. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228634. {
  228635. // when the component becomes invisible, some stuff like flash
  228636. // carries on playing audio, so we need to force it onto a blank
  228637. // page to avoid this, (and send it back when it's made visible again).
  228638. blankPageShown = true;
  228639. browser->goToURL ("about:blank", 0, 0);
  228640. }
  228641. }
  228642. }
  228643. void WebBrowserComponent::reloadLastURL()
  228644. {
  228645. if (lastURL.isNotEmpty())
  228646. {
  228647. goToURL (lastURL, &lastHeaders, &lastPostData);
  228648. lastURL = String::empty;
  228649. }
  228650. }
  228651. void WebBrowserComponent::parentHierarchyChanged()
  228652. {
  228653. checkWindowAssociation();
  228654. }
  228655. void WebBrowserComponent::resized()
  228656. {
  228657. browser->setSize (getWidth(), getHeight());
  228658. }
  228659. void WebBrowserComponent::visibilityChanged()
  228660. {
  228661. checkWindowAssociation();
  228662. }
  228663. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228664. {
  228665. return true;
  228666. }
  228667. #else
  228668. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228669. {
  228670. }
  228671. WebBrowserComponent::~WebBrowserComponent()
  228672. {
  228673. }
  228674. void WebBrowserComponent::goToURL (const String& url,
  228675. const StringArray* headers,
  228676. const MemoryBlock* postData)
  228677. {
  228678. }
  228679. void WebBrowserComponent::stop()
  228680. {
  228681. }
  228682. void WebBrowserComponent::goBack()
  228683. {
  228684. }
  228685. void WebBrowserComponent::goForward()
  228686. {
  228687. }
  228688. void WebBrowserComponent::refresh()
  228689. {
  228690. }
  228691. void WebBrowserComponent::paint (Graphics& g)
  228692. {
  228693. }
  228694. void WebBrowserComponent::checkWindowAssociation()
  228695. {
  228696. }
  228697. void WebBrowserComponent::reloadLastURL()
  228698. {
  228699. }
  228700. void WebBrowserComponent::parentHierarchyChanged()
  228701. {
  228702. }
  228703. void WebBrowserComponent::resized()
  228704. {
  228705. }
  228706. void WebBrowserComponent::visibilityChanged()
  228707. {
  228708. }
  228709. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228710. {
  228711. return true;
  228712. }
  228713. #endif
  228714. #endif
  228715. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228716. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228717. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228718. // compiled on its own).
  228719. #if JUCE_INCLUDED_FILE
  228720. class IPhoneAudioIODevice : public AudioIODevice
  228721. {
  228722. public:
  228723. IPhoneAudioIODevice (const String& deviceName)
  228724. : AudioIODevice (deviceName, "Audio"),
  228725. actualBufferSize (0),
  228726. isRunning (false),
  228727. audioUnit (0),
  228728. callback (0),
  228729. floatData (1, 2)
  228730. {
  228731. numInputChannels = 2;
  228732. numOutputChannels = 2;
  228733. preferredBufferSize = 0;
  228734. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228735. updateDeviceInfo();
  228736. }
  228737. ~IPhoneAudioIODevice()
  228738. {
  228739. close();
  228740. }
  228741. const StringArray getOutputChannelNames()
  228742. {
  228743. StringArray s;
  228744. s.add ("Left");
  228745. s.add ("Right");
  228746. return s;
  228747. }
  228748. const StringArray getInputChannelNames()
  228749. {
  228750. StringArray s;
  228751. if (audioInputIsAvailable)
  228752. {
  228753. s.add ("Left");
  228754. s.add ("Right");
  228755. }
  228756. return s;
  228757. }
  228758. int getNumSampleRates()
  228759. {
  228760. return 1;
  228761. }
  228762. double getSampleRate (int index)
  228763. {
  228764. return sampleRate;
  228765. }
  228766. int getNumBufferSizesAvailable()
  228767. {
  228768. return 1;
  228769. }
  228770. int getBufferSizeSamples (int index)
  228771. {
  228772. return getDefaultBufferSize();
  228773. }
  228774. int getDefaultBufferSize()
  228775. {
  228776. return 1024;
  228777. }
  228778. const String open (const BigInteger& inputChannels,
  228779. const BigInteger& outputChannels,
  228780. double sampleRate,
  228781. int bufferSize)
  228782. {
  228783. close();
  228784. lastError = String::empty;
  228785. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228786. // xxx set up channel mapping
  228787. activeOutputChans = outputChannels;
  228788. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228789. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228790. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228791. activeInputChans = inputChannels;
  228792. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228793. numInputChannels = activeInputChans.countNumberOfSetBits();
  228794. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228795. AudioSessionSetActive (true);
  228796. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228797. : kAudioSessionCategory_MediaPlayback;
  228798. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228799. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228800. fixAudioRouteIfSetToReceiver();
  228801. updateDeviceInfo();
  228802. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228803. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228804. actualBufferSize = preferredBufferSize;
  228805. prepareFloatBuffers();
  228806. isRunning = true;
  228807. propertyChanged (0, 0, 0); // creates and starts the AU
  228808. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228809. return lastError;
  228810. }
  228811. void close()
  228812. {
  228813. if (isRunning)
  228814. {
  228815. isRunning = false;
  228816. AudioSessionSetActive (false);
  228817. if (audioUnit != 0)
  228818. {
  228819. AudioComponentInstanceDispose (audioUnit);
  228820. audioUnit = 0;
  228821. }
  228822. }
  228823. }
  228824. bool isOpen()
  228825. {
  228826. return isRunning;
  228827. }
  228828. int getCurrentBufferSizeSamples()
  228829. {
  228830. return actualBufferSize;
  228831. }
  228832. double getCurrentSampleRate()
  228833. {
  228834. return sampleRate;
  228835. }
  228836. int getCurrentBitDepth()
  228837. {
  228838. return 16;
  228839. }
  228840. const BigInteger getActiveOutputChannels() const
  228841. {
  228842. return activeOutputChans;
  228843. }
  228844. const BigInteger getActiveInputChannels() const
  228845. {
  228846. return activeInputChans;
  228847. }
  228848. int getOutputLatencyInSamples()
  228849. {
  228850. return 0; //xxx
  228851. }
  228852. int getInputLatencyInSamples()
  228853. {
  228854. return 0; //xxx
  228855. }
  228856. void start (AudioIODeviceCallback* callback_)
  228857. {
  228858. if (isRunning && callback != callback_)
  228859. {
  228860. if (callback_ != 0)
  228861. callback_->audioDeviceAboutToStart (this);
  228862. const ScopedLock sl (callbackLock);
  228863. callback = callback_;
  228864. }
  228865. }
  228866. void stop()
  228867. {
  228868. if (isRunning)
  228869. {
  228870. AudioIODeviceCallback* lastCallback;
  228871. {
  228872. const ScopedLock sl (callbackLock);
  228873. lastCallback = callback;
  228874. callback = 0;
  228875. }
  228876. if (lastCallback != 0)
  228877. lastCallback->audioDeviceStopped();
  228878. }
  228879. }
  228880. bool isPlaying()
  228881. {
  228882. return isRunning && callback != 0;
  228883. }
  228884. const String getLastError()
  228885. {
  228886. return lastError;
  228887. }
  228888. private:
  228889. CriticalSection callbackLock;
  228890. Float64 sampleRate;
  228891. int numInputChannels, numOutputChannels;
  228892. int preferredBufferSize;
  228893. int actualBufferSize;
  228894. bool isRunning;
  228895. String lastError;
  228896. AudioStreamBasicDescription format;
  228897. AudioUnit audioUnit;
  228898. UInt32 audioInputIsAvailable;
  228899. AudioIODeviceCallback* callback;
  228900. BigInteger activeOutputChans, activeInputChans;
  228901. AudioSampleBuffer floatData;
  228902. float* inputChannels[3];
  228903. float* outputChannels[3];
  228904. bool monoInputChannelNumber, monoOutputChannelNumber;
  228905. void prepareFloatBuffers()
  228906. {
  228907. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228908. zerostruct (inputChannels);
  228909. zerostruct (outputChannels);
  228910. for (int i = 0; i < numInputChannels; ++i)
  228911. inputChannels[i] = floatData.getSampleData (i);
  228912. for (int i = 0; i < numOutputChannels; ++i)
  228913. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228914. }
  228915. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228916. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228917. {
  228918. OSStatus err = noErr;
  228919. if (audioInputIsAvailable)
  228920. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228921. const ScopedLock sl (callbackLock);
  228922. if (callback != 0)
  228923. {
  228924. if (audioInputIsAvailable && numInputChannels > 0)
  228925. {
  228926. short* shortData = (short*) ioData->mBuffers[0].mData;
  228927. if (numInputChannels >= 2)
  228928. {
  228929. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228930. {
  228931. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228932. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228933. }
  228934. }
  228935. else
  228936. {
  228937. if (monoInputChannelNumber > 0)
  228938. ++shortData;
  228939. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228940. {
  228941. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228942. ++shortData;
  228943. }
  228944. }
  228945. }
  228946. else
  228947. {
  228948. for (int i = numInputChannels; --i >= 0;)
  228949. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228950. }
  228951. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228952. outputChannels, numOutputChannels,
  228953. (int) inNumberFrames);
  228954. short* shortData = (short*) ioData->mBuffers[0].mData;
  228955. int n = 0;
  228956. if (numOutputChannels >= 2)
  228957. {
  228958. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228959. {
  228960. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228961. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228962. }
  228963. }
  228964. else if (numOutputChannels == 1)
  228965. {
  228966. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228967. {
  228968. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228969. shortData [n++] = s;
  228970. shortData [n++] = s;
  228971. }
  228972. }
  228973. else
  228974. {
  228975. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228976. }
  228977. }
  228978. else
  228979. {
  228980. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228981. }
  228982. return err;
  228983. }
  228984. void updateDeviceInfo()
  228985. {
  228986. UInt32 size = sizeof (sampleRate);
  228987. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228988. size = sizeof (audioInputIsAvailable);
  228989. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228990. }
  228991. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228992. {
  228993. if (! isRunning)
  228994. return;
  228995. if (inPropertyValue != 0)
  228996. {
  228997. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228998. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228999. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229000. SInt32 routeChangeReason;
  229001. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229002. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229003. fixAudioRouteIfSetToReceiver();
  229004. }
  229005. updateDeviceInfo();
  229006. createAudioUnit();
  229007. AudioSessionSetActive (true);
  229008. if (audioUnit != 0)
  229009. {
  229010. UInt32 formatSize = sizeof (format);
  229011. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229012. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229013. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229014. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229015. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229016. AudioOutputUnitStart (audioUnit);
  229017. }
  229018. }
  229019. void interruptionListener (UInt32 inInterruption)
  229020. {
  229021. /*if (inInterruption == kAudioSessionBeginInterruption)
  229022. {
  229023. isRunning = false;
  229024. AudioOutputUnitStop (audioUnit);
  229025. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229026. "This could have been interrupted by another application or by unplugging a headset",
  229027. @"Resume",
  229028. @"Cancel"))
  229029. {
  229030. isRunning = true;
  229031. propertyChanged (0, 0, 0);
  229032. }
  229033. }*/
  229034. if (inInterruption == kAudioSessionEndInterruption)
  229035. {
  229036. isRunning = true;
  229037. AudioSessionSetActive (true);
  229038. AudioOutputUnitStart (audioUnit);
  229039. }
  229040. }
  229041. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229042. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229043. {
  229044. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229045. }
  229046. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229047. {
  229048. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229049. }
  229050. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229051. {
  229052. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229053. }
  229054. void resetFormat (const int numChannels)
  229055. {
  229056. memset (&format, 0, sizeof (format));
  229057. format.mFormatID = kAudioFormatLinearPCM;
  229058. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229059. format.mBitsPerChannel = 8 * sizeof (short);
  229060. format.mChannelsPerFrame = 2;
  229061. format.mFramesPerPacket = 1;
  229062. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229063. }
  229064. bool createAudioUnit()
  229065. {
  229066. if (audioUnit != 0)
  229067. {
  229068. AudioComponentInstanceDispose (audioUnit);
  229069. audioUnit = 0;
  229070. }
  229071. resetFormat (2);
  229072. AudioComponentDescription desc;
  229073. desc.componentType = kAudioUnitType_Output;
  229074. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229075. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229076. desc.componentFlags = 0;
  229077. desc.componentFlagsMask = 0;
  229078. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229079. AudioComponentInstanceNew (comp, &audioUnit);
  229080. if (audioUnit == 0)
  229081. return false;
  229082. const UInt32 one = 1;
  229083. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229084. AudioChannelLayout layout;
  229085. layout.mChannelBitmap = 0;
  229086. layout.mNumberChannelDescriptions = 0;
  229087. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229088. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229089. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229090. AURenderCallbackStruct inputProc;
  229091. inputProc.inputProc = processStatic;
  229092. inputProc.inputProcRefCon = this;
  229093. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229094. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229095. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229096. AudioUnitInitialize (audioUnit);
  229097. return true;
  229098. }
  229099. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229100. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229101. static void fixAudioRouteIfSetToReceiver()
  229102. {
  229103. CFStringRef audioRoute = 0;
  229104. UInt32 propertySize = sizeof (audioRoute);
  229105. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229106. {
  229107. NSString* route = (NSString*) audioRoute;
  229108. //DBG ("audio route: " + nsStringToJuce (route));
  229109. if ([route hasPrefix: @"Receiver"])
  229110. {
  229111. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229112. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229113. }
  229114. CFRelease (audioRoute);
  229115. }
  229116. }
  229117. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  229118. };
  229119. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229120. {
  229121. public:
  229122. IPhoneAudioIODeviceType()
  229123. : AudioIODeviceType ("iPhone Audio")
  229124. {
  229125. }
  229126. void scanForDevices()
  229127. {
  229128. }
  229129. const StringArray getDeviceNames (bool wantInputNames) const
  229130. {
  229131. StringArray s;
  229132. s.add ("iPhone Audio");
  229133. return s;
  229134. }
  229135. int getDefaultDeviceIndex (bool forInput) const
  229136. {
  229137. return 0;
  229138. }
  229139. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229140. {
  229141. return device != 0 ? 0 : -1;
  229142. }
  229143. bool hasSeparateInputsAndOutputs() const { return false; }
  229144. AudioIODevice* createDevice (const String& outputDeviceName,
  229145. const String& inputDeviceName)
  229146. {
  229147. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229148. {
  229149. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229150. : inputDeviceName);
  229151. }
  229152. return 0;
  229153. }
  229154. private:
  229155. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  229156. };
  229157. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229158. {
  229159. return new IPhoneAudioIODeviceType();
  229160. }
  229161. #endif
  229162. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229163. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229164. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229165. // compiled on its own).
  229166. #if JUCE_INCLUDED_FILE
  229167. #if JUCE_MAC
  229168. namespace CoreMidiHelpers
  229169. {
  229170. bool logError (const OSStatus err, const int lineNum)
  229171. {
  229172. if (err == noErr)
  229173. return true;
  229174. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229175. jassertfalse;
  229176. return false;
  229177. }
  229178. #undef CHECK_ERROR
  229179. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229180. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229181. {
  229182. String result;
  229183. CFStringRef str = 0;
  229184. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229185. if (str != 0)
  229186. {
  229187. result = PlatformUtilities::cfStringToJuceString (str);
  229188. CFRelease (str);
  229189. str = 0;
  229190. }
  229191. MIDIEntityRef entity = 0;
  229192. MIDIEndpointGetEntity (endpoint, &entity);
  229193. if (entity == 0)
  229194. return result; // probably virtual
  229195. if (result.isEmpty())
  229196. {
  229197. // endpoint name has zero length - try the entity
  229198. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229199. if (str != 0)
  229200. {
  229201. result += PlatformUtilities::cfStringToJuceString (str);
  229202. CFRelease (str);
  229203. str = 0;
  229204. }
  229205. }
  229206. // now consider the device's name
  229207. MIDIDeviceRef device = 0;
  229208. MIDIEntityGetDevice (entity, &device);
  229209. if (device == 0)
  229210. return result;
  229211. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229212. if (str != 0)
  229213. {
  229214. const String s (PlatformUtilities::cfStringToJuceString (str));
  229215. CFRelease (str);
  229216. // if an external device has only one entity, throw away
  229217. // the endpoint name and just use the device name
  229218. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229219. {
  229220. result = s;
  229221. }
  229222. else if (! result.startsWithIgnoreCase (s))
  229223. {
  229224. // prepend the device name to the entity name
  229225. result = (s + " " + result).trimEnd();
  229226. }
  229227. }
  229228. return result;
  229229. }
  229230. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229231. {
  229232. String result;
  229233. // Does the endpoint have connections?
  229234. CFDataRef connections = 0;
  229235. int numConnections = 0;
  229236. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229237. if (connections != 0)
  229238. {
  229239. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229240. if (numConnections > 0)
  229241. {
  229242. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229243. for (int i = 0; i < numConnections; ++i, ++pid)
  229244. {
  229245. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229246. MIDIObjectRef connObject;
  229247. MIDIObjectType connObjectType;
  229248. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229249. if (err == noErr)
  229250. {
  229251. String s;
  229252. if (connObjectType == kMIDIObjectType_ExternalSource
  229253. || connObjectType == kMIDIObjectType_ExternalDestination)
  229254. {
  229255. // Connected to an external device's endpoint (10.3 and later).
  229256. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229257. }
  229258. else
  229259. {
  229260. // Connected to an external device (10.2) (or something else, catch-all)
  229261. CFStringRef str = 0;
  229262. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229263. if (str != 0)
  229264. {
  229265. s = PlatformUtilities::cfStringToJuceString (str);
  229266. CFRelease (str);
  229267. }
  229268. }
  229269. if (s.isNotEmpty())
  229270. {
  229271. if (result.isNotEmpty())
  229272. result += ", ";
  229273. result += s;
  229274. }
  229275. }
  229276. }
  229277. }
  229278. CFRelease (connections);
  229279. }
  229280. if (result.isNotEmpty())
  229281. return result;
  229282. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229283. return getEndpointName (endpoint, false);
  229284. }
  229285. MIDIClientRef getGlobalMidiClient()
  229286. {
  229287. static MIDIClientRef globalMidiClient = 0;
  229288. if (globalMidiClient == 0)
  229289. {
  229290. String name ("JUCE");
  229291. if (JUCEApplication::getInstance() != 0)
  229292. name = JUCEApplication::getInstance()->getApplicationName();
  229293. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229294. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229295. CFRelease (appName);
  229296. }
  229297. return globalMidiClient;
  229298. }
  229299. class MidiPortAndEndpoint
  229300. {
  229301. public:
  229302. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229303. : port (port_), endPoint (endPoint_)
  229304. {
  229305. }
  229306. ~MidiPortAndEndpoint()
  229307. {
  229308. if (port != 0)
  229309. MIDIPortDispose (port);
  229310. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229311. MIDIEndpointDispose (endPoint);
  229312. }
  229313. void send (const MIDIPacketList* const packets)
  229314. {
  229315. if (port != 0)
  229316. MIDISend (port, endPoint, packets);
  229317. else
  229318. MIDIReceived (endPoint, packets);
  229319. }
  229320. MIDIPortRef port;
  229321. MIDIEndpointRef endPoint;
  229322. };
  229323. class MidiPortAndCallback;
  229324. CriticalSection callbackLock;
  229325. Array<MidiPortAndCallback*> activeCallbacks;
  229326. class MidiPortAndCallback
  229327. {
  229328. public:
  229329. MidiPortAndCallback (MidiInputCallback& callback_)
  229330. : input (0), active (false), callback (callback_), concatenator (2048)
  229331. {
  229332. }
  229333. ~MidiPortAndCallback()
  229334. {
  229335. active = false;
  229336. {
  229337. const ScopedLock sl (callbackLock);
  229338. activeCallbacks.removeValue (this);
  229339. }
  229340. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229341. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229342. }
  229343. void handlePackets (const MIDIPacketList* const pktlist)
  229344. {
  229345. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229346. const ScopedLock sl (callbackLock);
  229347. if (activeCallbacks.contains (this) && active)
  229348. {
  229349. const MIDIPacket* packet = &pktlist->packet[0];
  229350. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229351. {
  229352. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229353. input, callback);
  229354. packet = MIDIPacketNext (packet);
  229355. }
  229356. }
  229357. }
  229358. MidiInput* input;
  229359. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229360. volatile bool active;
  229361. private:
  229362. MidiInputCallback& callback;
  229363. MidiDataConcatenator concatenator;
  229364. };
  229365. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229366. {
  229367. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229368. }
  229369. }
  229370. const StringArray MidiOutput::getDevices()
  229371. {
  229372. StringArray s;
  229373. const ItemCount num = MIDIGetNumberOfDestinations();
  229374. for (ItemCount i = 0; i < num; ++i)
  229375. {
  229376. MIDIEndpointRef dest = MIDIGetDestination (i);
  229377. if (dest != 0)
  229378. {
  229379. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229380. if (name.isEmpty())
  229381. name = "<error>";
  229382. s.add (name);
  229383. }
  229384. else
  229385. {
  229386. s.add ("<error>");
  229387. }
  229388. }
  229389. return s;
  229390. }
  229391. int MidiOutput::getDefaultDeviceIndex()
  229392. {
  229393. return 0;
  229394. }
  229395. MidiOutput* MidiOutput::openDevice (int index)
  229396. {
  229397. MidiOutput* mo = 0;
  229398. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  229399. {
  229400. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229401. CFStringRef pname;
  229402. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229403. {
  229404. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229405. MIDIPortRef port;
  229406. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229407. {
  229408. mo = new MidiOutput();
  229409. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229410. }
  229411. CFRelease (pname);
  229412. }
  229413. }
  229414. return mo;
  229415. }
  229416. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229417. {
  229418. MidiOutput* mo = 0;
  229419. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229420. MIDIEndpointRef endPoint;
  229421. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229422. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229423. {
  229424. mo = new MidiOutput();
  229425. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229426. }
  229427. CFRelease (name);
  229428. return mo;
  229429. }
  229430. MidiOutput::~MidiOutput()
  229431. {
  229432. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229433. }
  229434. void MidiOutput::reset()
  229435. {
  229436. }
  229437. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229438. {
  229439. return false;
  229440. }
  229441. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229442. {
  229443. }
  229444. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229445. {
  229446. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229447. if (message.isSysEx())
  229448. {
  229449. const int maxPacketSize = 256;
  229450. int pos = 0, bytesLeft = message.getRawDataSize();
  229451. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229452. HeapBlock <MIDIPacketList> packets;
  229453. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229454. packets->numPackets = numPackets;
  229455. MIDIPacket* p = packets->packet;
  229456. for (int i = 0; i < numPackets; ++i)
  229457. {
  229458. p->timeStamp = AudioGetCurrentHostTime();
  229459. p->length = jmin (maxPacketSize, bytesLeft);
  229460. memcpy (p->data, message.getRawData() + pos, p->length);
  229461. pos += p->length;
  229462. bytesLeft -= p->length;
  229463. p = MIDIPacketNext (p);
  229464. }
  229465. mpe->send (packets);
  229466. }
  229467. else
  229468. {
  229469. MIDIPacketList packets;
  229470. packets.numPackets = 1;
  229471. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229472. packets.packet[0].length = message.getRawDataSize();
  229473. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229474. mpe->send (&packets);
  229475. }
  229476. }
  229477. const StringArray MidiInput::getDevices()
  229478. {
  229479. StringArray s;
  229480. const ItemCount num = MIDIGetNumberOfSources();
  229481. for (ItemCount i = 0; i < num; ++i)
  229482. {
  229483. MIDIEndpointRef source = MIDIGetSource (i);
  229484. if (source != 0)
  229485. {
  229486. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229487. if (name.isEmpty())
  229488. name = "<error>";
  229489. s.add (name);
  229490. }
  229491. else
  229492. {
  229493. s.add ("<error>");
  229494. }
  229495. }
  229496. return s;
  229497. }
  229498. int MidiInput::getDefaultDeviceIndex()
  229499. {
  229500. return 0;
  229501. }
  229502. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229503. {
  229504. jassert (callback != 0);
  229505. using namespace CoreMidiHelpers;
  229506. MidiInput* newInput = 0;
  229507. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229508. {
  229509. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229510. if (endPoint != 0)
  229511. {
  229512. CFStringRef name;
  229513. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229514. {
  229515. MIDIClientRef client = getGlobalMidiClient();
  229516. if (client != 0)
  229517. {
  229518. MIDIPortRef port;
  229519. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229520. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229521. {
  229522. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229523. {
  229524. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229525. newInput = new MidiInput (getDevices() [index]);
  229526. mpc->input = newInput;
  229527. newInput->internal = mpc;
  229528. const ScopedLock sl (callbackLock);
  229529. activeCallbacks.add (mpc.release());
  229530. }
  229531. else
  229532. {
  229533. CHECK_ERROR (MIDIPortDispose (port));
  229534. }
  229535. }
  229536. }
  229537. }
  229538. CFRelease (name);
  229539. }
  229540. }
  229541. return newInput;
  229542. }
  229543. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229544. {
  229545. jassert (callback != 0);
  229546. using namespace CoreMidiHelpers;
  229547. MidiInput* mi = 0;
  229548. MIDIClientRef client = getGlobalMidiClient();
  229549. if (client != 0)
  229550. {
  229551. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229552. mpc->active = false;
  229553. MIDIEndpointRef endPoint;
  229554. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229555. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229556. {
  229557. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229558. mi = new MidiInput (deviceName);
  229559. mpc->input = mi;
  229560. mi->internal = mpc;
  229561. const ScopedLock sl (callbackLock);
  229562. activeCallbacks.add (mpc.release());
  229563. }
  229564. CFRelease (name);
  229565. }
  229566. return mi;
  229567. }
  229568. MidiInput::MidiInput (const String& name_)
  229569. : name (name_)
  229570. {
  229571. }
  229572. MidiInput::~MidiInput()
  229573. {
  229574. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229575. }
  229576. void MidiInput::start()
  229577. {
  229578. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229579. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229580. }
  229581. void MidiInput::stop()
  229582. {
  229583. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229584. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229585. }
  229586. #undef CHECK_ERROR
  229587. #else // Stubs for iOS...
  229588. MidiOutput::~MidiOutput() {}
  229589. void MidiOutput::reset() {}
  229590. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229591. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229592. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229593. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229594. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229595. const StringArray MidiInput::getDevices() { return StringArray(); }
  229596. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229597. #endif
  229598. #endif
  229599. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229600. #else
  229601. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229602. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229603. // compiled on its own).
  229604. #if JUCE_INCLUDED_FILE
  229605. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229606. #define SUPPORT_10_4_FONTS 1
  229607. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229608. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229609. #define SUPPORT_ONLY_10_4_FONTS 1
  229610. #endif
  229611. END_JUCE_NAMESPACE
  229612. @interface NSFont (PrivateHack)
  229613. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229614. @end
  229615. BEGIN_JUCE_NAMESPACE
  229616. #endif
  229617. class MacTypeface : public Typeface
  229618. {
  229619. public:
  229620. MacTypeface (const Font& font)
  229621. : Typeface (font.getTypefaceName())
  229622. {
  229623. const ScopedAutoReleasePool pool;
  229624. renderingTransform = CGAffineTransformIdentity;
  229625. bool needsItalicTransform = false;
  229626. #if JUCE_IOS
  229627. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229628. if (font.isItalic() || font.isBold())
  229629. {
  229630. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229631. for (NSString* i in familyFonts)
  229632. {
  229633. const String fn (nsStringToJuce (i));
  229634. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229635. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229636. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229637. || afterDash.containsIgnoreCase ("italic")
  229638. || fn.endsWithIgnoreCase ("oblique")
  229639. || fn.endsWithIgnoreCase ("italic");
  229640. if (probablyBold == font.isBold()
  229641. && probablyItalic == font.isItalic())
  229642. {
  229643. fontName = i;
  229644. needsItalicTransform = false;
  229645. break;
  229646. }
  229647. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229648. {
  229649. fontName = i;
  229650. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229651. }
  229652. }
  229653. if (needsItalicTransform)
  229654. renderingTransform.c = 0.15f;
  229655. }
  229656. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229657. const int ascender = abs (CGFontGetAscent (fontRef));
  229658. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229659. ascent = ascender / totalHeight;
  229660. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229661. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229662. #else
  229663. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229664. if (font.isItalic())
  229665. {
  229666. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229667. toHaveTrait: NSItalicFontMask];
  229668. if (newFont == nsFont)
  229669. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229670. nsFont = newFont;
  229671. }
  229672. if (font.isBold())
  229673. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229674. [nsFont retain];
  229675. ascent = std::abs ((float) [nsFont ascender]);
  229676. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229677. ascent /= totalSize;
  229678. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229679. if (needsItalicTransform)
  229680. {
  229681. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229682. renderingTransform.c = 0.15f;
  229683. }
  229684. #if SUPPORT_ONLY_10_4_FONTS
  229685. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229686. if (atsFont == 0)
  229687. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229688. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229689. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229690. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229691. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229692. #else
  229693. #if SUPPORT_10_4_FONTS
  229694. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229695. {
  229696. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229697. if (atsFont == 0)
  229698. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229699. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229700. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229701. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229702. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229703. }
  229704. else
  229705. #endif
  229706. {
  229707. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229708. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229709. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229710. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229711. }
  229712. #endif
  229713. #endif
  229714. }
  229715. ~MacTypeface()
  229716. {
  229717. #if ! JUCE_IOS
  229718. [nsFont release];
  229719. #endif
  229720. if (fontRef != 0)
  229721. CGFontRelease (fontRef);
  229722. }
  229723. float getAscent() const
  229724. {
  229725. return ascent;
  229726. }
  229727. float getDescent() const
  229728. {
  229729. return 1.0f - ascent;
  229730. }
  229731. float getStringWidth (const String& text)
  229732. {
  229733. if (fontRef == 0 || text.isEmpty())
  229734. return 0;
  229735. const int length = text.length();
  229736. HeapBlock <CGGlyph> glyphs;
  229737. createGlyphsForString (text, length, glyphs);
  229738. float x = 0;
  229739. #if SUPPORT_ONLY_10_4_FONTS
  229740. HeapBlock <NSSize> advances (length);
  229741. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229742. for (int i = 0; i < length; ++i)
  229743. x += advances[i].width;
  229744. #else
  229745. #if SUPPORT_10_4_FONTS
  229746. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229747. {
  229748. HeapBlock <NSSize> advances (length);
  229749. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229750. for (int i = 0; i < length; ++i)
  229751. x += advances[i].width;
  229752. }
  229753. else
  229754. #endif
  229755. {
  229756. HeapBlock <int> advances (length);
  229757. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229758. for (int i = 0; i < length; ++i)
  229759. x += advances[i];
  229760. }
  229761. #endif
  229762. return x * unitsToHeightScaleFactor;
  229763. }
  229764. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229765. {
  229766. xOffsets.add (0);
  229767. if (fontRef == 0 || text.isEmpty())
  229768. return;
  229769. const int length = text.length();
  229770. HeapBlock <CGGlyph> glyphs;
  229771. createGlyphsForString (text, length, glyphs);
  229772. #if SUPPORT_ONLY_10_4_FONTS
  229773. HeapBlock <NSSize> advances (length);
  229774. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229775. int x = 0;
  229776. for (int i = 0; i < length; ++i)
  229777. {
  229778. x += advances[i].width;
  229779. xOffsets.add (x * unitsToHeightScaleFactor);
  229780. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229781. }
  229782. #else
  229783. #if SUPPORT_10_4_FONTS
  229784. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229785. {
  229786. HeapBlock <NSSize> advances (length);
  229787. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229788. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229789. float x = 0;
  229790. for (int i = 0; i < length; ++i)
  229791. {
  229792. x += advances[i].width;
  229793. xOffsets.add (x * unitsToHeightScaleFactor);
  229794. resultGlyphs.add (nsGlyphs[i]);
  229795. }
  229796. }
  229797. else
  229798. #endif
  229799. {
  229800. HeapBlock <int> advances (length);
  229801. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229802. {
  229803. int x = 0;
  229804. for (int i = 0; i < length; ++i)
  229805. {
  229806. x += advances [i];
  229807. xOffsets.add (x * unitsToHeightScaleFactor);
  229808. resultGlyphs.add (glyphs[i]);
  229809. }
  229810. }
  229811. }
  229812. #endif
  229813. }
  229814. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229815. {
  229816. #if JUCE_IOS
  229817. return false;
  229818. #else
  229819. if (nsFont == 0)
  229820. return false;
  229821. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229822. jassert (path.isEmpty());
  229823. const ScopedAutoReleasePool pool;
  229824. NSBezierPath* bez = [NSBezierPath bezierPath];
  229825. [bez moveToPoint: NSMakePoint (0, 0)];
  229826. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229827. inFont: nsFont];
  229828. for (int i = 0; i < [bez elementCount]; ++i)
  229829. {
  229830. NSPoint p[3];
  229831. switch ([bez elementAtIndex: i associatedPoints: p])
  229832. {
  229833. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229834. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229835. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229836. (float) p[1].x, (float) -p[1].y,
  229837. (float) p[2].x, (float) -p[2].y); break;
  229838. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229839. default: jassertfalse; break;
  229840. }
  229841. }
  229842. path.applyTransform (pathTransform);
  229843. return true;
  229844. #endif
  229845. }
  229846. CGFontRef fontRef;
  229847. float fontHeightToCGSizeFactor;
  229848. CGAffineTransform renderingTransform;
  229849. private:
  229850. float ascent, unitsToHeightScaleFactor;
  229851. #if JUCE_IOS
  229852. #else
  229853. NSFont* nsFont;
  229854. AffineTransform pathTransform;
  229855. #endif
  229856. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  229857. {
  229858. #if SUPPORT_10_4_FONTS
  229859. #if ! SUPPORT_ONLY_10_4_FONTS
  229860. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229861. #endif
  229862. {
  229863. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229864. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229865. for (int i = 0; i < length; ++i)
  229866. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  229867. return;
  229868. }
  229869. #endif
  229870. #if ! SUPPORT_ONLY_10_4_FONTS
  229871. if (charToGlyphMapper == 0)
  229872. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229873. glyphs.malloc (length);
  229874. for (int i = 0; i < length; ++i)
  229875. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  229876. #endif
  229877. }
  229878. #if ! SUPPORT_ONLY_10_4_FONTS
  229879. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229880. class CharToGlyphMapper
  229881. {
  229882. public:
  229883. CharToGlyphMapper (CGFontRef fontRef)
  229884. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229885. idRangeOffset (0), glyphIndexes (0)
  229886. {
  229887. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229888. if (cmapTable != 0)
  229889. {
  229890. const int numSubtables = getValue16 (cmapTable, 2);
  229891. for (int i = 0; i < numSubtables; ++i)
  229892. {
  229893. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229894. {
  229895. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229896. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229897. {
  229898. const int length = getValue16 (cmapTable, offset + 2);
  229899. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229900. segCount = segCountX2 / 2;
  229901. const int endCodeOffset = offset + 14;
  229902. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229903. const int idDeltaOffset = startCodeOffset + segCountX2;
  229904. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229905. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229906. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229907. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229908. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229909. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229910. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229911. }
  229912. break;
  229913. }
  229914. }
  229915. CFRelease (cmapTable);
  229916. }
  229917. }
  229918. ~CharToGlyphMapper()
  229919. {
  229920. if (endCode != 0)
  229921. {
  229922. CFRelease (endCode);
  229923. CFRelease (startCode);
  229924. CFRelease (idDelta);
  229925. CFRelease (idRangeOffset);
  229926. CFRelease (glyphIndexes);
  229927. }
  229928. }
  229929. int getGlyphForCharacter (const juce_wchar c) const
  229930. {
  229931. for (int i = 0; i < segCount; ++i)
  229932. {
  229933. if (getValue16 (endCode, i * 2) >= c)
  229934. {
  229935. const int start = getValue16 (startCode, i * 2);
  229936. if (start > c)
  229937. break;
  229938. const int delta = getValue16 (idDelta, i * 2);
  229939. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229940. if (rangeOffset == 0)
  229941. return delta + c;
  229942. else
  229943. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229944. }
  229945. }
  229946. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229947. return jmax (-1, (int) c - 29);
  229948. }
  229949. private:
  229950. int segCount;
  229951. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229952. static uint16 getValue16 (CFDataRef data, const int index)
  229953. {
  229954. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229955. }
  229956. static uint32 getValue32 (CFDataRef data, const int index)
  229957. {
  229958. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229959. }
  229960. };
  229961. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229962. #endif
  229963. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229964. };
  229965. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229966. {
  229967. return new MacTypeface (font);
  229968. }
  229969. const StringArray Font::findAllTypefaceNames()
  229970. {
  229971. StringArray names;
  229972. const ScopedAutoReleasePool pool;
  229973. #if JUCE_IOS
  229974. NSArray* fonts = [UIFont familyNames];
  229975. #else
  229976. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229977. #endif
  229978. for (unsigned int i = 0; i < [fonts count]; ++i)
  229979. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229980. names.sort (true);
  229981. return names;
  229982. }
  229983. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229984. {
  229985. #if JUCE_IOS
  229986. defaultSans = "Helvetica";
  229987. defaultSerif = "Times New Roman";
  229988. defaultFixed = "Courier New";
  229989. #else
  229990. defaultSans = "Lucida Grande";
  229991. defaultSerif = "Times New Roman";
  229992. defaultFixed = "Monaco";
  229993. #endif
  229994. defaultFallback = "Arial Unicode MS";
  229995. }
  229996. #endif
  229997. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229998. // (must go before juce_mac_CoreGraphicsContext.mm)
  229999. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230000. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230001. // compiled on its own).
  230002. #if JUCE_INCLUDED_FILE
  230003. class CoreGraphicsImage : public Image::SharedImage
  230004. {
  230005. public:
  230006. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230007. : Image::SharedImage (format_, width_, height_)
  230008. {
  230009. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230010. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230011. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230012. imageData = imageDataAllocated;
  230013. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230014. : CGColorSpaceCreateDeviceRGB();
  230015. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230016. colourSpace, getCGImageFlags (format_));
  230017. CGColorSpaceRelease (colourSpace);
  230018. }
  230019. ~CoreGraphicsImage()
  230020. {
  230021. CGContextRelease (context);
  230022. }
  230023. Image::ImageType getType() const { return Image::NativeImage; }
  230024. LowLevelGraphicsContext* createLowLevelContext();
  230025. SharedImage* clone()
  230026. {
  230027. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230028. memcpy (im->imageData, imageData, lineStride * height);
  230029. return im;
  230030. }
  230031. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230032. {
  230033. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230034. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230035. {
  230036. return CGBitmapContextCreateImage (nativeImage->context);
  230037. }
  230038. else
  230039. {
  230040. const Image::BitmapData srcData (juceImage, false);
  230041. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230042. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230043. 8, srcData.pixelStride * 8, srcData.lineStride,
  230044. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230045. 0, true, kCGRenderingIntentDefault);
  230046. CGDataProviderRelease (provider);
  230047. return imageRef;
  230048. }
  230049. }
  230050. #if JUCE_MAC
  230051. static NSImage* createNSImage (const Image& image)
  230052. {
  230053. const ScopedAutoReleasePool pool;
  230054. NSImage* im = [[NSImage alloc] init];
  230055. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230056. [im lockFocus];
  230057. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230058. CGImageRef imageRef = createImage (image, false, colourSpace);
  230059. CGColorSpaceRelease (colourSpace);
  230060. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230061. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230062. CGImageRelease (imageRef);
  230063. [im unlockFocus];
  230064. return im;
  230065. }
  230066. #endif
  230067. CGContextRef context;
  230068. HeapBlock<uint8> imageDataAllocated;
  230069. private:
  230070. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230071. {
  230072. #if JUCE_BIG_ENDIAN
  230073. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230074. #else
  230075. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230076. #endif
  230077. }
  230078. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  230079. };
  230080. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230081. {
  230082. #if USE_COREGRAPHICS_RENDERING
  230083. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230084. #else
  230085. return createSoftwareImage (format, width, height, clearImage);
  230086. #endif
  230087. }
  230088. class CoreGraphicsContext : public LowLevelGraphicsContext
  230089. {
  230090. public:
  230091. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230092. : context (context_),
  230093. flipHeight (flipHeight_),
  230094. lastClipRectIsValid (false),
  230095. state (new SavedState()),
  230096. numGradientLookupEntries (0)
  230097. {
  230098. CGContextRetain (context);
  230099. CGContextSaveGState(context);
  230100. CGContextSetShouldSmoothFonts (context, true);
  230101. CGContextSetShouldAntialias (context, true);
  230102. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230103. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230104. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230105. gradientCallbacks.version = 0;
  230106. gradientCallbacks.evaluate = gradientCallback;
  230107. gradientCallbacks.releaseInfo = 0;
  230108. setFont (Font());
  230109. }
  230110. ~CoreGraphicsContext()
  230111. {
  230112. CGContextRestoreGState (context);
  230113. CGContextRelease (context);
  230114. CGColorSpaceRelease (rgbColourSpace);
  230115. CGColorSpaceRelease (greyColourSpace);
  230116. }
  230117. bool isVectorDevice() const { return false; }
  230118. void setOrigin (int x, int y)
  230119. {
  230120. CGContextTranslateCTM (context, x, -y);
  230121. if (lastClipRectIsValid)
  230122. lastClipRect.translate (-x, -y);
  230123. }
  230124. void addTransform (const AffineTransform& transform)
  230125. {
  230126. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  230127. .translated (0, flipHeight)
  230128. .followedBy (transform)
  230129. .translated (0, -flipHeight)
  230130. .scaled (1.0f, -1.0f));
  230131. lastClipRectIsValid = false;
  230132. }
  230133. float getScaleFactor()
  230134. {
  230135. CGAffineTransform t = CGContextGetCTM (context);
  230136. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  230137. }
  230138. bool clipToRectangle (const Rectangle<int>& r)
  230139. {
  230140. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230141. if (lastClipRectIsValid)
  230142. {
  230143. // This is actually incorrect, because the actual clip region may be complex, and
  230144. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230145. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230146. // when calculating the resultant clip bounds, and makes the same mistake!
  230147. lastClipRect = lastClipRect.getIntersection (r);
  230148. return ! lastClipRect.isEmpty();
  230149. }
  230150. return ! isClipEmpty();
  230151. }
  230152. bool clipToRectangleList (const RectangleList& clipRegion)
  230153. {
  230154. if (clipRegion.isEmpty())
  230155. {
  230156. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230157. lastClipRectIsValid = true;
  230158. lastClipRect = Rectangle<int>();
  230159. return false;
  230160. }
  230161. else
  230162. {
  230163. const int numRects = clipRegion.getNumRectangles();
  230164. HeapBlock <CGRect> rects (numRects);
  230165. for (int i = 0; i < numRects; ++i)
  230166. {
  230167. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230168. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230169. }
  230170. CGContextClipToRects (context, rects, numRects);
  230171. lastClipRectIsValid = false;
  230172. return ! isClipEmpty();
  230173. }
  230174. }
  230175. void excludeClipRectangle (const Rectangle<int>& r)
  230176. {
  230177. RectangleList remaining (getClipBounds());
  230178. remaining.subtract (r);
  230179. clipToRectangleList (remaining);
  230180. lastClipRectIsValid = false;
  230181. }
  230182. void clipToPath (const Path& path, const AffineTransform& transform)
  230183. {
  230184. createPath (path, transform);
  230185. CGContextClip (context);
  230186. lastClipRectIsValid = false;
  230187. }
  230188. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230189. {
  230190. if (! transform.isSingularity())
  230191. {
  230192. Image singleChannelImage (sourceImage);
  230193. if (sourceImage.getFormat() != Image::SingleChannel)
  230194. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230195. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230196. flip();
  230197. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230198. applyTransform (t);
  230199. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230200. CGContextClipToMask (context, r, image);
  230201. applyTransform (t.inverted());
  230202. flip();
  230203. CGImageRelease (image);
  230204. lastClipRectIsValid = false;
  230205. }
  230206. }
  230207. bool clipRegionIntersects (const Rectangle<int>& r)
  230208. {
  230209. return getClipBounds().intersects (r);
  230210. }
  230211. const Rectangle<int> getClipBounds() const
  230212. {
  230213. if (! lastClipRectIsValid)
  230214. {
  230215. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230216. lastClipRectIsValid = true;
  230217. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230218. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230219. roundToInt (bounds.size.width),
  230220. roundToInt (bounds.size.height));
  230221. }
  230222. return lastClipRect;
  230223. }
  230224. bool isClipEmpty() const
  230225. {
  230226. return getClipBounds().isEmpty();
  230227. }
  230228. void saveState()
  230229. {
  230230. CGContextSaveGState (context);
  230231. stateStack.add (new SavedState (*state));
  230232. }
  230233. void restoreState()
  230234. {
  230235. CGContextRestoreGState (context);
  230236. SavedState* const top = stateStack.getLast();
  230237. if (top != 0)
  230238. {
  230239. state = top;
  230240. stateStack.removeLast (1, false);
  230241. lastClipRectIsValid = false;
  230242. }
  230243. else
  230244. {
  230245. jassertfalse; // trying to pop with an empty stack!
  230246. }
  230247. }
  230248. void beginTransparencyLayer (float opacity)
  230249. {
  230250. saveState();
  230251. CGContextSetAlpha (context, opacity);
  230252. CGContextBeginTransparencyLayer (context, 0);
  230253. }
  230254. void endTransparencyLayer()
  230255. {
  230256. CGContextEndTransparencyLayer (context);
  230257. restoreState();
  230258. }
  230259. void setFill (const FillType& fillType)
  230260. {
  230261. state->fillType = fillType;
  230262. if (fillType.isColour())
  230263. {
  230264. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230265. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230266. CGContextSetAlpha (context, 1.0f);
  230267. }
  230268. }
  230269. void setOpacity (float newOpacity)
  230270. {
  230271. state->fillType.setOpacity (newOpacity);
  230272. setFill (state->fillType);
  230273. }
  230274. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230275. {
  230276. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230277. ? kCGInterpolationLow
  230278. : kCGInterpolationHigh);
  230279. }
  230280. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230281. {
  230282. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230283. }
  230284. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230285. {
  230286. if (replaceExistingContents)
  230287. {
  230288. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230289. CGContextClearRect (context, cgRect);
  230290. #else
  230291. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230292. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230293. CGContextClearRect (context, cgRect);
  230294. else
  230295. #endif
  230296. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230297. #endif
  230298. fillCGRect (cgRect, false);
  230299. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230300. }
  230301. else
  230302. {
  230303. if (state->fillType.isColour())
  230304. {
  230305. CGContextFillRect (context, cgRect);
  230306. }
  230307. else if (state->fillType.isGradient())
  230308. {
  230309. CGContextSaveGState (context);
  230310. CGContextClipToRect (context, cgRect);
  230311. drawGradient();
  230312. CGContextRestoreGState (context);
  230313. }
  230314. else
  230315. {
  230316. CGContextSaveGState (context);
  230317. CGContextClipToRect (context, cgRect);
  230318. drawImage (state->fillType.image, state->fillType.transform, true);
  230319. CGContextRestoreGState (context);
  230320. }
  230321. }
  230322. }
  230323. void fillPath (const Path& path, const AffineTransform& transform)
  230324. {
  230325. CGContextSaveGState (context);
  230326. if (state->fillType.isColour())
  230327. {
  230328. flip();
  230329. applyTransform (transform);
  230330. createPath (path);
  230331. if (path.isUsingNonZeroWinding())
  230332. CGContextFillPath (context);
  230333. else
  230334. CGContextEOFillPath (context);
  230335. }
  230336. else
  230337. {
  230338. createPath (path, transform);
  230339. if (path.isUsingNonZeroWinding())
  230340. CGContextClip (context);
  230341. else
  230342. CGContextEOClip (context);
  230343. if (state->fillType.isGradient())
  230344. drawGradient();
  230345. else
  230346. drawImage (state->fillType.image, state->fillType.transform, true);
  230347. }
  230348. CGContextRestoreGState (context);
  230349. }
  230350. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230351. {
  230352. const int iw = sourceImage.getWidth();
  230353. const int ih = sourceImage.getHeight();
  230354. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230355. CGContextSaveGState (context);
  230356. CGContextSetAlpha (context, state->fillType.getOpacity());
  230357. flip();
  230358. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230359. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230360. if (fillEntireClipAsTiles)
  230361. {
  230362. #if JUCE_IOS
  230363. CGContextDrawTiledImage (context, imageRect, image);
  230364. #else
  230365. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230366. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230367. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230368. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230369. CGContextDrawTiledImage (context, imageRect, image);
  230370. else
  230371. #endif
  230372. {
  230373. // Fallback to manually doing a tiled fill on 10.4
  230374. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230375. int x = 0, y = 0;
  230376. while (x > clip.origin.x) x -= iw;
  230377. while (y > clip.origin.y) y -= ih;
  230378. const int right = (int) (clip.origin.x + clip.size.width);
  230379. const int bottom = (int) (clip.origin.y + clip.size.height);
  230380. while (y < bottom)
  230381. {
  230382. for (int x2 = x; x2 < right; x2 += iw)
  230383. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230384. y += ih;
  230385. }
  230386. }
  230387. #endif
  230388. }
  230389. else
  230390. {
  230391. CGContextDrawImage (context, imageRect, image);
  230392. }
  230393. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230394. CGContextRestoreGState (context);
  230395. }
  230396. void drawLine (const Line<float>& line)
  230397. {
  230398. if (state->fillType.isColour())
  230399. {
  230400. CGContextSetLineCap (context, kCGLineCapSquare);
  230401. CGContextSetLineWidth (context, 1.0f);
  230402. CGContextSetRGBStrokeColor (context,
  230403. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230404. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230405. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230406. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230407. CGContextStrokeLineSegments (context, cgLine, 1);
  230408. }
  230409. else
  230410. {
  230411. Path p;
  230412. p.addLineSegment (line, 1.0f);
  230413. fillPath (p, AffineTransform::identity);
  230414. }
  230415. }
  230416. void drawVerticalLine (const int x, float top, float bottom)
  230417. {
  230418. if (state->fillType.isColour())
  230419. {
  230420. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230421. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230422. #else
  230423. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230424. // the x co-ord slightly to trick it..
  230425. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230426. #endif
  230427. }
  230428. else
  230429. {
  230430. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230431. }
  230432. }
  230433. void drawHorizontalLine (const int y, float left, float right)
  230434. {
  230435. if (state->fillType.isColour())
  230436. {
  230437. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230438. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230439. #else
  230440. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230441. // the x co-ord slightly to trick it..
  230442. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230443. #endif
  230444. }
  230445. else
  230446. {
  230447. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230448. }
  230449. }
  230450. void setFont (const Font& newFont)
  230451. {
  230452. if (state->font != newFont)
  230453. {
  230454. state->fontRef = 0;
  230455. state->font = newFont;
  230456. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230457. if (mf != 0)
  230458. {
  230459. state->fontRef = mf->fontRef;
  230460. CGContextSetFont (context, state->fontRef);
  230461. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230462. state->fontTransform = mf->renderingTransform;
  230463. state->fontTransform.a *= state->font.getHorizontalScale();
  230464. CGContextSetTextMatrix (context, state->fontTransform);
  230465. }
  230466. }
  230467. }
  230468. const Font getFont()
  230469. {
  230470. return state->font;
  230471. }
  230472. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230473. {
  230474. if (state->fontRef != 0 && state->fillType.isColour())
  230475. {
  230476. if (transform.isOnlyTranslation())
  230477. {
  230478. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230479. CGGlyph g = glyphNumber;
  230480. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230481. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230482. }
  230483. else
  230484. {
  230485. CGContextSaveGState (context);
  230486. flip();
  230487. applyTransform (transform);
  230488. CGAffineTransform t = state->fontTransform;
  230489. t.d = -t.d;
  230490. CGContextSetTextMatrix (context, t);
  230491. CGGlyph g = glyphNumber;
  230492. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230493. CGContextRestoreGState (context);
  230494. }
  230495. }
  230496. else
  230497. {
  230498. Path p;
  230499. Font& f = state->font;
  230500. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230501. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230502. .followedBy (transform));
  230503. }
  230504. }
  230505. private:
  230506. CGContextRef context;
  230507. const CGFloat flipHeight;
  230508. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230509. CGFunctionCallbacks gradientCallbacks;
  230510. mutable Rectangle<int> lastClipRect;
  230511. mutable bool lastClipRectIsValid;
  230512. struct SavedState
  230513. {
  230514. SavedState()
  230515. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230516. {
  230517. }
  230518. SavedState (const SavedState& other)
  230519. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230520. fontTransform (other.fontTransform)
  230521. {
  230522. }
  230523. FillType fillType;
  230524. Font font;
  230525. CGFontRef fontRef;
  230526. CGAffineTransform fontTransform;
  230527. };
  230528. ScopedPointer <SavedState> state;
  230529. OwnedArray <SavedState> stateStack;
  230530. HeapBlock <PixelARGB> gradientLookupTable;
  230531. int numGradientLookupEntries;
  230532. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230533. {
  230534. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230535. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230536. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230537. colour.unpremultiply();
  230538. outData[0] = colour.getRed() / 255.0f;
  230539. outData[1] = colour.getGreen() / 255.0f;
  230540. outData[2] = colour.getBlue() / 255.0f;
  230541. outData[3] = colour.getAlpha() / 255.0f;
  230542. }
  230543. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230544. {
  230545. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230546. CGShadingRef result = 0;
  230547. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230548. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230549. if (gradient.isRadial)
  230550. {
  230551. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230552. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230553. function, true, true);
  230554. }
  230555. else
  230556. {
  230557. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230558. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230559. function, true, true);
  230560. }
  230561. CGFunctionRelease (function);
  230562. return result;
  230563. }
  230564. void drawGradient()
  230565. {
  230566. flip();
  230567. applyTransform (state->fillType.transform);
  230568. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230569. // you draw a gradient with high quality interp enabled).
  230570. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230571. CGContextSetAlpha (context, state->fillType.getOpacity());
  230572. CGContextDrawShading (context, shading);
  230573. CGShadingRelease (shading);
  230574. }
  230575. void createPath (const Path& path) const
  230576. {
  230577. CGContextBeginPath (context);
  230578. Path::Iterator i (path);
  230579. while (i.next())
  230580. {
  230581. switch (i.elementType)
  230582. {
  230583. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230584. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230585. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230586. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230587. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230588. default: jassertfalse; break;
  230589. }
  230590. }
  230591. }
  230592. void createPath (const Path& path, const AffineTransform& transform) const
  230593. {
  230594. CGContextBeginPath (context);
  230595. Path::Iterator i (path);
  230596. while (i.next())
  230597. {
  230598. switch (i.elementType)
  230599. {
  230600. case Path::Iterator::startNewSubPath:
  230601. transform.transformPoint (i.x1, i.y1);
  230602. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230603. break;
  230604. case Path::Iterator::lineTo:
  230605. transform.transformPoint (i.x1, i.y1);
  230606. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230607. break;
  230608. case Path::Iterator::quadraticTo:
  230609. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230610. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230611. break;
  230612. case Path::Iterator::cubicTo:
  230613. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230614. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230615. break;
  230616. case Path::Iterator::closePath:
  230617. CGContextClosePath (context); break;
  230618. default:
  230619. jassertfalse;
  230620. break;
  230621. }
  230622. }
  230623. }
  230624. void flip() const
  230625. {
  230626. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230627. }
  230628. void applyTransform (const AffineTransform& transform) const
  230629. {
  230630. CGAffineTransform t;
  230631. t.a = transform.mat00;
  230632. t.b = transform.mat10;
  230633. t.c = transform.mat01;
  230634. t.d = transform.mat11;
  230635. t.tx = transform.mat02;
  230636. t.ty = transform.mat12;
  230637. CGContextConcatCTM (context, t);
  230638. }
  230639. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230640. };
  230641. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230642. {
  230643. return new CoreGraphicsContext (context, height);
  230644. }
  230645. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230646. const Image juce_loadWithCoreImage (InputStream& input)
  230647. {
  230648. MemoryBlock data;
  230649. input.readIntoMemoryBlock (data, -1);
  230650. #if JUCE_IOS
  230651. JUCE_AUTORELEASEPOOL
  230652. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230653. length: data.getSize()
  230654. freeWhenDone: NO]];
  230655. if (image != nil)
  230656. {
  230657. CGImageRef loadedImage = image.CGImage;
  230658. #else
  230659. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230660. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230661. CGDataProviderRelease (provider);
  230662. if (imageSource != 0)
  230663. {
  230664. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230665. CFRelease (imageSource);
  230666. #endif
  230667. if (loadedImage != 0)
  230668. {
  230669. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230670. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230671. && alphaInfo != kCGImageAlphaNoneSkipLast
  230672. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230673. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230674. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230675. hasAlphaChan, Image::NativeImage);
  230676. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230677. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230678. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230679. CGContextFlush (cgImage->context);
  230680. #if ! JUCE_IOS
  230681. CFRelease (loadedImage);
  230682. #endif
  230683. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230684. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230685. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230686. return image;
  230687. }
  230688. }
  230689. return Image::null;
  230690. }
  230691. #endif
  230692. #endif
  230693. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230694. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230695. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230696. // compiled on its own).
  230697. #if JUCE_INCLUDED_FILE
  230698. class NSViewComponentPeer;
  230699. END_JUCE_NAMESPACE
  230700. @interface NSEvent (JuceDeviceDelta)
  230701. - (float) deviceDeltaX;
  230702. - (float) deviceDeltaY;
  230703. @end
  230704. #define JuceNSView MakeObjCClassName(JuceNSView)
  230705. @interface JuceNSView : NSView<NSTextInput>
  230706. {
  230707. @public
  230708. NSViewComponentPeer* owner;
  230709. NSNotificationCenter* notificationCenter;
  230710. String* stringBeingComposed;
  230711. bool textWasInserted;
  230712. }
  230713. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230714. - (void) dealloc;
  230715. - (BOOL) isOpaque;
  230716. - (void) drawRect: (NSRect) r;
  230717. - (void) mouseDown: (NSEvent*) ev;
  230718. - (void) asyncMouseDown: (NSEvent*) ev;
  230719. - (void) mouseUp: (NSEvent*) ev;
  230720. - (void) asyncMouseUp: (NSEvent*) ev;
  230721. - (void) mouseDragged: (NSEvent*) ev;
  230722. - (void) mouseMoved: (NSEvent*) ev;
  230723. - (void) mouseEntered: (NSEvent*) ev;
  230724. - (void) mouseExited: (NSEvent*) ev;
  230725. - (void) rightMouseDown: (NSEvent*) ev;
  230726. - (void) rightMouseDragged: (NSEvent*) ev;
  230727. - (void) rightMouseUp: (NSEvent*) ev;
  230728. - (void) otherMouseDown: (NSEvent*) ev;
  230729. - (void) otherMouseDragged: (NSEvent*) ev;
  230730. - (void) otherMouseUp: (NSEvent*) ev;
  230731. - (void) scrollWheel: (NSEvent*) ev;
  230732. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230733. - (void) frameChanged: (NSNotification*) n;
  230734. - (void) viewDidMoveToWindow;
  230735. - (void) keyDown: (NSEvent*) ev;
  230736. - (void) keyUp: (NSEvent*) ev;
  230737. // NSTextInput Methods
  230738. - (void) insertText: (id) aString;
  230739. - (void) doCommandBySelector: (SEL) aSelector;
  230740. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230741. - (void) unmarkText;
  230742. - (BOOL) hasMarkedText;
  230743. - (long) conversationIdentifier;
  230744. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230745. - (NSRange) markedRange;
  230746. - (NSRange) selectedRange;
  230747. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230748. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230749. - (NSArray*) validAttributesForMarkedText;
  230750. - (void) flagsChanged: (NSEvent*) ev;
  230751. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230752. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230753. #endif
  230754. - (BOOL) becomeFirstResponder;
  230755. - (BOOL) resignFirstResponder;
  230756. - (BOOL) acceptsFirstResponder;
  230757. - (void) asyncRepaint: (id) rect;
  230758. - (NSArray*) getSupportedDragTypes;
  230759. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230760. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230761. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230762. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230763. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230764. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230765. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230766. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230767. @end
  230768. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230769. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230770. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230771. #else
  230772. @interface JuceNSWindow : NSWindow
  230773. #endif
  230774. {
  230775. @private
  230776. NSViewComponentPeer* owner;
  230777. bool isZooming;
  230778. }
  230779. - (void) setOwner: (NSViewComponentPeer*) owner;
  230780. - (BOOL) canBecomeKeyWindow;
  230781. - (void) becomeKeyWindow;
  230782. - (BOOL) windowShouldClose: (id) window;
  230783. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230784. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230785. - (void) zoom: (id) sender;
  230786. @end
  230787. BEGIN_JUCE_NAMESPACE
  230788. class NSViewComponentPeer : public ComponentPeer
  230789. {
  230790. public:
  230791. NSViewComponentPeer (Component* const component,
  230792. const int windowStyleFlags,
  230793. NSView* viewToAttachTo);
  230794. ~NSViewComponentPeer();
  230795. void* getNativeHandle() const;
  230796. void setVisible (bool shouldBeVisible);
  230797. void setTitle (const String& title);
  230798. void setPosition (int x, int y);
  230799. void setSize (int w, int h);
  230800. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230801. const Rectangle<int> getBounds (const bool global) const;
  230802. const Rectangle<int> getBounds() const;
  230803. const Point<int> getScreenPosition() const;
  230804. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230805. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230806. void setAlpha (float newAlpha);
  230807. void setMinimised (bool shouldBeMinimised);
  230808. bool isMinimised() const;
  230809. void setFullScreen (bool shouldBeFullScreen);
  230810. bool isFullScreen() const;
  230811. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230812. const BorderSize getFrameSize() const;
  230813. bool setAlwaysOnTop (bool alwaysOnTop);
  230814. void toFront (bool makeActiveWindow);
  230815. void toBehind (ComponentPeer* other);
  230816. void setIcon (const Image& newIcon);
  230817. const StringArray getAvailableRenderingEngines();
  230818. int getCurrentRenderingEngine() throw();
  230819. void setCurrentRenderingEngine (int index);
  230820. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230821. for example having more than one juce plugin loaded into a host, then when a
  230822. method is called, the actual code that runs might actually be in a different module
  230823. than the one you expect... So any calls to library functions or statics that are
  230824. made inside obj-c methods will probably end up getting executed in a different DLL's
  230825. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230826. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230827. virtual methods of an object that's known to live inside the right module's space.
  230828. */
  230829. virtual void redirectMouseDown (NSEvent* ev);
  230830. virtual void redirectMouseUp (NSEvent* ev);
  230831. virtual void redirectMouseDrag (NSEvent* ev);
  230832. virtual void redirectMouseMove (NSEvent* ev);
  230833. virtual void redirectMouseEnter (NSEvent* ev);
  230834. virtual void redirectMouseExit (NSEvent* ev);
  230835. virtual void redirectMouseWheel (NSEvent* ev);
  230836. void sendMouseEvent (NSEvent* ev);
  230837. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230838. virtual bool redirectKeyDown (NSEvent* ev);
  230839. virtual bool redirectKeyUp (NSEvent* ev);
  230840. virtual void redirectModKeyChange (NSEvent* ev);
  230841. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230842. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230843. #endif
  230844. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230845. virtual bool isOpaque();
  230846. virtual void drawRect (NSRect r);
  230847. virtual bool canBecomeKeyWindow();
  230848. virtual bool windowShouldClose();
  230849. virtual void redirectMovedOrResized();
  230850. virtual void viewMovedToWindow();
  230851. virtual NSRect constrainRect (NSRect r);
  230852. static void showArrowCursorIfNeeded();
  230853. static void updateModifiers (NSEvent* e);
  230854. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230855. static int getKeyCodeFromEvent (NSEvent* ev)
  230856. {
  230857. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230858. int keyCode = unmodified[0];
  230859. if (keyCode == 0x19) // (backwards-tab)
  230860. keyCode = '\t';
  230861. else if (keyCode == 0x03) // (enter)
  230862. keyCode = '\r';
  230863. else
  230864. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230865. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230866. {
  230867. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230868. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230869. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230870. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230871. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230872. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230873. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230874. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230875. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230876. if (keyCode == numPadConversions [i])
  230877. keyCode = numPadConversions [i + 1];
  230878. }
  230879. return keyCode;
  230880. }
  230881. static int64 getMouseTime (NSEvent* e)
  230882. {
  230883. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230884. + (int64) ([e timestamp] * 1000.0);
  230885. }
  230886. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230887. {
  230888. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230889. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230890. }
  230891. static int getModifierForButtonNumber (const NSInteger num)
  230892. {
  230893. return num == 0 ? ModifierKeys::leftButtonModifier
  230894. : (num == 1 ? ModifierKeys::rightButtonModifier
  230895. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230896. }
  230897. virtual void viewFocusGain();
  230898. virtual void viewFocusLoss();
  230899. bool isFocused() const;
  230900. void grabFocus();
  230901. void textInputRequired (const Point<int>& position);
  230902. void repaint (const Rectangle<int>& area);
  230903. void performAnyPendingRepaintsNow();
  230904. NSWindow* window;
  230905. JuceNSView* view;
  230906. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230907. static ModifierKeys currentModifiers;
  230908. static ComponentPeer* currentlyFocusedPeer;
  230909. static Array<int> keysCurrentlyDown;
  230910. private:
  230911. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230912. };
  230913. END_JUCE_NAMESPACE
  230914. @implementation JuceNSView
  230915. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230916. withFrame: (NSRect) frame
  230917. {
  230918. [super initWithFrame: frame];
  230919. owner = owner_;
  230920. stringBeingComposed = 0;
  230921. textWasInserted = false;
  230922. notificationCenter = [NSNotificationCenter defaultCenter];
  230923. [notificationCenter addObserver: self
  230924. selector: @selector (frameChanged:)
  230925. name: NSViewFrameDidChangeNotification
  230926. object: self];
  230927. if (! owner_->isSharedWindow)
  230928. {
  230929. [notificationCenter addObserver: self
  230930. selector: @selector (frameChanged:)
  230931. name: NSWindowDidMoveNotification
  230932. object: owner_->window];
  230933. }
  230934. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230935. return self;
  230936. }
  230937. - (void) dealloc
  230938. {
  230939. [notificationCenter removeObserver: self];
  230940. delete stringBeingComposed;
  230941. [super dealloc];
  230942. }
  230943. - (void) drawRect: (NSRect) r
  230944. {
  230945. if (owner != 0)
  230946. owner->drawRect (r);
  230947. }
  230948. - (BOOL) isOpaque
  230949. {
  230950. return owner == 0 || owner->isOpaque();
  230951. }
  230952. - (void) mouseDown: (NSEvent*) ev
  230953. {
  230954. if (JUCEApplication::isStandaloneApp())
  230955. [self asyncMouseDown: ev];
  230956. else
  230957. // In some host situations, the host will stop modal loops from working
  230958. // correctly if they're called from a mouse event, so we'll trigger
  230959. // the event asynchronously..
  230960. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230961. withObject: ev
  230962. waitUntilDone: NO];
  230963. }
  230964. - (void) asyncMouseDown: (NSEvent*) ev
  230965. {
  230966. if (owner != 0)
  230967. owner->redirectMouseDown (ev);
  230968. }
  230969. - (void) mouseUp: (NSEvent*) ev
  230970. {
  230971. if (! JUCEApplication::isStandaloneApp())
  230972. [self asyncMouseUp: ev];
  230973. else
  230974. // In some host situations, the host will stop modal loops from working
  230975. // correctly if they're called from a mouse event, so we'll trigger
  230976. // the event asynchronously..
  230977. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230978. withObject: ev
  230979. waitUntilDone: NO];
  230980. }
  230981. - (void) asyncMouseUp: (NSEvent*) ev
  230982. {
  230983. if (owner != 0)
  230984. owner->redirectMouseUp (ev);
  230985. }
  230986. - (void) mouseDragged: (NSEvent*) ev
  230987. {
  230988. if (owner != 0)
  230989. owner->redirectMouseDrag (ev);
  230990. }
  230991. - (void) mouseMoved: (NSEvent*) ev
  230992. {
  230993. if (owner != 0)
  230994. owner->redirectMouseMove (ev);
  230995. }
  230996. - (void) mouseEntered: (NSEvent*) ev
  230997. {
  230998. if (owner != 0)
  230999. owner->redirectMouseEnter (ev);
  231000. }
  231001. - (void) mouseExited: (NSEvent*) ev
  231002. {
  231003. if (owner != 0)
  231004. owner->redirectMouseExit (ev);
  231005. }
  231006. - (void) rightMouseDown: (NSEvent*) ev
  231007. {
  231008. [self mouseDown: ev];
  231009. }
  231010. - (void) rightMouseDragged: (NSEvent*) ev
  231011. {
  231012. [self mouseDragged: ev];
  231013. }
  231014. - (void) rightMouseUp: (NSEvent*) ev
  231015. {
  231016. [self mouseUp: ev];
  231017. }
  231018. - (void) otherMouseDown: (NSEvent*) ev
  231019. {
  231020. [self mouseDown: ev];
  231021. }
  231022. - (void) otherMouseDragged: (NSEvent*) ev
  231023. {
  231024. [self mouseDragged: ev];
  231025. }
  231026. - (void) otherMouseUp: (NSEvent*) ev
  231027. {
  231028. [self mouseUp: ev];
  231029. }
  231030. - (void) scrollWheel: (NSEvent*) ev
  231031. {
  231032. if (owner != 0)
  231033. owner->redirectMouseWheel (ev);
  231034. }
  231035. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231036. {
  231037. (void) ev;
  231038. return YES;
  231039. }
  231040. - (void) frameChanged: (NSNotification*) n
  231041. {
  231042. (void) n;
  231043. if (owner != 0)
  231044. owner->redirectMovedOrResized();
  231045. }
  231046. - (void) viewDidMoveToWindow
  231047. {
  231048. if (owner != 0)
  231049. owner->viewMovedToWindow();
  231050. }
  231051. - (void) asyncRepaint: (id) rect
  231052. {
  231053. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231054. [self setNeedsDisplayInRect: *r];
  231055. }
  231056. - (void) keyDown: (NSEvent*) ev
  231057. {
  231058. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231059. textWasInserted = false;
  231060. if (target != 0)
  231061. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231062. else
  231063. deleteAndZero (stringBeingComposed);
  231064. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231065. [super keyDown: ev];
  231066. }
  231067. - (void) keyUp: (NSEvent*) ev
  231068. {
  231069. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231070. [super keyUp: ev];
  231071. }
  231072. - (void) insertText: (id) aString
  231073. {
  231074. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231075. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231076. if ([newText length] > 0)
  231077. {
  231078. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231079. if (target != 0)
  231080. {
  231081. target->insertTextAtCaret (nsStringToJuce (newText));
  231082. textWasInserted = true;
  231083. }
  231084. }
  231085. deleteAndZero (stringBeingComposed);
  231086. }
  231087. - (void) doCommandBySelector: (SEL) aSelector
  231088. {
  231089. (void) aSelector;
  231090. }
  231091. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231092. {
  231093. (void) selectionRange;
  231094. if (stringBeingComposed == 0)
  231095. stringBeingComposed = new String();
  231096. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231097. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231098. if (target != 0)
  231099. {
  231100. const Range<int> currentHighlight (target->getHighlightedRegion());
  231101. target->insertTextAtCaret (*stringBeingComposed);
  231102. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231103. textWasInserted = true;
  231104. }
  231105. }
  231106. - (void) unmarkText
  231107. {
  231108. if (stringBeingComposed != 0)
  231109. {
  231110. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231111. if (target != 0)
  231112. {
  231113. target->insertTextAtCaret (*stringBeingComposed);
  231114. textWasInserted = true;
  231115. }
  231116. }
  231117. deleteAndZero (stringBeingComposed);
  231118. }
  231119. - (BOOL) hasMarkedText
  231120. {
  231121. return stringBeingComposed != 0;
  231122. }
  231123. - (long) conversationIdentifier
  231124. {
  231125. return (long) (pointer_sized_int) self;
  231126. }
  231127. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231128. {
  231129. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231130. if (target != 0)
  231131. {
  231132. const Range<int> r ((int) theRange.location,
  231133. (int) (theRange.location + theRange.length));
  231134. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231135. }
  231136. return nil;
  231137. }
  231138. - (NSRange) markedRange
  231139. {
  231140. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231141. : NSMakeRange (NSNotFound, 0);
  231142. }
  231143. - (NSRange) selectedRange
  231144. {
  231145. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231146. if (target != 0)
  231147. {
  231148. const Range<int> highlight (target->getHighlightedRegion());
  231149. if (! highlight.isEmpty())
  231150. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231151. }
  231152. return NSMakeRange (NSNotFound, 0);
  231153. }
  231154. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231155. {
  231156. (void) theRange;
  231157. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231158. if (comp == 0)
  231159. return NSMakeRect (0, 0, 0, 0);
  231160. const Rectangle<int> bounds (comp->getScreenBounds());
  231161. return NSMakeRect (bounds.getX(),
  231162. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231163. bounds.getWidth(),
  231164. bounds.getHeight());
  231165. }
  231166. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231167. {
  231168. (void) thePoint;
  231169. return NSNotFound;
  231170. }
  231171. - (NSArray*) validAttributesForMarkedText
  231172. {
  231173. return [NSArray array];
  231174. }
  231175. - (void) flagsChanged: (NSEvent*) ev
  231176. {
  231177. if (owner != 0)
  231178. owner->redirectModKeyChange (ev);
  231179. }
  231180. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231181. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231182. {
  231183. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231184. return true;
  231185. return [super performKeyEquivalent: ev];
  231186. }
  231187. #endif
  231188. - (BOOL) becomeFirstResponder
  231189. {
  231190. if (owner != 0)
  231191. owner->viewFocusGain();
  231192. return true;
  231193. }
  231194. - (BOOL) resignFirstResponder
  231195. {
  231196. if (owner != 0)
  231197. owner->viewFocusLoss();
  231198. return true;
  231199. }
  231200. - (BOOL) acceptsFirstResponder
  231201. {
  231202. return owner != 0 && owner->canBecomeKeyWindow();
  231203. }
  231204. - (NSArray*) getSupportedDragTypes
  231205. {
  231206. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231207. }
  231208. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231209. {
  231210. return owner != 0 && owner->sendDragCallback (type, sender);
  231211. }
  231212. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231213. {
  231214. if ([self sendDragCallback: 0 sender: sender])
  231215. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231216. else
  231217. return NSDragOperationNone;
  231218. }
  231219. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231220. {
  231221. if ([self sendDragCallback: 0 sender: sender])
  231222. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231223. else
  231224. return NSDragOperationNone;
  231225. }
  231226. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231227. {
  231228. [self sendDragCallback: 1 sender: sender];
  231229. }
  231230. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231231. {
  231232. [self sendDragCallback: 1 sender: sender];
  231233. }
  231234. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231235. {
  231236. (void) sender;
  231237. return YES;
  231238. }
  231239. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231240. {
  231241. return [self sendDragCallback: 2 sender: sender];
  231242. }
  231243. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231244. {
  231245. (void) sender;
  231246. }
  231247. @end
  231248. @implementation JuceNSWindow
  231249. - (void) setOwner: (NSViewComponentPeer*) owner_
  231250. {
  231251. owner = owner_;
  231252. isZooming = false;
  231253. }
  231254. - (BOOL) canBecomeKeyWindow
  231255. {
  231256. return owner != 0 && owner->canBecomeKeyWindow();
  231257. }
  231258. - (void) becomeKeyWindow
  231259. {
  231260. [super becomeKeyWindow];
  231261. if (owner != 0)
  231262. owner->grabFocus();
  231263. }
  231264. - (BOOL) windowShouldClose: (id) window
  231265. {
  231266. (void) window;
  231267. return owner == 0 || owner->windowShouldClose();
  231268. }
  231269. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231270. {
  231271. (void) screen;
  231272. if (owner != 0)
  231273. frameRect = owner->constrainRect (frameRect);
  231274. return frameRect;
  231275. }
  231276. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231277. {
  231278. (void) window;
  231279. if (isZooming)
  231280. return proposedFrameSize;
  231281. NSRect frameRect = [self frame];
  231282. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231283. frameRect.size = proposedFrameSize;
  231284. if (owner != 0)
  231285. frameRect = owner->constrainRect (frameRect);
  231286. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231287. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231288. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231289. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231290. return frameRect.size;
  231291. }
  231292. - (void) zoom: (id) sender
  231293. {
  231294. isZooming = true;
  231295. [super zoom: sender];
  231296. isZooming = false;
  231297. }
  231298. - (void) windowWillMove: (NSNotification*) notification
  231299. {
  231300. (void) notification;
  231301. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231302. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231303. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231304. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231305. }
  231306. @end
  231307. BEGIN_JUCE_NAMESPACE
  231308. ModifierKeys NSViewComponentPeer::currentModifiers;
  231309. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231310. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231311. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231312. {
  231313. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231314. return true;
  231315. if (keyCode >= 'A' && keyCode <= 'Z'
  231316. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231317. return true;
  231318. if (keyCode >= 'a' && keyCode <= 'z'
  231319. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231320. return true;
  231321. return false;
  231322. }
  231323. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231324. {
  231325. int m = 0;
  231326. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231327. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231328. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231329. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231330. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231331. }
  231332. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231333. {
  231334. updateModifiers (ev);
  231335. int keyCode = getKeyCodeFromEvent (ev);
  231336. if (keyCode != 0)
  231337. {
  231338. if (isKeyDown)
  231339. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231340. else
  231341. keysCurrentlyDown.removeValue (keyCode);
  231342. }
  231343. }
  231344. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231345. {
  231346. return NSViewComponentPeer::currentModifiers;
  231347. }
  231348. void ModifierKeys::updateCurrentModifiers() throw()
  231349. {
  231350. currentModifiers = NSViewComponentPeer::currentModifiers;
  231351. }
  231352. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231353. const int windowStyleFlags,
  231354. NSView* viewToAttachTo)
  231355. : ComponentPeer (component_, windowStyleFlags),
  231356. window (0),
  231357. view (0),
  231358. isSharedWindow (viewToAttachTo != 0),
  231359. fullScreen (false),
  231360. insideDrawRect (false),
  231361. #if USE_COREGRAPHICS_RENDERING
  231362. usingCoreGraphics (true),
  231363. #else
  231364. usingCoreGraphics (false),
  231365. #endif
  231366. recursiveToFrontCall (false)
  231367. {
  231368. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231369. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231370. [view setPostsFrameChangedNotifications: YES];
  231371. if (isSharedWindow)
  231372. {
  231373. window = [viewToAttachTo window];
  231374. [viewToAttachTo addSubview: view];
  231375. }
  231376. else
  231377. {
  231378. r.origin.x = (float) component->getX();
  231379. r.origin.y = (float) component->getY();
  231380. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231381. unsigned int style = 0;
  231382. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231383. style = NSBorderlessWindowMask;
  231384. else
  231385. style = NSTitledWindowMask;
  231386. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231387. style |= NSMiniaturizableWindowMask;
  231388. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231389. style |= NSClosableWindowMask;
  231390. if ((windowStyleFlags & windowIsResizable) != 0)
  231391. style |= NSResizableWindowMask;
  231392. window = [[JuceNSWindow alloc] initWithContentRect: r
  231393. styleMask: style
  231394. backing: NSBackingStoreBuffered
  231395. defer: YES];
  231396. [((JuceNSWindow*) window) setOwner: this];
  231397. [window orderOut: nil];
  231398. [window setDelegate: (JuceNSWindow*) window];
  231399. [window setOpaque: component->isOpaque()];
  231400. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231401. if (component->isAlwaysOnTop())
  231402. [window setLevel: NSFloatingWindowLevel];
  231403. [window setContentView: view];
  231404. [window setAutodisplay: YES];
  231405. [window setAcceptsMouseMovedEvents: YES];
  231406. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231407. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231408. [window setReleasedWhenClosed: YES];
  231409. [window retain];
  231410. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231411. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231412. }
  231413. const float alpha = component->getAlpha();
  231414. if (alpha < 1.0f)
  231415. setAlpha (alpha);
  231416. setTitle (component->getName());
  231417. }
  231418. NSViewComponentPeer::~NSViewComponentPeer()
  231419. {
  231420. view->owner = 0;
  231421. [view removeFromSuperview];
  231422. [view release];
  231423. if (! isSharedWindow)
  231424. {
  231425. [((JuceNSWindow*) window) setOwner: 0];
  231426. [window close];
  231427. [window release];
  231428. }
  231429. }
  231430. void* NSViewComponentPeer::getNativeHandle() const
  231431. {
  231432. return view;
  231433. }
  231434. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231435. {
  231436. if (isSharedWindow)
  231437. {
  231438. [view setHidden: ! shouldBeVisible];
  231439. }
  231440. else
  231441. {
  231442. if (shouldBeVisible)
  231443. {
  231444. [window orderFront: nil];
  231445. handleBroughtToFront();
  231446. }
  231447. else
  231448. {
  231449. [window orderOut: nil];
  231450. }
  231451. }
  231452. }
  231453. void NSViewComponentPeer::setTitle (const String& title)
  231454. {
  231455. const ScopedAutoReleasePool pool;
  231456. if (! isSharedWindow)
  231457. [window setTitle: juceStringToNS (title)];
  231458. }
  231459. void NSViewComponentPeer::setPosition (int x, int y)
  231460. {
  231461. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231462. }
  231463. void NSViewComponentPeer::setSize (int w, int h)
  231464. {
  231465. setBounds (component->getX(), component->getY(), w, h, false);
  231466. }
  231467. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231468. {
  231469. fullScreen = isNowFullScreen;
  231470. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231471. if (isSharedWindow)
  231472. {
  231473. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231474. if ([view frame].size.width != r.size.width
  231475. || [view frame].size.height != r.size.height)
  231476. [view setNeedsDisplay: true];
  231477. [view setFrame: r];
  231478. }
  231479. else
  231480. {
  231481. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231482. [window setFrame: [window frameRectForContentRect: r]
  231483. display: true];
  231484. }
  231485. }
  231486. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231487. {
  231488. NSRect r = [view frame];
  231489. if (global && [view window] != 0)
  231490. {
  231491. r = [view convertRect: r toView: nil];
  231492. NSRect wr = [[view window] frame];
  231493. r.origin.x += wr.origin.x;
  231494. r.origin.y += wr.origin.y;
  231495. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231496. }
  231497. else
  231498. {
  231499. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231500. }
  231501. return Rectangle<int> (convertToRectInt (r));
  231502. }
  231503. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231504. {
  231505. return getBounds (! isSharedWindow);
  231506. }
  231507. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231508. {
  231509. return getBounds (true).getPosition();
  231510. }
  231511. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231512. {
  231513. return relativePosition + getScreenPosition();
  231514. }
  231515. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231516. {
  231517. return screenPosition - getScreenPosition();
  231518. }
  231519. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231520. {
  231521. if (constrainer != 0)
  231522. {
  231523. NSRect current = [window frame];
  231524. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231525. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231526. Rectangle<int> pos (convertToRectInt (r));
  231527. Rectangle<int> original (convertToRectInt (current));
  231528. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231529. if ([window inLiveResize])
  231530. #else
  231531. if ([window respondsToSelector: @selector (inLiveResize)]
  231532. && [window performSelector: @selector (inLiveResize)])
  231533. #endif
  231534. {
  231535. constrainer->checkBounds (pos, original,
  231536. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231537. false, false, true, true);
  231538. }
  231539. else
  231540. {
  231541. constrainer->checkBounds (pos, original,
  231542. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231543. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231544. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231545. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231546. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231547. }
  231548. r.origin.x = pos.getX();
  231549. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231550. r.size.width = pos.getWidth();
  231551. r.size.height = pos.getHeight();
  231552. }
  231553. return r;
  231554. }
  231555. void NSViewComponentPeer::setAlpha (float newAlpha)
  231556. {
  231557. if (! isSharedWindow)
  231558. [window setAlphaValue: (CGFloat) newAlpha];
  231559. else
  231560. [view setAlphaValue: (CGFloat) newAlpha];
  231561. }
  231562. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231563. {
  231564. if (! isSharedWindow)
  231565. {
  231566. if (shouldBeMinimised)
  231567. [window miniaturize: nil];
  231568. else
  231569. [window deminiaturize: nil];
  231570. }
  231571. }
  231572. bool NSViewComponentPeer::isMinimised() const
  231573. {
  231574. return window != 0 && [window isMiniaturized];
  231575. }
  231576. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231577. {
  231578. if (! isSharedWindow)
  231579. {
  231580. Rectangle<int> r (lastNonFullscreenBounds);
  231581. setMinimised (false);
  231582. if (fullScreen != shouldBeFullScreen)
  231583. {
  231584. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231585. {
  231586. fullScreen = true;
  231587. [window performZoom: nil];
  231588. }
  231589. else
  231590. {
  231591. if (shouldBeFullScreen)
  231592. r = Desktop::getInstance().getMainMonitorArea();
  231593. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231594. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231595. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231596. }
  231597. }
  231598. }
  231599. }
  231600. bool NSViewComponentPeer::isFullScreen() const
  231601. {
  231602. return fullScreen;
  231603. }
  231604. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231605. {
  231606. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231607. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231608. return false;
  231609. NSPoint p;
  231610. p.x = (float) position.getX();
  231611. p.y = (float) position.getY();
  231612. NSView* v = [view hitTest: p];
  231613. if (trueIfInAChildWindow)
  231614. return v != nil;
  231615. return v == view;
  231616. }
  231617. const BorderSize NSViewComponentPeer::getFrameSize() const
  231618. {
  231619. BorderSize b;
  231620. if (! isSharedWindow)
  231621. {
  231622. NSRect v = [view convertRect: [view frame] toView: nil];
  231623. NSRect w = [window frame];
  231624. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231625. b.setBottom ((int) v.origin.y);
  231626. b.setLeft ((int) v.origin.x);
  231627. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231628. }
  231629. return b;
  231630. }
  231631. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231632. {
  231633. if (! isSharedWindow)
  231634. {
  231635. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231636. : NSNormalWindowLevel];
  231637. }
  231638. return true;
  231639. }
  231640. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231641. {
  231642. if (isSharedWindow)
  231643. {
  231644. [[view superview] addSubview: view
  231645. positioned: NSWindowAbove
  231646. relativeTo: nil];
  231647. }
  231648. if (window != 0 && component->isVisible())
  231649. {
  231650. if (makeActiveWindow)
  231651. [window makeKeyAndOrderFront: nil];
  231652. else
  231653. [window orderFront: nil];
  231654. if (! recursiveToFrontCall)
  231655. {
  231656. recursiveToFrontCall = true;
  231657. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231658. handleBroughtToFront();
  231659. recursiveToFrontCall = false;
  231660. }
  231661. }
  231662. }
  231663. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231664. {
  231665. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231666. jassert (otherPeer != 0); // wrong type of window?
  231667. if (otherPeer != 0)
  231668. {
  231669. if (isSharedWindow)
  231670. {
  231671. [[view superview] addSubview: view
  231672. positioned: NSWindowBelow
  231673. relativeTo: otherPeer->view];
  231674. }
  231675. else
  231676. {
  231677. [window orderWindow: NSWindowBelow
  231678. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231679. : nil ];
  231680. }
  231681. }
  231682. }
  231683. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231684. {
  231685. // to do..
  231686. }
  231687. void NSViewComponentPeer::viewFocusGain()
  231688. {
  231689. if (currentlyFocusedPeer != this)
  231690. {
  231691. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231692. currentlyFocusedPeer->handleFocusLoss();
  231693. currentlyFocusedPeer = this;
  231694. handleFocusGain();
  231695. }
  231696. }
  231697. void NSViewComponentPeer::viewFocusLoss()
  231698. {
  231699. if (currentlyFocusedPeer == this)
  231700. {
  231701. currentlyFocusedPeer = 0;
  231702. handleFocusLoss();
  231703. }
  231704. }
  231705. void juce_HandleProcessFocusChange()
  231706. {
  231707. NSViewComponentPeer::keysCurrentlyDown.clear();
  231708. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231709. {
  231710. if (Process::isForegroundProcess())
  231711. {
  231712. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231713. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231714. }
  231715. else
  231716. {
  231717. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231718. // turn kiosk mode off if we lose focus..
  231719. Desktop::getInstance().setKioskModeComponent (0);
  231720. }
  231721. }
  231722. }
  231723. bool NSViewComponentPeer::isFocused() const
  231724. {
  231725. return isSharedWindow ? this == currentlyFocusedPeer
  231726. : (window != 0 && [window isKeyWindow]);
  231727. }
  231728. void NSViewComponentPeer::grabFocus()
  231729. {
  231730. if (window != 0)
  231731. {
  231732. [window makeKeyWindow];
  231733. [window makeFirstResponder: view];
  231734. viewFocusGain();
  231735. }
  231736. }
  231737. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231738. {
  231739. }
  231740. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231741. {
  231742. String unicode (nsStringToJuce ([ev characters]));
  231743. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231744. int keyCode = getKeyCodeFromEvent (ev);
  231745. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231746. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231747. if (unicode.isNotEmpty() || keyCode != 0)
  231748. {
  231749. if (isKeyDown)
  231750. {
  231751. bool used = false;
  231752. while (unicode.length() > 0)
  231753. {
  231754. juce_wchar textCharacter = unicode[0];
  231755. unicode = unicode.substring (1);
  231756. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231757. textCharacter = 0;
  231758. used = handleKeyUpOrDown (true) || used;
  231759. used = handleKeyPress (keyCode, textCharacter) || used;
  231760. }
  231761. return used;
  231762. }
  231763. else
  231764. {
  231765. if (handleKeyUpOrDown (false))
  231766. return true;
  231767. }
  231768. }
  231769. return false;
  231770. }
  231771. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231772. {
  231773. updateKeysDown (ev, true);
  231774. bool used = handleKeyEvent (ev, true);
  231775. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231776. {
  231777. // for command keys, the key-up event is thrown away, so simulate one..
  231778. updateKeysDown (ev, false);
  231779. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231780. }
  231781. // (If we're running modally, don't allow unused keystrokes to be passed
  231782. // along to other blocked views..)
  231783. if (Component::getCurrentlyModalComponent() != 0)
  231784. used = true;
  231785. return used;
  231786. }
  231787. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231788. {
  231789. updateKeysDown (ev, false);
  231790. return handleKeyEvent (ev, false)
  231791. || Component::getCurrentlyModalComponent() != 0;
  231792. }
  231793. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231794. {
  231795. keysCurrentlyDown.clear();
  231796. handleKeyUpOrDown (true);
  231797. updateModifiers (ev);
  231798. handleModifierKeysChange();
  231799. }
  231800. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231801. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231802. {
  231803. if ([ev type] == NSKeyDown)
  231804. return redirectKeyDown (ev);
  231805. else if ([ev type] == NSKeyUp)
  231806. return redirectKeyUp (ev);
  231807. return false;
  231808. }
  231809. #endif
  231810. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231811. {
  231812. updateModifiers (ev);
  231813. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231814. }
  231815. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231816. {
  231817. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231818. sendMouseEvent (ev);
  231819. }
  231820. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231821. {
  231822. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231823. sendMouseEvent (ev);
  231824. showArrowCursorIfNeeded();
  231825. }
  231826. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231827. {
  231828. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231829. sendMouseEvent (ev);
  231830. }
  231831. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231832. {
  231833. currentModifiers = currentModifiers.withoutMouseButtons();
  231834. sendMouseEvent (ev);
  231835. showArrowCursorIfNeeded();
  231836. }
  231837. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231838. {
  231839. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231840. currentModifiers = currentModifiers.withoutMouseButtons();
  231841. sendMouseEvent (ev);
  231842. }
  231843. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231844. {
  231845. currentModifiers = currentModifiers.withoutMouseButtons();
  231846. sendMouseEvent (ev);
  231847. }
  231848. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231849. {
  231850. updateModifiers (ev);
  231851. float x = 0, y = 0;
  231852. @try
  231853. {
  231854. x = [ev deviceDeltaX] * 0.5f;
  231855. y = [ev deviceDeltaY] * 0.5f;
  231856. }
  231857. @catch (...)
  231858. {}
  231859. if (x == 0 && y == 0)
  231860. {
  231861. x = [ev deltaX] * 10.0f;
  231862. y = [ev deltaY] * 10.0f;
  231863. }
  231864. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231865. }
  231866. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231867. {
  231868. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231869. if (mouse.getComponentUnderMouse() == 0
  231870. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231871. {
  231872. [[NSCursor arrowCursor] set];
  231873. }
  231874. }
  231875. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231876. {
  231877. NSString* bestType
  231878. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231879. if (bestType == nil)
  231880. return false;
  231881. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231882. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231883. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231884. if (list == nil)
  231885. return false;
  231886. StringArray files;
  231887. if ([list isKindOfClass: [NSArray class]])
  231888. {
  231889. NSArray* items = (NSArray*) list;
  231890. for (unsigned int i = 0; i < [items count]; ++i)
  231891. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231892. }
  231893. if (files.size() == 0)
  231894. return false;
  231895. if (type == 0)
  231896. handleFileDragMove (files, pos);
  231897. else if (type == 1)
  231898. handleFileDragExit (files);
  231899. else if (type == 2)
  231900. handleFileDragDrop (files, pos);
  231901. return true;
  231902. }
  231903. bool NSViewComponentPeer::isOpaque()
  231904. {
  231905. return component == 0 || component->isOpaque();
  231906. }
  231907. void NSViewComponentPeer::drawRect (NSRect r)
  231908. {
  231909. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231910. return;
  231911. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231912. if (! component->isOpaque())
  231913. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231914. #if USE_COREGRAPHICS_RENDERING
  231915. if (usingCoreGraphics)
  231916. {
  231917. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231918. insideDrawRect = true;
  231919. handlePaint (context);
  231920. insideDrawRect = false;
  231921. }
  231922. else
  231923. #endif
  231924. {
  231925. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231926. (int) (r.size.width + 0.5f),
  231927. (int) (r.size.height + 0.5f),
  231928. ! getComponent()->isOpaque());
  231929. const int xOffset = -roundToInt (r.origin.x);
  231930. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231931. const NSRect* rects = 0;
  231932. NSInteger numRects = 0;
  231933. [view getRectsBeingDrawn: &rects count: &numRects];
  231934. const Rectangle<int> clipBounds (temp.getBounds());
  231935. RectangleList clip;
  231936. for (int i = 0; i < numRects; ++i)
  231937. {
  231938. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231939. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231940. roundToInt (rects[i].size.width),
  231941. roundToInt (rects[i].size.height))));
  231942. }
  231943. if (! clip.isEmpty())
  231944. {
  231945. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231946. insideDrawRect = true;
  231947. handlePaint (context);
  231948. insideDrawRect = false;
  231949. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231950. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  231951. CGColorSpaceRelease (colourSpace);
  231952. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231953. CGImageRelease (image);
  231954. }
  231955. }
  231956. }
  231957. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231958. {
  231959. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231960. #if USE_COREGRAPHICS_RENDERING
  231961. s.add ("CoreGraphics Renderer");
  231962. #endif
  231963. return s;
  231964. }
  231965. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231966. {
  231967. return usingCoreGraphics ? 1 : 0;
  231968. }
  231969. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231970. {
  231971. #if USE_COREGRAPHICS_RENDERING
  231972. if (usingCoreGraphics != (index > 0))
  231973. {
  231974. usingCoreGraphics = index > 0;
  231975. [view setNeedsDisplay: true];
  231976. }
  231977. #endif
  231978. }
  231979. bool NSViewComponentPeer::canBecomeKeyWindow()
  231980. {
  231981. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231982. }
  231983. bool NSViewComponentPeer::windowShouldClose()
  231984. {
  231985. if (! isValidPeer (this))
  231986. return YES;
  231987. handleUserClosingWindow();
  231988. return NO;
  231989. }
  231990. void NSViewComponentPeer::redirectMovedOrResized()
  231991. {
  231992. handleMovedOrResized();
  231993. }
  231994. void NSViewComponentPeer::viewMovedToWindow()
  231995. {
  231996. if (isSharedWindow)
  231997. window = [view window];
  231998. }
  231999. void Desktop::createMouseInputSources()
  232000. {
  232001. mouseSources.add (new MouseInputSource (0, true));
  232002. }
  232003. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232004. {
  232005. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  232006. if (enableOrDisable)
  232007. {
  232008. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  232009. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  232010. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232011. }
  232012. else
  232013. {
  232014. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  232015. }
  232016. #else
  232017. if (enableOrDisable)
  232018. {
  232019. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232020. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232021. }
  232022. else
  232023. {
  232024. SetSystemUIMode (kUIModeNormal, 0);
  232025. }
  232026. #endif
  232027. }
  232028. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232029. {
  232030. if (insideDrawRect)
  232031. {
  232032. class AsyncRepaintMessage : public CallbackMessage
  232033. {
  232034. public:
  232035. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232036. : peer (peer_), rect (rect_)
  232037. {
  232038. }
  232039. void messageCallback()
  232040. {
  232041. if (ComponentPeer::isValidPeer (peer))
  232042. peer->repaint (rect);
  232043. }
  232044. private:
  232045. NSViewComponentPeer* const peer;
  232046. const Rectangle<int> rect;
  232047. };
  232048. (new AsyncRepaintMessage (this, area))->post();
  232049. }
  232050. else
  232051. {
  232052. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232053. (float) area.getWidth(), (float) area.getHeight())];
  232054. }
  232055. }
  232056. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232057. {
  232058. [view displayIfNeeded];
  232059. }
  232060. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232061. {
  232062. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232063. }
  232064. const Image juce_createIconForFile (const File& file)
  232065. {
  232066. const ScopedAutoReleasePool pool;
  232067. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232068. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232069. [NSGraphicsContext saveGraphicsState];
  232070. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232071. [image drawAtPoint: NSMakePoint (0, 0)
  232072. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232073. operation: NSCompositeSourceOver fraction: 1.0f];
  232074. [[NSGraphicsContext currentContext] flushGraphics];
  232075. [NSGraphicsContext restoreGraphicsState];
  232076. return Image (result);
  232077. }
  232078. const int KeyPress::spaceKey = ' ';
  232079. const int KeyPress::returnKey = 0x0d;
  232080. const int KeyPress::escapeKey = 0x1b;
  232081. const int KeyPress::backspaceKey = 0x7f;
  232082. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232083. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232084. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232085. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232086. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232087. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232088. const int KeyPress::endKey = NSEndFunctionKey;
  232089. const int KeyPress::homeKey = NSHomeFunctionKey;
  232090. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232091. const int KeyPress::insertKey = -1;
  232092. const int KeyPress::tabKey = 9;
  232093. const int KeyPress::F1Key = NSF1FunctionKey;
  232094. const int KeyPress::F2Key = NSF2FunctionKey;
  232095. const int KeyPress::F3Key = NSF3FunctionKey;
  232096. const int KeyPress::F4Key = NSF4FunctionKey;
  232097. const int KeyPress::F5Key = NSF5FunctionKey;
  232098. const int KeyPress::F6Key = NSF6FunctionKey;
  232099. const int KeyPress::F7Key = NSF7FunctionKey;
  232100. const int KeyPress::F8Key = NSF8FunctionKey;
  232101. const int KeyPress::F9Key = NSF9FunctionKey;
  232102. const int KeyPress::F10Key = NSF10FunctionKey;
  232103. const int KeyPress::F11Key = NSF1FunctionKey;
  232104. const int KeyPress::F12Key = NSF12FunctionKey;
  232105. const int KeyPress::F13Key = NSF13FunctionKey;
  232106. const int KeyPress::F14Key = NSF14FunctionKey;
  232107. const int KeyPress::F15Key = NSF15FunctionKey;
  232108. const int KeyPress::F16Key = NSF16FunctionKey;
  232109. const int KeyPress::numberPad0 = 0x30020;
  232110. const int KeyPress::numberPad1 = 0x30021;
  232111. const int KeyPress::numberPad2 = 0x30022;
  232112. const int KeyPress::numberPad3 = 0x30023;
  232113. const int KeyPress::numberPad4 = 0x30024;
  232114. const int KeyPress::numberPad5 = 0x30025;
  232115. const int KeyPress::numberPad6 = 0x30026;
  232116. const int KeyPress::numberPad7 = 0x30027;
  232117. const int KeyPress::numberPad8 = 0x30028;
  232118. const int KeyPress::numberPad9 = 0x30029;
  232119. const int KeyPress::numberPadAdd = 0x3002a;
  232120. const int KeyPress::numberPadSubtract = 0x3002b;
  232121. const int KeyPress::numberPadMultiply = 0x3002c;
  232122. const int KeyPress::numberPadDivide = 0x3002d;
  232123. const int KeyPress::numberPadSeparator = 0x3002e;
  232124. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232125. const int KeyPress::numberPadEquals = 0x30030;
  232126. const int KeyPress::numberPadDelete = 0x30031;
  232127. const int KeyPress::playKey = 0x30000;
  232128. const int KeyPress::stopKey = 0x30001;
  232129. const int KeyPress::fastForwardKey = 0x30002;
  232130. const int KeyPress::rewindKey = 0x30003;
  232131. #endif
  232132. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232133. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232134. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232135. // compiled on its own).
  232136. #if JUCE_INCLUDED_FILE
  232137. #if JUCE_MAC
  232138. namespace MouseCursorHelpers
  232139. {
  232140. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232141. {
  232142. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232143. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232144. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232145. [im release];
  232146. return c;
  232147. }
  232148. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232149. {
  232150. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232151. BufferedInputStream buf (fileStream, 4096);
  232152. PNGImageFormat pngFormat;
  232153. Image im (pngFormat.decodeImage (buf));
  232154. if (im.isValid())
  232155. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232156. jassertfalse;
  232157. return 0;
  232158. }
  232159. }
  232160. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232161. {
  232162. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232163. }
  232164. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232165. {
  232166. const ScopedAutoReleasePool pool;
  232167. NSCursor* c = 0;
  232168. switch (type)
  232169. {
  232170. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232171. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232172. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232173. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232174. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232175. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232176. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232177. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232178. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232179. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232180. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232181. case UpDownResizeCursor:
  232182. case TopEdgeResizeCursor:
  232183. case BottomEdgeResizeCursor:
  232184. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232185. case TopLeftCornerResizeCursor:
  232186. case BottomRightCornerResizeCursor:
  232187. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232188. case TopRightCornerResizeCursor:
  232189. case BottomLeftCornerResizeCursor:
  232190. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232191. case UpDownLeftRightResizeCursor:
  232192. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232193. default:
  232194. jassertfalse;
  232195. break;
  232196. }
  232197. [c retain];
  232198. return c;
  232199. }
  232200. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232201. {
  232202. [((NSCursor*) cursorHandle) release];
  232203. }
  232204. void MouseCursor::showInAllWindows() const
  232205. {
  232206. showInWindow (0);
  232207. }
  232208. void MouseCursor::showInWindow (ComponentPeer*) const
  232209. {
  232210. NSCursor* c = (NSCursor*) getHandle();
  232211. if (c == 0)
  232212. c = [NSCursor arrowCursor];
  232213. [c set];
  232214. }
  232215. #else
  232216. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232217. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232218. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232219. void MouseCursor::showInAllWindows() const {}
  232220. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232221. #endif
  232222. #endif
  232223. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232224. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232225. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232226. // compiled on its own).
  232227. #if JUCE_INCLUDED_FILE
  232228. class NSViewComponentInternal : public ComponentMovementWatcher
  232229. {
  232230. Component* const owner;
  232231. NSViewComponentPeer* currentPeer;
  232232. bool wasShowing;
  232233. public:
  232234. NSView* const view;
  232235. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232236. : ComponentMovementWatcher (owner_),
  232237. owner (owner_),
  232238. currentPeer (0),
  232239. wasShowing (false),
  232240. view (view_)
  232241. {
  232242. [view_ retain];
  232243. if (owner_->isShowing())
  232244. componentPeerChanged();
  232245. }
  232246. ~NSViewComponentInternal()
  232247. {
  232248. [view removeFromSuperview];
  232249. [view release];
  232250. }
  232251. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232252. {
  232253. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232254. // The ComponentMovementWatcher version of this method avoids calling
  232255. // us when the top-level comp is resized, but for an NSView we need to know this
  232256. // because with inverted co-ords, we need to update the position even if the
  232257. // top-left pos hasn't changed
  232258. if (comp.isOnDesktop() && wasResized)
  232259. componentMovedOrResized (wasMoved, wasResized);
  232260. }
  232261. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232262. {
  232263. Component* const topComp = owner->getTopLevelComponent();
  232264. if (topComp->getPeer() != 0)
  232265. {
  232266. const Point<int> pos (topComp->getLocalPoint (owner, Point<int>()));
  232267. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232268. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232269. [view setFrame: r];
  232270. }
  232271. }
  232272. void componentPeerChanged()
  232273. {
  232274. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232275. if (currentPeer != peer)
  232276. {
  232277. if ([view superview] != nil)
  232278. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  232279. // override the call and use it as a sign that they're being deleted, which breaks everything..
  232280. currentPeer = peer;
  232281. if (peer != 0)
  232282. {
  232283. [peer->view addSubview: view];
  232284. componentMovedOrResized (false, false);
  232285. }
  232286. }
  232287. [view setHidden: ! owner->isShowing()];
  232288. }
  232289. void componentVisibilityChanged (Component&)
  232290. {
  232291. componentPeerChanged();
  232292. }
  232293. const Rectangle<int> getViewBounds() const
  232294. {
  232295. NSRect r = [view frame];
  232296. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  232297. }
  232298. private:
  232299. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  232300. };
  232301. NSViewComponent::NSViewComponent()
  232302. {
  232303. }
  232304. NSViewComponent::~NSViewComponent()
  232305. {
  232306. }
  232307. void NSViewComponent::setView (void* view)
  232308. {
  232309. if (view != getView())
  232310. {
  232311. if (view != 0)
  232312. info = new NSViewComponentInternal ((NSView*) view, this);
  232313. else
  232314. info = 0;
  232315. }
  232316. }
  232317. void* NSViewComponent::getView() const
  232318. {
  232319. return info == 0 ? 0 : info->view;
  232320. }
  232321. void NSViewComponent::resizeToFitView()
  232322. {
  232323. if (info != 0)
  232324. setBounds (info->getViewBounds());
  232325. }
  232326. void NSViewComponent::paint (Graphics&)
  232327. {
  232328. }
  232329. #endif
  232330. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232331. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232332. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232333. // compiled on its own).
  232334. #if JUCE_INCLUDED_FILE
  232335. AppleRemoteDevice::AppleRemoteDevice()
  232336. : device (0),
  232337. queue (0),
  232338. remoteId (0)
  232339. {
  232340. }
  232341. AppleRemoteDevice::~AppleRemoteDevice()
  232342. {
  232343. stop();
  232344. }
  232345. namespace
  232346. {
  232347. io_object_t getAppleRemoteDevice()
  232348. {
  232349. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232350. io_iterator_t iter = 0;
  232351. io_object_t iod = 0;
  232352. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232353. && iter != 0)
  232354. {
  232355. iod = IOIteratorNext (iter);
  232356. }
  232357. IOObjectRelease (iter);
  232358. return iod;
  232359. }
  232360. bool createAppleRemoteInterface (io_object_t iod, void** device)
  232361. {
  232362. jassert (*device == 0);
  232363. io_name_t classname;
  232364. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232365. {
  232366. IOCFPlugInInterface** cfPlugInInterface = 0;
  232367. SInt32 score = 0;
  232368. if (IOCreatePlugInInterfaceForService (iod,
  232369. kIOHIDDeviceUserClientTypeID,
  232370. kIOCFPlugInInterfaceID,
  232371. &cfPlugInInterface,
  232372. &score) == kIOReturnSuccess)
  232373. {
  232374. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232375. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232376. device);
  232377. (void) hr;
  232378. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232379. }
  232380. }
  232381. return *device != 0;
  232382. }
  232383. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232384. {
  232385. if (result == kIOReturnSuccess)
  232386. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232387. }
  232388. }
  232389. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232390. {
  232391. if (queue != 0)
  232392. return true;
  232393. stop();
  232394. bool result = false;
  232395. io_object_t iod = getAppleRemoteDevice();
  232396. if (iod != 0)
  232397. {
  232398. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232399. result = true;
  232400. else
  232401. stop();
  232402. IOObjectRelease (iod);
  232403. }
  232404. return result;
  232405. }
  232406. void AppleRemoteDevice::stop()
  232407. {
  232408. if (queue != 0)
  232409. {
  232410. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232411. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232412. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232413. queue = 0;
  232414. }
  232415. if (device != 0)
  232416. {
  232417. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232418. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232419. device = 0;
  232420. }
  232421. }
  232422. bool AppleRemoteDevice::isActive() const
  232423. {
  232424. return queue != 0;
  232425. }
  232426. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232427. {
  232428. Array <int> cookies;
  232429. CFArrayRef elements;
  232430. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232431. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232432. return false;
  232433. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232434. {
  232435. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232436. // get the cookie
  232437. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232438. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232439. continue;
  232440. long number;
  232441. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232442. continue;
  232443. cookies.add ((int) number);
  232444. }
  232445. CFRelease (elements);
  232446. if ((*(IOHIDDeviceInterface**) device)
  232447. ->open ((IOHIDDeviceInterface**) device,
  232448. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232449. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232450. {
  232451. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232452. if (queue != 0)
  232453. {
  232454. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232455. for (int i = 0; i < cookies.size(); ++i)
  232456. {
  232457. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232458. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232459. }
  232460. CFRunLoopSourceRef eventSource;
  232461. if ((*(IOHIDQueueInterface**) queue)
  232462. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232463. {
  232464. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232465. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232466. {
  232467. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232468. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232469. return true;
  232470. }
  232471. }
  232472. }
  232473. }
  232474. return false;
  232475. }
  232476. void AppleRemoteDevice::handleCallbackInternal()
  232477. {
  232478. int totalValues = 0;
  232479. AbsoluteTime nullTime = { 0, 0 };
  232480. char cookies [12];
  232481. int numCookies = 0;
  232482. while (numCookies < numElementsInArray (cookies))
  232483. {
  232484. IOHIDEventStruct e;
  232485. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232486. break;
  232487. if ((int) e.elementCookie == 19)
  232488. {
  232489. remoteId = e.value;
  232490. buttonPressed (switched, false);
  232491. }
  232492. else
  232493. {
  232494. totalValues += e.value;
  232495. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232496. }
  232497. }
  232498. cookies [numCookies++] = 0;
  232499. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232500. static const char buttonPatterns[] =
  232501. {
  232502. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232503. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232504. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232505. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232506. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232507. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232508. 0x1f, 0x12, 0x04, 0x02, 0,
  232509. 0x1f, 0x12, 0x03, 0x02, 0,
  232510. 0x1f, 0x12, 0x1f, 0x12, 0,
  232511. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232512. 19, 0
  232513. };
  232514. int buttonNum = (int) menuButton;
  232515. int i = 0;
  232516. while (i < numElementsInArray (buttonPatterns))
  232517. {
  232518. if (strcmp (cookies, buttonPatterns + i) == 0)
  232519. {
  232520. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232521. break;
  232522. }
  232523. i += (int) strlen (buttonPatterns + i) + 1;
  232524. ++buttonNum;
  232525. }
  232526. }
  232527. #endif
  232528. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232529. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232530. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232531. // compiled on its own).
  232532. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232533. #if JUCE_MAC
  232534. END_JUCE_NAMESPACE
  232535. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232536. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232537. {
  232538. CriticalSection* contextLock;
  232539. bool needsUpdate;
  232540. }
  232541. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232542. - (bool) makeActive;
  232543. - (void) makeInactive;
  232544. - (void) reshape;
  232545. @end
  232546. @implementation ThreadSafeNSOpenGLView
  232547. - (id) initWithFrame: (NSRect) frameRect
  232548. pixelFormat: (NSOpenGLPixelFormat*) format
  232549. {
  232550. contextLock = new CriticalSection();
  232551. self = [super initWithFrame: frameRect pixelFormat: format];
  232552. if (self != nil)
  232553. [[NSNotificationCenter defaultCenter] addObserver: self
  232554. selector: @selector (_surfaceNeedsUpdate:)
  232555. name: NSViewGlobalFrameDidChangeNotification
  232556. object: self];
  232557. return self;
  232558. }
  232559. - (void) dealloc
  232560. {
  232561. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232562. delete contextLock;
  232563. [super dealloc];
  232564. }
  232565. - (bool) makeActive
  232566. {
  232567. const ScopedLock sl (*contextLock);
  232568. if ([self openGLContext] == 0)
  232569. return false;
  232570. [[self openGLContext] makeCurrentContext];
  232571. if (needsUpdate)
  232572. {
  232573. [super update];
  232574. needsUpdate = false;
  232575. }
  232576. return true;
  232577. }
  232578. - (void) makeInactive
  232579. {
  232580. const ScopedLock sl (*contextLock);
  232581. [NSOpenGLContext clearCurrentContext];
  232582. }
  232583. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232584. {
  232585. (void) notification;
  232586. const ScopedLock sl (*contextLock);
  232587. needsUpdate = true;
  232588. }
  232589. - (void) update
  232590. {
  232591. const ScopedLock sl (*contextLock);
  232592. needsUpdate = true;
  232593. }
  232594. - (void) reshape
  232595. {
  232596. const ScopedLock sl (*contextLock);
  232597. needsUpdate = true;
  232598. }
  232599. @end
  232600. BEGIN_JUCE_NAMESPACE
  232601. class WindowedGLContext : public OpenGLContext
  232602. {
  232603. public:
  232604. WindowedGLContext (Component* const component,
  232605. const OpenGLPixelFormat& pixelFormat_,
  232606. NSOpenGLContext* sharedContext)
  232607. : renderContext (0),
  232608. pixelFormat (pixelFormat_)
  232609. {
  232610. jassert (component != 0);
  232611. NSOpenGLPixelFormatAttribute attribs [64];
  232612. int n = 0;
  232613. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232614. attribs[n++] = NSOpenGLPFAAccelerated;
  232615. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232616. attribs[n++] = NSOpenGLPFAColorSize;
  232617. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232618. pixelFormat.greenBits,
  232619. pixelFormat.blueBits);
  232620. attribs[n++] = NSOpenGLPFAAlphaSize;
  232621. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232622. attribs[n++] = NSOpenGLPFADepthSize;
  232623. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232624. attribs[n++] = NSOpenGLPFAStencilSize;
  232625. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232626. attribs[n++] = NSOpenGLPFAAccumSize;
  232627. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232628. pixelFormat.accumulationBufferGreenBits,
  232629. pixelFormat.accumulationBufferBlueBits,
  232630. pixelFormat.accumulationBufferAlphaBits);
  232631. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232632. attribs[n++] = NSOpenGLPFASampleBuffers;
  232633. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232634. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232635. attribs[n++] = NSOpenGLPFANoRecovery;
  232636. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232637. NSOpenGLPixelFormat* format
  232638. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232639. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232640. pixelFormat: format];
  232641. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232642. shareContext: sharedContext] autorelease];
  232643. const GLint swapInterval = 1;
  232644. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232645. [view setOpenGLContext: renderContext];
  232646. [format release];
  232647. viewHolder = new NSViewComponentInternal (view, component);
  232648. }
  232649. ~WindowedGLContext()
  232650. {
  232651. deleteContext();
  232652. viewHolder = 0;
  232653. }
  232654. void deleteContext()
  232655. {
  232656. makeInactive();
  232657. [renderContext clearDrawable];
  232658. [renderContext setView: nil];
  232659. [view setOpenGLContext: nil];
  232660. renderContext = nil;
  232661. }
  232662. bool makeActive() const throw()
  232663. {
  232664. jassert (renderContext != 0);
  232665. if ([renderContext view] != view)
  232666. [renderContext setView: view];
  232667. [view makeActive];
  232668. return isActive();
  232669. }
  232670. bool makeInactive() const throw()
  232671. {
  232672. [view makeInactive];
  232673. return true;
  232674. }
  232675. bool isActive() const throw()
  232676. {
  232677. return [NSOpenGLContext currentContext] == renderContext;
  232678. }
  232679. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232680. void* getRawContext() const throw() { return renderContext; }
  232681. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232682. {
  232683. }
  232684. void swapBuffers()
  232685. {
  232686. [renderContext flushBuffer];
  232687. }
  232688. bool setSwapInterval (const int numFramesPerSwap)
  232689. {
  232690. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232691. forParameter: NSOpenGLCPSwapInterval];
  232692. return true;
  232693. }
  232694. int getSwapInterval() const
  232695. {
  232696. GLint numFrames = 0;
  232697. [renderContext getValues: &numFrames
  232698. forParameter: NSOpenGLCPSwapInterval];
  232699. return numFrames;
  232700. }
  232701. void repaint()
  232702. {
  232703. // we need to invalidate the juce view that holds this gl view, to make it
  232704. // cause a repaint callback
  232705. NSView* v = (NSView*) viewHolder->view;
  232706. NSRect r = [v frame];
  232707. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232708. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232709. // repaint message, thus never causing our paint() callback, and never repainting
  232710. // the comp. So invalidating just a little bit around the edge helps..
  232711. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232712. }
  232713. void* getNativeWindowHandle() const { return viewHolder->view; }
  232714. NSOpenGLContext* renderContext;
  232715. ThreadSafeNSOpenGLView* view;
  232716. private:
  232717. OpenGLPixelFormat pixelFormat;
  232718. ScopedPointer <NSViewComponentInternal> viewHolder;
  232719. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232720. };
  232721. OpenGLContext* OpenGLComponent::createContext()
  232722. {
  232723. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232724. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232725. return (c->renderContext != 0) ? c.release() : 0;
  232726. }
  232727. void* OpenGLComponent::getNativeWindowHandle() const
  232728. {
  232729. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232730. : 0;
  232731. }
  232732. void juce_glViewport (const int w, const int h)
  232733. {
  232734. glViewport (0, 0, w, h);
  232735. }
  232736. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232737. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232738. {
  232739. /* GLint attribs [64];
  232740. int n = 0;
  232741. attribs[n++] = AGL_RGBA;
  232742. attribs[n++] = AGL_DOUBLEBUFFER;
  232743. attribs[n++] = AGL_ACCELERATED;
  232744. attribs[n++] = AGL_NO_RECOVERY;
  232745. attribs[n++] = AGL_NONE;
  232746. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232747. while (p != 0)
  232748. {
  232749. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232750. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232751. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232752. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232753. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232754. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232755. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232756. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232757. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232758. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232759. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232760. results.add (pf);
  232761. p = aglNextPixelFormat (p);
  232762. }*/
  232763. //jassertfalse // can't see how you do this in cocoa!
  232764. }
  232765. #else
  232766. END_JUCE_NAMESPACE
  232767. @interface JuceGLView : UIView
  232768. {
  232769. }
  232770. + (Class) layerClass;
  232771. @end
  232772. @implementation JuceGLView
  232773. + (Class) layerClass
  232774. {
  232775. return [CAEAGLLayer class];
  232776. }
  232777. @end
  232778. BEGIN_JUCE_NAMESPACE
  232779. class GLESContext : public OpenGLContext
  232780. {
  232781. public:
  232782. GLESContext (UIViewComponentPeer* peer,
  232783. Component* const component_,
  232784. const OpenGLPixelFormat& pixelFormat_,
  232785. const GLESContext* const sharedContext,
  232786. NSUInteger apiType)
  232787. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232788. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232789. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232790. {
  232791. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232792. view.opaque = YES;
  232793. view.hidden = NO;
  232794. view.backgroundColor = [UIColor blackColor];
  232795. view.userInteractionEnabled = NO;
  232796. glLayer = (CAEAGLLayer*) [view layer];
  232797. [peer->view addSubview: view];
  232798. if (sharedContext != 0)
  232799. context = [[EAGLContext alloc] initWithAPI: apiType
  232800. sharegroup: [sharedContext->context sharegroup]];
  232801. else
  232802. context = [[EAGLContext alloc] initWithAPI: apiType];
  232803. createGLBuffers();
  232804. }
  232805. ~GLESContext()
  232806. {
  232807. deleteContext();
  232808. [view removeFromSuperview];
  232809. [view release];
  232810. freeGLBuffers();
  232811. }
  232812. void deleteContext()
  232813. {
  232814. makeInactive();
  232815. [context release];
  232816. context = nil;
  232817. }
  232818. bool makeActive() const throw()
  232819. {
  232820. jassert (context != 0);
  232821. [EAGLContext setCurrentContext: context];
  232822. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232823. return true;
  232824. }
  232825. void swapBuffers()
  232826. {
  232827. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232828. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232829. }
  232830. bool makeInactive() const throw()
  232831. {
  232832. return [EAGLContext setCurrentContext: nil];
  232833. }
  232834. bool isActive() const throw()
  232835. {
  232836. return [EAGLContext currentContext] == context;
  232837. }
  232838. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232839. void* getRawContext() const throw() { return glLayer; }
  232840. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232841. {
  232842. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232843. if (lastWidth != w || lastHeight != h)
  232844. {
  232845. lastWidth = w;
  232846. lastHeight = h;
  232847. freeGLBuffers();
  232848. createGLBuffers();
  232849. }
  232850. }
  232851. bool setSwapInterval (const int numFramesPerSwap)
  232852. {
  232853. numFrames = numFramesPerSwap;
  232854. return true;
  232855. }
  232856. int getSwapInterval() const
  232857. {
  232858. return numFrames;
  232859. }
  232860. void repaint()
  232861. {
  232862. }
  232863. void createGLBuffers()
  232864. {
  232865. makeActive();
  232866. glGenFramebuffersOES (1, &frameBufferHandle);
  232867. glGenRenderbuffersOES (1, &colorBufferHandle);
  232868. glGenRenderbuffersOES (1, &depthBufferHandle);
  232869. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232870. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232871. GLint width, height;
  232872. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232873. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232874. if (useDepthBuffer)
  232875. {
  232876. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232877. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232878. }
  232879. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232880. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232881. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232882. if (useDepthBuffer)
  232883. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232884. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232885. }
  232886. void freeGLBuffers()
  232887. {
  232888. if (frameBufferHandle != 0)
  232889. {
  232890. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232891. frameBufferHandle = 0;
  232892. }
  232893. if (colorBufferHandle != 0)
  232894. {
  232895. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232896. colorBufferHandle = 0;
  232897. }
  232898. if (depthBufferHandle != 0)
  232899. {
  232900. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232901. depthBufferHandle = 0;
  232902. }
  232903. }
  232904. private:
  232905. WeakReference<Component> component;
  232906. OpenGLPixelFormat pixelFormat;
  232907. JuceGLView* view;
  232908. CAEAGLLayer* glLayer;
  232909. EAGLContext* context;
  232910. bool useDepthBuffer;
  232911. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232912. int numFrames;
  232913. int lastWidth, lastHeight;
  232914. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232915. };
  232916. OpenGLContext* OpenGLComponent::createContext()
  232917. {
  232918. ScopedAutoReleasePool pool;
  232919. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232920. if (peer != 0)
  232921. return new GLESContext (peer, this, preferredPixelFormat,
  232922. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232923. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232924. return 0;
  232925. }
  232926. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232927. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232928. {
  232929. }
  232930. void juce_glViewport (const int w, const int h)
  232931. {
  232932. glViewport (0, 0, w, h);
  232933. }
  232934. #endif
  232935. #endif
  232936. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232937. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232938. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232939. // compiled on its own).
  232940. #if JUCE_INCLUDED_FILE
  232941. class JuceMainMenuHandler;
  232942. END_JUCE_NAMESPACE
  232943. using namespace JUCE_NAMESPACE;
  232944. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232945. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232946. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232947. #else
  232948. @interface JuceMenuCallback : NSObject
  232949. #endif
  232950. {
  232951. JuceMainMenuHandler* owner;
  232952. }
  232953. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232954. - (void) dealloc;
  232955. - (void) menuItemInvoked: (id) menu;
  232956. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232957. @end
  232958. BEGIN_JUCE_NAMESPACE
  232959. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232960. private DeletedAtShutdown
  232961. {
  232962. public:
  232963. JuceMainMenuHandler()
  232964. : currentModel (0),
  232965. lastUpdateTime (0)
  232966. {
  232967. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232968. }
  232969. ~JuceMainMenuHandler()
  232970. {
  232971. setMenu (0);
  232972. jassert (instance == this);
  232973. instance = 0;
  232974. [callback release];
  232975. }
  232976. void setMenu (MenuBarModel* const newMenuBarModel)
  232977. {
  232978. if (currentModel != newMenuBarModel)
  232979. {
  232980. if (currentModel != 0)
  232981. currentModel->removeListener (this);
  232982. currentModel = newMenuBarModel;
  232983. if (currentModel != 0)
  232984. currentModel->addListener (this);
  232985. menuBarItemsChanged (0);
  232986. }
  232987. }
  232988. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232989. const String& name, const int menuId, const int tag)
  232990. {
  232991. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232992. action: nil
  232993. keyEquivalent: @""];
  232994. [item setTag: tag];
  232995. NSMenu* sub = createMenu (child, name, menuId, tag);
  232996. [parent setSubmenu: sub forItem: item];
  232997. [sub setAutoenablesItems: false];
  232998. [sub release];
  232999. }
  233000. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233001. const String& name, const int menuId, const int tag)
  233002. {
  233003. [parentItem setTag: tag];
  233004. NSMenu* menu = [parentItem submenu];
  233005. [menu setTitle: juceStringToNS (name)];
  233006. while ([menu numberOfItems] > 0)
  233007. [menu removeItemAtIndex: 0];
  233008. PopupMenu::MenuItemIterator iter (menuToCopy);
  233009. while (iter.next())
  233010. addMenuItem (iter, menu, menuId, tag);
  233011. [menu setAutoenablesItems: false];
  233012. [menu update];
  233013. }
  233014. void menuBarItemsChanged (MenuBarModel*)
  233015. {
  233016. lastUpdateTime = Time::getMillisecondCounter();
  233017. StringArray menuNames;
  233018. if (currentModel != 0)
  233019. menuNames = currentModel->getMenuBarNames();
  233020. NSMenu* menuBar = [NSApp mainMenu];
  233021. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233022. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233023. int menuId = 1;
  233024. for (int i = 0; i < menuNames.size(); ++i)
  233025. {
  233026. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233027. if (i >= [menuBar numberOfItems] - 1)
  233028. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233029. else
  233030. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233031. }
  233032. }
  233033. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233034. {
  233035. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233036. if (item != 0)
  233037. flashMenuBar ([item menu]);
  233038. }
  233039. void updateMenus (NSMenu* menu)
  233040. {
  233041. if (PopupMenu::dismissAllActiveMenus())
  233042. {
  233043. // If we were running a juce menu, then we should let that modal loop finish before allowing
  233044. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  233045. if ([menu respondsToSelector: @selector (cancelTracking)])
  233046. [menu performSelector: @selector (cancelTracking)];
  233047. }
  233048. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233049. menuBarItemsChanged (0);
  233050. }
  233051. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233052. {
  233053. if (currentModel != 0)
  233054. {
  233055. if (commandManager != 0)
  233056. {
  233057. ApplicationCommandTarget::InvocationInfo info (commandId);
  233058. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233059. commandManager->invoke (info, true);
  233060. }
  233061. currentModel->menuItemSelected (commandId, topLevelIndex);
  233062. }
  233063. }
  233064. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233065. const int topLevelMenuId, const int topLevelIndex)
  233066. {
  233067. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233068. if (text == 0)
  233069. text = @"";
  233070. if (iter.isSeparator)
  233071. {
  233072. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233073. }
  233074. else if (iter.isSectionHeader)
  233075. {
  233076. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233077. action: nil
  233078. keyEquivalent: @""];
  233079. [item setEnabled: false];
  233080. }
  233081. else if (iter.subMenu != 0)
  233082. {
  233083. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233084. action: nil
  233085. keyEquivalent: @""];
  233086. [item setTag: iter.itemId];
  233087. [item setEnabled: iter.isEnabled];
  233088. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233089. [sub setDelegate: nil];
  233090. [menuToAddTo setSubmenu: sub forItem: item];
  233091. [sub release];
  233092. }
  233093. else
  233094. {
  233095. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233096. action: @selector (menuItemInvoked:)
  233097. keyEquivalent: @""];
  233098. [item setTag: iter.itemId];
  233099. [item setEnabled: iter.isEnabled];
  233100. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233101. [item setTarget: (id) callback];
  233102. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233103. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233104. [item setRepresentedObject: info];
  233105. if (iter.commandManager != 0)
  233106. {
  233107. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233108. ->getKeyPressesAssignedToCommand (iter.itemId));
  233109. if (keyPresses.size() > 0)
  233110. {
  233111. const KeyPress& kp = keyPresses.getReference(0);
  233112. if (kp.getKeyCode() != KeyPress::backspaceKey
  233113. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233114. // every time you press the key while editing text)
  233115. {
  233116. juce_wchar key = kp.getTextCharacter();
  233117. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233118. key = NSBackspaceCharacter;
  233119. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233120. key = NSDeleteCharacter;
  233121. else if (key == 0)
  233122. key = (juce_wchar) kp.getKeyCode();
  233123. unsigned int mods = 0;
  233124. if (kp.getModifiers().isShiftDown())
  233125. mods |= NSShiftKeyMask;
  233126. if (kp.getModifiers().isCtrlDown())
  233127. mods |= NSControlKeyMask;
  233128. if (kp.getModifiers().isAltDown())
  233129. mods |= NSAlternateKeyMask;
  233130. if (kp.getModifiers().isCommandDown())
  233131. mods |= NSCommandKeyMask;
  233132. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233133. [item setKeyEquivalentModifierMask: mods];
  233134. }
  233135. }
  233136. }
  233137. }
  233138. }
  233139. static JuceMainMenuHandler* instance;
  233140. MenuBarModel* currentModel;
  233141. uint32 lastUpdateTime;
  233142. JuceMenuCallback* callback;
  233143. private:
  233144. NSMenu* createMenu (const PopupMenu menu,
  233145. const String& menuName,
  233146. const int topLevelMenuId,
  233147. const int topLevelIndex)
  233148. {
  233149. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233150. [m setAutoenablesItems: false];
  233151. [m setDelegate: callback];
  233152. PopupMenu::MenuItemIterator iter (menu);
  233153. while (iter.next())
  233154. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233155. [m update];
  233156. return m;
  233157. }
  233158. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233159. {
  233160. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233161. {
  233162. NSMenuItem* m = [menu itemAtIndex: i];
  233163. if ([m tag] == info.commandID)
  233164. return m;
  233165. if ([m submenu] != 0)
  233166. {
  233167. NSMenuItem* found = findMenuItem ([m submenu], info);
  233168. if (found != 0)
  233169. return found;
  233170. }
  233171. }
  233172. return 0;
  233173. }
  233174. static void flashMenuBar (NSMenu* menu)
  233175. {
  233176. if ([[menu title] isEqualToString: @"Apple"])
  233177. return;
  233178. [menu retain];
  233179. const unichar f35Key = NSF35FunctionKey;
  233180. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233181. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233182. action: nil
  233183. keyEquivalent: f35String];
  233184. [item setTarget: nil];
  233185. [menu insertItem: item atIndex: [menu numberOfItems]];
  233186. [item release];
  233187. if ([menu indexOfItem: item] >= 0)
  233188. {
  233189. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233190. location: NSZeroPoint
  233191. modifierFlags: NSCommandKeyMask
  233192. timestamp: 0
  233193. windowNumber: 0
  233194. context: [NSGraphicsContext currentContext]
  233195. characters: f35String
  233196. charactersIgnoringModifiers: f35String
  233197. isARepeat: NO
  233198. keyCode: 0];
  233199. [menu performKeyEquivalent: f35Event];
  233200. if ([menu indexOfItem: item] >= 0)
  233201. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233202. }
  233203. [menu release];
  233204. }
  233205. };
  233206. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233207. END_JUCE_NAMESPACE
  233208. @implementation JuceMenuCallback
  233209. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233210. {
  233211. [super init];
  233212. owner = owner_;
  233213. return self;
  233214. }
  233215. - (void) dealloc
  233216. {
  233217. [super dealloc];
  233218. }
  233219. - (void) menuItemInvoked: (id) menu
  233220. {
  233221. NSMenuItem* item = (NSMenuItem*) menu;
  233222. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233223. {
  233224. // 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
  233225. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233226. // into the focused component and let it trigger the menu item indirectly.
  233227. NSEvent* e = [NSApp currentEvent];
  233228. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233229. {
  233230. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233231. {
  233232. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233233. if (peer != 0)
  233234. {
  233235. if ([e type] == NSKeyDown)
  233236. peer->redirectKeyDown (e);
  233237. else
  233238. peer->redirectKeyUp (e);
  233239. return;
  233240. }
  233241. }
  233242. }
  233243. NSArray* info = (NSArray*) [item representedObject];
  233244. owner->invoke ((int) [item tag],
  233245. (ApplicationCommandManager*) (pointer_sized_int)
  233246. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233247. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233248. }
  233249. }
  233250. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233251. {
  233252. if (JuceMainMenuHandler::instance != 0)
  233253. JuceMainMenuHandler::instance->updateMenus (menu);
  233254. }
  233255. @end
  233256. BEGIN_JUCE_NAMESPACE
  233257. namespace MainMenuHelpers
  233258. {
  233259. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233260. {
  233261. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233262. {
  233263. PopupMenu::MenuItemIterator iter (*extraItems);
  233264. while (iter.next())
  233265. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233266. [menu addItem: [NSMenuItem separatorItem]];
  233267. }
  233268. NSMenuItem* item;
  233269. // Services...
  233270. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233271. action: nil keyEquivalent: @""];
  233272. [menu addItem: item];
  233273. [item release];
  233274. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233275. [menu setSubmenu: servicesMenu forItem: item];
  233276. [NSApp setServicesMenu: servicesMenu];
  233277. [servicesMenu release];
  233278. [menu addItem: [NSMenuItem separatorItem]];
  233279. // Hide + Show stuff...
  233280. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233281. action: @selector (hide:) keyEquivalent: @"h"];
  233282. [item setTarget: NSApp];
  233283. [menu addItem: item];
  233284. [item release];
  233285. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233286. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233287. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233288. [item setTarget: NSApp];
  233289. [menu addItem: item];
  233290. [item release];
  233291. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233292. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233293. [item setTarget: NSApp];
  233294. [menu addItem: item];
  233295. [item release];
  233296. [menu addItem: [NSMenuItem separatorItem]];
  233297. // Quit item....
  233298. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233299. action: @selector (terminate:) keyEquivalent: @"q"];
  233300. [item setTarget: NSApp];
  233301. [menu addItem: item];
  233302. [item release];
  233303. return menu;
  233304. }
  233305. // Since our app has no NIB, this initialises a standard app menu...
  233306. void rebuildMainMenu (const PopupMenu* extraItems)
  233307. {
  233308. // this can't be used in a plugin!
  233309. jassert (JUCEApplication::isStandaloneApp());
  233310. if (JUCEApplication::getInstance() != 0)
  233311. {
  233312. const ScopedAutoReleasePool pool;
  233313. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233314. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233315. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233316. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233317. [mainMenu setSubmenu: appMenu forItem: item];
  233318. [NSApp setMainMenu: mainMenu];
  233319. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233320. [appMenu release];
  233321. [mainMenu release];
  233322. }
  233323. }
  233324. }
  233325. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233326. const PopupMenu* extraAppleMenuItems)
  233327. {
  233328. if (getMacMainMenu() != newMenuBarModel)
  233329. {
  233330. const ScopedAutoReleasePool pool;
  233331. if (newMenuBarModel == 0)
  233332. {
  233333. delete JuceMainMenuHandler::instance;
  233334. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233335. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233336. extraAppleMenuItems = 0;
  233337. }
  233338. else
  233339. {
  233340. if (JuceMainMenuHandler::instance == 0)
  233341. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233342. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233343. }
  233344. }
  233345. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  233346. if (newMenuBarModel != 0)
  233347. newMenuBarModel->menuItemsChanged();
  233348. }
  233349. MenuBarModel* MenuBarModel::getMacMainMenu()
  233350. {
  233351. return JuceMainMenuHandler::instance != 0
  233352. ? JuceMainMenuHandler::instance->currentModel : 0;
  233353. }
  233354. void juce_initialiseMacMainMenu()
  233355. {
  233356. if (JuceMainMenuHandler::instance == 0)
  233357. MainMenuHelpers::rebuildMainMenu (0);
  233358. }
  233359. #endif
  233360. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233361. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233362. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233363. // compiled on its own).
  233364. #if JUCE_INCLUDED_FILE
  233365. #if JUCE_MAC
  233366. END_JUCE_NAMESPACE
  233367. using namespace JUCE_NAMESPACE;
  233368. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233369. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233370. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233371. #else
  233372. @interface JuceFileChooserDelegate : NSObject
  233373. #endif
  233374. {
  233375. StringArray* filters;
  233376. }
  233377. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233378. - (void) dealloc;
  233379. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233380. @end
  233381. @implementation JuceFileChooserDelegate
  233382. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233383. {
  233384. [super init];
  233385. filters = filters_;
  233386. return self;
  233387. }
  233388. - (void) dealloc
  233389. {
  233390. delete filters;
  233391. [super dealloc];
  233392. }
  233393. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233394. {
  233395. (void) sender;
  233396. const File f (nsStringToJuce (filename));
  233397. for (int i = filters->size(); --i >= 0;)
  233398. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233399. return true;
  233400. return f.isDirectory();
  233401. }
  233402. @end
  233403. BEGIN_JUCE_NAMESPACE
  233404. void FileChooser::showPlatformDialog (Array<File>& results,
  233405. const String& title,
  233406. const File& currentFileOrDirectory,
  233407. const String& filter,
  233408. bool selectsDirectory,
  233409. bool selectsFiles,
  233410. bool isSaveDialogue,
  233411. bool /*warnAboutOverwritingExistingFiles*/,
  233412. bool selectMultipleFiles,
  233413. FilePreviewComponent* /*extraInfoComponent*/)
  233414. {
  233415. const ScopedAutoReleasePool pool;
  233416. StringArray* filters = new StringArray();
  233417. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233418. filters->trim();
  233419. filters->removeEmptyStrings();
  233420. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233421. [delegate autorelease];
  233422. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233423. : [NSOpenPanel openPanel];
  233424. [panel setTitle: juceStringToNS (title)];
  233425. if (! isSaveDialogue)
  233426. {
  233427. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233428. [openPanel setCanChooseDirectories: selectsDirectory];
  233429. [openPanel setCanChooseFiles: selectsFiles];
  233430. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233431. }
  233432. [panel setDelegate: delegate];
  233433. if (isSaveDialogue || selectsDirectory)
  233434. [panel setCanCreateDirectories: YES];
  233435. String directory, filename;
  233436. if (currentFileOrDirectory.isDirectory())
  233437. {
  233438. directory = currentFileOrDirectory.getFullPathName();
  233439. }
  233440. else
  233441. {
  233442. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233443. filename = currentFileOrDirectory.getFileName();
  233444. }
  233445. if ([panel runModalForDirectory: juceStringToNS (directory)
  233446. file: juceStringToNS (filename)]
  233447. == NSOKButton)
  233448. {
  233449. if (isSaveDialogue)
  233450. {
  233451. results.add (File (nsStringToJuce ([panel filename])));
  233452. }
  233453. else
  233454. {
  233455. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233456. NSArray* urls = [openPanel filenames];
  233457. for (unsigned int i = 0; i < [urls count]; ++i)
  233458. {
  233459. NSString* f = [urls objectAtIndex: i];
  233460. results.add (File (nsStringToJuce (f)));
  233461. }
  233462. }
  233463. }
  233464. [panel setDelegate: nil];
  233465. }
  233466. #else
  233467. void FileChooser::showPlatformDialog (Array<File>& results,
  233468. const String& title,
  233469. const File& currentFileOrDirectory,
  233470. const String& filter,
  233471. bool selectsDirectory,
  233472. bool selectsFiles,
  233473. bool isSaveDialogue,
  233474. bool warnAboutOverwritingExistingFiles,
  233475. bool selectMultipleFiles,
  233476. FilePreviewComponent* extraInfoComponent)
  233477. {
  233478. const ScopedAutoReleasePool pool;
  233479. jassertfalse; //xxx to do
  233480. }
  233481. #endif
  233482. #endif
  233483. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233484. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233485. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233486. // compiled on its own).
  233487. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233488. END_JUCE_NAMESPACE
  233489. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233490. @interface NonInterceptingQTMovieView : QTMovieView
  233491. {
  233492. }
  233493. - (id) initWithFrame: (NSRect) frame;
  233494. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233495. - (NSView*) hitTest: (NSPoint) p;
  233496. @end
  233497. @implementation NonInterceptingQTMovieView
  233498. - (id) initWithFrame: (NSRect) frame
  233499. {
  233500. self = [super initWithFrame: frame];
  233501. [self setNextResponder: [self superview]];
  233502. return self;
  233503. }
  233504. - (void) dealloc
  233505. {
  233506. [super dealloc];
  233507. }
  233508. - (NSView*) hitTest: (NSPoint) point
  233509. {
  233510. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233511. }
  233512. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233513. {
  233514. return YES;
  233515. }
  233516. @end
  233517. BEGIN_JUCE_NAMESPACE
  233518. #define theMovie (static_cast <QTMovie*> (movie))
  233519. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233520. : movie (0)
  233521. {
  233522. setOpaque (true);
  233523. setVisible (true);
  233524. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233525. setView (view);
  233526. [view release];
  233527. }
  233528. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233529. {
  233530. closeMovie();
  233531. setView (0);
  233532. }
  233533. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233534. {
  233535. return true;
  233536. }
  233537. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233538. {
  233539. // unfortunately, QTMovie objects can only be created on the main thread..
  233540. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233541. QTMovie* movie = 0;
  233542. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233543. if (fin != 0)
  233544. {
  233545. movieFile = fin->getFile();
  233546. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233547. error: nil];
  233548. }
  233549. else
  233550. {
  233551. MemoryBlock temp;
  233552. movieStream->readIntoMemoryBlock (temp);
  233553. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233554. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233555. {
  233556. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233557. length: temp.getSize()]
  233558. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233559. MIMEType: @""]
  233560. error: nil];
  233561. if (movie != 0)
  233562. break;
  233563. }
  233564. }
  233565. return movie;
  233566. }
  233567. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233568. const bool isControllerVisible_)
  233569. {
  233570. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233571. }
  233572. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233573. const bool controllerVisible_)
  233574. {
  233575. closeMovie();
  233576. if (getPeer() == 0)
  233577. {
  233578. // To open a movie, this component must be visible inside a functioning window, so that
  233579. // the QT control can be assigned to the window.
  233580. jassertfalse;
  233581. return false;
  233582. }
  233583. movie = openMovieFromStream (movieStream, movieFile);
  233584. [theMovie retain];
  233585. QTMovieView* view = (QTMovieView*) getView();
  233586. [view setMovie: theMovie];
  233587. [view setControllerVisible: controllerVisible_];
  233588. setLooping (looping);
  233589. return movie != nil;
  233590. }
  233591. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233592. const bool isControllerVisible_)
  233593. {
  233594. // unfortunately, QTMovie objects can only be created on the main thread..
  233595. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233596. closeMovie();
  233597. if (getPeer() == 0)
  233598. {
  233599. // To open a movie, this component must be visible inside a functioning window, so that
  233600. // the QT control can be assigned to the window.
  233601. jassertfalse;
  233602. return false;
  233603. }
  233604. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233605. NSError* err;
  233606. if ([QTMovie canInitWithURL: url])
  233607. movie = [QTMovie movieWithURL: url error: &err];
  233608. [theMovie retain];
  233609. QTMovieView* view = (QTMovieView*) getView();
  233610. [view setMovie: theMovie];
  233611. [view setControllerVisible: controllerVisible];
  233612. setLooping (looping);
  233613. return movie != nil;
  233614. }
  233615. void QuickTimeMovieComponent::closeMovie()
  233616. {
  233617. stop();
  233618. QTMovieView* view = (QTMovieView*) getView();
  233619. [view setMovie: nil];
  233620. [theMovie release];
  233621. movie = 0;
  233622. movieFile = File::nonexistent;
  233623. }
  233624. bool QuickTimeMovieComponent::isMovieOpen() const
  233625. {
  233626. return movie != nil;
  233627. }
  233628. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233629. {
  233630. return movieFile;
  233631. }
  233632. void QuickTimeMovieComponent::play()
  233633. {
  233634. [theMovie play];
  233635. }
  233636. void QuickTimeMovieComponent::stop()
  233637. {
  233638. [theMovie stop];
  233639. }
  233640. bool QuickTimeMovieComponent::isPlaying() const
  233641. {
  233642. return movie != 0 && [theMovie rate] != 0;
  233643. }
  233644. void QuickTimeMovieComponent::setPosition (const double seconds)
  233645. {
  233646. if (movie != 0)
  233647. {
  233648. QTTime t;
  233649. t.timeValue = (uint64) (100000.0 * seconds);
  233650. t.timeScale = 100000;
  233651. t.flags = 0;
  233652. [theMovie setCurrentTime: t];
  233653. }
  233654. }
  233655. double QuickTimeMovieComponent::getPosition() const
  233656. {
  233657. if (movie == 0)
  233658. return 0.0;
  233659. QTTime t = [theMovie currentTime];
  233660. return t.timeValue / (double) t.timeScale;
  233661. }
  233662. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233663. {
  233664. [theMovie setRate: newSpeed];
  233665. }
  233666. double QuickTimeMovieComponent::getMovieDuration() const
  233667. {
  233668. if (movie == 0)
  233669. return 0.0;
  233670. QTTime t = [theMovie duration];
  233671. return t.timeValue / (double) t.timeScale;
  233672. }
  233673. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233674. {
  233675. looping = shouldLoop;
  233676. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233677. forKey: QTMovieLoopsAttribute];
  233678. }
  233679. bool QuickTimeMovieComponent::isLooping() const
  233680. {
  233681. return looping;
  233682. }
  233683. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233684. {
  233685. [theMovie setVolume: newVolume];
  233686. }
  233687. float QuickTimeMovieComponent::getMovieVolume() const
  233688. {
  233689. return movie != 0 ? [theMovie volume] : 0.0f;
  233690. }
  233691. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233692. {
  233693. width = 0;
  233694. height = 0;
  233695. if (movie != 0)
  233696. {
  233697. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233698. width = (int) s.width;
  233699. height = (int) s.height;
  233700. }
  233701. }
  233702. void QuickTimeMovieComponent::paint (Graphics& g)
  233703. {
  233704. if (movie == 0)
  233705. g.fillAll (Colours::black);
  233706. }
  233707. bool QuickTimeMovieComponent::isControllerVisible() const
  233708. {
  233709. return controllerVisible;
  233710. }
  233711. void QuickTimeMovieComponent::goToStart()
  233712. {
  233713. setPosition (0.0);
  233714. }
  233715. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233716. const RectanglePlacement& placement)
  233717. {
  233718. int normalWidth, normalHeight;
  233719. getMovieNormalSize (normalWidth, normalHeight);
  233720. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233721. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233722. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233723. else
  233724. setBounds (spaceToFitWithin);
  233725. }
  233726. #if ! (JUCE_MAC && JUCE_64BIT)
  233727. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233728. {
  233729. if (movieStream == 0)
  233730. return false;
  233731. File file;
  233732. QTMovie* movie = openMovieFromStream (movieStream, file);
  233733. if (movie != nil)
  233734. result = [movie quickTimeMovie];
  233735. return movie != nil;
  233736. }
  233737. #endif
  233738. #endif
  233739. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233740. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233741. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233742. // compiled on its own).
  233743. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233744. const int kilobytesPerSecond1x = 176;
  233745. END_JUCE_NAMESPACE
  233746. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233747. @interface OpenDiskDevice : NSObject
  233748. {
  233749. @public
  233750. DRDevice* device;
  233751. NSMutableArray* tracks;
  233752. bool underrunProtection;
  233753. }
  233754. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233755. - (void) dealloc;
  233756. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233757. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233758. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233759. @end
  233760. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233761. @interface AudioTrackProducer : NSObject
  233762. {
  233763. JUCE_NAMESPACE::AudioSource* source;
  233764. int readPosition, lengthInFrames;
  233765. }
  233766. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233767. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233768. - (void) dealloc;
  233769. - (void) setupTrackProperties: (DRTrack*) track;
  233770. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233771. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233772. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233773. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233774. toMedia:(NSDictionary*)mediaInfo;
  233775. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233776. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233777. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233778. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233779. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233780. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233781. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233782. ioFlags:(uint32_t*)flags;
  233783. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233784. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233785. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233786. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233787. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233788. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233789. ioFlags:(uint32_t*)flags;
  233790. @end
  233791. @implementation OpenDiskDevice
  233792. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233793. {
  233794. [super init];
  233795. device = device_;
  233796. tracks = [[NSMutableArray alloc] init];
  233797. underrunProtection = true;
  233798. return self;
  233799. }
  233800. - (void) dealloc
  233801. {
  233802. [tracks release];
  233803. [super dealloc];
  233804. }
  233805. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233806. {
  233807. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233808. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233809. [p setupTrackProperties: t];
  233810. [tracks addObject: t];
  233811. [t release];
  233812. [p release];
  233813. }
  233814. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233815. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233816. {
  233817. DRBurn* burn = [DRBurn burnForDevice: device];
  233818. if (! [device acquireExclusiveAccess])
  233819. {
  233820. *error = "Couldn't open or write to the CD device";
  233821. return;
  233822. }
  233823. [device acquireMediaReservation];
  233824. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233825. [d autorelease];
  233826. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233827. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233828. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233829. if (burnSpeed > 0)
  233830. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233831. if (! underrunProtection)
  233832. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233833. [burn setProperties: d];
  233834. [burn writeLayout: tracks];
  233835. for (;;)
  233836. {
  233837. JUCE_NAMESPACE::Thread::sleep (300);
  233838. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233839. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233840. {
  233841. [burn abort];
  233842. *error = "User cancelled the write operation";
  233843. break;
  233844. }
  233845. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233846. {
  233847. *error = "Write operation failed";
  233848. break;
  233849. }
  233850. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233851. {
  233852. break;
  233853. }
  233854. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233855. objectForKey: DRErrorStatusErrorStringKey];
  233856. if ([err length] > 0)
  233857. {
  233858. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233859. break;
  233860. }
  233861. }
  233862. [device releaseMediaReservation];
  233863. [device releaseExclusiveAccess];
  233864. }
  233865. @end
  233866. @implementation AudioTrackProducer
  233867. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233868. {
  233869. lengthInFrames = lengthInFrames_;
  233870. readPosition = 0;
  233871. return self;
  233872. }
  233873. - (void) setupTrackProperties: (DRTrack*) track
  233874. {
  233875. NSMutableDictionary* p = [[track properties] mutableCopy];
  233876. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233877. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233878. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233879. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233880. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233881. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233882. [track setProperties: p];
  233883. [p release];
  233884. }
  233885. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233886. {
  233887. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233888. if (s != nil)
  233889. s->source = source_;
  233890. return s;
  233891. }
  233892. - (void) dealloc
  233893. {
  233894. if (source != 0)
  233895. {
  233896. source->releaseResources();
  233897. delete source;
  233898. }
  233899. [super dealloc];
  233900. }
  233901. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233902. {
  233903. (void) track;
  233904. }
  233905. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233906. {
  233907. (void) track;
  233908. return true;
  233909. }
  233910. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233911. {
  233912. (void) track;
  233913. return lengthInFrames;
  233914. }
  233915. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233916. toMedia: (NSDictionary*) mediaInfo
  233917. {
  233918. (void) track; (void) burn; (void) mediaInfo;
  233919. if (source != 0)
  233920. source->prepareToPlay (44100 / 75, 44100);
  233921. readPosition = 0;
  233922. return true;
  233923. }
  233924. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233925. {
  233926. (void) track;
  233927. if (source != 0)
  233928. source->prepareToPlay (44100 / 75, 44100);
  233929. return true;
  233930. }
  233931. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233932. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233933. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233934. {
  233935. (void) track; (void) address; (void) blockSize; (void) flags;
  233936. if (source != 0)
  233937. {
  233938. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233939. if (numSamples > 0)
  233940. {
  233941. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233942. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233943. info.buffer = &tempBuffer;
  233944. info.startSample = 0;
  233945. info.numSamples = numSamples;
  233946. source->getNextAudioBlock (info);
  233947. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233948. JUCE_NAMESPACE::AudioData::LittleEndian,
  233949. JUCE_NAMESPACE::AudioData::Interleaved,
  233950. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233951. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233952. JUCE_NAMESPACE::AudioData::NativeEndian,
  233953. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233954. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233955. CDSampleFormat left (buffer, 2);
  233956. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233957. CDSampleFormat right (buffer + 2, 2);
  233958. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233959. readPosition += numSamples;
  233960. }
  233961. return numSamples * 4;
  233962. }
  233963. return 0;
  233964. }
  233965. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233966. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233967. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233968. ioFlags: (uint32_t*) flags
  233969. {
  233970. (void) track; (void) address; (void) blockSize; (void) flags;
  233971. zeromem (buffer, bufferLength);
  233972. return bufferLength;
  233973. }
  233974. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233975. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233976. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233977. {
  233978. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233979. return true;
  233980. }
  233981. @end
  233982. BEGIN_JUCE_NAMESPACE
  233983. class AudioCDBurner::Pimpl : public Timer
  233984. {
  233985. public:
  233986. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233987. : device (0), owner (owner_)
  233988. {
  233989. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233990. if (dev != 0)
  233991. {
  233992. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233993. lastState = getDiskState();
  233994. startTimer (1000);
  233995. }
  233996. }
  233997. ~Pimpl()
  233998. {
  233999. stopTimer();
  234000. [device release];
  234001. }
  234002. void timerCallback()
  234003. {
  234004. const DiskState state = getDiskState();
  234005. if (state != lastState)
  234006. {
  234007. lastState = state;
  234008. owner.sendChangeMessage();
  234009. }
  234010. }
  234011. DiskState getDiskState() const
  234012. {
  234013. if ([device->device isValid])
  234014. {
  234015. NSDictionary* status = [device->device status];
  234016. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234017. if ([state isEqualTo: DRDeviceMediaStateNone])
  234018. {
  234019. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234020. return trayOpen;
  234021. return noDisc;
  234022. }
  234023. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234024. {
  234025. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234026. return writableDiskPresent;
  234027. else
  234028. return readOnlyDiskPresent;
  234029. }
  234030. }
  234031. return unknown;
  234032. }
  234033. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234034. const Array<int> getAvailableWriteSpeeds() const
  234035. {
  234036. Array<int> results;
  234037. if ([device->device isValid])
  234038. {
  234039. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234040. for (unsigned int i = 0; i < [speeds count]; ++i)
  234041. {
  234042. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234043. results.add (kbPerSec / kilobytesPerSecond1x);
  234044. }
  234045. }
  234046. return results;
  234047. }
  234048. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234049. {
  234050. if ([device->device isValid])
  234051. {
  234052. device->underrunProtection = shouldBeEnabled;
  234053. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234054. }
  234055. return false;
  234056. }
  234057. int getNumAvailableAudioBlocks() const
  234058. {
  234059. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234060. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234061. }
  234062. OpenDiskDevice* device;
  234063. private:
  234064. DiskState lastState;
  234065. AudioCDBurner& owner;
  234066. };
  234067. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234068. {
  234069. pimpl = new Pimpl (*this, deviceIndex);
  234070. }
  234071. AudioCDBurner::~AudioCDBurner()
  234072. {
  234073. }
  234074. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234075. {
  234076. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234077. if (b->pimpl->device == 0)
  234078. b = 0;
  234079. return b.release();
  234080. }
  234081. namespace
  234082. {
  234083. NSArray* findDiskBurnerDevices()
  234084. {
  234085. NSMutableArray* results = [NSMutableArray array];
  234086. NSArray* devs = [DRDevice devices];
  234087. for (int i = 0; i < [devs count]; ++i)
  234088. {
  234089. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234090. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234091. if (name != nil)
  234092. [results addObject: name];
  234093. }
  234094. return results;
  234095. }
  234096. }
  234097. const StringArray AudioCDBurner::findAvailableDevices()
  234098. {
  234099. NSArray* names = findDiskBurnerDevices();
  234100. StringArray s;
  234101. for (unsigned int i = 0; i < [names count]; ++i)
  234102. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234103. return s;
  234104. }
  234105. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234106. {
  234107. return pimpl->getDiskState();
  234108. }
  234109. bool AudioCDBurner::isDiskPresent() const
  234110. {
  234111. return getDiskState() == writableDiskPresent;
  234112. }
  234113. bool AudioCDBurner::openTray()
  234114. {
  234115. return pimpl->openTray();
  234116. }
  234117. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234118. {
  234119. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234120. DiskState oldState = getDiskState();
  234121. DiskState newState = oldState;
  234122. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234123. {
  234124. newState = getDiskState();
  234125. Thread::sleep (100);
  234126. }
  234127. return newState;
  234128. }
  234129. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234130. {
  234131. return pimpl->getAvailableWriteSpeeds();
  234132. }
  234133. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234134. {
  234135. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234136. }
  234137. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234138. {
  234139. return pimpl->getNumAvailableAudioBlocks();
  234140. }
  234141. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234142. {
  234143. if ([pimpl->device->device isValid])
  234144. {
  234145. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234146. return true;
  234147. }
  234148. return false;
  234149. }
  234150. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234151. bool ejectDiscAfterwards,
  234152. bool performFakeBurnForTesting,
  234153. int writeSpeed)
  234154. {
  234155. String error ("Couldn't open or write to the CD device");
  234156. if ([pimpl->device->device isValid])
  234157. {
  234158. error = String::empty;
  234159. [pimpl->device burn: listener
  234160. errorString: &error
  234161. ejectAfterwards: ejectDiscAfterwards
  234162. isFake: performFakeBurnForTesting
  234163. speed: writeSpeed];
  234164. }
  234165. return error;
  234166. }
  234167. #endif
  234168. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234169. void AudioCDReader::ejectDisk()
  234170. {
  234171. const ScopedAutoReleasePool p;
  234172. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234173. }
  234174. #endif
  234175. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234176. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234177. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234178. // compiled on its own).
  234179. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234180. namespace CDReaderHelpers
  234181. {
  234182. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234183. {
  234184. forEachXmlChildElementWithTagName (xml, child, "key")
  234185. if (child->getAllSubText().trim() == key)
  234186. return child->getNextElement();
  234187. return 0;
  234188. }
  234189. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234190. {
  234191. const XmlElement* const block = getElementForKey (xml, key);
  234192. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234193. }
  234194. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234195. // Returns NULL on success, otherwise a const char* representing an error.
  234196. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234197. {
  234198. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234199. if (xml == 0)
  234200. return "Couldn't parse XML in file";
  234201. const XmlElement* const dict = xml->getChildByName ("dict");
  234202. if (dict == 0)
  234203. return "Couldn't get top level dictionary";
  234204. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234205. if (sessions == 0)
  234206. return "Couldn't find sessions key";
  234207. const XmlElement* const session = sessions->getFirstChildElement();
  234208. if (session == 0)
  234209. return "Couldn't find first session";
  234210. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234211. if (leadOut < 0)
  234212. return "Couldn't find Leadout Block";
  234213. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234214. if (trackArray == 0)
  234215. return "Couldn't find Track Array";
  234216. forEachXmlChildElement (*trackArray, track)
  234217. {
  234218. const int trackValue = getIntValueForKey (*track, "Start Block");
  234219. if (trackValue < 0)
  234220. return "Couldn't find Start Block in the track";
  234221. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234222. }
  234223. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234224. return 0;
  234225. }
  234226. static void findDevices (Array<File>& cds)
  234227. {
  234228. File volumes ("/Volumes");
  234229. volumes.findChildFiles (cds, File::findDirectories, false);
  234230. for (int i = cds.size(); --i >= 0;)
  234231. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234232. cds.remove (i);
  234233. }
  234234. struct TrackSorter
  234235. {
  234236. static int getCDTrackNumber (const File& file)
  234237. {
  234238. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234239. }
  234240. static int compareElements (const File& first, const File& second)
  234241. {
  234242. const int firstTrack = getCDTrackNumber (first);
  234243. const int secondTrack = getCDTrackNumber (second);
  234244. jassert (firstTrack > 0 && secondTrack > 0);
  234245. return firstTrack - secondTrack;
  234246. }
  234247. };
  234248. }
  234249. const StringArray AudioCDReader::getAvailableCDNames()
  234250. {
  234251. Array<File> cds;
  234252. CDReaderHelpers::findDevices (cds);
  234253. StringArray names;
  234254. for (int i = 0; i < cds.size(); ++i)
  234255. names.add (cds.getReference(i).getFileName());
  234256. return names;
  234257. }
  234258. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234259. {
  234260. Array<File> cds;
  234261. CDReaderHelpers::findDevices (cds);
  234262. if (cds[index].exists())
  234263. return new AudioCDReader (cds[index]);
  234264. return 0;
  234265. }
  234266. AudioCDReader::AudioCDReader (const File& volume)
  234267. : AudioFormatReader (0, "CD Audio"),
  234268. volumeDir (volume),
  234269. currentReaderTrack (-1),
  234270. reader (0)
  234271. {
  234272. sampleRate = 44100.0;
  234273. bitsPerSample = 16;
  234274. numChannels = 2;
  234275. usesFloatingPointData = false;
  234276. refreshTrackLengths();
  234277. }
  234278. AudioCDReader::~AudioCDReader()
  234279. {
  234280. }
  234281. void AudioCDReader::refreshTrackLengths()
  234282. {
  234283. tracks.clear();
  234284. trackStartSamples.clear();
  234285. lengthInSamples = 0;
  234286. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234287. CDReaderHelpers::TrackSorter sorter;
  234288. tracks.sort (sorter);
  234289. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234290. if (toc.exists())
  234291. {
  234292. XmlDocument doc (toc);
  234293. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234294. (void) error; // could be logged..
  234295. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234296. }
  234297. }
  234298. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234299. int64 startSampleInFile, int numSamples)
  234300. {
  234301. while (numSamples > 0)
  234302. {
  234303. int track = -1;
  234304. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234305. {
  234306. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234307. {
  234308. track = i;
  234309. break;
  234310. }
  234311. }
  234312. if (track < 0)
  234313. return false;
  234314. if (track != currentReaderTrack)
  234315. {
  234316. reader = 0;
  234317. FileInputStream* const in = tracks [track].createInputStream();
  234318. if (in != 0)
  234319. {
  234320. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234321. AiffAudioFormat format;
  234322. reader = format.createReaderFor (bin, true);
  234323. if (reader == 0)
  234324. currentReaderTrack = -1;
  234325. else
  234326. currentReaderTrack = track;
  234327. }
  234328. }
  234329. if (reader == 0)
  234330. return false;
  234331. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234332. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234333. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234334. numSamples -= numAvailable;
  234335. startSampleInFile += numAvailable;
  234336. }
  234337. return true;
  234338. }
  234339. bool AudioCDReader::isCDStillPresent() const
  234340. {
  234341. return volumeDir.exists();
  234342. }
  234343. bool AudioCDReader::isTrackAudio (int trackNum) const
  234344. {
  234345. return tracks [trackNum].hasFileExtension (".aiff");
  234346. }
  234347. void AudioCDReader::enableIndexScanning (bool)
  234348. {
  234349. // any way to do this on a Mac??
  234350. }
  234351. int AudioCDReader::getLastIndex() const
  234352. {
  234353. return 0;
  234354. }
  234355. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  234356. {
  234357. return Array <int>();
  234358. }
  234359. #endif
  234360. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234361. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234362. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234363. // compiled on its own).
  234364. #if JUCE_INCLUDED_FILE
  234365. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234366. for example having more than one juce plugin loaded into a host, then when a
  234367. method is called, the actual code that runs might actually be in a different module
  234368. than the one you expect... So any calls to library functions or statics that are
  234369. made inside obj-c methods will probably end up getting executed in a different DLL's
  234370. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234371. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234372. virtual methods of an object that's known to live inside the right module's space.
  234373. */
  234374. class AppDelegateRedirector
  234375. {
  234376. public:
  234377. AppDelegateRedirector()
  234378. {
  234379. }
  234380. virtual ~AppDelegateRedirector()
  234381. {
  234382. }
  234383. virtual NSApplicationTerminateReply shouldTerminate()
  234384. {
  234385. if (JUCEApplication::getInstance() != 0)
  234386. {
  234387. JUCEApplication::getInstance()->systemRequestedQuit();
  234388. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234389. return NSTerminateCancel;
  234390. }
  234391. return NSTerminateNow;
  234392. }
  234393. virtual void willTerminate()
  234394. {
  234395. JUCEApplication::appWillTerminateByForce();
  234396. }
  234397. virtual BOOL openFile (NSString* filename)
  234398. {
  234399. if (JUCEApplication::getInstance() != 0)
  234400. {
  234401. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234402. return YES;
  234403. }
  234404. return NO;
  234405. }
  234406. virtual void openFiles (NSArray* filenames)
  234407. {
  234408. StringArray files;
  234409. for (unsigned int i = 0; i < [filenames count]; ++i)
  234410. {
  234411. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234412. if (filename.containsChar (' '))
  234413. filename = filename.quoted('"');
  234414. files.add (filename);
  234415. }
  234416. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234417. {
  234418. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234419. }
  234420. }
  234421. virtual void focusChanged()
  234422. {
  234423. juce_HandleProcessFocusChange();
  234424. }
  234425. struct CallbackMessagePayload
  234426. {
  234427. MessageCallbackFunction* function;
  234428. void* parameter;
  234429. void* volatile result;
  234430. bool volatile hasBeenExecuted;
  234431. };
  234432. virtual void performCallback (CallbackMessagePayload* pl)
  234433. {
  234434. pl->result = (*pl->function) (pl->parameter);
  234435. pl->hasBeenExecuted = true;
  234436. }
  234437. virtual void deleteSelf()
  234438. {
  234439. delete this;
  234440. }
  234441. void postMessage (Message* const m)
  234442. {
  234443. messageQueue.post (m);
  234444. }
  234445. private:
  234446. CFRunLoopRef runLoop;
  234447. CFRunLoopSourceRef runLoopSource;
  234448. MessageQueue messageQueue;
  234449. };
  234450. END_JUCE_NAMESPACE
  234451. using namespace JUCE_NAMESPACE;
  234452. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234453. @interface JuceAppDelegate : NSObject
  234454. {
  234455. @private
  234456. id oldDelegate;
  234457. @public
  234458. AppDelegateRedirector* redirector;
  234459. }
  234460. - (JuceAppDelegate*) init;
  234461. - (void) dealloc;
  234462. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234463. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234464. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234465. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234466. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234467. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234468. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234469. - (void) performCallback: (id) info;
  234470. - (void) dummyMethod;
  234471. @end
  234472. @implementation JuceAppDelegate
  234473. - (JuceAppDelegate*) init
  234474. {
  234475. [super init];
  234476. redirector = new AppDelegateRedirector();
  234477. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234478. if (JUCEApplication::isStandaloneApp())
  234479. {
  234480. oldDelegate = [NSApp delegate];
  234481. [NSApp setDelegate: self];
  234482. }
  234483. else
  234484. {
  234485. oldDelegate = 0;
  234486. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234487. name: NSApplicationDidResignActiveNotification object: NSApp];
  234488. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234489. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234490. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234491. name: NSApplicationWillUnhideNotification object: NSApp];
  234492. }
  234493. return self;
  234494. }
  234495. - (void) dealloc
  234496. {
  234497. if (oldDelegate != 0)
  234498. [NSApp setDelegate: oldDelegate];
  234499. redirector->deleteSelf();
  234500. [super dealloc];
  234501. }
  234502. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234503. {
  234504. (void) app;
  234505. return redirector->shouldTerminate();
  234506. }
  234507. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234508. {
  234509. (void) aNotification;
  234510. redirector->willTerminate();
  234511. }
  234512. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234513. {
  234514. (void) app;
  234515. return redirector->openFile (filename);
  234516. }
  234517. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234518. {
  234519. (void) sender;
  234520. return redirector->openFiles (filenames);
  234521. }
  234522. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234523. {
  234524. (void) notification;
  234525. redirector->focusChanged();
  234526. }
  234527. - (void) applicationDidResignActive: (NSNotification*) notification
  234528. {
  234529. (void) notification;
  234530. redirector->focusChanged();
  234531. }
  234532. - (void) applicationWillUnhide: (NSNotification*) notification
  234533. {
  234534. (void) notification;
  234535. redirector->focusChanged();
  234536. }
  234537. - (void) performCallback: (id) info
  234538. {
  234539. if ([info isKindOfClass: [NSData class]])
  234540. {
  234541. AppDelegateRedirector::CallbackMessagePayload* pl
  234542. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234543. if (pl != 0)
  234544. redirector->performCallback (pl);
  234545. }
  234546. else
  234547. {
  234548. jassertfalse; // should never get here!
  234549. }
  234550. }
  234551. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234552. @end
  234553. BEGIN_JUCE_NAMESPACE
  234554. static JuceAppDelegate* juceAppDelegate = 0;
  234555. void MessageManager::runDispatchLoop()
  234556. {
  234557. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234558. {
  234559. const ScopedAutoReleasePool pool;
  234560. // must only be called by the message thread!
  234561. jassert (isThisTheMessageThread());
  234562. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234563. @try
  234564. {
  234565. [NSApp run];
  234566. }
  234567. @catch (NSException* e)
  234568. {
  234569. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234570. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234571. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234572. }
  234573. @finally
  234574. {
  234575. }
  234576. #else
  234577. [NSApp run];
  234578. #endif
  234579. }
  234580. }
  234581. void MessageManager::stopDispatchLoop()
  234582. {
  234583. quitMessagePosted = true;
  234584. [NSApp stop: nil];
  234585. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234586. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234587. }
  234588. namespace
  234589. {
  234590. bool isEventBlockedByModalComps (NSEvent* e)
  234591. {
  234592. if (Component::getNumCurrentlyModalComponents() == 0)
  234593. return false;
  234594. NSWindow* const w = [e window];
  234595. if (w == 0 || [w worksWhenModal])
  234596. return false;
  234597. bool isKey = false, isInputAttempt = false;
  234598. switch ([e type])
  234599. {
  234600. case NSKeyDown:
  234601. case NSKeyUp:
  234602. isKey = isInputAttempt = true;
  234603. break;
  234604. case NSLeftMouseDown:
  234605. case NSRightMouseDown:
  234606. case NSOtherMouseDown:
  234607. isInputAttempt = true;
  234608. break;
  234609. case NSLeftMouseDragged:
  234610. case NSRightMouseDragged:
  234611. case NSLeftMouseUp:
  234612. case NSRightMouseUp:
  234613. case NSOtherMouseUp:
  234614. case NSOtherMouseDragged:
  234615. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234616. return false;
  234617. break;
  234618. case NSMouseMoved:
  234619. case NSMouseEntered:
  234620. case NSMouseExited:
  234621. case NSCursorUpdate:
  234622. case NSScrollWheel:
  234623. case NSTabletPoint:
  234624. case NSTabletProximity:
  234625. break;
  234626. default:
  234627. return false;
  234628. }
  234629. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234630. {
  234631. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234632. NSView* const compView = (NSView*) peer->getNativeHandle();
  234633. if ([compView window] == w)
  234634. {
  234635. if (isKey)
  234636. {
  234637. if (compView == [w firstResponder])
  234638. return false;
  234639. }
  234640. else
  234641. {
  234642. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234643. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234644. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234645. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234646. return false;
  234647. }
  234648. }
  234649. }
  234650. if (isInputAttempt)
  234651. {
  234652. if (! [NSApp isActive])
  234653. [NSApp activateIgnoringOtherApps: YES];
  234654. Component* const modal = Component::getCurrentlyModalComponent (0);
  234655. if (modal != 0)
  234656. modal->inputAttemptWhenModal();
  234657. }
  234658. return true;
  234659. }
  234660. }
  234661. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234662. {
  234663. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234664. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234665. while (! quitMessagePosted)
  234666. {
  234667. const ScopedAutoReleasePool pool;
  234668. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234669. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234670. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234671. inMode: NSDefaultRunLoopMode
  234672. dequeue: YES];
  234673. if (e != 0 && ! isEventBlockedByModalComps (e))
  234674. [NSApp sendEvent: e];
  234675. if (Time::getMillisecondCounter() >= endTime)
  234676. break;
  234677. }
  234678. return ! quitMessagePosted;
  234679. }
  234680. void MessageManager::doPlatformSpecificInitialisation()
  234681. {
  234682. if (juceAppDelegate == 0)
  234683. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234684. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234685. // correctly (needed prior to 10.5)
  234686. if (! [NSThread isMultiThreaded])
  234687. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234688. toTarget: juceAppDelegate
  234689. withObject: nil];
  234690. }
  234691. void MessageManager::doPlatformSpecificShutdown()
  234692. {
  234693. if (juceAppDelegate != 0)
  234694. {
  234695. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234696. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234697. [juceAppDelegate release];
  234698. juceAppDelegate = 0;
  234699. }
  234700. }
  234701. bool juce_postMessageToSystemQueue (Message* message)
  234702. {
  234703. juceAppDelegate->redirector->postMessage (message);
  234704. return true;
  234705. }
  234706. void MessageManager::broadcastMessage (const String&)
  234707. {
  234708. }
  234709. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234710. {
  234711. if (isThisTheMessageThread())
  234712. {
  234713. return (*callback) (data);
  234714. }
  234715. else
  234716. {
  234717. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234718. // deadlock because the message manager is blocked from running, so can never
  234719. // call your function..
  234720. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234721. const ScopedAutoReleasePool pool;
  234722. AppDelegateRedirector::CallbackMessagePayload cmp;
  234723. cmp.function = callback;
  234724. cmp.parameter = data;
  234725. cmp.result = 0;
  234726. cmp.hasBeenExecuted = false;
  234727. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234728. withObject: [NSData dataWithBytesNoCopy: &cmp
  234729. length: sizeof (cmp)
  234730. freeWhenDone: NO]
  234731. waitUntilDone: YES];
  234732. return cmp.result;
  234733. }
  234734. }
  234735. #endif
  234736. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234737. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234738. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234739. // compiled on its own).
  234740. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234741. #if JUCE_MAC
  234742. END_JUCE_NAMESPACE
  234743. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234744. @interface DownloadClickDetector : NSObject
  234745. {
  234746. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234747. }
  234748. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234749. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234750. request: (NSURLRequest*) request
  234751. frame: (WebFrame*) frame
  234752. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234753. @end
  234754. @implementation DownloadClickDetector
  234755. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234756. {
  234757. [super init];
  234758. ownerComponent = ownerComponent_;
  234759. return self;
  234760. }
  234761. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234762. request: (NSURLRequest*) request
  234763. frame: (WebFrame*) frame
  234764. decisionListener: (id <WebPolicyDecisionListener>) listener
  234765. {
  234766. (void) sender;
  234767. (void) request;
  234768. (void) frame;
  234769. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234770. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234771. [listener use];
  234772. else
  234773. [listener ignore];
  234774. }
  234775. @end
  234776. BEGIN_JUCE_NAMESPACE
  234777. class WebBrowserComponentInternal : public NSViewComponent
  234778. {
  234779. public:
  234780. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234781. {
  234782. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234783. frameName: @""
  234784. groupName: @""];
  234785. setView (webView);
  234786. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234787. [webView setPolicyDelegate: clickListener];
  234788. }
  234789. ~WebBrowserComponentInternal()
  234790. {
  234791. [webView setPolicyDelegate: nil];
  234792. [clickListener release];
  234793. setView (0);
  234794. }
  234795. void goToURL (const String& url,
  234796. const StringArray* headers,
  234797. const MemoryBlock* postData)
  234798. {
  234799. NSMutableURLRequest* r
  234800. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234801. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234802. timeoutInterval: 30.0];
  234803. if (postData != 0 && postData->getSize() > 0)
  234804. {
  234805. [r setHTTPMethod: @"POST"];
  234806. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234807. length: postData->getSize()]];
  234808. }
  234809. if (headers != 0)
  234810. {
  234811. for (int i = 0; i < headers->size(); ++i)
  234812. {
  234813. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234814. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234815. [r setValue: juceStringToNS (headerValue)
  234816. forHTTPHeaderField: juceStringToNS (headerName)];
  234817. }
  234818. }
  234819. stop();
  234820. [[webView mainFrame] loadRequest: r];
  234821. }
  234822. void goBack()
  234823. {
  234824. [webView goBack];
  234825. }
  234826. void goForward()
  234827. {
  234828. [webView goForward];
  234829. }
  234830. void stop()
  234831. {
  234832. [webView stopLoading: nil];
  234833. }
  234834. void refresh()
  234835. {
  234836. [webView reload: nil];
  234837. }
  234838. void mouseMove (const MouseEvent&)
  234839. {
  234840. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234841. // them work is to push them via this non-public method..
  234842. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234843. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234844. }
  234845. private:
  234846. WebView* webView;
  234847. DownloadClickDetector* clickListener;
  234848. };
  234849. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234850. : browser (0),
  234851. blankPageShown (false),
  234852. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234853. {
  234854. setOpaque (true);
  234855. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234856. }
  234857. WebBrowserComponent::~WebBrowserComponent()
  234858. {
  234859. deleteAndZero (browser);
  234860. }
  234861. void WebBrowserComponent::goToURL (const String& url,
  234862. const StringArray* headers,
  234863. const MemoryBlock* postData)
  234864. {
  234865. lastURL = url;
  234866. lastHeaders.clear();
  234867. if (headers != 0)
  234868. lastHeaders = *headers;
  234869. lastPostData.setSize (0);
  234870. if (postData != 0)
  234871. lastPostData = *postData;
  234872. blankPageShown = false;
  234873. browser->goToURL (url, headers, postData);
  234874. }
  234875. void WebBrowserComponent::stop()
  234876. {
  234877. browser->stop();
  234878. }
  234879. void WebBrowserComponent::goBack()
  234880. {
  234881. lastURL = String::empty;
  234882. blankPageShown = false;
  234883. browser->goBack();
  234884. }
  234885. void WebBrowserComponent::goForward()
  234886. {
  234887. lastURL = String::empty;
  234888. browser->goForward();
  234889. }
  234890. void WebBrowserComponent::refresh()
  234891. {
  234892. browser->refresh();
  234893. }
  234894. void WebBrowserComponent::paint (Graphics&)
  234895. {
  234896. }
  234897. void WebBrowserComponent::checkWindowAssociation()
  234898. {
  234899. if (isShowing())
  234900. {
  234901. if (blankPageShown)
  234902. goBack();
  234903. }
  234904. else
  234905. {
  234906. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234907. {
  234908. // when the component becomes invisible, some stuff like flash
  234909. // carries on playing audio, so we need to force it onto a blank
  234910. // page to avoid this, (and send it back when it's made visible again).
  234911. blankPageShown = true;
  234912. browser->goToURL ("about:blank", 0, 0);
  234913. }
  234914. }
  234915. }
  234916. void WebBrowserComponent::reloadLastURL()
  234917. {
  234918. if (lastURL.isNotEmpty())
  234919. {
  234920. goToURL (lastURL, &lastHeaders, &lastPostData);
  234921. lastURL = String::empty;
  234922. }
  234923. }
  234924. void WebBrowserComponent::parentHierarchyChanged()
  234925. {
  234926. checkWindowAssociation();
  234927. }
  234928. void WebBrowserComponent::resized()
  234929. {
  234930. browser->setSize (getWidth(), getHeight());
  234931. }
  234932. void WebBrowserComponent::visibilityChanged()
  234933. {
  234934. checkWindowAssociation();
  234935. }
  234936. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234937. {
  234938. return true;
  234939. }
  234940. #else
  234941. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234942. {
  234943. }
  234944. WebBrowserComponent::~WebBrowserComponent()
  234945. {
  234946. }
  234947. void WebBrowserComponent::goToURL (const String& url,
  234948. const StringArray* headers,
  234949. const MemoryBlock* postData)
  234950. {
  234951. }
  234952. void WebBrowserComponent::stop()
  234953. {
  234954. }
  234955. void WebBrowserComponent::goBack()
  234956. {
  234957. }
  234958. void WebBrowserComponent::goForward()
  234959. {
  234960. }
  234961. void WebBrowserComponent::refresh()
  234962. {
  234963. }
  234964. void WebBrowserComponent::paint (Graphics& g)
  234965. {
  234966. }
  234967. void WebBrowserComponent::checkWindowAssociation()
  234968. {
  234969. }
  234970. void WebBrowserComponent::reloadLastURL()
  234971. {
  234972. }
  234973. void WebBrowserComponent::parentHierarchyChanged()
  234974. {
  234975. }
  234976. void WebBrowserComponent::resized()
  234977. {
  234978. }
  234979. void WebBrowserComponent::visibilityChanged()
  234980. {
  234981. }
  234982. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234983. {
  234984. return true;
  234985. }
  234986. #endif
  234987. #endif
  234988. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234989. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234990. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234991. // compiled on its own).
  234992. #if JUCE_INCLUDED_FILE
  234993. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234994. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234995. #endif
  234996. #undef log
  234997. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234998. #define log(a) Logger::writeToLog (a)
  234999. #else
  235000. #define log(a)
  235001. #endif
  235002. #undef OK
  235003. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235004. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235005. {
  235006. if (err == noErr)
  235007. return true;
  235008. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235009. jassertfalse;
  235010. return false;
  235011. }
  235012. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235013. #else
  235014. #define OK(a) (a == noErr)
  235015. #endif
  235016. class CoreAudioInternal : public Timer
  235017. {
  235018. public:
  235019. CoreAudioInternal (AudioDeviceID id)
  235020. : inputLatency (0),
  235021. outputLatency (0),
  235022. callback (0),
  235023. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235024. audioProcID (0),
  235025. #endif
  235026. isSlaveDevice (false),
  235027. deviceID (id),
  235028. started (false),
  235029. sampleRate (0),
  235030. bufferSize (512),
  235031. numInputChans (0),
  235032. numOutputChans (0),
  235033. callbacksAllowed (true),
  235034. numInputChannelInfos (0),
  235035. numOutputChannelInfos (0)
  235036. {
  235037. jassert (deviceID != 0);
  235038. updateDetailsFromDevice();
  235039. AudioObjectPropertyAddress pa;
  235040. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235041. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235042. pa.mElement = kAudioObjectPropertyElementWildcard;
  235043. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235044. }
  235045. ~CoreAudioInternal()
  235046. {
  235047. AudioObjectPropertyAddress pa;
  235048. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235049. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235050. pa.mElement = kAudioObjectPropertyElementWildcard;
  235051. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235052. stop (false);
  235053. }
  235054. void allocateTempBuffers()
  235055. {
  235056. const int tempBufSize = bufferSize + 4;
  235057. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235058. tempInputBuffers.calloc (numInputChans + 2);
  235059. tempOutputBuffers.calloc (numOutputChans + 2);
  235060. int i, count = 0;
  235061. for (i = 0; i < numInputChans; ++i)
  235062. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235063. for (i = 0; i < numOutputChans; ++i)
  235064. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235065. }
  235066. // returns the number of actual available channels
  235067. void fillInChannelInfo (const bool input)
  235068. {
  235069. int chanNum = 0;
  235070. UInt32 size;
  235071. AudioObjectPropertyAddress pa;
  235072. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235073. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235074. pa.mElement = kAudioObjectPropertyElementMaster;
  235075. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235076. {
  235077. HeapBlock <AudioBufferList> bufList;
  235078. bufList.calloc (size, 1);
  235079. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235080. {
  235081. const int numStreams = bufList->mNumberBuffers;
  235082. for (int i = 0; i < numStreams; ++i)
  235083. {
  235084. const AudioBuffer& b = bufList->mBuffers[i];
  235085. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235086. {
  235087. String name;
  235088. {
  235089. char channelName [256];
  235090. zerostruct (channelName);
  235091. UInt32 nameSize = sizeof (channelName);
  235092. UInt32 channelNum = chanNum + 1;
  235093. pa.mSelector = kAudioDevicePropertyChannelName;
  235094. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235095. name = String::fromUTF8 (channelName, nameSize);
  235096. }
  235097. if (input)
  235098. {
  235099. if (activeInputChans[chanNum])
  235100. {
  235101. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235102. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235103. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235104. ++numInputChannelInfos;
  235105. }
  235106. if (name.isEmpty())
  235107. name << "Input " << (chanNum + 1);
  235108. inChanNames.add (name);
  235109. }
  235110. else
  235111. {
  235112. if (activeOutputChans[chanNum])
  235113. {
  235114. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235115. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235116. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235117. ++numOutputChannelInfos;
  235118. }
  235119. if (name.isEmpty())
  235120. name << "Output " << (chanNum + 1);
  235121. outChanNames.add (name);
  235122. }
  235123. ++chanNum;
  235124. }
  235125. }
  235126. }
  235127. }
  235128. }
  235129. void updateDetailsFromDevice()
  235130. {
  235131. stopTimer();
  235132. if (deviceID == 0)
  235133. return;
  235134. const ScopedLock sl (callbackLock);
  235135. Float64 sr;
  235136. UInt32 size = sizeof (Float64);
  235137. AudioObjectPropertyAddress pa;
  235138. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235139. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235140. pa.mElement = kAudioObjectPropertyElementMaster;
  235141. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235142. sampleRate = sr;
  235143. UInt32 framesPerBuf;
  235144. size = sizeof (framesPerBuf);
  235145. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235146. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235147. {
  235148. bufferSize = framesPerBuf;
  235149. allocateTempBuffers();
  235150. }
  235151. bufferSizes.clear();
  235152. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235153. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235154. {
  235155. HeapBlock <AudioValueRange> ranges;
  235156. ranges.calloc (size, 1);
  235157. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235158. {
  235159. bufferSizes.add ((int) ranges[0].mMinimum);
  235160. for (int i = 32; i < 2048; i += 32)
  235161. {
  235162. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235163. {
  235164. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235165. {
  235166. bufferSizes.addIfNotAlreadyThere (i);
  235167. break;
  235168. }
  235169. }
  235170. }
  235171. if (bufferSize > 0)
  235172. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235173. }
  235174. }
  235175. if (bufferSizes.size() == 0 && bufferSize > 0)
  235176. bufferSizes.add (bufferSize);
  235177. sampleRates.clear();
  235178. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235179. String rates;
  235180. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235181. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235182. {
  235183. HeapBlock <AudioValueRange> ranges;
  235184. ranges.calloc (size, 1);
  235185. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235186. {
  235187. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235188. {
  235189. bool ok = false;
  235190. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235191. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235192. ok = true;
  235193. if (ok)
  235194. {
  235195. sampleRates.add (possibleRates[i]);
  235196. rates << possibleRates[i] << ' ';
  235197. }
  235198. }
  235199. }
  235200. }
  235201. if (sampleRates.size() == 0 && sampleRate > 0)
  235202. {
  235203. sampleRates.add (sampleRate);
  235204. rates << sampleRate;
  235205. }
  235206. log ("sr: " + rates);
  235207. inputLatency = 0;
  235208. outputLatency = 0;
  235209. UInt32 lat;
  235210. size = sizeof (lat);
  235211. pa.mSelector = kAudioDevicePropertyLatency;
  235212. pa.mScope = kAudioDevicePropertyScopeInput;
  235213. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235214. inputLatency = (int) lat;
  235215. pa.mScope = kAudioDevicePropertyScopeOutput;
  235216. size = sizeof (lat);
  235217. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235218. outputLatency = (int) lat;
  235219. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235220. inChanNames.clear();
  235221. outChanNames.clear();
  235222. inputChannelInfo.calloc (numInputChans + 2);
  235223. numInputChannelInfos = 0;
  235224. outputChannelInfo.calloc (numOutputChans + 2);
  235225. numOutputChannelInfos = 0;
  235226. fillInChannelInfo (true);
  235227. fillInChannelInfo (false);
  235228. }
  235229. const StringArray getSources (bool input)
  235230. {
  235231. StringArray s;
  235232. HeapBlock <OSType> types;
  235233. const int num = getAllDataSourcesForDevice (deviceID, types);
  235234. for (int i = 0; i < num; ++i)
  235235. {
  235236. AudioValueTranslation avt;
  235237. char buffer[256];
  235238. avt.mInputData = &(types[i]);
  235239. avt.mInputDataSize = sizeof (UInt32);
  235240. avt.mOutputData = buffer;
  235241. avt.mOutputDataSize = 256;
  235242. UInt32 transSize = sizeof (avt);
  235243. AudioObjectPropertyAddress pa;
  235244. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235245. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235246. pa.mElement = kAudioObjectPropertyElementMaster;
  235247. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235248. {
  235249. DBG (buffer);
  235250. s.add (buffer);
  235251. }
  235252. }
  235253. return s;
  235254. }
  235255. int getCurrentSourceIndex (bool input) const
  235256. {
  235257. OSType currentSourceID = 0;
  235258. UInt32 size = sizeof (currentSourceID);
  235259. int result = -1;
  235260. AudioObjectPropertyAddress pa;
  235261. pa.mSelector = kAudioDevicePropertyDataSource;
  235262. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235263. pa.mElement = kAudioObjectPropertyElementMaster;
  235264. if (deviceID != 0)
  235265. {
  235266. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235267. {
  235268. HeapBlock <OSType> types;
  235269. const int num = getAllDataSourcesForDevice (deviceID, types);
  235270. for (int i = 0; i < num; ++i)
  235271. {
  235272. if (types[num] == currentSourceID)
  235273. {
  235274. result = i;
  235275. break;
  235276. }
  235277. }
  235278. }
  235279. }
  235280. return result;
  235281. }
  235282. void setCurrentSourceIndex (int index, bool input)
  235283. {
  235284. if (deviceID != 0)
  235285. {
  235286. HeapBlock <OSType> types;
  235287. const int num = getAllDataSourcesForDevice (deviceID, types);
  235288. if (isPositiveAndBelow (index, num))
  235289. {
  235290. AudioObjectPropertyAddress pa;
  235291. pa.mSelector = kAudioDevicePropertyDataSource;
  235292. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235293. pa.mElement = kAudioObjectPropertyElementMaster;
  235294. OSType typeId = types[index];
  235295. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235296. }
  235297. }
  235298. }
  235299. const String reopen (const BigInteger& inputChannels,
  235300. const BigInteger& outputChannels,
  235301. double newSampleRate,
  235302. int bufferSizeSamples)
  235303. {
  235304. String error;
  235305. log ("CoreAudio reopen");
  235306. callbacksAllowed = false;
  235307. stopTimer();
  235308. stop (false);
  235309. activeInputChans = inputChannels;
  235310. activeInputChans.setRange (inChanNames.size(),
  235311. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235312. false);
  235313. activeOutputChans = outputChannels;
  235314. activeOutputChans.setRange (outChanNames.size(),
  235315. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235316. false);
  235317. numInputChans = activeInputChans.countNumberOfSetBits();
  235318. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235319. // set sample rate
  235320. AudioObjectPropertyAddress pa;
  235321. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235322. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235323. pa.mElement = kAudioObjectPropertyElementMaster;
  235324. Float64 sr = newSampleRate;
  235325. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235326. {
  235327. error = "Couldn't change sample rate";
  235328. }
  235329. else
  235330. {
  235331. // change buffer size
  235332. UInt32 framesPerBuf = bufferSizeSamples;
  235333. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235334. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235335. {
  235336. error = "Couldn't change buffer size";
  235337. }
  235338. else
  235339. {
  235340. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235341. // correctly report their new settings until some random time in the future, so
  235342. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235343. // to make sure we're using the correct numbers..
  235344. updateDetailsFromDevice();
  235345. sampleRate = newSampleRate;
  235346. bufferSize = bufferSizeSamples;
  235347. if (sampleRates.size() == 0)
  235348. error = "Device has no available sample-rates";
  235349. else if (bufferSizes.size() == 0)
  235350. error = "Device has no available buffer-sizes";
  235351. else if (inputDevice != 0)
  235352. error = inputDevice->reopen (inputChannels,
  235353. outputChannels,
  235354. newSampleRate,
  235355. bufferSizeSamples);
  235356. }
  235357. }
  235358. callbacksAllowed = true;
  235359. return error;
  235360. }
  235361. bool start (AudioIODeviceCallback* cb)
  235362. {
  235363. if (! started)
  235364. {
  235365. callback = 0;
  235366. if (deviceID != 0)
  235367. {
  235368. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235369. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235370. #else
  235371. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235372. #endif
  235373. {
  235374. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235375. {
  235376. started = true;
  235377. }
  235378. else
  235379. {
  235380. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235381. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235382. #else
  235383. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235384. audioProcID = 0;
  235385. #endif
  235386. }
  235387. }
  235388. }
  235389. }
  235390. if (started)
  235391. {
  235392. const ScopedLock sl (callbackLock);
  235393. callback = cb;
  235394. }
  235395. if (inputDevice != 0)
  235396. return started && inputDevice->start (cb);
  235397. else
  235398. return started;
  235399. }
  235400. void stop (bool leaveInterruptRunning)
  235401. {
  235402. {
  235403. const ScopedLock sl (callbackLock);
  235404. callback = 0;
  235405. }
  235406. if (started
  235407. && (deviceID != 0)
  235408. && ! leaveInterruptRunning)
  235409. {
  235410. OK (AudioDeviceStop (deviceID, audioIOProc));
  235411. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235412. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235413. #else
  235414. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235415. audioProcID = 0;
  235416. #endif
  235417. started = false;
  235418. { const ScopedLock sl (callbackLock); }
  235419. // wait until it's definately stopped calling back..
  235420. for (int i = 40; --i >= 0;)
  235421. {
  235422. Thread::sleep (50);
  235423. UInt32 running = 0;
  235424. UInt32 size = sizeof (running);
  235425. AudioObjectPropertyAddress pa;
  235426. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235427. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235428. pa.mElement = kAudioObjectPropertyElementMaster;
  235429. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235430. if (running == 0)
  235431. break;
  235432. }
  235433. const ScopedLock sl (callbackLock);
  235434. }
  235435. if (inputDevice != 0)
  235436. inputDevice->stop (leaveInterruptRunning);
  235437. }
  235438. double getSampleRate() const
  235439. {
  235440. return sampleRate;
  235441. }
  235442. int getBufferSize() const
  235443. {
  235444. return bufferSize;
  235445. }
  235446. void audioCallback (const AudioBufferList* inInputData,
  235447. AudioBufferList* outOutputData)
  235448. {
  235449. int i;
  235450. const ScopedLock sl (callbackLock);
  235451. if (callback != 0)
  235452. {
  235453. if (inputDevice == 0)
  235454. {
  235455. for (i = numInputChans; --i >= 0;)
  235456. {
  235457. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235458. float* dest = tempInputBuffers [i];
  235459. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235460. + info.dataOffsetSamples;
  235461. const int stride = info.dataStrideSamples;
  235462. if (stride != 0) // if this is zero, info is invalid
  235463. {
  235464. for (int j = bufferSize; --j >= 0;)
  235465. {
  235466. *dest++ = *src;
  235467. src += stride;
  235468. }
  235469. }
  235470. }
  235471. }
  235472. if (! isSlaveDevice)
  235473. {
  235474. if (inputDevice == 0)
  235475. {
  235476. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235477. numInputChans,
  235478. tempOutputBuffers,
  235479. numOutputChans,
  235480. bufferSize);
  235481. }
  235482. else
  235483. {
  235484. jassert (inputDevice->bufferSize == bufferSize);
  235485. // Sometimes the two linked devices seem to get their callbacks in
  235486. // parallel, so we need to lock both devices to stop the input data being
  235487. // changed while inside our callback..
  235488. const ScopedLock sl2 (inputDevice->callbackLock);
  235489. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235490. inputDevice->numInputChans,
  235491. tempOutputBuffers,
  235492. numOutputChans,
  235493. bufferSize);
  235494. }
  235495. for (i = numOutputChans; --i >= 0;)
  235496. {
  235497. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235498. const float* src = tempOutputBuffers [i];
  235499. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235500. + info.dataOffsetSamples;
  235501. const int stride = info.dataStrideSamples;
  235502. if (stride != 0) // if this is zero, info is invalid
  235503. {
  235504. for (int j = bufferSize; --j >= 0;)
  235505. {
  235506. *dest = *src++;
  235507. dest += stride;
  235508. }
  235509. }
  235510. }
  235511. }
  235512. }
  235513. else
  235514. {
  235515. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235516. {
  235517. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235518. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235519. + info.dataOffsetSamples;
  235520. const int stride = info.dataStrideSamples;
  235521. if (stride != 0) // if this is zero, info is invalid
  235522. {
  235523. for (int j = bufferSize; --j >= 0;)
  235524. {
  235525. *dest = 0.0f;
  235526. dest += stride;
  235527. }
  235528. }
  235529. }
  235530. }
  235531. }
  235532. // called by callbacks
  235533. void deviceDetailsChanged()
  235534. {
  235535. if (callbacksAllowed)
  235536. startTimer (100);
  235537. }
  235538. void timerCallback()
  235539. {
  235540. stopTimer();
  235541. log ("CoreAudio device changed callback");
  235542. const double oldSampleRate = sampleRate;
  235543. const int oldBufferSize = bufferSize;
  235544. updateDetailsFromDevice();
  235545. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235546. {
  235547. callbacksAllowed = false;
  235548. stop (false);
  235549. updateDetailsFromDevice();
  235550. callbacksAllowed = true;
  235551. }
  235552. }
  235553. CoreAudioInternal* getRelatedDevice() const
  235554. {
  235555. UInt32 size = 0;
  235556. ScopedPointer <CoreAudioInternal> result;
  235557. AudioObjectPropertyAddress pa;
  235558. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235559. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235560. pa.mElement = kAudioObjectPropertyElementMaster;
  235561. if (deviceID != 0
  235562. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235563. && size > 0)
  235564. {
  235565. HeapBlock <AudioDeviceID> devs;
  235566. devs.calloc (size, 1);
  235567. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235568. {
  235569. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235570. {
  235571. if (devs[i] != deviceID && devs[i] != 0)
  235572. {
  235573. result = new CoreAudioInternal (devs[i]);
  235574. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235575. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235576. if (thisIsInput != otherIsInput
  235577. || (inChanNames.size() + outChanNames.size() == 0)
  235578. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235579. break;
  235580. result = 0;
  235581. }
  235582. }
  235583. }
  235584. }
  235585. return result.release();
  235586. }
  235587. int inputLatency, outputLatency;
  235588. BigInteger activeInputChans, activeOutputChans;
  235589. StringArray inChanNames, outChanNames;
  235590. Array <double> sampleRates;
  235591. Array <int> bufferSizes;
  235592. AudioIODeviceCallback* callback;
  235593. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235594. AudioDeviceIOProcID audioProcID;
  235595. #endif
  235596. ScopedPointer<CoreAudioInternal> inputDevice;
  235597. bool isSlaveDevice;
  235598. private:
  235599. CriticalSection callbackLock;
  235600. AudioDeviceID deviceID;
  235601. bool started;
  235602. double sampleRate;
  235603. int bufferSize;
  235604. HeapBlock <float> audioBuffer;
  235605. int numInputChans, numOutputChans;
  235606. bool callbacksAllowed;
  235607. struct CallbackDetailsForChannel
  235608. {
  235609. int streamNum;
  235610. int dataOffsetSamples;
  235611. int dataStrideSamples;
  235612. };
  235613. int numInputChannelInfos, numOutputChannelInfos;
  235614. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235615. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235616. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235617. const AudioTimeStamp* /*inNow*/,
  235618. const AudioBufferList* inInputData,
  235619. const AudioTimeStamp* /*inInputTime*/,
  235620. AudioBufferList* outOutputData,
  235621. const AudioTimeStamp* /*inOutputTime*/,
  235622. void* device)
  235623. {
  235624. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235625. return noErr;
  235626. }
  235627. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235628. {
  235629. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235630. switch (pa->mSelector)
  235631. {
  235632. case kAudioDevicePropertyBufferSize:
  235633. case kAudioDevicePropertyBufferFrameSize:
  235634. case kAudioDevicePropertyNominalSampleRate:
  235635. case kAudioDevicePropertyStreamFormat:
  235636. case kAudioDevicePropertyDeviceIsAlive:
  235637. intern->deviceDetailsChanged();
  235638. break;
  235639. case kAudioDevicePropertyBufferSizeRange:
  235640. case kAudioDevicePropertyVolumeScalar:
  235641. case kAudioDevicePropertyMute:
  235642. case kAudioDevicePropertyPlayThru:
  235643. case kAudioDevicePropertyDataSource:
  235644. case kAudioDevicePropertyDeviceIsRunning:
  235645. break;
  235646. }
  235647. return noErr;
  235648. }
  235649. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235650. {
  235651. AudioObjectPropertyAddress pa;
  235652. pa.mSelector = kAudioDevicePropertyDataSources;
  235653. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235654. pa.mElement = kAudioObjectPropertyElementMaster;
  235655. UInt32 size = 0;
  235656. if (deviceID != 0
  235657. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235658. {
  235659. types.calloc (size, 1);
  235660. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235661. return size / (int) sizeof (OSType);
  235662. }
  235663. return 0;
  235664. }
  235665. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235666. };
  235667. class CoreAudioIODevice : public AudioIODevice
  235668. {
  235669. public:
  235670. CoreAudioIODevice (const String& deviceName,
  235671. AudioDeviceID inputDeviceId,
  235672. const int inputIndex_,
  235673. AudioDeviceID outputDeviceId,
  235674. const int outputIndex_)
  235675. : AudioIODevice (deviceName, "CoreAudio"),
  235676. inputIndex (inputIndex_),
  235677. outputIndex (outputIndex_),
  235678. isOpen_ (false),
  235679. isStarted (false)
  235680. {
  235681. CoreAudioInternal* device = 0;
  235682. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235683. {
  235684. jassert (inputDeviceId != 0);
  235685. device = new CoreAudioInternal (inputDeviceId);
  235686. }
  235687. else
  235688. {
  235689. device = new CoreAudioInternal (outputDeviceId);
  235690. if (inputDeviceId != 0)
  235691. {
  235692. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235693. device->inputDevice = secondDevice;
  235694. secondDevice->isSlaveDevice = true;
  235695. }
  235696. }
  235697. internal = device;
  235698. AudioObjectPropertyAddress pa;
  235699. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235700. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235701. pa.mElement = kAudioObjectPropertyElementWildcard;
  235702. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235703. }
  235704. ~CoreAudioIODevice()
  235705. {
  235706. AudioObjectPropertyAddress pa;
  235707. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235708. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235709. pa.mElement = kAudioObjectPropertyElementWildcard;
  235710. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235711. }
  235712. const StringArray getOutputChannelNames()
  235713. {
  235714. return internal->outChanNames;
  235715. }
  235716. const StringArray getInputChannelNames()
  235717. {
  235718. if (internal->inputDevice != 0)
  235719. return internal->inputDevice->inChanNames;
  235720. else
  235721. return internal->inChanNames;
  235722. }
  235723. int getNumSampleRates()
  235724. {
  235725. return internal->sampleRates.size();
  235726. }
  235727. double getSampleRate (int index)
  235728. {
  235729. return internal->sampleRates [index];
  235730. }
  235731. int getNumBufferSizesAvailable()
  235732. {
  235733. return internal->bufferSizes.size();
  235734. }
  235735. int getBufferSizeSamples (int index)
  235736. {
  235737. return internal->bufferSizes [index];
  235738. }
  235739. int getDefaultBufferSize()
  235740. {
  235741. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235742. if (getBufferSizeSamples(i) >= 512)
  235743. return getBufferSizeSamples(i);
  235744. return 512;
  235745. }
  235746. const String open (const BigInteger& inputChannels,
  235747. const BigInteger& outputChannels,
  235748. double sampleRate,
  235749. int bufferSizeSamples)
  235750. {
  235751. isOpen_ = true;
  235752. if (bufferSizeSamples <= 0)
  235753. bufferSizeSamples = getDefaultBufferSize();
  235754. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235755. isOpen_ = lastError.isEmpty();
  235756. return lastError;
  235757. }
  235758. void close()
  235759. {
  235760. isOpen_ = false;
  235761. internal->stop (false);
  235762. }
  235763. bool isOpen()
  235764. {
  235765. return isOpen_;
  235766. }
  235767. int getCurrentBufferSizeSamples()
  235768. {
  235769. return internal != 0 ? internal->getBufferSize() : 512;
  235770. }
  235771. double getCurrentSampleRate()
  235772. {
  235773. return internal != 0 ? internal->getSampleRate() : 0;
  235774. }
  235775. int getCurrentBitDepth()
  235776. {
  235777. return 32; // no way to find out, so just assume it's high..
  235778. }
  235779. const BigInteger getActiveOutputChannels() const
  235780. {
  235781. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235782. }
  235783. const BigInteger getActiveInputChannels() const
  235784. {
  235785. BigInteger chans;
  235786. if (internal != 0)
  235787. {
  235788. chans = internal->activeInputChans;
  235789. if (internal->inputDevice != 0)
  235790. chans |= internal->inputDevice->activeInputChans;
  235791. }
  235792. return chans;
  235793. }
  235794. int getOutputLatencyInSamples()
  235795. {
  235796. if (internal == 0)
  235797. return 0;
  235798. // this seems like a good guess at getting the latency right - comparing
  235799. // this with a round-trip measurement, it gets it to within a few millisecs
  235800. // for the built-in mac soundcard
  235801. return internal->outputLatency + internal->getBufferSize() * 2;
  235802. }
  235803. int getInputLatencyInSamples()
  235804. {
  235805. if (internal == 0)
  235806. return 0;
  235807. return internal->inputLatency + internal->getBufferSize() * 2;
  235808. }
  235809. void start (AudioIODeviceCallback* callback)
  235810. {
  235811. if (internal != 0 && ! isStarted)
  235812. {
  235813. if (callback != 0)
  235814. callback->audioDeviceAboutToStart (this);
  235815. isStarted = true;
  235816. internal->start (callback);
  235817. }
  235818. }
  235819. void stop()
  235820. {
  235821. if (isStarted && internal != 0)
  235822. {
  235823. AudioIODeviceCallback* const lastCallback = internal->callback;
  235824. isStarted = false;
  235825. internal->stop (true);
  235826. if (lastCallback != 0)
  235827. lastCallback->audioDeviceStopped();
  235828. }
  235829. }
  235830. bool isPlaying()
  235831. {
  235832. if (internal->callback == 0)
  235833. isStarted = false;
  235834. return isStarted;
  235835. }
  235836. const String getLastError()
  235837. {
  235838. return lastError;
  235839. }
  235840. int inputIndex, outputIndex;
  235841. private:
  235842. ScopedPointer<CoreAudioInternal> internal;
  235843. bool isOpen_, isStarted;
  235844. String lastError;
  235845. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235846. {
  235847. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235848. switch (pa->mSelector)
  235849. {
  235850. case kAudioHardwarePropertyDevices:
  235851. intern->deviceDetailsChanged();
  235852. break;
  235853. case kAudioHardwarePropertyDefaultOutputDevice:
  235854. case kAudioHardwarePropertyDefaultInputDevice:
  235855. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235856. break;
  235857. }
  235858. return noErr;
  235859. }
  235860. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235861. };
  235862. class CoreAudioIODeviceType : public AudioIODeviceType
  235863. {
  235864. public:
  235865. CoreAudioIODeviceType()
  235866. : AudioIODeviceType ("CoreAudio"),
  235867. hasScanned (false)
  235868. {
  235869. }
  235870. ~CoreAudioIODeviceType()
  235871. {
  235872. }
  235873. void scanForDevices()
  235874. {
  235875. hasScanned = true;
  235876. inputDeviceNames.clear();
  235877. outputDeviceNames.clear();
  235878. inputIds.clear();
  235879. outputIds.clear();
  235880. UInt32 size;
  235881. AudioObjectPropertyAddress pa;
  235882. pa.mSelector = kAudioHardwarePropertyDevices;
  235883. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235884. pa.mElement = kAudioObjectPropertyElementMaster;
  235885. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235886. {
  235887. HeapBlock <AudioDeviceID> devs;
  235888. devs.calloc (size, 1);
  235889. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235890. {
  235891. const int num = size / (int) sizeof (AudioDeviceID);
  235892. for (int i = 0; i < num; ++i)
  235893. {
  235894. char name [1024];
  235895. size = sizeof (name);
  235896. pa.mSelector = kAudioDevicePropertyDeviceName;
  235897. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235898. {
  235899. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235900. const int numIns = getNumChannels (devs[i], true);
  235901. const int numOuts = getNumChannels (devs[i], false);
  235902. if (numIns > 0)
  235903. {
  235904. inputDeviceNames.add (nameString);
  235905. inputIds.add (devs[i]);
  235906. }
  235907. if (numOuts > 0)
  235908. {
  235909. outputDeviceNames.add (nameString);
  235910. outputIds.add (devs[i]);
  235911. }
  235912. }
  235913. }
  235914. }
  235915. }
  235916. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235917. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235918. }
  235919. const StringArray getDeviceNames (bool wantInputNames) const
  235920. {
  235921. jassert (hasScanned); // need to call scanForDevices() before doing this
  235922. if (wantInputNames)
  235923. return inputDeviceNames;
  235924. else
  235925. return outputDeviceNames;
  235926. }
  235927. int getDefaultDeviceIndex (bool forInput) const
  235928. {
  235929. jassert (hasScanned); // need to call scanForDevices() before doing this
  235930. AudioDeviceID deviceID;
  235931. UInt32 size = sizeof (deviceID);
  235932. // if they're asking for any input channels at all, use the default input, so we
  235933. // get the built-in mic rather than the built-in output with no inputs..
  235934. AudioObjectPropertyAddress pa;
  235935. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235936. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235937. pa.mElement = kAudioObjectPropertyElementMaster;
  235938. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235939. {
  235940. if (forInput)
  235941. {
  235942. for (int i = inputIds.size(); --i >= 0;)
  235943. if (inputIds[i] == deviceID)
  235944. return i;
  235945. }
  235946. else
  235947. {
  235948. for (int i = outputIds.size(); --i >= 0;)
  235949. if (outputIds[i] == deviceID)
  235950. return i;
  235951. }
  235952. }
  235953. return 0;
  235954. }
  235955. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235956. {
  235957. jassert (hasScanned); // need to call scanForDevices() before doing this
  235958. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235959. if (d == 0)
  235960. return -1;
  235961. return asInput ? d->inputIndex
  235962. : d->outputIndex;
  235963. }
  235964. bool hasSeparateInputsAndOutputs() const { return true; }
  235965. AudioIODevice* createDevice (const String& outputDeviceName,
  235966. const String& inputDeviceName)
  235967. {
  235968. jassert (hasScanned); // need to call scanForDevices() before doing this
  235969. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235970. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235971. String deviceName (outputDeviceName);
  235972. if (deviceName.isEmpty())
  235973. deviceName = inputDeviceName;
  235974. if (index >= 0)
  235975. return new CoreAudioIODevice (deviceName,
  235976. inputIds [inputIndex],
  235977. inputIndex,
  235978. outputIds [outputIndex],
  235979. outputIndex);
  235980. return 0;
  235981. }
  235982. private:
  235983. StringArray inputDeviceNames, outputDeviceNames;
  235984. Array <AudioDeviceID> inputIds, outputIds;
  235985. bool hasScanned;
  235986. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235987. {
  235988. int total = 0;
  235989. UInt32 size;
  235990. AudioObjectPropertyAddress pa;
  235991. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235992. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235993. pa.mElement = kAudioObjectPropertyElementMaster;
  235994. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235995. {
  235996. HeapBlock <AudioBufferList> bufList;
  235997. bufList.calloc (size, 1);
  235998. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235999. {
  236000. const int numStreams = bufList->mNumberBuffers;
  236001. for (int i = 0; i < numStreams; ++i)
  236002. {
  236003. const AudioBuffer& b = bufList->mBuffers[i];
  236004. total += b.mNumberChannels;
  236005. }
  236006. }
  236007. }
  236008. return total;
  236009. }
  236010. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  236011. };
  236012. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236013. {
  236014. return new CoreAudioIODeviceType();
  236015. }
  236016. #undef log
  236017. #endif
  236018. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236019. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236020. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236021. // compiled on its own).
  236022. #if JUCE_INCLUDED_FILE
  236023. #if JUCE_MAC
  236024. namespace CoreMidiHelpers
  236025. {
  236026. bool logError (const OSStatus err, const int lineNum)
  236027. {
  236028. if (err == noErr)
  236029. return true;
  236030. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236031. jassertfalse;
  236032. return false;
  236033. }
  236034. #undef CHECK_ERROR
  236035. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236036. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236037. {
  236038. String result;
  236039. CFStringRef str = 0;
  236040. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236041. if (str != 0)
  236042. {
  236043. result = PlatformUtilities::cfStringToJuceString (str);
  236044. CFRelease (str);
  236045. str = 0;
  236046. }
  236047. MIDIEntityRef entity = 0;
  236048. MIDIEndpointGetEntity (endpoint, &entity);
  236049. if (entity == 0)
  236050. return result; // probably virtual
  236051. if (result.isEmpty())
  236052. {
  236053. // endpoint name has zero length - try the entity
  236054. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236055. if (str != 0)
  236056. {
  236057. result += PlatformUtilities::cfStringToJuceString (str);
  236058. CFRelease (str);
  236059. str = 0;
  236060. }
  236061. }
  236062. // now consider the device's name
  236063. MIDIDeviceRef device = 0;
  236064. MIDIEntityGetDevice (entity, &device);
  236065. if (device == 0)
  236066. return result;
  236067. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236068. if (str != 0)
  236069. {
  236070. const String s (PlatformUtilities::cfStringToJuceString (str));
  236071. CFRelease (str);
  236072. // if an external device has only one entity, throw away
  236073. // the endpoint name and just use the device name
  236074. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236075. {
  236076. result = s;
  236077. }
  236078. else if (! result.startsWithIgnoreCase (s))
  236079. {
  236080. // prepend the device name to the entity name
  236081. result = (s + " " + result).trimEnd();
  236082. }
  236083. }
  236084. return result;
  236085. }
  236086. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236087. {
  236088. String result;
  236089. // Does the endpoint have connections?
  236090. CFDataRef connections = 0;
  236091. int numConnections = 0;
  236092. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236093. if (connections != 0)
  236094. {
  236095. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236096. if (numConnections > 0)
  236097. {
  236098. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236099. for (int i = 0; i < numConnections; ++i, ++pid)
  236100. {
  236101. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236102. MIDIObjectRef connObject;
  236103. MIDIObjectType connObjectType;
  236104. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236105. if (err == noErr)
  236106. {
  236107. String s;
  236108. if (connObjectType == kMIDIObjectType_ExternalSource
  236109. || connObjectType == kMIDIObjectType_ExternalDestination)
  236110. {
  236111. // Connected to an external device's endpoint (10.3 and later).
  236112. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236113. }
  236114. else
  236115. {
  236116. // Connected to an external device (10.2) (or something else, catch-all)
  236117. CFStringRef str = 0;
  236118. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236119. if (str != 0)
  236120. {
  236121. s = PlatformUtilities::cfStringToJuceString (str);
  236122. CFRelease (str);
  236123. }
  236124. }
  236125. if (s.isNotEmpty())
  236126. {
  236127. if (result.isNotEmpty())
  236128. result += ", ";
  236129. result += s;
  236130. }
  236131. }
  236132. }
  236133. }
  236134. CFRelease (connections);
  236135. }
  236136. if (result.isNotEmpty())
  236137. return result;
  236138. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236139. return getEndpointName (endpoint, false);
  236140. }
  236141. MIDIClientRef getGlobalMidiClient()
  236142. {
  236143. static MIDIClientRef globalMidiClient = 0;
  236144. if (globalMidiClient == 0)
  236145. {
  236146. String name ("JUCE");
  236147. if (JUCEApplication::getInstance() != 0)
  236148. name = JUCEApplication::getInstance()->getApplicationName();
  236149. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236150. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236151. CFRelease (appName);
  236152. }
  236153. return globalMidiClient;
  236154. }
  236155. class MidiPortAndEndpoint
  236156. {
  236157. public:
  236158. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236159. : port (port_), endPoint (endPoint_)
  236160. {
  236161. }
  236162. ~MidiPortAndEndpoint()
  236163. {
  236164. if (port != 0)
  236165. MIDIPortDispose (port);
  236166. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236167. MIDIEndpointDispose (endPoint);
  236168. }
  236169. void send (const MIDIPacketList* const packets)
  236170. {
  236171. if (port != 0)
  236172. MIDISend (port, endPoint, packets);
  236173. else
  236174. MIDIReceived (endPoint, packets);
  236175. }
  236176. MIDIPortRef port;
  236177. MIDIEndpointRef endPoint;
  236178. };
  236179. class MidiPortAndCallback;
  236180. CriticalSection callbackLock;
  236181. Array<MidiPortAndCallback*> activeCallbacks;
  236182. class MidiPortAndCallback
  236183. {
  236184. public:
  236185. MidiPortAndCallback (MidiInputCallback& callback_)
  236186. : input (0), active (false), callback (callback_), concatenator (2048)
  236187. {
  236188. }
  236189. ~MidiPortAndCallback()
  236190. {
  236191. active = false;
  236192. {
  236193. const ScopedLock sl (callbackLock);
  236194. activeCallbacks.removeValue (this);
  236195. }
  236196. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236197. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236198. }
  236199. void handlePackets (const MIDIPacketList* const pktlist)
  236200. {
  236201. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236202. const ScopedLock sl (callbackLock);
  236203. if (activeCallbacks.contains (this) && active)
  236204. {
  236205. const MIDIPacket* packet = &pktlist->packet[0];
  236206. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236207. {
  236208. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236209. input, callback);
  236210. packet = MIDIPacketNext (packet);
  236211. }
  236212. }
  236213. }
  236214. MidiInput* input;
  236215. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236216. volatile bool active;
  236217. private:
  236218. MidiInputCallback& callback;
  236219. MidiDataConcatenator concatenator;
  236220. };
  236221. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236222. {
  236223. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236224. }
  236225. }
  236226. const StringArray MidiOutput::getDevices()
  236227. {
  236228. StringArray s;
  236229. const ItemCount num = MIDIGetNumberOfDestinations();
  236230. for (ItemCount i = 0; i < num; ++i)
  236231. {
  236232. MIDIEndpointRef dest = MIDIGetDestination (i);
  236233. if (dest != 0)
  236234. {
  236235. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236236. if (name.isEmpty())
  236237. name = "<error>";
  236238. s.add (name);
  236239. }
  236240. else
  236241. {
  236242. s.add ("<error>");
  236243. }
  236244. }
  236245. return s;
  236246. }
  236247. int MidiOutput::getDefaultDeviceIndex()
  236248. {
  236249. return 0;
  236250. }
  236251. MidiOutput* MidiOutput::openDevice (int index)
  236252. {
  236253. MidiOutput* mo = 0;
  236254. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  236255. {
  236256. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236257. CFStringRef pname;
  236258. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236259. {
  236260. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236261. MIDIPortRef port;
  236262. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236263. {
  236264. mo = new MidiOutput();
  236265. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236266. }
  236267. CFRelease (pname);
  236268. }
  236269. }
  236270. return mo;
  236271. }
  236272. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236273. {
  236274. MidiOutput* mo = 0;
  236275. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236276. MIDIEndpointRef endPoint;
  236277. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236278. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236279. {
  236280. mo = new MidiOutput();
  236281. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236282. }
  236283. CFRelease (name);
  236284. return mo;
  236285. }
  236286. MidiOutput::~MidiOutput()
  236287. {
  236288. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236289. }
  236290. void MidiOutput::reset()
  236291. {
  236292. }
  236293. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236294. {
  236295. return false;
  236296. }
  236297. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236298. {
  236299. }
  236300. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236301. {
  236302. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236303. if (message.isSysEx())
  236304. {
  236305. const int maxPacketSize = 256;
  236306. int pos = 0, bytesLeft = message.getRawDataSize();
  236307. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236308. HeapBlock <MIDIPacketList> packets;
  236309. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236310. packets->numPackets = numPackets;
  236311. MIDIPacket* p = packets->packet;
  236312. for (int i = 0; i < numPackets; ++i)
  236313. {
  236314. p->timeStamp = AudioGetCurrentHostTime();
  236315. p->length = jmin (maxPacketSize, bytesLeft);
  236316. memcpy (p->data, message.getRawData() + pos, p->length);
  236317. pos += p->length;
  236318. bytesLeft -= p->length;
  236319. p = MIDIPacketNext (p);
  236320. }
  236321. mpe->send (packets);
  236322. }
  236323. else
  236324. {
  236325. MIDIPacketList packets;
  236326. packets.numPackets = 1;
  236327. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  236328. packets.packet[0].length = message.getRawDataSize();
  236329. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236330. mpe->send (&packets);
  236331. }
  236332. }
  236333. const StringArray MidiInput::getDevices()
  236334. {
  236335. StringArray s;
  236336. const ItemCount num = MIDIGetNumberOfSources();
  236337. for (ItemCount i = 0; i < num; ++i)
  236338. {
  236339. MIDIEndpointRef source = MIDIGetSource (i);
  236340. if (source != 0)
  236341. {
  236342. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236343. if (name.isEmpty())
  236344. name = "<error>";
  236345. s.add (name);
  236346. }
  236347. else
  236348. {
  236349. s.add ("<error>");
  236350. }
  236351. }
  236352. return s;
  236353. }
  236354. int MidiInput::getDefaultDeviceIndex()
  236355. {
  236356. return 0;
  236357. }
  236358. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236359. {
  236360. jassert (callback != 0);
  236361. using namespace CoreMidiHelpers;
  236362. MidiInput* newInput = 0;
  236363. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  236364. {
  236365. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236366. if (endPoint != 0)
  236367. {
  236368. CFStringRef name;
  236369. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236370. {
  236371. MIDIClientRef client = getGlobalMidiClient();
  236372. if (client != 0)
  236373. {
  236374. MIDIPortRef port;
  236375. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236376. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236377. {
  236378. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236379. {
  236380. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236381. newInput = new MidiInput (getDevices() [index]);
  236382. mpc->input = newInput;
  236383. newInput->internal = mpc;
  236384. const ScopedLock sl (callbackLock);
  236385. activeCallbacks.add (mpc.release());
  236386. }
  236387. else
  236388. {
  236389. CHECK_ERROR (MIDIPortDispose (port));
  236390. }
  236391. }
  236392. }
  236393. }
  236394. CFRelease (name);
  236395. }
  236396. }
  236397. return newInput;
  236398. }
  236399. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236400. {
  236401. jassert (callback != 0);
  236402. using namespace CoreMidiHelpers;
  236403. MidiInput* mi = 0;
  236404. MIDIClientRef client = getGlobalMidiClient();
  236405. if (client != 0)
  236406. {
  236407. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236408. mpc->active = false;
  236409. MIDIEndpointRef endPoint;
  236410. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236411. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236412. {
  236413. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236414. mi = new MidiInput (deviceName);
  236415. mpc->input = mi;
  236416. mi->internal = mpc;
  236417. const ScopedLock sl (callbackLock);
  236418. activeCallbacks.add (mpc.release());
  236419. }
  236420. CFRelease (name);
  236421. }
  236422. return mi;
  236423. }
  236424. MidiInput::MidiInput (const String& name_)
  236425. : name (name_)
  236426. {
  236427. }
  236428. MidiInput::~MidiInput()
  236429. {
  236430. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236431. }
  236432. void MidiInput::start()
  236433. {
  236434. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236435. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236436. }
  236437. void MidiInput::stop()
  236438. {
  236439. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236440. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236441. }
  236442. #undef CHECK_ERROR
  236443. #else // Stubs for iOS...
  236444. MidiOutput::~MidiOutput() {}
  236445. void MidiOutput::reset() {}
  236446. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236447. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236448. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236449. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236450. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236451. const StringArray MidiInput::getDevices() { return StringArray(); }
  236452. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236453. #endif
  236454. #endif
  236455. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236456. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236457. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236458. // compiled on its own).
  236459. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236460. #if ! JUCE_QUICKTIME
  236461. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236462. #endif
  236463. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236464. class QTCameraDeviceInteral;
  236465. END_JUCE_NAMESPACE
  236466. @interface QTCaptureCallbackDelegate : NSObject
  236467. {
  236468. @public
  236469. CameraDevice* owner;
  236470. QTCameraDeviceInteral* internal;
  236471. int64 firstPresentationTime;
  236472. int64 averageTimeOffset;
  236473. }
  236474. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236475. - (void) dealloc;
  236476. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236477. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236478. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236479. fromConnection: (QTCaptureConnection*) connection;
  236480. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236481. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236482. fromConnection: (QTCaptureConnection*) connection;
  236483. @end
  236484. BEGIN_JUCE_NAMESPACE
  236485. class QTCameraDeviceInteral
  236486. {
  236487. public:
  236488. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236489. {
  236490. const ScopedAutoReleasePool pool;
  236491. session = [[QTCaptureSession alloc] init];
  236492. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236493. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236494. input = 0;
  236495. audioInput = 0;
  236496. audioDevice = 0;
  236497. fileOutput = 0;
  236498. imageOutput = 0;
  236499. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236500. internalDev: this];
  236501. NSError* err = 0;
  236502. [device retain];
  236503. [device open: &err];
  236504. if (err == 0)
  236505. {
  236506. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236507. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236508. [session addInput: input error: &err];
  236509. if (err == 0)
  236510. {
  236511. resetFile();
  236512. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236513. [imageOutput setDelegate: callbackDelegate];
  236514. if (err == 0)
  236515. {
  236516. [session startRunning];
  236517. return;
  236518. }
  236519. }
  236520. }
  236521. openingError = nsStringToJuce ([err description]);
  236522. DBG (openingError);
  236523. }
  236524. ~QTCameraDeviceInteral()
  236525. {
  236526. [session stopRunning];
  236527. [session removeOutput: imageOutput];
  236528. [session release];
  236529. [input release];
  236530. [device release];
  236531. [audioDevice release];
  236532. [audioInput release];
  236533. [fileOutput release];
  236534. [imageOutput release];
  236535. [callbackDelegate release];
  236536. }
  236537. void resetFile()
  236538. {
  236539. [fileOutput recordToOutputFileURL: nil];
  236540. [session removeOutput: fileOutput];
  236541. [fileOutput release];
  236542. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236543. [session removeInput: audioInput];
  236544. [audioInput release];
  236545. audioInput = 0;
  236546. [audioDevice release];
  236547. audioDevice = 0;
  236548. [fileOutput setDelegate: callbackDelegate];
  236549. }
  236550. void addDefaultAudioInput()
  236551. {
  236552. NSError* err = nil;
  236553. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236554. if ([audioDevice open: &err])
  236555. [audioDevice retain];
  236556. else
  236557. audioDevice = nil;
  236558. if (audioDevice != 0)
  236559. {
  236560. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236561. [session addInput: audioInput error: &err];
  236562. }
  236563. }
  236564. void addListener (CameraDevice::Listener* listenerToAdd)
  236565. {
  236566. const ScopedLock sl (listenerLock);
  236567. if (listeners.size() == 0)
  236568. [session addOutput: imageOutput error: nil];
  236569. listeners.addIfNotAlreadyThere (listenerToAdd);
  236570. }
  236571. void removeListener (CameraDevice::Listener* listenerToRemove)
  236572. {
  236573. const ScopedLock sl (listenerLock);
  236574. listeners.removeValue (listenerToRemove);
  236575. if (listeners.size() == 0)
  236576. [session removeOutput: imageOutput];
  236577. }
  236578. void callListeners (CIImage* frame, int w, int h)
  236579. {
  236580. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236581. Image image (cgImage);
  236582. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236583. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236584. CGContextFlush (cgImage->context);
  236585. const ScopedLock sl (listenerLock);
  236586. for (int i = listeners.size(); --i >= 0;)
  236587. {
  236588. CameraDevice::Listener* const l = listeners[i];
  236589. if (l != 0)
  236590. l->imageReceived (image);
  236591. }
  236592. }
  236593. QTCaptureDevice* device;
  236594. QTCaptureDeviceInput* input;
  236595. QTCaptureDevice* audioDevice;
  236596. QTCaptureDeviceInput* audioInput;
  236597. QTCaptureSession* session;
  236598. QTCaptureMovieFileOutput* fileOutput;
  236599. QTCaptureDecompressedVideoOutput* imageOutput;
  236600. QTCaptureCallbackDelegate* callbackDelegate;
  236601. String openingError;
  236602. Array<CameraDevice::Listener*> listeners;
  236603. CriticalSection listenerLock;
  236604. };
  236605. END_JUCE_NAMESPACE
  236606. @implementation QTCaptureCallbackDelegate
  236607. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236608. internalDev: (QTCameraDeviceInteral*) d
  236609. {
  236610. [super init];
  236611. owner = owner_;
  236612. internal = d;
  236613. firstPresentationTime = 0;
  236614. averageTimeOffset = 0;
  236615. return self;
  236616. }
  236617. - (void) dealloc
  236618. {
  236619. [super dealloc];
  236620. }
  236621. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236622. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236623. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236624. fromConnection: (QTCaptureConnection*) connection
  236625. {
  236626. if (internal->listeners.size() > 0)
  236627. {
  236628. const ScopedAutoReleasePool pool;
  236629. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236630. CVPixelBufferGetWidth (videoFrame),
  236631. CVPixelBufferGetHeight (videoFrame));
  236632. }
  236633. }
  236634. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236635. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236636. fromConnection: (QTCaptureConnection*) connection
  236637. {
  236638. const Time now (Time::getCurrentTime());
  236639. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236640. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236641. #else
  236642. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236643. #endif
  236644. int64 presentationTime = (hosttime != nil)
  236645. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236646. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236647. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236648. if (firstPresentationTime == 0)
  236649. {
  236650. firstPresentationTime = presentationTime;
  236651. averageTimeOffset = timeDiff;
  236652. }
  236653. else
  236654. {
  236655. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236656. }
  236657. }
  236658. @end
  236659. BEGIN_JUCE_NAMESPACE
  236660. class QTCaptureViewerComp : public NSViewComponent
  236661. {
  236662. public:
  236663. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236664. {
  236665. const ScopedAutoReleasePool pool;
  236666. captureView = [[QTCaptureView alloc] init];
  236667. [captureView setCaptureSession: internal->session];
  236668. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236669. setView (captureView);
  236670. }
  236671. ~QTCaptureViewerComp()
  236672. {
  236673. setView (0);
  236674. [captureView setCaptureSession: nil];
  236675. [captureView release];
  236676. }
  236677. QTCaptureView* captureView;
  236678. };
  236679. CameraDevice::CameraDevice (const String& name_, int index)
  236680. : name (name_)
  236681. {
  236682. isRecording = false;
  236683. internal = new QTCameraDeviceInteral (this, index);
  236684. }
  236685. CameraDevice::~CameraDevice()
  236686. {
  236687. stopRecording();
  236688. delete static_cast <QTCameraDeviceInteral*> (internal);
  236689. internal = 0;
  236690. }
  236691. Component* CameraDevice::createViewerComponent()
  236692. {
  236693. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236694. }
  236695. const String CameraDevice::getFileExtension()
  236696. {
  236697. return ".mov";
  236698. }
  236699. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236700. {
  236701. stopRecording();
  236702. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236703. d->callbackDelegate->firstPresentationTime = 0;
  236704. file.deleteFile();
  236705. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236706. // out wrong, so we'll put some audio in there too..,
  236707. d->addDefaultAudioInput();
  236708. [d->session addOutput: d->fileOutput error: nil];
  236709. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236710. for (;;)
  236711. {
  236712. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236713. if (connection == 0)
  236714. break;
  236715. QTCompressionOptions* options = 0;
  236716. NSString* mediaType = [connection mediaType];
  236717. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236718. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236719. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236720. : @"QTCompressionOptions240SizeH264Video"];
  236721. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236722. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236723. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236724. }
  236725. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236726. isRecording = true;
  236727. }
  236728. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236729. {
  236730. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236731. if (d->callbackDelegate->firstPresentationTime != 0)
  236732. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236733. return Time();
  236734. }
  236735. void CameraDevice::stopRecording()
  236736. {
  236737. if (isRecording)
  236738. {
  236739. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236740. isRecording = false;
  236741. }
  236742. }
  236743. void CameraDevice::addListener (Listener* listenerToAdd)
  236744. {
  236745. if (listenerToAdd != 0)
  236746. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236747. }
  236748. void CameraDevice::removeListener (Listener* listenerToRemove)
  236749. {
  236750. if (listenerToRemove != 0)
  236751. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236752. }
  236753. const StringArray CameraDevice::getAvailableDevices()
  236754. {
  236755. const ScopedAutoReleasePool pool;
  236756. StringArray results;
  236757. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236758. for (int i = 0; i < (int) [devs count]; ++i)
  236759. {
  236760. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236761. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236762. }
  236763. return results;
  236764. }
  236765. CameraDevice* CameraDevice::openDevice (int index,
  236766. int minWidth, int minHeight,
  236767. int maxWidth, int maxHeight)
  236768. {
  236769. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236770. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236771. return d.release();
  236772. return 0;
  236773. }
  236774. #endif
  236775. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236776. #endif
  236777. #endif
  236778. END_JUCE_NAMESPACE
  236779. #endif
  236780. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236781. #endif
  236782. #endif